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