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