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