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