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