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