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