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