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