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