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