Added hint for startup on Red Hat
[privoxy.git] / loaders.c
1 const char loaders_rcs[] = "$Id: loaders.c,v 1.48 2002/04/05 00:56:09 gliptak Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/loaders.c,v $
5  *
6  * Purpose     :  Functions to load and unload the various
7  *                configuration files.  Also contains code to manage
8  *                the list of active loaders, and to automatically
9  *                unload files that are no longer in use.
10  *
11  * Copyright   :  Written by and Copyright (C) 2001 the SourceForge
12  *                Privoxy team. http://www.privoxy.org/
13  *
14  *                Based on the Internet Junkbuster originally written
15  *                by and Copyright (C) 1997 Anonymous Coders and
16  *                Junkbusters Corporation.  http://www.junkbusters.com
17  *
18  *                This program is free software; you can redistribute it
19  *                and/or modify it under the terms of the GNU General
20  *                Public License as published by the Free Software
21  *                Foundation; either version 2 of the License, or (at
22  *                your option) any later version.
23  *
24  *                This program is distributed in the hope that it will
25  *                be useful, but WITHOUT ANY WARRANTY; without even the
26  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
27  *                PARTICULAR PURPOSE.  See the GNU General Public
28  *                License for more details.
29  *
30  *                The GNU General Public License should be included with
31  *                this file.  If not, you can view it at
32  *                http://www.gnu.org/copyleft/gpl.html
33  *                or write to the Free Software Foundation, Inc., 59
34  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
35  *
36  * Revisions   :
37  *    $Log: loaders.c,v $
38  *    Revision 1.48  2002/04/05 00:56:09  gliptak
39  *    Correcting typo to clean up on realloc failure
40  *
41  *    Revision 1.47  2002/03/26 22:29:55  swa
42  *    we have a new homepage!
43  *
44  *    Revision 1.46  2002/03/24 13:25:43  swa
45  *    name change related issues
46  *
47  *    Revision 1.45  2002/03/16 23:54:06  jongfoster
48  *    Adding graceful termination feature, to help look for memory leaks.
49  *    If you enable this (which, by design, has to be done by hand
50  *    editing config.h) and then go to http://i.j.b/die, then the program
51  *    will exit cleanly after the *next* request.  It should free all the
52  *    memory that was used.
53  *
54  *    Revision 1.44  2002/03/16 21:51:00  jongfoster
55  *    Fixing free(NULL).
56  *
57  *    Revision 1.43  2002/03/16 20:28:34  oes
58  *    Added descriptions to the filters so users will know what they select in the cgi editor
59  *
60  *    Revision 1.42  2002/03/13 00:27:05  jongfoster
61  *    Killing warnings
62  *
63  *    Revision 1.41  2002/03/12 01:42:50  oes
64  *    Introduced modular filters
65  *
66  *    Revision 1.40  2002/03/08 17:46:04  jongfoster
67  *    Fixing int/size_t warnings
68  *
69  *    Revision 1.39  2002/03/07 03:46:17  oes
70  *    Fixed compiler warnings
71  *
72  *    Revision 1.38  2002/03/06 22:54:35  jongfoster
73  *    Automated function-comment nitpicking.
74  *
75  *    Revision 1.37  2002/03/03 15:07:49  oes
76  *    Re-enabled automatic config reloading
77  *
78  *    Revision 1.36  2002/01/22 23:46:18  jongfoster
79  *    Moving edit_read_line() and simple_read_line() to loaders.c, and
80  *    extending them to support reading MS-DOS, Mac and UNIX style files
81  *    on all platforms.
82  *
83  *    Modifying read_config_line() (without changing it's prototype) to
84  *    be a trivial wrapper for edit_read_line().  This means that we have
85  *    one function to read a line and handle comments, which is common
86  *    between the initialization code and the edit interface.
87  *
88  *    Revision 1.35  2002/01/17 21:03:08  jongfoster
89  *    Moving all our URL and URL pattern parsing code to urlmatch.c.
90  *
91  *    Renaming free_url to free_url_spec, since it frees a struct url_spec.
92  *
93  *    Revision 1.34  2001/12/30 14:07:32  steudten
94  *    - Add signal handling (unix)
95  *    - Add SIGHUP handler (unix)
96  *    - Add creation of pidfile (unix)
97  *    - Add action 'top' in rc file (RH)
98  *    - Add entry 'SIGNALS' to manpage
99  *    - Add exit message to logfile (unix)
100  *
101  *    Revision 1.33  2001/11/13 00:16:38  jongfoster
102  *    Replacing references to malloc.h with the standard stdlib.h
103  *    (See ANSI or K&R 2nd Ed)
104  *
105  *    Revision 1.32  2001/11/07 00:02:13  steudten
106  *    Add line number in error output for lineparsing for
107  *    actionsfile and configfile.
108  *    Special handling for CLF added.
109  *
110  *    Revision 1.31  2001/10/26 17:39:01  oes
111  *    Removed csp->referrer
112  *    Moved ijb_isspace and ijb_tolower to project.h
113  *
114  *    Revision 1.30  2001/10/25 03:40:48  david__schmidt
115  *    Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
116  *    threads to call select() simultaneously.  So, it's time to do a real, live,
117  *    native OS/2 port.  See defines for __EMX__ (the porting layer) vs. __OS2__
118  *    (native). Both versions will work, but using __OS2__ offers multi-threading.
119  *
120  *    Revision 1.29  2001/10/23 21:38:53  jongfoster
121  *    Adding error-checking to create_url_spec()
122  *
123  *    Revision 1.28  2001/10/07 15:40:39  oes
124  *    Replaced 6 boolean members of csp with one bitmap (csp->flags)
125  *
126  *    Revision 1.27  2001/09/22 16:36:59  jongfoster
127  *    Removing unused parameter fs from read_config_line()
128  *
129  *    Revision 1.26  2001/09/22 14:05:22  jongfoster
130  *    Bugfix: Multiple escaped "#" characters in a configuration
131  *    file are now permitted.
132  *    Also removing 3 unused headers.
133  *
134  *    Revision 1.25  2001/09/13 22:44:03  jongfoster
135  *    Adding {} to an if statement
136  *
137  *    Revision 1.24  2001/07/30 22:08:36  jongfoster
138  *    Tidying up #defines:
139  *    - All feature #defines are now of the form FEATURE_xxx
140  *    - Permanently turned off WIN_GUI_EDIT
141  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
142  *
143  *    Revision 1.23  2001/07/20 15:51:54  oes
144  *    Fixed indentation of prepocessor commands
145  *
146  *    Revision 1.22  2001/07/20 15:16:17  haroon
147  *    - per Guy's suggestion, added a while loop in sweep() to catch not just
148  *      the last inactive CSP but all other consecutive inactive CSPs after that
149  *      as well
150  *
151  *    Revision 1.21  2001/07/18 17:26:24  oes
152  *    Changed to conform to new pcrs interface
153  *
154  *    Revision 1.20  2001/07/17 13:07:01  oes
155  *    Fixed segv when last line in config files
156  *     lacked a terminating (\r)\n
157  *
158  *    Revision 1.19  2001/07/13 14:01:54  oes
159  *    Removed all #ifdef PCRS
160  *
161  *    Revision 1.18  2001/06/29 21:45:41  oes
162  *    Indentation, CRLF->LF, Tab-> Space
163  *
164  *    Revision 1.17  2001/06/29 13:31:51  oes
165  *    Various adaptions
166  *
167  *    Revision 1.16  2001/06/09 10:55:28  jongfoster
168  *    Changing BUFSIZ ==> BUFFER_SIZE
169  *
170  *    Revision 1.15  2001/06/07 23:14:14  jongfoster
171  *    Removing ACL and forward file loaders - these
172  *    files have been merged into the config file.
173  *    Cosmetic: Moving unloader funcs next to their
174  *    respective loader funcs
175  *
176  *    Revision 1.14  2001/06/01 03:27:04  oes
177  *    Fixed line continuation problem
178  *
179  *    Revision 1.13  2001/05/31 21:28:49  jongfoster
180  *    Removed all permissionsfile code - it's now called the actions
181  *    file, and (almost) all the code is in actions.c
182  *
183  *    Revision 1.12  2001/05/31 17:32:31  oes
184  *
185  *     - Enhanced domain part globbing with infix and prefix asterisk
186  *       matching and optional unanchored operation
187  *
188  *    Revision 1.11  2001/05/29 23:25:24  oes
189  *
190  *     - load_config_line() and load_permissions_file() now use chomp()
191  *
192  *    Revision 1.10  2001/05/29 09:50:24  jongfoster
193  *    Unified blocklist/imagelist/permissionslist.
194  *    File format is still under discussion, but the internal changes
195  *    are (mostly) done.
196  *
197  *    Also modified interceptor behaviour:
198  *    - We now intercept all URLs beginning with one of the following
199  *      prefixes (and *only* these prefixes):
200  *        * http://i.j.b/
201  *        * http://ijbswa.sf.net/config/
202  *        * http://ijbswa.sourceforge.net/config/
203  *    - New interceptors "home page" - go to http://i.j.b/ to see it.
204  *    - Internal changes so that intercepted and fast redirect pages
205  *      are not replaced with an image.
206  *    - Interceptors now have the option to send a binary page direct
207  *      to the client. (i.e. ijb-send-banner uses this)
208  *    - Implemented show-url-info interceptor.  (Which is why I needed
209  *      the above interceptors changes - a typical URL is
210  *      "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
211  *      The previous mechanism would not have intercepted that, and
212  *      if it had been intercepted then it then it would have replaced
213  *      it with an image.)
214  *
215  *    Revision 1.9  2001/05/26 17:12:07  jongfoster
216  *    Fatal errors loading configuration files now give better error messages.
217  *
218  *    Revision 1.8  2001/05/26 00:55:20  jongfoster
219  *    Removing duplicated code.  load_forwardfile() now uses create_url_spec()
220  *
221  *    Revision 1.7  2001/05/26 00:28:36  jongfoster
222  *    Automatic reloading of config file.
223  *    Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
224  *    Most of the global variables have been moved to a new
225  *    struct configuration_spec, accessed through csp->config->globalname
226  *    Most of the globals remaining are used by the Win32 GUI.
227  *
228  *    Revision 1.6  2001/05/23 12:27:33  oes
229  *
230  *    Fixed ugly indentation of my last changes
231  *
232  *    Revision 1.5  2001/05/23 10:39:05  oes
233  *    - Added support for escaping the comment character
234  *      in config files by a backslash
235  *    - Added support for line continuation in config
236  *      files
237  *    - Fixed a buffer overflow bug with long config lines
238  *
239  *    Revision 1.4  2001/05/22 18:56:28  oes
240  *    CRLF -> LF
241  *
242  *    Revision 1.3  2001/05/20 01:21:20  jongfoster
243  *    Version 2.9.4 checkin.
244  *    - Merged popupfile and cookiefile, and added control over PCRS
245  *      filtering, in new "permissionsfile".
246  *    - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
247  *      file error you now get a message box (in the Win32 GUI) rather
248  *      than the program exiting with no explanation.
249  *    - Made killpopup use the PCRS MIME-type checking and HTTP-header
250  *      skipping.
251  *    - Removed tabs from "config"
252  *    - Moved duplicated url parsing code in "loaders.c" to a new funcition.
253  *    - Bumped up version number.
254  *
255  *    Revision 1.2  2001/05/17 23:01:01  oes
256  *     - Cleaned CRLF's from the sources and related files
257  *
258  *    Revision 1.1.1.1  2001/05/15 13:58:59  oes
259  *    Initial import of version 2.9.3 source tree
260  *
261  *
262  *********************************************************************/
263 \f
264
265 #include "config.h"
266
267 #include <stdio.h>
268 #include <stdlib.h>
269 #include <sys/types.h>
270 #include <string.h>
271 #include <errno.h>
272 #include <sys/stat.h>
273 #include <ctype.h>
274 #include <assert.h>
275
276 #if !defined(_WIN32) && !defined(__OS2__)
277 #include <unistd.h>
278 #endif
279
280 #include "project.h"
281 #include "list.h"
282 #include "loaders.h"
283 #include "filters.h"
284 #include "parsers.h"
285 #include "jcc.h"
286 #include "miscutil.h"
287 #include "errlog.h"
288 #include "actions.h"
289 #include "urlmatch.h"
290
291 const char loaders_h_rcs[] = LOADERS_H_VERSION;
292
293 /*
294  * Currently active files.
295  * These are also entered in the main linked list of files.
296  */
297
298 #ifdef FEATURE_TRUST
299 static struct file_list *current_trustfile      = NULL;
300 #endif /* def FEATURE_TRUST */
301
302 static struct file_list *current_re_filterfile  = NULL;
303
304
305
306 /*********************************************************************
307  *
308  * Function    :  sweep
309  *
310  * Description :  Basically a mark and sweep garbage collector, it is run
311  *                (by the parent thread) every once in a while to reclaim memory.
312  *
313  * It uses a mark and sweep strategy:
314  *   1) mark all files as inactive
315  *
316  *   2) check with each client:
317  *       if it is active,   mark its files as active
318  *       if it is inactive, free its resources
319  *
320  *   3) free the resources of all of the files that
321  *      are still marked as inactive (and are obsolete).
322  *
323  *   N.B. files that are not obsolete don't have an unloader defined.
324  *
325  * Parameters  :  None
326  *
327  * Returns     :  N/A
328  *
329  *********************************************************************/
330 void sweep(void)
331 {
332    struct file_list *fl, *nfl;
333    struct client_state *csp, *ncsp;
334
335    /* clear all of the file's active flags */
336    for ( fl = files->next; NULL != fl; fl = fl->next )
337    {
338       fl->active = 0;
339    }
340
341    for (csp = clients; csp && (NULL != (ncsp = csp->next)) ; csp = csp->next)
342    {
343       if (ncsp->flags & CSP_FLAG_ACTIVE)
344       {
345          /* mark this client's files as active */
346
347          /*
348           * Always have a configuration file.
349           * (Also note the slightly non-standard extra
350           * indirection here.)
351           */
352          ncsp->config->config_file_list->active = 1;
353
354          if (ncsp->actions_list)     /* actions files */
355          {
356             ncsp->actions_list->active = 1;
357          }
358
359          if (ncsp->rlist)     /* pcrsjob files */
360          {
361             ncsp->rlist->active = 1;
362          }
363
364 #ifdef FEATURE_TRUST
365          if (ncsp->tlist)     /* trust files */
366          {
367             ncsp->tlist->active = 1;
368          }
369 #endif /* def FEATURE_TRUST */
370
371       }
372       else
373       /*
374        * this client is not active, release its resources
375        * and the ones of all inactive clients that might
376        * follow it
377        */
378       {
379          while (!(ncsp->flags & CSP_FLAG_ACTIVE))
380          {
381             csp->next = ncsp->next;
382
383             freez(ncsp->ip_addr_str);
384             freez(ncsp->my_ip_addr_str);
385             freez(ncsp->my_hostname);
386             freez(ncsp->x_forwarded);
387             freez(ncsp->iob->buf);
388
389             free_http_request(ncsp->http);
390
391             destroy_list(ncsp->headers);
392             destroy_list(ncsp->cookie_list);
393
394             free_current_action(ncsp->action);
395
396 #ifdef FEATURE_STATISTICS
397             urls_read++;
398             if (ncsp->flags & CSP_FLAG_REJECTED)
399             {
400                urls_rejected++;
401             }
402 #endif /* def FEATURE_STATISTICS */
403
404             freez(ncsp);
405
406             /* are there any more in sequence after it? */
407             if( (ncsp = csp->next) == NULL)
408                break;
409          }
410       }
411    }
412
413    for (fl = files; fl && ((nfl = fl->next) != NULL) ; fl = fl->next)
414    {
415       if ( ( 0 == nfl->active ) && ( NULL != nfl->unloader ) )
416       {
417          fl->next = nfl->next;
418
419          (nfl->unloader)(nfl->f);
420
421          freez(nfl->filename);
422
423          freez(nfl);
424       }
425    }
426
427 }
428
429
430 /*********************************************************************
431  *
432  * Function    :  check_file_changed
433  *
434  * Description :  Helper function to check if a file needs reloading.
435  *                If "current" is still current, return it.  Otherwise
436  *                allocates a new (zeroed) "struct file_list", fills
437  *                in the disk file name and timestamp, and returns it.
438  *
439  * Parameters  :
440  *          1  :  current = The file_list currently being used - will
441  *                          be checked to see if it is out of date.
442  *                          May be NULL (which is treated as out of
443  *                          date).
444  *          2  :  filename = Name of file to check.
445  *          3  :  newfl    = New file list. [Output only]
446  *                           This will be set to NULL, OR a struct
447  *                           file_list newly allocated on the
448  *                           heap, with the filename and lastmodified
449  *                           fields filled, and all others zeroed.
450  *
451  * Returns     :  If file unchanged: 0 (and sets newfl == NULL)
452  *                If file changed: 1 and sets newfl != NULL
453  *                On error: 1 and sets newfl == NULL
454  *
455  *********************************************************************/
456 int check_file_changed(const struct file_list * current,
457                        const char * filename,
458                        struct file_list ** newfl)
459 {
460    struct file_list *fs;
461    struct stat statbuf[1];
462
463    *newfl = NULL;
464
465    if (stat(filename, statbuf) < 0)
466    {
467       /* Error, probably file not found. */
468       return 1;
469    }
470
471    if (current
472        && (current->lastmodified == statbuf->st_mtime)
473        && (0 == strcmp(current->filename, filename)))
474    {
475       return 0;
476    }
477
478    fs = (struct file_list *)zalloc(sizeof(struct file_list));
479    if (fs == NULL)
480    {
481       /* Out of memory error */
482       return 1;
483    }
484
485    fs->filename = strdup(filename);
486    fs->lastmodified = statbuf->st_mtime;
487
488    if (fs->filename == NULL)
489    {
490       /* Out of memory error */
491       freez (fs);
492       return 1;
493    }
494    *newfl = fs;
495    return 1;
496 }
497
498
499 /*********************************************************************
500  *
501  * Function    :  simple_read_line
502  *
503  * Description :  Read a single line from a file and return it.
504  *                This is basically a version of fgets() that malloc()s
505  *                it's own line buffer.  Note that the buffer will
506  *                always be a multiple of BUFFER_SIZE bytes long.
507  *                Therefore if you are going to keep the string for
508  *                an extended period of time, you should probably
509  *                strdup() it and free() the original, to save memory.
510  *
511  *
512  * Parameters  :
513  *          1  :  dest = destination for newly malloc'd pointer to
514  *                line data.  Will be set to NULL on error.
515  *          2  :  fp = File to read from
516  *          3  :  newline = Standard for newlines in the file.
517  *                Will be unchanged if it's value on input is not
518  *                NEWLINE_UNKNOWN.
519  *                On output, may be changed from NEWLINE_UNKNOWN to
520  *                actual convention in file.
521  *
522  * Returns     :  JB_ERR_OK     on success
523  *                JB_ERR_MEMORY on out-of-memory
524  *                JB_ERR_FILE   on EOF.
525  *
526  *********************************************************************/
527 jb_err simple_read_line(FILE *fp, char **dest, int *newline)
528 {
529    size_t len = 0;
530    size_t buflen = BUFFER_SIZE;
531    char * buf;
532    char * p;
533    int ch;
534    int realnewline = NEWLINE_UNKNOWN;
535
536    if (NULL == (buf = malloc(buflen)))
537    {
538       return JB_ERR_MEMORY;
539    }
540
541    p = buf;
542
543 /*
544  * Character codes.  If you have a wierd compiler and the following are
545  * incorrect, you also need to fix NEWLINE() in loaders.h
546  */
547 #define CHAR_CR '\r' /* ASCII 13 */
548 #define CHAR_LF '\n' /* ASCII 10 */
549
550    for (;;)
551    {
552       ch = getc(fp);
553       if (ch == EOF)
554       {
555          if (len > 0)
556          {
557             *p = '\0';
558             *dest = buf;
559             return JB_ERR_OK;
560          }
561          else
562          {
563             free(buf);
564             *dest = NULL;
565             return JB_ERR_FILE;
566          }
567       }
568       else if (ch == CHAR_CR)
569       {
570          ch = getc(fp);
571          if (ch == CHAR_LF)
572          {
573             if (*newline == NEWLINE_UNKNOWN)
574             {
575                *newline = NEWLINE_DOS;
576             }
577          }
578          else
579          {
580             if (ch != EOF)
581             {
582                ungetc(ch, fp);
583             }
584             if (*newline == NEWLINE_UNKNOWN)
585             {
586                *newline = NEWLINE_MAC;
587             }
588          }
589          *p = '\0';
590          *dest = buf;
591          if (*newline == NEWLINE_UNKNOWN)
592          {
593             *newline = realnewline;
594          }
595          return JB_ERR_OK;
596       }
597       else if (ch == CHAR_LF)
598       {
599          *p = '\0';
600          *dest = buf;
601          if (*newline == NEWLINE_UNKNOWN)
602          {
603             *newline = NEWLINE_UNIX;
604          }
605          return JB_ERR_OK;
606       }
607       else if (ch == 0)
608       {
609          *p = '\0';
610          *dest = buf;
611          return JB_ERR_OK;
612       }
613
614       *p++ = ch;
615
616       if (++len >= buflen)
617       {
618          buflen += BUFFER_SIZE;
619          if (NULL == (p = realloc(buf, buflen)))
620          {
621             free(buf);
622             return JB_ERR_MEMORY;
623          }
624          buf = p;
625          p = buf + len;
626       }
627    }
628 }
629
630
631 /*********************************************************************
632  *
633  * Function    :  edit_read_line
634  *
635  * Description :  Read a single non-empty line from a file and return
636  *                it.  Trims comments, leading and trailing whitespace
637  *                and respects escaping of newline and comment char.
638  *                Provides the line in 2 alternative forms: raw and
639  *                preprocessed.
640  *                - raw is the raw data read from the file.  If the
641  *                  line is not modified, then this should be written
642  *                  to the new file.
643  *                - prefix is any comments and blank lines that were
644  *                  read from the file.  If the line is modified, then
645  *                  this should be written out to the file followed
646  *                  by the modified data.  (If this string is non-empty
647  *                  then it will have a newline at the end).
648  *                - data is the actual data that will be parsed
649  *                  further by appropriate routines.
650  *                On EOF, the 3 strings will all be set to NULL and
651  *                0 will be returned.
652  *
653  * Parameters  :
654  *          1  :  fp = File to read from
655  *          2  :  raw_out = destination for newly malloc'd pointer to
656  *                raw line data.  May be NULL if you don't want it.
657  *          3  :  prefix_out = destination for newly malloc'd pointer to
658  *                comments.  May be NULL if you don't want it.
659  *          4  :  data_out = destination for newly malloc'd pointer to
660  *                line data with comments and leading/trailing spaces
661  *                removed, and line continuation performed.  May be
662  *                NULL if you don't want it.
663  *          5  :  newline = Standard for newlines in the file.
664  *                On input, set to value to use or NEWLINE_UNKNOWN.
665  *                On output, may be changed from NEWLINE_UNKNOWN to
666  *                actual convention in file.  May be NULL if you
667  *                don't want it.
668  *          6  :  line_number = Line number in file.  In "lines" as
669  *                reported by a text editor, not lines containing data.
670  *
671  * Returns     :  JB_ERR_OK     on success
672  *                JB_ERR_MEMORY on out-of-memory
673  *                JB_ERR_FILE   on EOF.
674  *
675  *********************************************************************/
676 jb_err edit_read_line(FILE *fp,
677                       char **raw_out,
678                       char **prefix_out,
679                       char **data_out,
680                       int *newline,
681                       unsigned long *line_number)
682 {
683    char *p;          /* Temporary pointer   */
684    char *linebuf;    /* Line read from file */
685    char *linestart;  /* Start of linebuf, usually first non-whitespace char */
686    int contflag = 0; /* Nonzero for line continuation - i.e. line ends '\' */
687    int is_empty = 1; /* Flag if not got any data yet */
688    char *raw    = NULL; /* String to be stored in raw_out    */
689    char *prefix = NULL; /* String to be stored in prefix_out */
690    char *data   = NULL; /* String to be stored in data_out   */
691    int scrapnewline;    /* Used for (*newline) if newline==NULL */
692    jb_err rval = JB_ERR_OK;
693
694    assert(fp);
695    assert(raw_out || data_out);
696    assert(newline == NULL
697        || *newline == NEWLINE_UNKNOWN
698        || *newline == NEWLINE_UNIX
699        || *newline == NEWLINE_DOS
700        || *newline == NEWLINE_MAC);
701
702    if (newline == NULL)
703    {
704       scrapnewline = NEWLINE_UNKNOWN;
705       newline = &scrapnewline;
706    }
707
708    /* Set output parameters to NULL */
709    if (raw_out)
710    {
711       *raw_out    = NULL;
712    }
713    if (prefix_out)
714    {
715       *prefix_out = NULL;
716    }
717    if (data_out)
718    {
719       *data_out   = NULL;
720    }
721
722    /* Set string variables to new, empty strings. */
723
724    if (raw_out)
725    {
726       if ((raw = malloc(1)) == NULL)
727       {
728          return JB_ERR_MEMORY;
729       }
730       *raw = '\0';
731    }
732    if (prefix_out)
733    {
734       if ((prefix = malloc(1)) == NULL)
735       {
736          freez(raw);
737          return JB_ERR_MEMORY;
738       }
739       *prefix = '\0';
740    }
741    if (data_out)
742    {
743       if ((data = malloc(1)) == NULL)
744       {
745          freez(raw);
746          freez(prefix);
747          return JB_ERR_MEMORY;
748       }
749       *data = '\0';
750    }
751
752    /* Main loop.  Loop while we need more data & it's not EOF. */
753
754    while ( (contflag || is_empty)
755         && (JB_ERR_OK == (rval = simple_read_line(fp, &linebuf, newline))))
756    {
757       if (line_number)
758       {
759          (*line_number)++;
760       }
761       if (raw)
762       {
763          string_append(&raw,linebuf);
764          if (string_append(&raw,NEWLINE(*newline)))
765          {
766             freez(prefix);
767             freez(data);
768             free(linebuf);
769             return JB_ERR_MEMORY;
770          }
771       }
772
773       /* Line continuation? Trim escape and set flag. */
774       p = linebuf + strlen(linebuf) - 1;
775       contflag = ((*linebuf != '\0') && (*p == '\\'));
776       if (contflag)
777       {
778          *p = '\0';
779       }
780
781       /* Trim leading spaces if we're at the start of the line */
782       linestart = linebuf;
783       if (*data == '\0')
784       {
785          /* Trim leading spaces */
786          while (*linestart && isspace((int)(unsigned char)*linestart))
787          {
788             linestart++;
789          }
790       }
791
792       /* Handle comment characters. */
793       p = linestart;
794       while ((p = strchr(p, '#')) != NULL)
795       {
796          /* Found a comment char.. */
797          if ((p != linebuf) && (*(p-1) == '\\'))
798          {
799             /* ..and it's escaped, left-shift the line over the escape. */
800             char *q = p - 1;
801             while ((*q = *(q + 1)) != '\0')
802             {
803                q++;
804             }
805             /* Now scan from just after the "#". */
806          }
807          else
808          {
809             /* Real comment.  Save it... */
810             if (p == linestart)
811             {
812                /* Special case:  Line only contains a comment, so all the
813                 * previous whitespace is considered part of the comment.
814                 * Undo the whitespace skipping, if any.
815                 */
816                linestart = linebuf;
817                p = linestart;
818             }
819             if (prefix)
820             {
821                string_append(&prefix,p);
822                if (string_append(&prefix, NEWLINE(*newline)))
823                {
824                   freez(raw);
825                   freez(data);
826                   free(linebuf);
827                   return JB_ERR_MEMORY;
828                }
829             }
830
831             /* ... and chop off the rest of the line */
832             *p = '\0';
833          }
834       } /* END while (there's a # character) */
835
836       /* Write to the buffer */
837       if (*linestart)
838       {
839          is_empty = 0;
840          if (data)
841          {
842             if (string_append(&data, linestart))
843             {
844                freez(raw);
845                freez(prefix);
846                free(linebuf);
847                return JB_ERR_MEMORY;
848             }
849          }
850       }
851
852       free(linebuf);
853    } /* END while(we need more data) */
854
855    /* Handle simple_read_line() errors - ignore EOF */
856    if ((rval != JB_ERR_OK) && (rval != JB_ERR_FILE))
857    {
858       freez(raw);
859       freez(prefix);
860       freez(data);
861       return rval;
862    }
863
864    if (raw ? (*raw == '\0') : is_empty)
865    {
866       /* EOF and no data there.  (Definition of "data" depends on whether
867        * the caller cares about "raw" or just "data").
868        */
869
870       freez(raw);
871       freez(prefix);
872       freez(data);
873
874       return JB_ERR_FILE;
875    }
876    else
877    {
878       /* Got at least some data */
879
880       /* Remove trailing whitespace */
881       chomp(data);
882
883       if (raw_out)
884       {
885          *raw_out    = raw;
886       }
887       else
888       {
889          freez(raw);
890       }
891       if (prefix_out)
892       {
893          *prefix_out = prefix;
894       }
895       else
896       {
897          freez(prefix);
898       }
899       if (data_out)
900       {
901          *data_out   = data;
902       }
903       else
904       {
905          freez(data);
906       }
907       return JB_ERR_OK;
908    }
909 }
910
911
912 /*********************************************************************
913  *
914  * Function    :  read_config_line
915  *
916  * Description :  Read a single non-empty line from a file and return
917  *                it.  Trims comments, leading and trailing whitespace
918  *                and respects escaping of newline and comment char.
919  *
920  * Parameters  :
921  *          1  :  buf = Buffer to use.
922  *          2  :  buflen = Size of buffer in bytes.
923  *          3  :  fp = File to read from
924  *          4  :  linenum = linenumber in file
925  *
926  * Returns     :  NULL on EOF or error
927  *                Otherwise, returns buf.
928  *
929  *********************************************************************/
930 char *read_config_line(char *buf, size_t buflen, FILE *fp, unsigned long *linenum)
931 {
932    jb_err err;
933    char *buf2 = NULL;
934    err = edit_read_line(fp, NULL, NULL, &buf2, NULL, linenum);
935    if (err)
936    {
937       if (err == JB_ERR_MEMORY)
938       {
939          log_error(LOG_LEVEL_FATAL, "Out of memory loading a config file");
940       }
941       return NULL;
942    }
943    else
944    {
945       assert(buf2);
946       assert(strlen(buf2) + 1U < buflen);
947       strncpy(buf, buf2, buflen - 1);
948       free(buf2);
949       buf[buflen - 1] = '\0';
950       return buf;
951    }
952 }
953
954
955 #ifdef FEATURE_TRUST
956 /*********************************************************************
957  *
958  * Function    :  unload_trustfile
959  *
960  * Description :  Unloads a trustfile.
961  *
962  * Parameters  :
963  *          1  :  f = the data structure associated with the trustfile.
964  *
965  * Returns     :  N/A
966  *
967  *********************************************************************/
968 static void unload_trustfile(void *f)
969 {
970    struct block_spec *cur = (struct block_spec *)f;
971    struct block_spec *next;
972
973    while (cur != NULL)
974    {
975       next = cur->next;
976
977       free_url_spec(cur->url);
978       free(cur);
979
980       cur = next;
981    }
982
983 }
984
985
986 #ifdef FEATURE_GRACEFUL_TERMINATION
987 /*********************************************************************
988  *
989  * Function    :  unload_current_trust_file
990  *
991  * Description :  Unloads current trust file - reset to state at
992  *                beginning of program.
993  *
994  * Parameters  :  None
995  *
996  * Returns     :  N/A
997  *
998  *********************************************************************/
999 void unload_current_trust_file(void)
1000 {
1001    if (current_trustfile)
1002    {
1003       current_trustfile->unloader = unload_trustfile;
1004       current_trustfile = NULL;
1005    }
1006 }
1007 #endif /* FEATURE_GRACEFUL_TERMINATION */
1008
1009
1010 /*********************************************************************
1011  *
1012  * Function    :  load_trustfile
1013  *
1014  * Description :  Read and parse a trustfile and add to files list.
1015  *
1016  * Parameters  :
1017  *          1  :  csp = Current client state (buffers, headers, etc...)
1018  *
1019  * Returns     :  0 => Ok, everything else is an error.
1020  *
1021  *********************************************************************/
1022 int load_trustfile(struct client_state *csp)
1023 {
1024    FILE *fp;
1025
1026    struct block_spec *b, *bl;
1027    struct url_spec **tl;
1028
1029    char  buf[BUFFER_SIZE], *p, *q;
1030    int reject, trusted;
1031    struct file_list *fs;
1032    unsigned long linenum = 0;
1033
1034    if (!check_file_changed(current_trustfile, csp->config->trustfile, &fs))
1035    {
1036       /* No need to load */
1037       if (csp)
1038       {
1039          csp->tlist = current_trustfile;
1040       }
1041       return(0);
1042    }
1043    if (!fs)
1044    {
1045       goto load_trustfile_error;
1046    }
1047
1048    fs->f = bl = (struct block_spec *)zalloc(sizeof(*bl));
1049    if (bl == NULL)
1050    {
1051       goto load_trustfile_error;
1052    }
1053
1054    if ((fp = fopen(csp->config->trustfile, "r")) == NULL)
1055    {
1056       goto load_trustfile_error;
1057    }
1058
1059    tl = csp->config->trust_list;
1060
1061    while (read_config_line(buf, sizeof(buf), fp, &linenum) != NULL)
1062    {
1063       trusted = 0;
1064       reject  = 1;
1065
1066       if (*buf == '+')
1067       {
1068          trusted = 1;
1069          *buf = '~';
1070       }
1071
1072       if (*buf == '~')
1073       {
1074          reject = 0;
1075          p = buf;
1076          q = p+1;
1077          while ((*p++ = *q++) != '\0')
1078          {
1079             /* nop */
1080          }
1081       }
1082
1083       /* skip blank lines */
1084       if (*buf == '\0')
1085       {
1086          continue;
1087       }
1088
1089       /* allocate a new node */
1090       if ((b = zalloc(sizeof(*b))) == NULL)
1091       {
1092          fclose(fp);
1093          goto load_trustfile_error;
1094       }
1095
1096       /* add it to the list */
1097       b->next  = bl->next;
1098       bl->next = b;
1099
1100       b->reject = reject;
1101
1102       /* Save the URL pattern */
1103       if (create_url_spec(b->url, buf))
1104       {
1105          fclose(fp);
1106          goto load_trustfile_error;
1107       }
1108
1109       /*
1110        * save a pointer to URL's spec in the list of trusted URL's, too
1111        */
1112       if (trusted)
1113       {
1114          *tl++ = b->url;
1115          /* FIXME BUFFER OVERFLOW if >=64 entries */
1116       }
1117    }
1118
1119    *tl = NULL;
1120
1121    fclose(fp);
1122
1123    /* the old one is now obsolete */
1124    if (current_trustfile)
1125    {
1126       current_trustfile->unloader = unload_trustfile;
1127    }
1128
1129    fs->next    = files->next;
1130    files->next = fs;
1131    current_trustfile = fs;
1132
1133    if (csp)
1134    {
1135       csp->tlist = fs;
1136    }
1137
1138    return(0);
1139
1140 load_trustfile_error:
1141    log_error(LOG_LEVEL_FATAL, "can't load trustfile '%s': %E",
1142              csp->config->trustfile);
1143    return(-1);
1144
1145 }
1146 #endif /* def FEATURE_TRUST */
1147
1148
1149 /*********************************************************************
1150  *
1151  * Function    :  unload_re_filterfile
1152  *
1153  * Description :  Unload the re_filter list by freeing all chained
1154  *                re_filterfile specs and their data.
1155  *
1156  * Parameters  :
1157  *          1  :  f = the data structure associated with the filterfile.
1158  *
1159  * Returns     :  N/A
1160  *
1161  *********************************************************************/
1162 static void unload_re_filterfile(void *f)
1163 {
1164    struct re_filterfile_spec *a, *b = (struct re_filterfile_spec *)f;
1165
1166    while (b != NULL)
1167    {
1168       a = b->next;
1169
1170       destroy_list(b->patterns);
1171       pcrs_free_joblist(b->joblist);
1172       freez(b->name);
1173       freez(b->description);
1174       freez(b);
1175
1176       b = a;
1177    }
1178
1179    return;
1180 }
1181
1182
1183 #ifdef FEATURE_GRACEFUL_TERMINATION
1184 /*********************************************************************
1185  *
1186  * Function    :  unload_current_re_filterfile
1187  *
1188  * Description :  Unloads current re_filter file - reset to state at
1189  *                beginning of program.
1190  *
1191  * Parameters  :  None
1192  *
1193  * Returns     :  N/A
1194  *
1195  *********************************************************************/
1196 void unload_current_re_filterfile(void)
1197 {
1198    if (current_re_filterfile)
1199    {
1200       current_re_filterfile->unloader = unload_re_filterfile;
1201       current_re_filterfile = NULL;
1202    }
1203 }
1204 #endif
1205
1206
1207 /*********************************************************************
1208  *
1209  * Function    :  load_re_filterfile
1210  *
1211  * Description :  Load the re_filterfile. 
1212  *                Generate a chained list of re_filterfile_spec's from
1213  *                the "FILTER: " blocks, compiling all their substitutions
1214  *                into chained lists of pcrs_job structs.
1215  *
1216  * Parameters  :
1217  *          1  :  csp = Current client state (buffers, headers, etc...)
1218  *
1219  * Returns     :  0 => Ok, everything else is an error.
1220  *
1221  *********************************************************************/
1222 int load_re_filterfile(struct client_state *csp)
1223 {
1224    FILE *fp;
1225
1226    struct re_filterfile_spec *new_bl, *bl = NULL;
1227    struct file_list *fs;
1228
1229    char  buf[BUFFER_SIZE];
1230    int error;
1231    unsigned long linenum = 0;
1232    pcrs_job *dummy;
1233
1234    /*
1235     * No need to reload if unchanged
1236     */
1237    if (!check_file_changed(current_re_filterfile, csp->config->re_filterfile, &fs))
1238    {
1239       if (csp)
1240       {
1241          csp->rlist = current_re_filterfile;
1242       }
1243       return(0);
1244    }
1245    if (!fs)
1246    {
1247       goto load_re_filterfile_error;
1248    }
1249
1250    /* 
1251     * Open the file or fail
1252     */
1253    if ((fp = fopen(csp->config->re_filterfile, "r")) == NULL)
1254    {
1255       goto load_re_filterfile_error;
1256    }
1257
1258    /* 
1259     * Read line by line
1260     */
1261    while (read_config_line(buf, sizeof(buf), fp, &linenum) != NULL)
1262    {
1263       /*
1264        * If this is the head of a new filter block, make it a
1265        * re_filterfile spec of its own and chain it to the list:
1266        */
1267       if (strncmp(buf, "FILTER:", 7) == 0)
1268       {
1269          new_bl = (struct re_filterfile_spec  *)zalloc(sizeof(*bl));
1270          if (new_bl == NULL)
1271          {
1272             goto load_re_filterfile_error;
1273          }
1274
1275          new_bl->name = chomp(buf + 7);
1276
1277          if (NULL != (new_bl->description = strchr(new_bl->name, ' ')))
1278          {
1279             *new_bl->description++ = '\0';
1280             new_bl->description = strdup(chomp(new_bl->description));
1281          }
1282          else
1283          {
1284             new_bl->description = strdup("No description available for this filter");
1285          }
1286
1287          new_bl->name = strdup(chomp(new_bl->name));
1288          
1289          /*
1290           * If this is the first filter block, chain it
1291           * to the file_list rather than its (nonexistant)
1292           * predecessor
1293           */
1294          if (fs->f == NULL)
1295          {
1296             fs->f = new_bl;
1297          }
1298          else
1299          {
1300             bl->next = new_bl;
1301          }
1302          bl = new_bl;
1303
1304          log_error(LOG_LEVEL_RE_FILTER, "Reading in filter \"%s\" (\"%s\")", bl->name, bl->description);
1305
1306          continue;
1307       }
1308
1309       /* 
1310        * Else, save the expression, make it a pcrs_job
1311        * and chain it into the current filter's joblist 
1312        */
1313       if (bl != NULL)
1314       {
1315          enlist(bl->patterns, buf);
1316
1317          if ((dummy = pcrs_compile_command(buf, &error)) == NULL)
1318          {
1319             log_error(LOG_LEVEL_RE_FILTER,
1320                       "Adding re_filter job %s to filter %s failed with error %d.", buf, bl->name, error);
1321             continue;
1322          }
1323          else
1324          {
1325             dummy->next = bl->joblist;
1326             bl->joblist = dummy;
1327             log_error(LOG_LEVEL_RE_FILTER, "Adding re_filter job %s to filter %s succeeded.", buf, bl->name);
1328          }
1329       }
1330       else
1331       {
1332          log_error(LOG_LEVEL_ERROR, "Ignoring job %s outside filter block in %s, line %d", buf, csp->config->re_filterfile, linenum);
1333       }
1334    }
1335
1336    fclose(fp);
1337
1338    /* 
1339     * Schedule the now-obsolete old data for unloading
1340     */
1341    if ( NULL != current_re_filterfile )
1342    {
1343       current_re_filterfile->unloader = unload_re_filterfile;
1344    }
1345
1346    /*
1347     * Chain this file into the global list of loaded files
1348     */
1349    fs->next    = files->next;
1350    files->next = fs;
1351    current_re_filterfile = fs;
1352
1353    if (csp)
1354    {
1355       csp->rlist = fs;
1356    }
1357
1358    return( 0 );
1359
1360 load_re_filterfile_error:
1361    log_error(LOG_LEVEL_FATAL, "can't load re_filterfile '%s': %E",
1362              csp->config->re_filterfile);
1363    return(-1);
1364
1365 }
1366
1367
1368 /*********************************************************************
1369  *
1370  * Function    :  add_loader
1371  *
1372  * Description :  Called from `load_config'.  Called once for each input
1373  *                file found in config.
1374  *
1375  * Parameters  :
1376  *          1  :  loader = pointer to a function that can parse and load
1377  *                the appropriate config file.
1378  *          2  :  config = The configuration_spec to add the loader to.
1379  *
1380  * Returns     :  N/A
1381  *
1382  *********************************************************************/
1383 void add_loader(int (*loader)(struct client_state *),
1384                 struct configuration_spec * config)
1385 {
1386    int i;
1387
1388    for (i=0; i < NLOADERS; i++)
1389    {
1390       if (config->loaders[i] == NULL)
1391       {
1392          config->loaders[i] = loader;
1393          break;
1394       }
1395    }
1396
1397 }
1398
1399
1400 /*********************************************************************
1401  *
1402  * Function    :  run_loader
1403  *
1404  * Description :  Called from `load_config' and `listen_loop'.  This
1405  *                function keeps the "csp" current with any file mods
1406  *                since the last loop.  If a file is unchanged, the
1407  *                loader functions do NOT reload the file.
1408  *
1409  * Parameters  :
1410  *          1  :  csp = Current client state (buffers, headers, etc...)
1411  *                      Must be non-null.  Reads: "csp->config"
1412  *                      Writes: various data members.
1413  *
1414  * Returns     :  0 => Ok, everything else is an error.
1415  *
1416  *********************************************************************/
1417 int run_loader(struct client_state *csp)
1418 {
1419    int ret = 0;
1420    int i;
1421
1422    for (i=0; i < NLOADERS; i++)
1423    {
1424       if (csp->config->loaders[i] == NULL)
1425       {
1426          break;
1427       }
1428       ret |= (csp->config->loaders[i])(csp);
1429    }
1430    return(ret);
1431
1432 }
1433
1434
1435 /*
1436   Local Variables:
1437   tab-width: 3
1438   end:
1439 */