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