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