Let test level 17 depend on FEATURE_64_BIT_TIME_T
[privoxy.git] / loaders.c
1 const char loaders_rcs[] = "$Id: loaders.c,v 1.101 2016/02/26 12:29:38 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          freez(csp->client_iob->buf);
186          freez(csp->iob->buf);
187          freez(csp->error_message);
188
189          if (csp->action->flags & ACTION_FORWARD_OVERRIDE &&
190              NULL != csp->fwd)
191          {
192             unload_forward_spec(csp->fwd);
193          }
194          free_http_request(csp->http);
195
196          destroy_list(csp->headers);
197          destroy_list(csp->tags);
198
199          free_current_action(csp->action);
200
201 #ifdef FEATURE_STATISTICS
202          urls_read++;
203          if (csp->flags & CSP_FLAG_REJECTED)
204          {
205             urls_rejected++;
206          }
207 #endif /* def FEATURE_STATISTICS */
208
209          freez(client_list);
210
211          client_list = last_active->next;
212       }
213    }
214
215    nfl = files;
216    fl = files->next;
217
218    while (fl != NULL)
219    {
220       if ((0 == fl->active) && (NULL != fl->unloader))
221       {
222          nfl->next = fl->next;
223
224          (fl->unloader)(fl->f);
225
226          freez(fl->filename);
227          freez(fl);
228
229          fl = nfl->next;
230       }
231       else
232       {
233          nfl = fl;
234          fl = fl->next;
235       }
236    }
237
238    return active_threads;
239
240 }
241
242
243 /*********************************************************************
244  *
245  * Function    :  check_file_changed
246  *
247  * Description :  Helper function to check if a file needs reloading.
248  *                If "current" is still current, return it.  Otherwise
249  *                allocates a new (zeroed) "struct file_list", fills
250  *                in the disk file name and timestamp, and returns it.
251  *
252  * Parameters  :
253  *          1  :  current = The file_list currently being used - will
254  *                          be checked to see if it is out of date.
255  *                          May be NULL (which is treated as out of
256  *                          date).
257  *          2  :  filename = Name of file to check.
258  *          3  :  newfl    = New file list. [Output only]
259  *                           This will be set to NULL, OR a struct
260  *                           file_list newly allocated on the
261  *                           heap, with the filename and lastmodified
262  *                           fields filled, and all others zeroed.
263  *
264  * Returns     :  If file unchanged: 0 (and sets newfl == NULL)
265  *                If file changed: 1 and sets newfl != NULL
266  *                On error: 1 and sets newfl == NULL
267  *
268  *********************************************************************/
269 int check_file_changed(const struct file_list * current,
270                        const char * filename,
271                        struct file_list ** newfl)
272 {
273    struct file_list *fs;
274    struct stat statbuf[1];
275
276    *newfl = NULL;
277
278    if (stat(filename, statbuf) < 0)
279    {
280       /* Error, probably file not found. */
281       return 1;
282    }
283
284    if (current
285        && (current->lastmodified == statbuf->st_mtime)
286        && (0 == strcmp(current->filename, filename)))
287    {
288       return 0;
289    }
290
291    fs = zalloc_or_die(sizeof(struct file_list));
292    fs->filename = strdup_or_die(filename);
293    fs->lastmodified = statbuf->st_mtime;
294
295    if (fs->filename == NULL)
296    {
297       /* Out of memory error */
298       freez (fs);
299       return 1;
300    }
301    *newfl = fs;
302    return 1;
303 }
304
305
306 /*********************************************************************
307  *
308  * Function    :  simple_read_line
309  *
310  * Description :  Read a single line from a file and return it.
311  *                This is basically a version of fgets() that malloc()s
312  *                it's own line buffer.  Note that the buffer will
313  *                always be a multiple of BUFFER_SIZE bytes long.
314  *                Therefore if you are going to keep the string for
315  *                an extended period of time, you should probably
316  *                strdup() it and free() the original, to save memory.
317  *
318  *
319  * Parameters  :
320  *          1  :  dest = destination for newly malloc'd pointer to
321  *                line data.  Will be set to NULL on error.
322  *          2  :  fp = File to read from
323  *          3  :  newline = Standard for newlines in the file.
324  *                Will be unchanged if it's value on input is not
325  *                NEWLINE_UNKNOWN.
326  *                On output, may be changed from NEWLINE_UNKNOWN to
327  *                actual convention in file.
328  *
329  * Returns     :  JB_ERR_OK     on success
330  *                JB_ERR_MEMORY on out-of-memory
331  *                JB_ERR_FILE   on EOF.
332  *
333  *********************************************************************/
334 jb_err simple_read_line(FILE *fp, char **dest, int *newline)
335 {
336    size_t len = 0;
337    size_t buflen = BUFFER_SIZE;
338    char * buf;
339    char * p;
340    int ch;
341    int realnewline = NEWLINE_UNKNOWN;
342
343    if (NULL == (buf = malloc(buflen)))
344    {
345       return JB_ERR_MEMORY;
346    }
347
348    p = buf;
349
350 /*
351  * Character codes.  If you have a weird compiler and the following are
352  * incorrect, you also need to fix NEWLINE() in loaders.h
353  */
354 #define CHAR_CR '\r' /* ASCII 13 */
355 #define CHAR_LF '\n' /* ASCII 10 */
356
357    for (;;)
358    {
359       ch = getc(fp);
360       if (ch == EOF)
361       {
362          if (len > 0)
363          {
364             *p = '\0';
365             *dest = buf;
366             return JB_ERR_OK;
367          }
368          else
369          {
370             free(buf);
371             *dest = NULL;
372             return JB_ERR_FILE;
373          }
374       }
375       else if (ch == CHAR_CR)
376       {
377          ch = getc(fp);
378          if (ch == CHAR_LF)
379          {
380             if (*newline == NEWLINE_UNKNOWN)
381             {
382                *newline = NEWLINE_DOS;
383             }
384          }
385          else
386          {
387             if (ch != EOF)
388             {
389                ungetc(ch, fp);
390             }
391             if (*newline == NEWLINE_UNKNOWN)
392             {
393                *newline = NEWLINE_MAC;
394             }
395          }
396          *p = '\0';
397          *dest = buf;
398          if (*newline == NEWLINE_UNKNOWN)
399          {
400             *newline = realnewline;
401          }
402          return JB_ERR_OK;
403       }
404       else if (ch == CHAR_LF)
405       {
406          *p = '\0';
407          *dest = buf;
408          if (*newline == NEWLINE_UNKNOWN)
409          {
410             *newline = NEWLINE_UNIX;
411          }
412          return JB_ERR_OK;
413       }
414       else if (ch == 0)
415       {
416          *p = '\0';
417          *dest = buf;
418          return JB_ERR_OK;
419       }
420
421       *p++ = (char)ch;
422
423       if (++len >= buflen)
424       {
425          buflen += BUFFER_SIZE;
426          if (NULL == (p = realloc(buf, buflen)))
427          {
428             free(buf);
429             return JB_ERR_MEMORY;
430          }
431          buf = p;
432          p = buf + len;
433       }
434    }
435 }
436
437
438 /*********************************************************************
439  *
440  * Function    :  edit_read_line
441  *
442  * Description :  Read a single non-empty line from a file and return
443  *                it.  Trims comments, leading and trailing whitespace
444  *                and respects escaping of newline and comment char.
445  *                Provides the line in 2 alternative forms: raw and
446  *                preprocessed.
447  *                - raw is the raw data read from the file.  If the
448  *                  line is not modified, then this should be written
449  *                  to the new file.
450  *                - prefix is any comments and blank lines that were
451  *                  read from the file.  If the line is modified, then
452  *                  this should be written out to the file followed
453  *                  by the modified data.  (If this string is non-empty
454  *                  then it will have a newline at the end).
455  *                - data is the actual data that will be parsed
456  *                  further by appropriate routines.
457  *                On EOF, the 3 strings will all be set to NULL and
458  *                0 will be returned.
459  *
460  * Parameters  :
461  *          1  :  fp = File to read from
462  *          2  :  raw_out = destination for newly malloc'd pointer to
463  *                raw line data.  May be NULL if you don't want it.
464  *          3  :  prefix_out = destination for newly malloc'd pointer to
465  *                comments.  May be NULL if you don't want it.
466  *          4  :  data_out = destination for newly malloc'd pointer to
467  *                line data with comments and leading/trailing spaces
468  *                removed, and line continuation performed.  May be
469  *                NULL if you don't want it.
470  *          5  :  newline = Standard for newlines in the file.
471  *                On input, set to value to use or NEWLINE_UNKNOWN.
472  *                On output, may be changed from NEWLINE_UNKNOWN to
473  *                actual convention in file.  May be NULL if you
474  *                don't want it.
475  *          6  :  line_number = Line number in file.  In "lines" as
476  *                reported by a text editor, not lines containing data.
477  *
478  * Returns     :  JB_ERR_OK     on success
479  *                JB_ERR_MEMORY on out-of-memory
480  *                JB_ERR_FILE   on EOF.
481  *
482  *********************************************************************/
483 jb_err edit_read_line(FILE *fp,
484                       char **raw_out,
485                       char **prefix_out,
486                       char **data_out,
487                       int *newline,
488                       unsigned long *line_number)
489 {
490    char *p;          /* Temporary pointer   */
491    char *linebuf;    /* Line read from file */
492    char *linestart;  /* Start of linebuf, usually first non-whitespace char */
493    int contflag = 0; /* Nonzero for line continuation - i.e. line ends '\' */
494    int is_empty = 1; /* Flag if not got any data yet */
495    char *raw    = NULL; /* String to be stored in raw_out    */
496    char *prefix = NULL; /* String to be stored in prefix_out */
497    char *data   = NULL; /* String to be stored in data_out   */
498    int scrapnewline;    /* Used for (*newline) if newline==NULL */
499    jb_err rval = JB_ERR_OK;
500
501    assert(fp);
502    assert(raw_out || data_out);
503    assert(newline == NULL
504        || *newline == NEWLINE_UNKNOWN
505        || *newline == NEWLINE_UNIX
506        || *newline == NEWLINE_DOS
507        || *newline == NEWLINE_MAC);
508
509    if (newline == NULL)
510    {
511       scrapnewline = NEWLINE_UNKNOWN;
512       newline = &scrapnewline;
513    }
514
515    /* Set output parameters to NULL */
516    if (raw_out)
517    {
518       *raw_out    = NULL;
519    }
520    if (prefix_out)
521    {
522       *prefix_out = NULL;
523    }
524    if (data_out)
525    {
526       *data_out   = NULL;
527    }
528
529    /* Set string variables to new, empty strings. */
530
531    if (raw_out)
532    {
533       raw = strdup_or_die("");
534    }
535    if (prefix_out)
536    {
537       prefix = strdup_or_die("");
538    }
539    if (data_out)
540    {
541       data = strdup_or_die("");
542    }
543
544    /* Main loop.  Loop while we need more data & it's not EOF. */
545
546    while ((contflag || is_empty)
547        && (JB_ERR_OK == (rval = simple_read_line(fp, &linebuf, newline))))
548    {
549       if (line_number)
550       {
551          (*line_number)++;
552       }
553       if (raw)
554       {
555          string_append(&raw,linebuf);
556          if (string_append(&raw,NEWLINE(*newline)))
557          {
558             freez(prefix);
559             freez(data);
560             free(linebuf);
561             return JB_ERR_MEMORY;
562          }
563       }
564
565       /* Line continuation? Trim escape and set flag. */
566       p = linebuf + strlen(linebuf) - 1;
567       contflag = ((*linebuf != '\0') && (*p == '\\'));
568       if (contflag)
569       {
570          *p = '\0';
571       }
572
573       /* Trim leading spaces if we're at the start of the line */
574       linestart = linebuf;
575       assert(NULL != data);
576       if (*data == '\0')
577       {
578          /* Trim leading spaces */
579          while (*linestart && isspace((int)(unsigned char)*linestart))
580          {
581             linestart++;
582          }
583       }
584
585       /* Handle comment characters. */
586       p = linestart;
587       while ((p = strchr(p, '#')) != NULL)
588       {
589          /* Found a comment char.. */
590          if ((p != linebuf) && (*(p-1) == '\\'))
591          {
592             /* ..and it's escaped, left-shift the line over the escape. */
593             char *q = p - 1;
594             while ((*q = *(q + 1)) != '\0')
595             {
596                q++;
597             }
598             /* Now scan from just after the "#". */
599          }
600          else
601          {
602             /* Real comment.  Save it... */
603             if (p == linestart)
604             {
605                /* Special case:  Line only contains a comment, so all the
606                 * previous whitespace is considered part of the comment.
607                 * Undo the whitespace skipping, if any.
608                 */
609                linestart = linebuf;
610                p = linestart;
611             }
612             if (prefix)
613             {
614                string_append(&prefix,p);
615                if (string_append(&prefix, NEWLINE(*newline)))
616                {
617                   freez(raw);
618                   freez(data);
619                   free(linebuf);
620                   return JB_ERR_MEMORY;
621                }
622             }
623
624             /* ... and chop off the rest of the line */
625             *p = '\0';
626          }
627       } /* END while (there's a # character) */
628
629       /* Write to the buffer */
630       if (*linestart)
631       {
632          is_empty = 0;
633          if (data)
634          {
635             if (string_append(&data, linestart))
636             {
637                freez(raw);
638                freez(prefix);
639                free(linebuf);
640                return JB_ERR_MEMORY;
641             }
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 */