Remove CVS revision logs. TODO item #33.
[privoxy.git] / loaders.c
1 const char loaders_rcs[] = "$Id: loaders.c,v 1.72 2009/04/24 15:29:43 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       assert(strlen(buf2) + 1U < buflen);
764       strncpy(buf, buf2, buflen - 1);
765       free(buf2);
766       buf[buflen - 1] = '\0';
767       return buf;
768    }
769 }
770
771
772 #ifdef FEATURE_TRUST
773 /*********************************************************************
774  *
775  * Function    :  unload_trustfile
776  *
777  * Description :  Unloads a trustfile.
778  *
779  * Parameters  :
780  *          1  :  f = the data structure associated with the trustfile.
781  *
782  * Returns     :  N/A
783  *
784  *********************************************************************/
785 static void unload_trustfile(void *f)
786 {
787    struct block_spec *cur = (struct block_spec *)f;
788    struct block_spec *next;
789
790    while (cur != NULL)
791    {
792       next = cur->next;
793
794       free_url_spec(cur->url);
795       free(cur);
796
797       cur = next;
798    }
799
800 }
801
802
803 #ifdef FEATURE_GRACEFUL_TERMINATION
804 /*********************************************************************
805  *
806  * Function    :  unload_current_trust_file
807  *
808  * Description :  Unloads current trust file - reset to state at
809  *                beginning of program.
810  *
811  * Parameters  :  None
812  *
813  * Returns     :  N/A
814  *
815  *********************************************************************/
816 void unload_current_trust_file(void)
817 {
818    if (current_trustfile)
819    {
820       current_trustfile->unloader = unload_trustfile;
821       current_trustfile = NULL;
822    }
823 }
824 #endif /* FEATURE_GRACEFUL_TERMINATION */
825
826
827 /*********************************************************************
828  *
829  * Function    :  load_trustfile
830  *
831  * Description :  Read and parse a trustfile and add to files list.
832  *
833  * Parameters  :
834  *          1  :  csp = Current client state (buffers, headers, etc...)
835  *
836  * Returns     :  0 => Ok, everything else is an error.
837  *
838  *********************************************************************/
839 int load_trustfile(struct client_state *csp)
840 {
841    FILE *fp;
842
843    struct block_spec *b, *bl;
844    struct url_spec **tl;
845
846    char  buf[BUFFER_SIZE], *p, *q;
847    int reject, trusted;
848    struct file_list *fs;
849    unsigned long linenum = 0;
850    int trusted_referrers = 0;
851
852    if (!check_file_changed(current_trustfile, csp->config->trustfile, &fs))
853    {
854       /* No need to load */
855       if (csp)
856       {
857          csp->tlist = current_trustfile;
858       }
859       return(0);
860    }
861    if (!fs)
862    {
863       goto load_trustfile_error;
864    }
865
866    fs->f = bl = (struct block_spec *)zalloc(sizeof(*bl));
867    if (bl == NULL)
868    {
869       goto load_trustfile_error;
870    }
871
872    if ((fp = fopen(csp->config->trustfile, "r")) == NULL)
873    {
874       goto load_trustfile_error;
875    }
876
877    tl = csp->config->trust_list;
878
879    while (read_config_line(buf, sizeof(buf), fp, &linenum) != NULL)
880    {
881       trusted = 0;
882       reject  = 1;
883
884       if (*buf == '+')
885       {
886          trusted = 1;
887          *buf = '~';
888       }
889
890       if (*buf == '~')
891       {
892          reject = 0;
893          p = buf;
894          q = p+1;
895          while ((*p++ = *q++) != '\0')
896          {
897             /* nop */
898          }
899       }
900
901       /* skip blank lines */
902       if (*buf == '\0')
903       {
904          continue;
905       }
906
907       /* allocate a new node */
908       if ((b = zalloc(sizeof(*b))) == NULL)
909       {
910          fclose(fp);
911          goto load_trustfile_error;
912       }
913
914       /* add it to the list */
915       b->next  = bl->next;
916       bl->next = b;
917
918       b->reject = reject;
919
920       /* Save the URL pattern */
921       if (create_url_spec(b->url, buf))
922       {
923          fclose(fp);
924          goto load_trustfile_error;
925       }
926
927       /*
928        * save a pointer to URL's spec in the list of trusted URL's, too
929        */
930       if (trusted)
931       {
932          if(++trusted_referrers < MAX_TRUSTED_REFERRERS)
933          {
934             *tl++ = b->url;
935          }
936       }
937    }
938
939    if(trusted_referrers >= MAX_TRUSTED_REFERRERS) 
940    {
941       /*
942        * FIXME: ... after Privoxy 3.0.4 is out.
943        */
944        log_error(LOG_LEVEL_ERROR, "Too many trusted referrers. Current limit is %d, you are using %d.\n"
945           "  Additional trusted referrers are treated like ordinary trusted URLs.\n"
946           "  (You can increase this limit by changing MAX_TRUSTED_REFERRERS in project.h and recompiling).",
947           MAX_TRUSTED_REFERRERS, trusted_referrers);
948    }
949
950    *tl = NULL;
951
952    fclose(fp);
953
954    /* the old one is now obsolete */
955    if (current_trustfile)
956    {
957       current_trustfile->unloader = unload_trustfile;
958    }
959
960    fs->next    = files->next;
961    files->next = fs;
962    current_trustfile = fs;
963
964    if (csp)
965    {
966       csp->tlist = fs;
967    }
968
969    return(0);
970
971 load_trustfile_error:
972    log_error(LOG_LEVEL_FATAL, "can't load trustfile '%s': %E",
973              csp->config->trustfile);
974    return(-1);
975
976 }
977 #endif /* def FEATURE_TRUST */
978
979
980 /*********************************************************************
981  *
982  * Function    :  unload_re_filterfile
983  *
984  * Description :  Unload the re_filter list by freeing all chained
985  *                re_filterfile specs and their data.
986  *
987  * Parameters  :
988  *          1  :  f = the data structure associated with the filterfile.
989  *
990  * Returns     :  N/A
991  *
992  *********************************************************************/
993 static void unload_re_filterfile(void *f)
994 {
995    struct re_filterfile_spec *a, *b = (struct re_filterfile_spec *)f;
996
997    while (b != NULL)
998    {
999       a = b->next;
1000
1001       destroy_list(b->patterns);
1002       pcrs_free_joblist(b->joblist);
1003       freez(b->name);
1004       freez(b->description);
1005       freez(b);
1006
1007       b = a;
1008    }
1009
1010    return;
1011 }
1012
1013 /*********************************************************************
1014  *
1015  * Function    :  unload_forward_spec
1016  *
1017  * Description :  Unload the forward spec settings by freeing all 
1018  *                memory referenced by members and the memory for
1019  *                the spec itself.
1020  *
1021  * Parameters  :
1022  *          1  :  fwd = the forward spec.
1023  *
1024  * Returns     :  N/A
1025  *
1026  *********************************************************************/
1027 void unload_forward_spec(struct forward_spec *fwd)
1028 {
1029    free_url_spec(fwd->url);
1030    freez(fwd->gateway_host);
1031    freez(fwd->forward_host);
1032    free(fwd);
1033
1034    return;
1035 }
1036
1037
1038 #ifdef FEATURE_GRACEFUL_TERMINATION
1039 /*********************************************************************
1040  *
1041  * Function    :  unload_current_re_filterfile
1042  *
1043  * Description :  Unloads current re_filter file - reset to state at
1044  *                beginning of program.
1045  *
1046  * Parameters  :  None
1047  *
1048  * Returns     :  N/A
1049  *
1050  *********************************************************************/
1051 void unload_current_re_filterfile(void)
1052 {
1053    int i;
1054
1055    for (i = 0; i < MAX_AF_FILES; i++)
1056    {
1057       if (current_re_filterfile[i])
1058       {
1059          current_re_filterfile[i]->unloader = unload_re_filterfile;
1060          current_re_filterfile[i] = NULL;
1061       }
1062    }
1063 }
1064 #endif
1065
1066
1067 /*********************************************************************
1068  *
1069  * Function    :  load_re_filterfiles
1070  *
1071  * Description :  Loads all the filterfiles. 
1072  *                Generate a chained list of re_filterfile_spec's from
1073  *                the "FILTER: " blocks, compiling all their substitutions
1074  *                into chained lists of pcrs_job structs.
1075  *
1076  * Parameters  :
1077  *          1  :  csp = Current client state (buffers, headers, etc...)
1078  *
1079  * Returns     :  0 => Ok, everything else is an error.
1080  *
1081  *********************************************************************/
1082 int load_re_filterfiles(struct client_state *csp)
1083 {
1084    int i;
1085    int result;
1086
1087    for (i = 0; i < MAX_AF_FILES; i++)
1088    {
1089       if (csp->config->re_filterfile[i])
1090       {
1091          result = load_one_re_filterfile(csp, i);
1092          if (result)
1093          {
1094             return result;
1095          }
1096       }
1097       else if (current_re_filterfile[i])
1098       {
1099          current_re_filterfile[i]->unloader = unload_re_filterfile;
1100          current_re_filterfile[i] = NULL;
1101       }
1102    }
1103
1104    return 0;
1105 }
1106
1107
1108 /*********************************************************************
1109  *
1110  * Function    :  load_one_re_filterfile
1111  *
1112  * Description :  Load a re_filterfile. 
1113  *                Generate a chained list of re_filterfile_spec's from
1114  *                the "FILTER: " blocks, compiling all their substitutions
1115  *                into chained lists of pcrs_job structs.
1116  *
1117  * Parameters  :
1118  *          1  :  csp = Current client state (buffers, headers, etc...)
1119  *
1120  * Returns     :  0 => Ok, everything else is an error.
1121  *
1122  *********************************************************************/
1123 int load_one_re_filterfile(struct client_state *csp, int fileid)
1124 {
1125    FILE *fp;
1126
1127    struct re_filterfile_spec *new_bl, *bl = NULL;
1128    struct file_list *fs;
1129
1130    char  buf[BUFFER_SIZE];
1131    int error;
1132    unsigned long linenum = 0;
1133    pcrs_job *dummy, *lastjob = NULL;
1134
1135    /*
1136     * No need to reload if unchanged
1137     */
1138    if (!check_file_changed(current_re_filterfile[fileid], csp->config->re_filterfile[fileid], &fs))
1139    {
1140       if (csp)
1141       {
1142          csp->rlist[fileid] = current_re_filterfile[fileid];
1143       }
1144       return(0);
1145    }
1146    if (!fs)
1147    {
1148       goto load_re_filterfile_error;
1149    }
1150
1151    /* 
1152     * Open the file or fail
1153     */
1154    if ((fp = fopen(csp->config->re_filterfile[fileid], "r")) == NULL)
1155    {
1156       goto load_re_filterfile_error;
1157    }
1158
1159    /* 
1160     * Read line by line
1161     */
1162    while (read_config_line(buf, sizeof(buf), fp, &linenum) != NULL)
1163    {
1164       int new_filter = NO_NEW_FILTER;
1165
1166       if (strncmp(buf, "FILTER:", 7) == 0)
1167       {
1168          new_filter = FT_CONTENT_FILTER;
1169       }
1170       else if (strncmp(buf, "SERVER-HEADER-FILTER:", 21) == 0)
1171       {
1172          new_filter = FT_SERVER_HEADER_FILTER;
1173       }
1174       else if (strncmp(buf, "CLIENT-HEADER-FILTER:", 21) == 0)
1175       {
1176          new_filter = FT_CLIENT_HEADER_FILTER;
1177       }
1178       else if (strncmp(buf, "CLIENT-HEADER-TAGGER:", 21) == 0)
1179       {
1180          new_filter = FT_CLIENT_HEADER_TAGGER;
1181       }
1182       else if (strncmp(buf, "SERVER-HEADER-TAGGER:", 21) == 0)
1183       {
1184          new_filter = FT_SERVER_HEADER_TAGGER;
1185       }
1186
1187       /*
1188        * If this is the head of a new filter block, make it a
1189        * re_filterfile spec of its own and chain it to the list:
1190        */
1191       if (new_filter != NO_NEW_FILTER)
1192       {
1193          new_bl = (struct re_filterfile_spec  *)zalloc(sizeof(*bl));
1194          if (new_bl == NULL)
1195          {
1196             goto load_re_filterfile_error;
1197          }
1198          if (new_filter == FT_CONTENT_FILTER)
1199          {
1200             new_bl->name = chomp(buf + 7);
1201          }
1202          else
1203          {
1204             new_bl->name = chomp(buf + 21);
1205          }
1206          new_bl->type = new_filter;
1207
1208          /*
1209           * If a filter description is available,
1210           * encode it to HTML and save it.
1211           */
1212          if (NULL != (new_bl->description = strpbrk(new_bl->name, " \t")))
1213          {
1214             *new_bl->description++ = '\0';
1215             new_bl->description = html_encode(chomp(new_bl->description));
1216             if (NULL == new_bl->description)
1217             {
1218                new_bl->description = strdup("Out of memory while encoding this filter's description to HTML");
1219             }
1220          }
1221          else
1222          {
1223             new_bl->description = strdup("No description available for this filter");
1224          }
1225
1226          new_bl->name = strdup(chomp(new_bl->name));
1227          
1228          /*
1229           * If this is the first filter block, chain it
1230           * to the file_list rather than its (nonexistant)
1231           * predecessor
1232           */
1233          if (fs->f == NULL)
1234          {
1235             fs->f = new_bl;
1236          }
1237          else
1238          {
1239             assert(NULL != bl);
1240             bl->next = new_bl;
1241          }
1242          bl = new_bl;
1243
1244          log_error(LOG_LEVEL_RE_FILTER, "Reading in filter \"%s\" (\"%s\")", bl->name, bl->description);
1245
1246          continue;
1247       }
1248
1249       /* 
1250        * Else, save the expression, make it a pcrs_job
1251        * and chain it into the current filter's joblist 
1252        */
1253       if (bl != NULL)
1254       {
1255          error = enlist(bl->patterns, buf);
1256          if (JB_ERR_MEMORY == error)
1257          {
1258             log_error(LOG_LEVEL_FATAL,
1259                "Out of memory while enlisting re_filter job \'%s\' for filter %s.", buf, bl->name);
1260          }
1261          assert(JB_ERR_OK == error);
1262
1263          if (pcrs_job_is_dynamic(buf))
1264          {
1265             /*
1266              * Dynamic pattern that might contain variables
1267              * and has to be recompiled for every request
1268              */
1269             if (bl->joblist != NULL)
1270             {
1271                 pcrs_free_joblist(bl->joblist);
1272                 bl->joblist = NULL;
1273             }
1274             bl->dynamic = 1;
1275             log_error(LOG_LEVEL_RE_FILTER,
1276                "Adding dynamic re_filter job \'%s\' to filter %s succeeded.", buf, bl->name);
1277             continue;             
1278          }
1279          else if (bl->dynamic)
1280          {
1281             /*
1282              * A previous job was dynamic and as we
1283              * recompile the whole filter anyway, it
1284              * makes no sense to compile this job now.
1285              */
1286             log_error(LOG_LEVEL_RE_FILTER,
1287                "Adding static re_filter job \'%s\' to dynamic filter %s succeeded.", buf, bl->name);
1288             continue;
1289          }
1290
1291          if ((dummy = pcrs_compile_command(buf, &error)) == NULL)
1292          {
1293             log_error(LOG_LEVEL_ERROR,
1294                "Adding re_filter job \'%s\' to filter %s failed with error %d.", buf, bl->name, error);
1295             continue;
1296          }
1297          else
1298          {
1299             if (bl->joblist == NULL)
1300             {
1301                bl->joblist = dummy;
1302             }
1303             else if (NULL != lastjob)
1304             {
1305                lastjob->next = dummy;
1306             }
1307             lastjob = dummy;
1308             log_error(LOG_LEVEL_RE_FILTER, "Adding re_filter job \'%s\' to filter %s succeeded.", buf, bl->name);
1309          }
1310       }
1311       else
1312       {
1313          log_error(LOG_LEVEL_ERROR, "Ignoring job %s outside filter block in %s, line %d",
1314             buf, csp->config->re_filterfile[fileid], linenum);
1315       }
1316    }
1317
1318    fclose(fp);
1319
1320    /* 
1321     * Schedule the now-obsolete old data for unloading
1322     */
1323    if ( NULL != current_re_filterfile[fileid] )
1324    {
1325       current_re_filterfile[fileid]->unloader = unload_re_filterfile;
1326    }
1327
1328    /*
1329     * Chain this file into the global list of loaded files
1330     */
1331    fs->next    = files->next;
1332    files->next = fs;
1333    current_re_filterfile[fileid] = fs;
1334
1335    if (csp)
1336    {
1337       csp->rlist[fileid] = fs;
1338    }
1339
1340    return( 0 );
1341
1342 load_re_filterfile_error:
1343    log_error(LOG_LEVEL_FATAL, "can't load re_filterfile '%s': %E",
1344              csp->config->re_filterfile[fileid]);
1345    return(-1);
1346
1347 }
1348
1349
1350 /*********************************************************************
1351  *
1352  * Function    :  add_loader
1353  *
1354  * Description :  Called from `load_config'.  Called once for each input
1355  *                file found in config.
1356  *
1357  * Parameters  :
1358  *          1  :  loader = pointer to a function that can parse and load
1359  *                the appropriate config file.
1360  *          2  :  config = The configuration_spec to add the loader to.
1361  *
1362  * Returns     :  N/A
1363  *
1364  *********************************************************************/
1365 void add_loader(int (*loader)(struct client_state *),
1366                 struct configuration_spec * config)
1367 {
1368    int i;
1369
1370    for (i=0; i < NLOADERS; i++)
1371    {
1372       if (config->loaders[i] == NULL)
1373       {
1374          config->loaders[i] = loader;
1375          break;
1376       }
1377    }
1378
1379 }
1380
1381
1382 /*********************************************************************
1383  *
1384  * Function    :  run_loader
1385  *
1386  * Description :  Called from `load_config' and `listen_loop'.  This
1387  *                function keeps the "csp" current with any file mods
1388  *                since the last loop.  If a file is unchanged, the
1389  *                loader functions do NOT reload the file.
1390  *
1391  * Parameters  :
1392  *          1  :  csp = Current client state (buffers, headers, etc...)
1393  *                      Must be non-null.  Reads: "csp->config"
1394  *                      Writes: various data members.
1395  *
1396  * Returns     :  0 => Ok, everything else is an error.
1397  *
1398  *********************************************************************/
1399 int run_loader(struct client_state *csp)
1400 {
1401    int ret = 0;
1402    int i;
1403
1404    for (i=0; i < NLOADERS; i++)
1405    {
1406       if (csp->config->loaders[i] == NULL)
1407       {
1408          break;
1409       }
1410       ret |= (csp->config->loaders[i])(csp);
1411    }
1412    return(ret);
1413
1414 }
1415
1416
1417 /*
1418   Local Variables:
1419   tab-width: 3
1420   end:
1421 */