adactio.com blocked by ad* filter & I dont' see any ads on the site.
[privoxy.git] / loaders.c
1 const char loaders_rcs[] = "$Id: loaders.c,v 1.73 2009/05/16 13:27:20 fabiankeil Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/loaders.c,v $
5  *
6  * Purpose     :  Functions to load and unload the various
7  *                configuration files.  Also contains code to manage
8  *                the list of active loaders, and to automatically
9  *                unload files that are no longer in use.
10  *
11  * Copyright   :  Written by and Copyright (C) 2001-2009 the
12  *                Privoxy team. http://www.privoxy.org/
13  *
14  *                Based on the Internet Junkbuster originally written
15  *                by and Copyright (C) 1997 Anonymous Coders and
16  *                Junkbusters Corporation.  http://www.junkbusters.com
17  *
18  *                This program is free software; you can redistribute it
19  *                and/or modify it under the terms of the GNU General
20  *                Public License as published by the Free Software
21  *                Foundation; either version 2 of the License, or (at
22  *                your option) any later version.
23  *
24  *                This program is distributed in the hope that it will
25  *                be useful, but WITHOUT ANY WARRANTY; without even the
26  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
27  *                PARTICULAR PURPOSE.  See the GNU General Public
28  *                License for more details.
29  *
30  *                The GNU General Public License should be included with
31  *                this file.  If not, you can view it at
32  *                http://www.gnu.org/copyleft/gpl.html
33  *                or write to the Free Software Foundation, Inc., 59
34  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
35  *
36  *********************************************************************/
37
38
39 #include "config.h"
40
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <sys/types.h>
44 #include <string.h>
45 #include <errno.h>
46 #include <sys/stat.h>
47 #include <ctype.h>
48 #include <assert.h>
49
50 #if !defined(_WIN32) && !defined(__OS2__)
51 #include <unistd.h>
52 #endif
53
54 #include "project.h"
55 #include "list.h"
56 #include "loaders.h"
57 #include "filters.h"
58 #include "parsers.h"
59 #include "jcc.h"
60 #include "miscutil.h"
61 #include "errlog.h"
62 #include "actions.h"
63 #include "urlmatch.h"
64 #include "encode.h"
65
66 const char loaders_h_rcs[] = LOADERS_H_VERSION;
67
68 /*
69  * Currently active files.
70  * These are also entered in the main linked list of files.
71  */
72
73 #ifdef FEATURE_TRUST
74 static struct file_list *current_trustfile      = NULL;
75 #endif /* def FEATURE_TRUST */
76
77 static int load_one_re_filterfile(struct client_state *csp, int fileid);
78
79 static struct file_list *current_re_filterfile[MAX_AF_FILES]  = {
80    NULL, NULL, NULL, NULL, NULL,
81    NULL, NULL, NULL, NULL, NULL
82 };
83
84 /*
85  * Pseudo filter type for load_one_re_filterfile
86  */
87 #define NO_NEW_FILTER -1
88
89
90 /*********************************************************************
91  *
92  * Function    :  sweep
93  *
94  * Description :  Basically a mark and sweep garbage collector, it is run
95  *                (by the parent thread) every once in a while to reclaim memory.
96  *
97  * It uses a mark and sweep strategy:
98  *   1) mark all files as inactive
99  *
100  *   2) check with each client:
101  *       if it is active,   mark its files as active
102  *       if it is inactive, free its resources
103  *
104  *   3) free the resources of all of the files that
105  *      are still marked as inactive (and are obsolete).
106  *
107  *   N.B. files that are not obsolete don't have an unloader defined.
108  *
109  * Parameters  :  None
110  *
111  * Returns     :  The number of threads that are still active.
112  *
113  *********************************************************************/
114 unsigned int sweep(void)
115 {
116    struct file_list *fl, *nfl;
117    struct client_state *csp, *last_active;
118    int i;
119    unsigned int active_threads = 0;
120
121    /* clear all of the file's active flags */
122    for ( fl = files->next; NULL != fl; fl = fl->next )
123    {
124       fl->active = 0;
125    }
126
127    last_active = clients;
128    csp = clients->next;
129
130    while (NULL != csp)
131    {
132       if (csp->flags & CSP_FLAG_ACTIVE)
133       {
134          /* Mark this client's files as active */
135
136          /*
137           * Always have a configuration file.
138           * (Also note the slightly non-standard extra
139           * indirection here.)
140           */
141          csp->config->config_file_list->active = 1;
142
143          /* 
144           * Actions files
145           */
146          for (i = 0; i < MAX_AF_FILES; i++)
147          {
148             if (csp->actions_list[i])     
149             {
150                csp->actions_list[i]->active = 1;
151             }
152          }
153
154          /*
155           * Filter files
156           */
157          for (i = 0; i < MAX_AF_FILES; i++)
158          {
159             if (csp->rlist[i])     
160             {
161                csp->rlist[i]->active = 1;
162             }
163          }
164
165          /*
166           * Trust file
167           */
168 #ifdef FEATURE_TRUST
169          if (csp->tlist)
170          {
171             csp->tlist->active = 1;
172          }
173 #endif /* def FEATURE_TRUST */
174
175          active_threads++;
176
177          last_active = csp;
178          csp = csp->next;
179       }
180       else 
181       /*
182        * This client is not active. Free its resources.
183        */
184       {
185          last_active->next = csp->next;
186
187          freez(csp->ip_addr_str);
188          freez(csp->iob->buf);
189          freez(csp->error_message);
190
191          if (csp->action->flags & ACTION_FORWARD_OVERRIDE &&
192              NULL != csp->fwd)
193          {
194             unload_forward_spec(csp->fwd);
195          }
196          free_http_request(csp->http);
197
198          destroy_list(csp->headers);
199          destroy_list(csp->tags);
200
201          free_current_action(csp->action);
202
203 #ifdef FEATURE_STATISTICS
204          urls_read++;
205          if (csp->flags & CSP_FLAG_REJECTED)
206          {
207             urls_rejected++;
208          }
209 #endif /* def FEATURE_STATISTICS */
210
211          freez(csp);
212          
213          csp = last_active->next;
214       }
215    }
216
217    nfl = files;
218    fl = files->next;
219
220    while (fl != NULL)
221    {
222       if ( ( 0 == fl->active ) && ( NULL != fl->unloader ) )
223       {
224          nfl->next = fl->next;
225
226          (fl->unloader)(fl->f);
227
228          freez(fl->filename);
229          freez(fl);
230
231          fl = nfl->next;
232       }
233       else
234       {
235          nfl = fl;
236          fl = fl->next;
237       }
238    }
239
240    return active_threads;
241
242 }
243
244
245 /*********************************************************************
246  *
247  * Function    :  check_file_changed
248  *
249  * Description :  Helper function to check if a file needs reloading.
250  *                If "current" is still current, return it.  Otherwise
251  *                allocates a new (zeroed) "struct file_list", fills
252  *                in the disk file name and timestamp, and returns it.
253  *
254  * Parameters  :
255  *          1  :  current = The file_list currently being used - will
256  *                          be checked to see if it is out of date.
257  *                          May be NULL (which is treated as out of
258  *                          date).
259  *          2  :  filename = Name of file to check.
260  *          3  :  newfl    = New file list. [Output only]
261  *                           This will be set to NULL, OR a struct
262  *                           file_list newly allocated on the
263  *                           heap, with the filename and lastmodified
264  *                           fields filled, and all others zeroed.
265  *
266  * Returns     :  If file unchanged: 0 (and sets newfl == NULL)
267  *                If file changed: 1 and sets newfl != NULL
268  *                On error: 1 and sets newfl == NULL
269  *
270  *********************************************************************/
271 int check_file_changed(const struct file_list * current,
272                        const char * filename,
273                        struct file_list ** newfl)
274 {
275    struct file_list *fs;
276    struct stat statbuf[1];
277
278    *newfl = NULL;
279
280    if (stat(filename, statbuf) < 0)
281    {
282       /* Error, probably file not found. */
283       return 1;
284    }
285
286    if (current
287        && (current->lastmodified == statbuf->st_mtime)
288        && (0 == strcmp(current->filename, filename)))
289    {
290       return 0;
291    }
292
293    fs = (struct file_list *)zalloc(sizeof(struct file_list));
294    if (fs == NULL)
295    {
296       /* Out of memory error */
297       return 1;
298    }
299
300
301    fs->filename = strdup(filename);
302    fs->lastmodified = statbuf->st_mtime;
303
304    if (fs->filename == NULL)
305    {
306       /* Out of memory error */
307       freez (fs);
308       return 1;
309    }
310    *newfl = fs;
311    return 1;
312 }
313
314
315 /*********************************************************************
316  *
317  * Function    :  simple_read_line
318  *
319  * Description :  Read a single line from a file and return it.
320  *                This is basically a version of fgets() that malloc()s
321  *                it's own line buffer.  Note that the buffer will
322  *                always be a multiple of BUFFER_SIZE bytes long.
323  *                Therefore if you are going to keep the string for
324  *                an extended period of time, you should probably
325  *                strdup() it and free() the original, to save memory.
326  *
327  *
328  * Parameters  :
329  *          1  :  dest = destination for newly malloc'd pointer to
330  *                line data.  Will be set to NULL on error.
331  *          2  :  fp = File to read from
332  *          3  :  newline = Standard for newlines in the file.
333  *                Will be unchanged if it's value on input is not
334  *                NEWLINE_UNKNOWN.
335  *                On output, may be changed from NEWLINE_UNKNOWN to
336  *                actual convention in file.
337  *
338  * Returns     :  JB_ERR_OK     on success
339  *                JB_ERR_MEMORY on out-of-memory
340  *                JB_ERR_FILE   on EOF.
341  *
342  *********************************************************************/
343 jb_err simple_read_line(FILE *fp, char **dest, int *newline)
344 {
345    size_t len = 0;
346    size_t buflen = BUFFER_SIZE;
347    char * buf;
348    char * p;
349    int ch;
350    int realnewline = NEWLINE_UNKNOWN;
351
352    if (NULL == (buf = malloc(buflen)))
353    {
354       return JB_ERR_MEMORY;
355    }
356
357    p = buf;
358
359 /*
360  * Character codes.  If you have a wierd compiler and the following are
361  * incorrect, you also need to fix NEWLINE() in loaders.h
362  */
363 #define CHAR_CR '\r' /* ASCII 13 */
364 #define CHAR_LF '\n' /* ASCII 10 */
365
366    for (;;)
367    {
368       ch = getc(fp);
369       if (ch == EOF)
370       {
371          if (len > 0)
372          {
373             *p = '\0';
374             *dest = buf;
375             return JB_ERR_OK;
376          }
377          else
378          {
379             free(buf);
380             *dest = NULL;
381             return JB_ERR_FILE;
382          }
383       }
384       else if (ch == CHAR_CR)
385       {
386          ch = getc(fp);
387          if (ch == CHAR_LF)
388          {
389             if (*newline == NEWLINE_UNKNOWN)
390             {
391                *newline = NEWLINE_DOS;
392             }
393          }
394          else
395          {
396             if (ch != EOF)
397             {
398                ungetc(ch, fp);
399             }
400             if (*newline == NEWLINE_UNKNOWN)
401             {
402                *newline = NEWLINE_MAC;
403             }
404          }
405          *p = '\0';
406          *dest = buf;
407          if (*newline == NEWLINE_UNKNOWN)
408          {
409             *newline = realnewline;
410          }
411          return JB_ERR_OK;
412       }
413       else if (ch == CHAR_LF)
414       {
415          *p = '\0';
416          *dest = buf;
417          if (*newline == NEWLINE_UNKNOWN)
418          {
419             *newline = NEWLINE_UNIX;
420          }
421          return JB_ERR_OK;
422       }
423       else if (ch == 0)
424       {
425          *p = '\0';
426          *dest = buf;
427          return JB_ERR_OK;
428       }
429
430       *p++ = (char)ch;
431
432       if (++len >= buflen)
433       {
434          buflen += BUFFER_SIZE;
435          if (NULL == (p = realloc(buf, buflen)))
436          {
437             free(buf);
438             return JB_ERR_MEMORY;
439          }
440          buf = p;
441          p = buf + len;
442       }
443    }
444 }
445
446
447 /*********************************************************************
448  *
449  * Function    :  edit_read_line
450  *
451  * Description :  Read a single non-empty line from a file and return
452  *                it.  Trims comments, leading and trailing whitespace
453  *                and respects escaping of newline and comment char.
454  *                Provides the line in 2 alternative forms: raw and
455  *                preprocessed.
456  *                - raw is the raw data read from the file.  If the
457  *                  line is not modified, then this should be written
458  *                  to the new file.
459  *                - prefix is any comments and blank lines that were
460  *                  read from the file.  If the line is modified, then
461  *                  this should be written out to the file followed
462  *                  by the modified data.  (If this string is non-empty
463  *                  then it will have a newline at the end).
464  *                - data is the actual data that will be parsed
465  *                  further by appropriate routines.
466  *                On EOF, the 3 strings will all be set to NULL and
467  *                0 will be returned.
468  *
469  * Parameters  :
470  *          1  :  fp = File to read from
471  *          2  :  raw_out = destination for newly malloc'd pointer to
472  *                raw line data.  May be NULL if you don't want it.
473  *          3  :  prefix_out = destination for newly malloc'd pointer to
474  *                comments.  May be NULL if you don't want it.
475  *          4  :  data_out = destination for newly malloc'd pointer to
476  *                line data with comments and leading/trailing spaces
477  *                removed, and line continuation performed.  May be
478  *                NULL if you don't want it.
479  *          5  :  newline = Standard for newlines in the file.
480  *                On input, set to value to use or NEWLINE_UNKNOWN.
481  *                On output, may be changed from NEWLINE_UNKNOWN to
482  *                actual convention in file.  May be NULL if you
483  *                don't want it.
484  *          6  :  line_number = Line number in file.  In "lines" as
485  *                reported by a text editor, not lines containing data.
486  *
487  * Returns     :  JB_ERR_OK     on success
488  *                JB_ERR_MEMORY on out-of-memory
489  *                JB_ERR_FILE   on EOF.
490  *
491  *********************************************************************/
492 jb_err edit_read_line(FILE *fp,
493                       char **raw_out,
494                       char **prefix_out,
495                       char **data_out,
496                       int *newline,
497                       unsigned long *line_number)
498 {
499    char *p;          /* Temporary pointer   */
500    char *linebuf;    /* Line read from file */
501    char *linestart;  /* Start of linebuf, usually first non-whitespace char */
502    int contflag = 0; /* Nonzero for line continuation - i.e. line ends '\' */
503    int is_empty = 1; /* Flag if not got any data yet */
504    char *raw    = NULL; /* String to be stored in raw_out    */
505    char *prefix = NULL; /* String to be stored in prefix_out */
506    char *data   = NULL; /* String to be stored in data_out   */
507    int scrapnewline;    /* Used for (*newline) if newline==NULL */
508    jb_err rval = JB_ERR_OK;
509
510    assert(fp);
511    assert(raw_out || data_out);
512    assert(newline == NULL
513        || *newline == NEWLINE_UNKNOWN
514        || *newline == NEWLINE_UNIX
515        || *newline == NEWLINE_DOS
516        || *newline == NEWLINE_MAC);
517
518    if (newline == NULL)
519    {
520       scrapnewline = NEWLINE_UNKNOWN;
521       newline = &scrapnewline;
522    }
523
524    /* Set output parameters to NULL */
525    if (raw_out)
526    {
527       *raw_out    = NULL;
528    }
529    if (prefix_out)
530    {
531       *prefix_out = NULL;
532    }
533    if (data_out)
534    {
535       *data_out   = NULL;
536    }
537
538    /* Set string variables to new, empty strings. */
539
540    if (raw_out)
541    {
542       raw = strdup("");
543       if (NULL == raw)
544       {
545          return JB_ERR_MEMORY;
546       }
547    }
548    if (prefix_out)
549    {
550       prefix = strdup("");
551       if (NULL == prefix)
552       {
553          freez(raw);
554          return JB_ERR_MEMORY;
555       }
556    }
557    if (data_out)
558    {
559       data = strdup("");
560       if (NULL == data)
561       {
562          freez(raw);
563          freez(prefix);
564          return JB_ERR_MEMORY;
565       }
566    }
567
568    /* Main loop.  Loop while we need more data & it's not EOF. */
569
570    while ( (contflag || is_empty)
571         && (JB_ERR_OK == (rval = simple_read_line(fp, &linebuf, newline))))
572    {
573       if (line_number)
574       {
575          (*line_number)++;
576       }
577       if (raw)
578       {
579          string_append(&raw,linebuf);
580          if (string_append(&raw,NEWLINE(*newline)))
581          {
582             freez(prefix);
583             freez(data);
584             free(linebuf);
585             return JB_ERR_MEMORY;
586          }
587       }
588
589       /* Line continuation? Trim escape and set flag. */
590       p = linebuf + strlen(linebuf) - 1;
591       contflag = ((*linebuf != '\0') && (*p == '\\'));
592       if (contflag)
593       {
594          *p = '\0';
595       }
596
597       /* Trim leading spaces if we're at the start of the line */
598       linestart = linebuf;
599       assert(NULL != data);
600       if (*data == '\0')
601       {
602          /* Trim leading spaces */
603          while (*linestart && isspace((int)(unsigned char)*linestart))
604          {
605             linestart++;
606          }
607       }
608
609       /* Handle comment characters. */
610       p = linestart;
611       while ((p = strchr(p, '#')) != NULL)
612       {
613          /* Found a comment char.. */
614          if ((p != linebuf) && (*(p-1) == '\\'))
615          {
616             /* ..and it's escaped, left-shift the line over the escape. */
617             char *q = p - 1;
618             while ((*q = *(q + 1)) != '\0')
619             {
620                q++;
621             }
622             /* Now scan from just after the "#". */
623          }
624          else
625          {
626             /* Real comment.  Save it... */
627             if (p == linestart)
628             {
629                /* Special case:  Line only contains a comment, so all the
630                 * previous whitespace is considered part of the comment.
631                 * Undo the whitespace skipping, if any.
632                 */
633                linestart = linebuf;
634                p = linestart;
635             }
636             if (prefix)
637             {
638                string_append(&prefix,p);
639                if (string_append(&prefix, NEWLINE(*newline)))
640                {
641                   freez(raw);
642                   freez(data);
643                   free(linebuf);
644                   return JB_ERR_MEMORY;
645                }
646             }
647
648             /* ... and chop off the rest of the line */
649             *p = '\0';
650          }
651       } /* END while (there's a # character) */
652
653       /* Write to the buffer */
654       if (*linestart)
655       {
656          is_empty = 0;
657          if (data)
658          {
659             if (string_append(&data, linestart))
660             {
661                freez(raw);
662                freez(prefix);
663                free(linebuf);
664                return JB_ERR_MEMORY;
665             }
666          }
667       }
668
669       free(linebuf);
670    } /* END while(we need more data) */
671
672    /* Handle simple_read_line() errors - ignore EOF */
673    if ((rval != JB_ERR_OK) && (rval != JB_ERR_FILE))
674    {
675       freez(raw);
676       freez(prefix);
677       freez(data);
678       return rval;
679    }
680
681    if (raw ? (*raw == '\0') : is_empty)
682    {
683       /* EOF and no data there.  (Definition of "data" depends on whether
684        * the caller cares about "raw" or just "data").
685        */
686
687       freez(raw);
688       freez(prefix);
689       freez(data);
690
691       return JB_ERR_FILE;
692    }
693    else
694    {
695       /* Got at least some data */
696
697       /* Remove trailing whitespace */
698       chomp(data);
699
700       if (raw_out)
701       {
702          *raw_out    = raw;
703       }
704       else
705       {
706          freez(raw);
707       }
708       if (prefix_out)
709       {
710          *prefix_out = prefix;
711       }
712       else
713       {
714          freez(prefix);
715       }
716       if (data_out)
717       {
718          *data_out   = data;
719       }
720       else
721       {
722          freez(data);
723       }
724       return JB_ERR_OK;
725    }
726 }
727
728
729 /*********************************************************************
730  *
731  * Function    :  read_config_line
732  *
733  * Description :  Read a single non-empty line from a file and return
734  *                it.  Trims comments, leading and trailing whitespace
735  *                and respects escaping of newline and comment char.
736  *
737  * Parameters  :
738  *          1  :  buf = Buffer to use.
739  *          2  :  buflen = Size of buffer in bytes.
740  *          3  :  fp = File to read from
741  *          4  :  linenum = linenumber in file
742  *
743  * Returns     :  NULL on EOF or error
744  *                Otherwise, returns buf.
745  *
746  *********************************************************************/
747 char *read_config_line(char *buf, size_t buflen, FILE *fp, unsigned long *linenum)
748 {
749    jb_err err;
750    char *buf2 = NULL;
751    err = edit_read_line(fp, NULL, NULL, &buf2, NULL, linenum);
752    if (err)
753    {
754       if (err == JB_ERR_MEMORY)
755       {
756          log_error(LOG_LEVEL_FATAL, "Out of memory loading a config file");
757       }
758       return NULL;
759    }
760    else
761    {
762       assert(buf2);
763       if (strlen(buf2) + 1U > buflen)
764       {
765          log_error(LOG_LEVEL_FATAL,
766             "Max line limit reached. Linenumber: %u. Lenght: %u. Max lenght: %u.",
767             *linenum, strlen(buf2), buflen-1);
768       }
769       strlcpy(buf, buf2, buflen);
770       free(buf2);
771       return buf;
772    }
773 }
774
775
776 #ifdef FEATURE_TRUST
777 /*********************************************************************
778  *
779  * Function    :  unload_trustfile
780  *
781  * Description :  Unloads a trustfile.
782  *
783  * Parameters  :
784  *          1  :  f = the data structure associated with the trustfile.
785  *
786  * Returns     :  N/A
787  *
788  *********************************************************************/
789 static void unload_trustfile(void *f)
790 {
791    struct block_spec *cur = (struct block_spec *)f;
792    struct block_spec *next;
793
794    while (cur != NULL)
795    {
796       next = cur->next;
797
798       free_url_spec(cur->url);
799       free(cur);
800
801       cur = next;
802    }
803
804 }
805
806
807 #ifdef FEATURE_GRACEFUL_TERMINATION
808 /*********************************************************************
809  *
810  * Function    :  unload_current_trust_file
811  *
812  * Description :  Unloads current trust file - reset to state at
813  *                beginning of program.
814  *
815  * Parameters  :  None
816  *
817  * Returns     :  N/A
818  *
819  *********************************************************************/
820 void unload_current_trust_file(void)
821 {
822    if (current_trustfile)
823    {
824       current_trustfile->unloader = unload_trustfile;
825       current_trustfile = NULL;
826    }
827 }
828 #endif /* FEATURE_GRACEFUL_TERMINATION */
829
830
831 /*********************************************************************
832  *
833  * Function    :  load_trustfile
834  *
835  * Description :  Read and parse a trustfile and add to files list.
836  *
837  * Parameters  :
838  *          1  :  csp = Current client state (buffers, headers, etc...)
839  *
840  * Returns     :  0 => Ok, everything else is an error.
841  *
842  *********************************************************************/
843 int load_trustfile(struct client_state *csp)
844 {
845    FILE *fp;
846
847    struct block_spec *b, *bl;
848    struct url_spec **tl;
849
850    char  buf[BUFFER_SIZE], *p, *q;
851    int reject, trusted;
852    struct file_list *fs;
853    unsigned long linenum = 0;
854    int trusted_referrers = 0;
855
856    if (!check_file_changed(current_trustfile, csp->config->trustfile, &fs))
857    {
858       /* No need to load */
859       if (csp)
860       {
861          csp->tlist = current_trustfile;
862       }
863       return(0);
864    }
865    if (!fs)
866    {
867       goto load_trustfile_error;
868    }
869
870    fs->f = bl = (struct block_spec *)zalloc(sizeof(*bl));
871    if (bl == NULL)
872    {
873       goto load_trustfile_error;
874    }
875
876    if ((fp = fopen(csp->config->trustfile, "r")) == NULL)
877    {
878       goto load_trustfile_error;
879    }
880
881    tl = csp->config->trust_list;
882
883    while (read_config_line(buf, sizeof(buf), fp, &linenum) != NULL)
884    {
885       trusted = 0;
886       reject  = 1;
887
888       if (*buf == '+')
889       {
890          trusted = 1;
891          *buf = '~';
892       }
893
894       if (*buf == '~')
895       {
896          reject = 0;
897          p = buf;
898          q = p+1;
899          while ((*p++ = *q++) != '\0')
900          {
901             /* nop */
902          }
903       }
904
905       /* skip blank lines */
906       if (*buf == '\0')
907       {
908          continue;
909       }
910
911       /* allocate a new node */
912       if ((b = zalloc(sizeof(*b))) == NULL)
913       {
914          fclose(fp);
915          goto load_trustfile_error;
916       }
917
918       /* add it to the list */
919       b->next  = bl->next;
920       bl->next = b;
921
922       b->reject = reject;
923
924       /* Save the URL pattern */
925       if (create_url_spec(b->url, buf))
926       {
927          fclose(fp);
928          goto load_trustfile_error;
929       }
930
931       /*
932        * save a pointer to URL's spec in the list of trusted URL's, too
933        */
934       if (trusted)
935       {
936          if(++trusted_referrers < MAX_TRUSTED_REFERRERS)
937          {
938             *tl++ = b->url;
939          }
940       }
941    }
942
943    if(trusted_referrers >= MAX_TRUSTED_REFERRERS) 
944    {
945       /*
946        * FIXME: ... after Privoxy 3.0.4 is out.
947        */
948        log_error(LOG_LEVEL_ERROR, "Too many trusted referrers. Current limit is %d, you are using %d.\n"
949           "  Additional trusted referrers are treated like ordinary trusted URLs.\n"
950           "  (You can increase this limit by changing MAX_TRUSTED_REFERRERS in project.h and recompiling).",
951           MAX_TRUSTED_REFERRERS, trusted_referrers);
952    }
953
954    *tl = NULL;
955
956    fclose(fp);
957
958    /* the old one is now obsolete */
959    if (current_trustfile)
960    {
961       current_trustfile->unloader = unload_trustfile;
962    }
963
964    fs->next    = files->next;
965    files->next = fs;
966    current_trustfile = fs;
967
968    if (csp)
969    {
970       csp->tlist = fs;
971    }
972
973    return(0);
974
975 load_trustfile_error:
976    log_error(LOG_LEVEL_FATAL, "can't load trustfile '%s': %E",
977              csp->config->trustfile);
978    return(-1);
979
980 }
981 #endif /* def FEATURE_TRUST */
982
983
984 /*********************************************************************
985  *
986  * Function    :  unload_re_filterfile
987  *
988  * Description :  Unload the re_filter list by freeing all chained
989  *                re_filterfile specs and their data.
990  *
991  * Parameters  :
992  *          1  :  f = the data structure associated with the filterfile.
993  *
994  * Returns     :  N/A
995  *
996  *********************************************************************/
997 static void unload_re_filterfile(void *f)
998 {
999    struct re_filterfile_spec *a, *b = (struct re_filterfile_spec *)f;
1000
1001    while (b != NULL)
1002    {
1003       a = b->next;
1004
1005       destroy_list(b->patterns);
1006       pcrs_free_joblist(b->joblist);
1007       freez(b->name);
1008       freez(b->description);
1009       freez(b);
1010
1011       b = a;
1012    }
1013
1014    return;
1015 }
1016
1017 /*********************************************************************
1018  *
1019  * Function    :  unload_forward_spec
1020  *
1021  * Description :  Unload the forward spec settings by freeing all 
1022  *                memory referenced by members and the memory for
1023  *                the spec itself.
1024  *
1025  * Parameters  :
1026  *          1  :  fwd = the forward spec.
1027  *
1028  * Returns     :  N/A
1029  *
1030  *********************************************************************/
1031 void unload_forward_spec(struct forward_spec *fwd)
1032 {
1033    free_url_spec(fwd->url);
1034    freez(fwd->gateway_host);
1035    freez(fwd->forward_host);
1036    free(fwd);
1037
1038    return;
1039 }
1040
1041
1042 #ifdef FEATURE_GRACEFUL_TERMINATION
1043 /*********************************************************************
1044  *
1045  * Function    :  unload_current_re_filterfile
1046  *
1047  * Description :  Unloads current re_filter file - reset to state at
1048  *                beginning of program.
1049  *
1050  * Parameters  :  None
1051  *
1052  * Returns     :  N/A
1053  *
1054  *********************************************************************/
1055 void unload_current_re_filterfile(void)
1056 {
1057    int i;
1058
1059    for (i = 0; i < MAX_AF_FILES; i++)
1060    {
1061       if (current_re_filterfile[i])
1062       {
1063          current_re_filterfile[i]->unloader = unload_re_filterfile;
1064          current_re_filterfile[i] = NULL;
1065       }
1066    }
1067 }
1068 #endif
1069
1070
1071 /*********************************************************************
1072  *
1073  * Function    :  load_re_filterfiles
1074  *
1075  * Description :  Loads all the filterfiles. 
1076  *                Generate a chained list of re_filterfile_spec's from
1077  *                the "FILTER: " blocks, compiling all their substitutions
1078  *                into chained lists of pcrs_job structs.
1079  *
1080  * Parameters  :
1081  *          1  :  csp = Current client state (buffers, headers, etc...)
1082  *
1083  * Returns     :  0 => Ok, everything else is an error.
1084  *
1085  *********************************************************************/
1086 int load_re_filterfiles(struct client_state *csp)
1087 {
1088    int i;
1089    int result;
1090
1091    for (i = 0; i < MAX_AF_FILES; i++)
1092    {
1093       if (csp->config->re_filterfile[i])
1094       {
1095          result = load_one_re_filterfile(csp, i);
1096          if (result)
1097          {
1098             return result;
1099          }
1100       }
1101       else if (current_re_filterfile[i])
1102       {
1103          current_re_filterfile[i]->unloader = unload_re_filterfile;
1104          current_re_filterfile[i] = NULL;
1105       }
1106    }
1107
1108    return 0;
1109 }
1110
1111
1112 /*********************************************************************
1113  *
1114  * Function    :  load_one_re_filterfile
1115  *
1116  * Description :  Load a re_filterfile. 
1117  *                Generate a chained list of re_filterfile_spec's from
1118  *                the "FILTER: " blocks, compiling all their substitutions
1119  *                into chained lists of pcrs_job structs.
1120  *
1121  * Parameters  :
1122  *          1  :  csp = Current client state (buffers, headers, etc...)
1123  *
1124  * Returns     :  0 => Ok, everything else is an error.
1125  *
1126  *********************************************************************/
1127 int load_one_re_filterfile(struct client_state *csp, int fileid)
1128 {
1129    FILE *fp;
1130
1131    struct re_filterfile_spec *new_bl, *bl = NULL;
1132    struct file_list *fs;
1133
1134    char  buf[BUFFER_SIZE];
1135    int error;
1136    unsigned long linenum = 0;
1137    pcrs_job *dummy, *lastjob = NULL;
1138
1139    /*
1140     * No need to reload if unchanged
1141     */
1142    if (!check_file_changed(current_re_filterfile[fileid], csp->config->re_filterfile[fileid], &fs))
1143    {
1144       if (csp)
1145       {
1146          csp->rlist[fileid] = current_re_filterfile[fileid];
1147       }
1148       return(0);
1149    }
1150    if (!fs)
1151    {
1152       goto load_re_filterfile_error;
1153    }
1154
1155    /* 
1156     * Open the file or fail
1157     */
1158    if ((fp = fopen(csp->config->re_filterfile[fileid], "r")) == NULL)
1159    {
1160       goto load_re_filterfile_error;
1161    }
1162
1163    /* 
1164     * Read line by line
1165     */
1166    while (read_config_line(buf, sizeof(buf), fp, &linenum) != NULL)
1167    {
1168       int new_filter = NO_NEW_FILTER;
1169
1170       if (strncmp(buf, "FILTER:", 7) == 0)
1171       {
1172          new_filter = FT_CONTENT_FILTER;
1173       }
1174       else if (strncmp(buf, "SERVER-HEADER-FILTER:", 21) == 0)
1175       {
1176          new_filter = FT_SERVER_HEADER_FILTER;
1177       }
1178       else if (strncmp(buf, "CLIENT-HEADER-FILTER:", 21) == 0)
1179       {
1180          new_filter = FT_CLIENT_HEADER_FILTER;
1181       }
1182       else if (strncmp(buf, "CLIENT-HEADER-TAGGER:", 21) == 0)
1183       {
1184          new_filter = FT_CLIENT_HEADER_TAGGER;
1185       }
1186       else if (strncmp(buf, "SERVER-HEADER-TAGGER:", 21) == 0)
1187       {
1188          new_filter = FT_SERVER_HEADER_TAGGER;
1189       }
1190
1191       /*
1192        * If this is the head of a new filter block, make it a
1193        * re_filterfile spec of its own and chain it to the list:
1194        */
1195       if (new_filter != NO_NEW_FILTER)
1196       {
1197          new_bl = (struct re_filterfile_spec  *)zalloc(sizeof(*bl));
1198          if (new_bl == NULL)
1199          {
1200             goto load_re_filterfile_error;
1201          }
1202          if (new_filter == FT_CONTENT_FILTER)
1203          {
1204             new_bl->name = chomp(buf + 7);
1205          }
1206          else
1207          {
1208             new_bl->name = chomp(buf + 21);
1209          }
1210          new_bl->type = new_filter;
1211
1212          /*
1213           * If a filter description is available,
1214           * encode it to HTML and save it.
1215           */
1216          if (NULL != (new_bl->description = strpbrk(new_bl->name, " \t")))
1217          {
1218             *new_bl->description++ = '\0';
1219             new_bl->description = html_encode(chomp(new_bl->description));
1220             if (NULL == new_bl->description)
1221             {
1222                new_bl->description = strdup("Out of memory while encoding this filter's description to HTML");
1223             }
1224          }
1225          else
1226          {
1227             new_bl->description = strdup("No description available for this filter");
1228          }
1229
1230          new_bl->name = strdup(chomp(new_bl->name));
1231          
1232          /*
1233           * If this is the first filter block, chain it
1234           * to the file_list rather than its (nonexistant)
1235           * predecessor
1236           */
1237          if (fs->f == NULL)
1238          {
1239             fs->f = new_bl;
1240          }
1241          else
1242          {
1243             assert(NULL != bl);
1244             bl->next = new_bl;
1245          }
1246          bl = new_bl;
1247
1248          log_error(LOG_LEVEL_RE_FILTER, "Reading in filter \"%s\" (\"%s\")", bl->name, bl->description);
1249
1250          continue;
1251       }
1252
1253       /* 
1254        * Else, save the expression, make it a pcrs_job
1255        * and chain it into the current filter's joblist 
1256        */
1257       if (bl != NULL)
1258       {
1259          error = enlist(bl->patterns, buf);
1260          if (JB_ERR_MEMORY == error)
1261          {
1262             log_error(LOG_LEVEL_FATAL,
1263                "Out of memory while enlisting re_filter job \'%s\' for filter %s.", buf, bl->name);
1264          }
1265          assert(JB_ERR_OK == error);
1266
1267          if (pcrs_job_is_dynamic(buf))
1268          {
1269             /*
1270              * Dynamic pattern that might contain variables
1271              * and has to be recompiled for every request
1272              */
1273             if (bl->joblist != NULL)
1274             {
1275                 pcrs_free_joblist(bl->joblist);
1276                 bl->joblist = NULL;
1277             }
1278             bl->dynamic = 1;
1279             log_error(LOG_LEVEL_RE_FILTER,
1280                "Adding dynamic re_filter job \'%s\' to filter %s succeeded.", buf, bl->name);
1281             continue;             
1282          }
1283          else if (bl->dynamic)
1284          {
1285             /*
1286              * A previous job was dynamic and as we
1287              * recompile the whole filter anyway, it
1288              * makes no sense to compile this job now.
1289              */
1290             log_error(LOG_LEVEL_RE_FILTER,
1291                "Adding static re_filter job \'%s\' to dynamic filter %s succeeded.", buf, bl->name);
1292             continue;
1293          }
1294
1295          if ((dummy = pcrs_compile_command(buf, &error)) == NULL)
1296          {
1297             log_error(LOG_LEVEL_ERROR,
1298                "Adding re_filter job \'%s\' to filter %s failed with error %d.", buf, bl->name, error);
1299             continue;
1300          }
1301          else
1302          {
1303             if (bl->joblist == NULL)
1304             {
1305                bl->joblist = dummy;
1306             }
1307             else if (NULL != lastjob)
1308             {
1309                lastjob->next = dummy;
1310             }
1311             lastjob = dummy;
1312             log_error(LOG_LEVEL_RE_FILTER, "Adding re_filter job \'%s\' to filter %s succeeded.", buf, bl->name);
1313          }
1314       }
1315       else
1316       {
1317          log_error(LOG_LEVEL_ERROR, "Ignoring job %s outside filter block in %s, line %d",
1318             buf, csp->config->re_filterfile[fileid], linenum);
1319       }
1320    }
1321
1322    fclose(fp);
1323
1324    /* 
1325     * Schedule the now-obsolete old data for unloading
1326     */
1327    if ( NULL != current_re_filterfile[fileid] )
1328    {
1329       current_re_filterfile[fileid]->unloader = unload_re_filterfile;
1330    }
1331
1332    /*
1333     * Chain this file into the global list of loaded files
1334     */
1335    fs->next    = files->next;
1336    files->next = fs;
1337    current_re_filterfile[fileid] = fs;
1338
1339    if (csp)
1340    {
1341       csp->rlist[fileid] = fs;
1342    }
1343
1344    return( 0 );
1345
1346 load_re_filterfile_error:
1347    log_error(LOG_LEVEL_FATAL, "can't load re_filterfile '%s': %E",
1348              csp->config->re_filterfile[fileid]);
1349    return(-1);
1350
1351 }
1352
1353
1354 /*********************************************************************
1355  *
1356  * Function    :  add_loader
1357  *
1358  * Description :  Called from `load_config'.  Called once for each input
1359  *                file found in config.
1360  *
1361  * Parameters  :
1362  *          1  :  loader = pointer to a function that can parse and load
1363  *                the appropriate config file.
1364  *          2  :  config = The configuration_spec to add the loader to.
1365  *
1366  * Returns     :  N/A
1367  *
1368  *********************************************************************/
1369 void add_loader(int (*loader)(struct client_state *),
1370                 struct configuration_spec * config)
1371 {
1372    int i;
1373
1374    for (i=0; i < NLOADERS; i++)
1375    {
1376       if (config->loaders[i] == NULL)
1377       {
1378          config->loaders[i] = loader;
1379          break;
1380       }
1381    }
1382
1383 }
1384
1385
1386 /*********************************************************************
1387  *
1388  * Function    :  run_loader
1389  *
1390  * Description :  Called from `load_config' and `listen_loop'.  This
1391  *                function keeps the "csp" current with any file mods
1392  *                since the last loop.  If a file is unchanged, the
1393  *                loader functions do NOT reload the file.
1394  *
1395  * Parameters  :
1396  *          1  :  csp = Current client state (buffers, headers, etc...)
1397  *                      Must be non-null.  Reads: "csp->config"
1398  *                      Writes: various data members.
1399  *
1400  * Returns     :  0 => Ok, everything else is an error.
1401  *
1402  *********************************************************************/
1403 int run_loader(struct client_state *csp)
1404 {
1405    int ret = 0;
1406    int i;
1407
1408    for (i=0; i < NLOADERS; i++)
1409    {
1410       if (csp->config->loaders[i] == NULL)
1411       {
1412          break;
1413       }
1414       ret |= (csp->config->loaders[i])(csp);
1415    }
1416    return(ret);
1417
1418 }
1419
1420
1421 /*
1422   Local Variables:
1423   tab-width: 3
1424   end:
1425 */