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