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