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