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