1 const char loaders_rcs[] = "$Id: loaders.c,v 1.65 2007/12/07 18:29:23 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/loaders.c,v $
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.
11 * Copyright : Written by and Copyright (C) 2001-2007 the SourceForge
12 * Privoxy team. http://www.privoxy.org/
14 * Based on the Internet Junkbuster originally written
15 * by and Copyright (C) 1997 Anonymous Coders and
16 * Junkbusters Corporation. http://www.junkbusters.com
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.
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.
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.
38 * Revision 1.65 2007/12/07 18:29:23 fabiankeil
39 * Remove now-obsolete csp member x_forwarded.
41 * Revision 1.64 2007/06/01 14:12:38 fabiankeil
42 * Add unload_forward_spec() in preparation for forward-override{}.
44 * Revision 1.63 2007/05/14 10:41:15 fabiankeil
45 * Ditch the csp member cookie_list[] which isn't used anymore.
47 * Revision 1.62 2007/04/30 15:02:18 fabiankeil
48 * Introduce dynamic pcrs jobs that can resolve variables.
50 * Revision 1.61 2007/04/15 16:39:21 fabiankeil
51 * Introduce tags as alternative way to specify which
52 * actions apply to a request. At the moment tags can be
53 * created based on client and server headers.
55 * Revision 1.60 2007/03/20 15:16:34 fabiankeil
56 * Use dedicated header filter actions instead of abusing "filter".
57 * Replace "filter-client-headers" and "filter-client-headers"
58 * with "server-header-filter" and "client-header-filter".
60 * Revision 1.59 2007/01/25 13:38:20 fabiankeil
61 * Freez csp->error_message in sweep().
63 * Revision 1.58 2006/12/31 14:25:20 fabiankeil
64 * Fix gcc43 compiler warnings.
66 * Revision 1.57 2006/12/21 12:22:22 fabiankeil
67 * html_encode filter descriptions.
69 * Have "Ignoring job ..." error messages
70 * print the filter file name correctly.
72 * Revision 1.56 2006/09/07 10:40:30 fabiankeil
73 * Turns out trusted referrers above our arbitrary
74 * limit are downgraded too ordinary trusted URLs.
75 * Adjusted error message.
77 * Revision 1.55 2006/09/07 10:25:39 fabiankeil
80 * Revision 1.54 2006/09/07 10:22:20 fabiankeil
81 * If too many trusted referrers are used,
82 * print only one error message instead of logging
83 * every single trusted referrer above the arbitrary
86 * Revision 1.53 2006/08/31 16:25:06 fabiankeil
87 * Work around a buffer overflow that caused Privoxy to
88 * segfault if too many trusted referrers were used. Good
89 * enough for now, but should be replaced with a real
90 * solution after the next release.
92 * Revision 1.52 2006/07/18 14:48:46 david__schmidt
93 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
94 * with what was really the latest development (the v_3_0_branch branch)
96 * Revision 1.50.2.8 2006/01/30 15:16:25 david__schmidt
97 * Remove a little residual debugging info
99 * Revision 1.50.2.7 2006/01/29 23:10:56 david__schmidt
100 * Multiple filter file support
102 * Revision 1.50.2.6 2003/10/24 10:17:54 oes
103 * Nit: Allowed tabs as separators in filter headings
105 * Revision 1.50.2.5 2003/05/08 15:19:15 oes
106 * sweep: Made loop structure of sweep step mirror that of mark step
108 * Revision 1.50.2.4 2003/05/06 15:57:12 oes
109 * Bugfix: Update last_active pointer in sweep() before
110 * leaving an active client. Closes bugs #724395, #727882
112 * Revision 1.50.2.3 2002/11/20 17:12:30 oes
113 * Ooops, forgot one change.
115 * Revision 1.50.2.2 2002/11/20 14:38:15 oes
116 * Fixed delayed/incomplete freeing of client resources and
117 * simplified loop structure in sweep.
118 * Thanks to Oliver Stoeneberg for the hint.
120 * Revision 1.50.2.1 2002/07/26 15:19:24 oes
121 * - PCRS jobs now chained in order of appearance. Previous
122 * reverse chaining was counter-intuitive.
123 * - Changed loglevel of PCRS job compile errors to
126 * Revision 1.50 2002/04/24 02:12:16 oes
127 * Jon's multiple AF patch: Sweep now takes care of all AFs
129 * Revision 1.49 2002/04/19 16:53:25 jongfoster
130 * Optimize away a function call by using an equivalent macro
132 * Revision 1.48 2002/04/05 00:56:09 gliptak
133 * Correcting typo to clean up on realloc failure
135 * Revision 1.47 2002/03/26 22:29:55 swa
136 * we have a new homepage!
138 * Revision 1.46 2002/03/24 13:25:43 swa
139 * name change related issues
141 * Revision 1.45 2002/03/16 23:54:06 jongfoster
142 * Adding graceful termination feature, to help look for memory leaks.
143 * If you enable this (which, by design, has to be done by hand
144 * editing config.h) and then go to http://i.j.b/die, then the program
145 * will exit cleanly after the *next* request. It should free all the
146 * memory that was used.
148 * Revision 1.44 2002/03/16 21:51:00 jongfoster
151 * Revision 1.43 2002/03/16 20:28:34 oes
152 * Added descriptions to the filters so users will know what they select in the cgi editor
154 * Revision 1.42 2002/03/13 00:27:05 jongfoster
157 * Revision 1.41 2002/03/12 01:42:50 oes
158 * Introduced modular filters
160 * Revision 1.40 2002/03/08 17:46:04 jongfoster
161 * Fixing int/size_t warnings
163 * Revision 1.39 2002/03/07 03:46:17 oes
164 * Fixed compiler warnings
166 * Revision 1.38 2002/03/06 22:54:35 jongfoster
167 * Automated function-comment nitpicking.
169 * Revision 1.37 2002/03/03 15:07:49 oes
170 * Re-enabled automatic config reloading
172 * Revision 1.36 2002/01/22 23:46:18 jongfoster
173 * Moving edit_read_line() and simple_read_line() to loaders.c, and
174 * extending them to support reading MS-DOS, Mac and UNIX style files
177 * Modifying read_config_line() (without changing it's prototype) to
178 * be a trivial wrapper for edit_read_line(). This means that we have
179 * one function to read a line and handle comments, which is common
180 * between the initialization code and the edit interface.
182 * Revision 1.35 2002/01/17 21:03:08 jongfoster
183 * Moving all our URL and URL pattern parsing code to urlmatch.c.
185 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
187 * Revision 1.34 2001/12/30 14:07:32 steudten
188 * - Add signal handling (unix)
189 * - Add SIGHUP handler (unix)
190 * - Add creation of pidfile (unix)
191 * - Add action 'top' in rc file (RH)
192 * - Add entry 'SIGNALS' to manpage
193 * - Add exit message to logfile (unix)
195 * Revision 1.33 2001/11/13 00:16:38 jongfoster
196 * Replacing references to malloc.h with the standard stdlib.h
197 * (See ANSI or K&R 2nd Ed)
199 * Revision 1.32 2001/11/07 00:02:13 steudten
200 * Add line number in error output for lineparsing for
201 * actionsfile and configfile.
202 * Special handling for CLF added.
204 * Revision 1.31 2001/10/26 17:39:01 oes
205 * Removed csp->referrer
206 * Moved ijb_isspace and ijb_tolower to project.h
208 * Revision 1.30 2001/10/25 03:40:48 david__schmidt
209 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
210 * threads to call select() simultaneously. So, it's time to do a real, live,
211 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
212 * (native). Both versions will work, but using __OS2__ offers multi-threading.
214 * Revision 1.29 2001/10/23 21:38:53 jongfoster
215 * Adding error-checking to create_url_spec()
217 * Revision 1.28 2001/10/07 15:40:39 oes
218 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
220 * Revision 1.27 2001/09/22 16:36:59 jongfoster
221 * Removing unused parameter fs from read_config_line()
223 * Revision 1.26 2001/09/22 14:05:22 jongfoster
224 * Bugfix: Multiple escaped "#" characters in a configuration
225 * file are now permitted.
226 * Also removing 3 unused headers.
228 * Revision 1.25 2001/09/13 22:44:03 jongfoster
229 * Adding {} to an if statement
231 * Revision 1.24 2001/07/30 22:08:36 jongfoster
232 * Tidying up #defines:
233 * - All feature #defines are now of the form FEATURE_xxx
234 * - Permanently turned off WIN_GUI_EDIT
235 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
237 * Revision 1.23 2001/07/20 15:51:54 oes
238 * Fixed indentation of prepocessor commands
240 * Revision 1.22 2001/07/20 15:16:17 haroon
241 * - per Guy's suggestion, added a while loop in sweep() to catch not just
242 * the last inactive CSP but all other consecutive inactive CSPs after that
245 * Revision 1.21 2001/07/18 17:26:24 oes
246 * Changed to conform to new pcrs interface
248 * Revision 1.20 2001/07/17 13:07:01 oes
249 * Fixed segv when last line in config files
250 * lacked a terminating (\r)\n
252 * Revision 1.19 2001/07/13 14:01:54 oes
253 * Removed all #ifdef PCRS
255 * Revision 1.18 2001/06/29 21:45:41 oes
256 * Indentation, CRLF->LF, Tab-> Space
258 * Revision 1.17 2001/06/29 13:31:51 oes
261 * Revision 1.16 2001/06/09 10:55:28 jongfoster
262 * Changing BUFSIZ ==> BUFFER_SIZE
264 * Revision 1.15 2001/06/07 23:14:14 jongfoster
265 * Removing ACL and forward file loaders - these
266 * files have been merged into the config file.
267 * Cosmetic: Moving unloader funcs next to their
268 * respective loader funcs
270 * Revision 1.14 2001/06/01 03:27:04 oes
271 * Fixed line continuation problem
273 * Revision 1.13 2001/05/31 21:28:49 jongfoster
274 * Removed all permissionsfile code - it's now called the actions
275 * file, and (almost) all the code is in actions.c
277 * Revision 1.12 2001/05/31 17:32:31 oes
279 * - Enhanced domain part globbing with infix and prefix asterisk
280 * matching and optional unanchored operation
282 * Revision 1.11 2001/05/29 23:25:24 oes
284 * - load_config_line() and load_permissions_file() now use chomp()
286 * Revision 1.10 2001/05/29 09:50:24 jongfoster
287 * Unified blocklist/imagelist/permissionslist.
288 * File format is still under discussion, but the internal changes
291 * Also modified interceptor behaviour:
292 * - We now intercept all URLs beginning with one of the following
293 * prefixes (and *only* these prefixes):
295 * * http://ijbswa.sf.net/config/
296 * * http://ijbswa.sourceforge.net/config/
297 * - New interceptors "home page" - go to http://i.j.b/ to see it.
298 * - Internal changes so that intercepted and fast redirect pages
299 * are not replaced with an image.
300 * - Interceptors now have the option to send a binary page direct
301 * to the client. (i.e. ijb-send-banner uses this)
302 * - Implemented show-url-info interceptor. (Which is why I needed
303 * the above interceptors changes - a typical URL is
304 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
305 * The previous mechanism would not have intercepted that, and
306 * if it had been intercepted then it then it would have replaced
309 * Revision 1.9 2001/05/26 17:12:07 jongfoster
310 * Fatal errors loading configuration files now give better error messages.
312 * Revision 1.8 2001/05/26 00:55:20 jongfoster
313 * Removing duplicated code. load_forwardfile() now uses create_url_spec()
315 * Revision 1.7 2001/05/26 00:28:36 jongfoster
316 * Automatic reloading of config file.
317 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
318 * Most of the global variables have been moved to a new
319 * struct configuration_spec, accessed through csp->config->globalname
320 * Most of the globals remaining are used by the Win32 GUI.
322 * Revision 1.6 2001/05/23 12:27:33 oes
324 * Fixed ugly indentation of my last changes
326 * Revision 1.5 2001/05/23 10:39:05 oes
327 * - Added support for escaping the comment character
328 * in config files by a backslash
329 * - Added support for line continuation in config
331 * - Fixed a buffer overflow bug with long config lines
333 * Revision 1.4 2001/05/22 18:56:28 oes
336 * Revision 1.3 2001/05/20 01:21:20 jongfoster
337 * Version 2.9.4 checkin.
338 * - Merged popupfile and cookiefile, and added control over PCRS
339 * filtering, in new "permissionsfile".
340 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
341 * file error you now get a message box (in the Win32 GUI) rather
342 * than the program exiting with no explanation.
343 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
345 * - Removed tabs from "config"
346 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
347 * - Bumped up version number.
349 * Revision 1.2 2001/05/17 23:01:01 oes
350 * - Cleaned CRLF's from the sources and related files
352 * Revision 1.1.1.1 2001/05/15 13:58:59 oes
353 * Initial import of version 2.9.3 source tree
356 *********************************************************************/
363 #include <sys/types.h>
366 #include <sys/stat.h>
370 #if !defined(_WIN32) && !defined(__OS2__)
380 #include "miscutil.h"
383 #include "urlmatch.h"
386 const char loaders_h_rcs[] = LOADERS_H_VERSION;
389 * Currently active files.
390 * These are also entered in the main linked list of files.
394 static struct file_list *current_trustfile = NULL;
395 #endif /* def FEATURE_TRUST */
397 static int load_one_re_filterfile(struct client_state *csp, int fileid);
399 static struct file_list *current_re_filterfile[MAX_AF_FILES] = {
400 NULL, NULL, NULL, NULL, NULL,
401 NULL, NULL, NULL, NULL, NULL
405 * Pseudo filter type for load_one_re_filterfile
407 #define NO_NEW_FILTER -1
410 /*********************************************************************
414 * Description : Basically a mark and sweep garbage collector, it is run
415 * (by the parent thread) every once in a while to reclaim memory.
417 * It uses a mark and sweep strategy:
418 * 1) mark all files as inactive
420 * 2) check with each client:
421 * if it is active, mark its files as active
422 * if it is inactive, free its resources
424 * 3) free the resources of all of the files that
425 * are still marked as inactive (and are obsolete).
427 * N.B. files that are not obsolete don't have an unloader defined.
433 *********************************************************************/
436 struct file_list *fl, *nfl;
437 struct client_state *csp, *last_active;
440 /* clear all of the file's active flags */
441 for ( fl = files->next; NULL != fl; fl = fl->next )
446 last_active = clients;
451 if (csp->flags & CSP_FLAG_ACTIVE)
453 /* Mark this client's files as active */
456 * Always have a configuration file.
457 * (Also note the slightly non-standard extra
460 csp->config->config_file_list->active = 1;
465 for (i = 0; i < MAX_AF_FILES; i++)
467 if (csp->actions_list[i])
469 csp->actions_list[i]->active = 1;
476 for (i = 0; i < MAX_AF_FILES; i++)
480 csp->rlist[i]->active = 1;
490 csp->tlist->active = 1;
492 #endif /* def FEATURE_TRUST */
500 * This client is not active. Free its resources.
503 last_active->next = csp->next;
505 freez(csp->ip_addr_str);
506 freez(csp->iob->buf);
507 freez(csp->error_message);
509 if (csp->action->flags & ACTION_FORWARD_OVERRIDE &&
512 unload_forward_spec(csp->fwd);
514 free_http_request(csp->http);
516 destroy_list(csp->headers);
517 destroy_list(csp->tags);
519 free_current_action(csp->action);
521 #ifdef FEATURE_STATISTICS
523 if (csp->flags & CSP_FLAG_REJECTED)
527 #endif /* def FEATURE_STATISTICS */
531 csp = last_active->next;
540 if ( ( 0 == fl->active ) && ( NULL != fl->unloader ) )
542 nfl->next = fl->next;
544 (fl->unloader)(fl->f);
561 /*********************************************************************
563 * Function : check_file_changed
565 * Description : Helper function to check if a file needs reloading.
566 * If "current" is still current, return it. Otherwise
567 * allocates a new (zeroed) "struct file_list", fills
568 * in the disk file name and timestamp, and returns it.
571 * 1 : current = The file_list currently being used - will
572 * be checked to see if it is out of date.
573 * May be NULL (which is treated as out of
575 * 2 : filename = Name of file to check.
576 * 3 : newfl = New file list. [Output only]
577 * This will be set to NULL, OR a struct
578 * file_list newly allocated on the
579 * heap, with the filename and lastmodified
580 * fields filled, and all others zeroed.
582 * Returns : If file unchanged: 0 (and sets newfl == NULL)
583 * If file changed: 1 and sets newfl != NULL
584 * On error: 1 and sets newfl == NULL
586 *********************************************************************/
587 int check_file_changed(const struct file_list * current,
588 const char * filename,
589 struct file_list ** newfl)
591 struct file_list *fs;
592 struct stat statbuf[1];
596 if (stat(filename, statbuf) < 0)
598 /* Error, probably file not found. */
603 && (current->lastmodified == statbuf->st_mtime)
604 && (0 == strcmp(current->filename, filename)))
609 fs = (struct file_list *)zalloc(sizeof(struct file_list));
612 /* Out of memory error */
617 fs->filename = strdup(filename);
618 fs->lastmodified = statbuf->st_mtime;
620 if (fs->filename == NULL)
622 /* Out of memory error */
631 /*********************************************************************
633 * Function : simple_read_line
635 * Description : Read a single line from a file and return it.
636 * This is basically a version of fgets() that malloc()s
637 * it's own line buffer. Note that the buffer will
638 * always be a multiple of BUFFER_SIZE bytes long.
639 * Therefore if you are going to keep the string for
640 * an extended period of time, you should probably
641 * strdup() it and free() the original, to save memory.
645 * 1 : dest = destination for newly malloc'd pointer to
646 * line data. Will be set to NULL on error.
647 * 2 : fp = File to read from
648 * 3 : newline = Standard for newlines in the file.
649 * Will be unchanged if it's value on input is not
651 * On output, may be changed from NEWLINE_UNKNOWN to
652 * actual convention in file.
654 * Returns : JB_ERR_OK on success
655 * JB_ERR_MEMORY on out-of-memory
656 * JB_ERR_FILE on EOF.
658 *********************************************************************/
659 jb_err simple_read_line(FILE *fp, char **dest, int *newline)
662 size_t buflen = BUFFER_SIZE;
666 int realnewline = NEWLINE_UNKNOWN;
668 if (NULL == (buf = malloc(buflen)))
670 return JB_ERR_MEMORY;
676 * Character codes. If you have a wierd compiler and the following are
677 * incorrect, you also need to fix NEWLINE() in loaders.h
679 #define CHAR_CR '\r' /* ASCII 13 */
680 #define CHAR_LF '\n' /* ASCII 10 */
700 else if (ch == CHAR_CR)
705 if (*newline == NEWLINE_UNKNOWN)
707 *newline = NEWLINE_DOS;
716 if (*newline == NEWLINE_UNKNOWN)
718 *newline = NEWLINE_MAC;
723 if (*newline == NEWLINE_UNKNOWN)
725 *newline = realnewline;
729 else if (ch == CHAR_LF)
733 if (*newline == NEWLINE_UNKNOWN)
735 *newline = NEWLINE_UNIX;
750 buflen += BUFFER_SIZE;
751 if (NULL == (p = realloc(buf, buflen)))
754 return JB_ERR_MEMORY;
763 /*********************************************************************
765 * Function : edit_read_line
767 * Description : Read a single non-empty line from a file and return
768 * it. Trims comments, leading and trailing whitespace
769 * and respects escaping of newline and comment char.
770 * Provides the line in 2 alternative forms: raw and
772 * - raw is the raw data read from the file. If the
773 * line is not modified, then this should be written
775 * - prefix is any comments and blank lines that were
776 * read from the file. If the line is modified, then
777 * this should be written out to the file followed
778 * by the modified data. (If this string is non-empty
779 * then it will have a newline at the end).
780 * - data is the actual data that will be parsed
781 * further by appropriate routines.
782 * On EOF, the 3 strings will all be set to NULL and
783 * 0 will be returned.
786 * 1 : fp = File to read from
787 * 2 : raw_out = destination for newly malloc'd pointer to
788 * raw line data. May be NULL if you don't want it.
789 * 3 : prefix_out = destination for newly malloc'd pointer to
790 * comments. May be NULL if you don't want it.
791 * 4 : data_out = destination for newly malloc'd pointer to
792 * line data with comments and leading/trailing spaces
793 * removed, and line continuation performed. May be
794 * NULL if you don't want it.
795 * 5 : newline = Standard for newlines in the file.
796 * On input, set to value to use or NEWLINE_UNKNOWN.
797 * On output, may be changed from NEWLINE_UNKNOWN to
798 * actual convention in file. May be NULL if you
800 * 6 : line_number = Line number in file. In "lines" as
801 * reported by a text editor, not lines containing data.
803 * Returns : JB_ERR_OK on success
804 * JB_ERR_MEMORY on out-of-memory
805 * JB_ERR_FILE on EOF.
807 *********************************************************************/
808 jb_err edit_read_line(FILE *fp,
813 unsigned long *line_number)
815 char *p; /* Temporary pointer */
816 char *linebuf; /* Line read from file */
817 char *linestart; /* Start of linebuf, usually first non-whitespace char */
818 int contflag = 0; /* Nonzero for line continuation - i.e. line ends '\' */
819 int is_empty = 1; /* Flag if not got any data yet */
820 char *raw = NULL; /* String to be stored in raw_out */
821 char *prefix = NULL; /* String to be stored in prefix_out */
822 char *data = NULL; /* String to be stored in data_out */
823 int scrapnewline; /* Used for (*newline) if newline==NULL */
824 jb_err rval = JB_ERR_OK;
827 assert(raw_out || data_out);
828 assert(newline == NULL
829 || *newline == NEWLINE_UNKNOWN
830 || *newline == NEWLINE_UNIX
831 || *newline == NEWLINE_DOS
832 || *newline == NEWLINE_MAC);
836 scrapnewline = NEWLINE_UNKNOWN;
837 newline = &scrapnewline;
840 /* Set output parameters to NULL */
854 /* Set string variables to new, empty strings. */
858 if ((raw = malloc(1)) == NULL)
860 return JB_ERR_MEMORY;
866 if ((prefix = malloc(1)) == NULL)
869 return JB_ERR_MEMORY;
875 if ((data = malloc(1)) == NULL)
879 return JB_ERR_MEMORY;
884 /* Main loop. Loop while we need more data & it's not EOF. */
886 while ( (contflag || is_empty)
887 && (JB_ERR_OK == (rval = simple_read_line(fp, &linebuf, newline))))
895 string_append(&raw,linebuf);
896 if (string_append(&raw,NEWLINE(*newline)))
901 return JB_ERR_MEMORY;
905 /* Line continuation? Trim escape and set flag. */
906 p = linebuf + strlen(linebuf) - 1;
907 contflag = ((*linebuf != '\0') && (*p == '\\'));
913 /* Trim leading spaces if we're at the start of the line */
917 /* Trim leading spaces */
918 while (*linestart && isspace((int)(unsigned char)*linestart))
924 /* Handle comment characters. */
926 while ((p = strchr(p, '#')) != NULL)
928 /* Found a comment char.. */
929 if ((p != linebuf) && (*(p-1) == '\\'))
931 /* ..and it's escaped, left-shift the line over the escape. */
933 while ((*q = *(q + 1)) != '\0')
937 /* Now scan from just after the "#". */
941 /* Real comment. Save it... */
944 /* Special case: Line only contains a comment, so all the
945 * previous whitespace is considered part of the comment.
946 * Undo the whitespace skipping, if any.
953 string_append(&prefix,p);
954 if (string_append(&prefix, NEWLINE(*newline)))
959 return JB_ERR_MEMORY;
963 /* ... and chop off the rest of the line */
966 } /* END while (there's a # character) */
968 /* Write to the buffer */
974 if (string_append(&data, linestart))
979 return JB_ERR_MEMORY;
985 } /* END while(we need more data) */
987 /* Handle simple_read_line() errors - ignore EOF */
988 if ((rval != JB_ERR_OK) && (rval != JB_ERR_FILE))
996 if (raw ? (*raw == '\0') : is_empty)
998 /* EOF and no data there. (Definition of "data" depends on whether
999 * the caller cares about "raw" or just "data").
1010 /* Got at least some data */
1012 /* Remove trailing whitespace */
1025 *prefix_out = prefix;
1044 /*********************************************************************
1046 * Function : read_config_line
1048 * Description : Read a single non-empty line from a file and return
1049 * it. Trims comments, leading and trailing whitespace
1050 * and respects escaping of newline and comment char.
1053 * 1 : buf = Buffer to use.
1054 * 2 : buflen = Size of buffer in bytes.
1055 * 3 : fp = File to read from
1056 * 4 : linenum = linenumber in file
1058 * Returns : NULL on EOF or error
1059 * Otherwise, returns buf.
1061 *********************************************************************/
1062 char *read_config_line(char *buf, size_t buflen, FILE *fp, unsigned long *linenum)
1066 err = edit_read_line(fp, NULL, NULL, &buf2, NULL, linenum);
1069 if (err == JB_ERR_MEMORY)
1071 log_error(LOG_LEVEL_FATAL, "Out of memory loading a config file");
1078 assert(strlen(buf2) + 1U < buflen);
1079 strncpy(buf, buf2, buflen - 1);
1081 buf[buflen - 1] = '\0';
1087 #ifdef FEATURE_TRUST
1088 /*********************************************************************
1090 * Function : unload_trustfile
1092 * Description : Unloads a trustfile.
1095 * 1 : f = the data structure associated with the trustfile.
1099 *********************************************************************/
1100 static void unload_trustfile(void *f)
1102 struct block_spec *cur = (struct block_spec *)f;
1103 struct block_spec *next;
1109 free_url_spec(cur->url);
1118 #ifdef FEATURE_GRACEFUL_TERMINATION
1119 /*********************************************************************
1121 * Function : unload_current_trust_file
1123 * Description : Unloads current trust file - reset to state at
1124 * beginning of program.
1130 *********************************************************************/
1131 void unload_current_trust_file(void)
1133 if (current_trustfile)
1135 current_trustfile->unloader = unload_trustfile;
1136 current_trustfile = NULL;
1139 #endif /* FEATURE_GRACEFUL_TERMINATION */
1142 /*********************************************************************
1144 * Function : load_trustfile
1146 * Description : Read and parse a trustfile and add to files list.
1149 * 1 : csp = Current client state (buffers, headers, etc...)
1151 * Returns : 0 => Ok, everything else is an error.
1153 *********************************************************************/
1154 int load_trustfile(struct client_state *csp)
1158 struct block_spec *b, *bl;
1159 struct url_spec **tl;
1161 char buf[BUFFER_SIZE], *p, *q;
1162 int reject, trusted;
1163 struct file_list *fs;
1164 unsigned long linenum = 0;
1165 int trusted_referrers = 0;
1167 if (!check_file_changed(current_trustfile, csp->config->trustfile, &fs))
1169 /* No need to load */
1172 csp->tlist = current_trustfile;
1178 goto load_trustfile_error;
1181 fs->f = bl = (struct block_spec *)zalloc(sizeof(*bl));
1184 goto load_trustfile_error;
1187 if ((fp = fopen(csp->config->trustfile, "r")) == NULL)
1189 goto load_trustfile_error;
1192 tl = csp->config->trust_list;
1194 while (read_config_line(buf, sizeof(buf), fp, &linenum) != NULL)
1210 while ((*p++ = *q++) != '\0')
1216 /* skip blank lines */
1222 /* allocate a new node */
1223 if ((b = zalloc(sizeof(*b))) == NULL)
1226 goto load_trustfile_error;
1229 /* add it to the list */
1235 /* Save the URL pattern */
1236 if (create_url_spec(b->url, buf))
1239 goto load_trustfile_error;
1243 * save a pointer to URL's spec in the list of trusted URL's, too
1247 if(++trusted_referrers < MAX_TRUSTED_REFERRERS)
1254 if(trusted_referrers >= MAX_TRUSTED_REFERRERS)
1257 * FIXME: ... after Privoxy 3.0.4 is out.
1259 log_error(LOG_LEVEL_ERROR, "Too many trusted referrers. Current limit is %d, you are using %d.\n"
1260 " Additional trusted referrers are treated like ordinary trusted URLs.\n"
1261 " (You can increase this limit by changing MAX_TRUSTED_REFERRERS in project.h and recompiling).",
1262 MAX_TRUSTED_REFERRERS, trusted_referrers);
1269 /* the old one is now obsolete */
1270 if (current_trustfile)
1272 current_trustfile->unloader = unload_trustfile;
1275 fs->next = files->next;
1277 current_trustfile = fs;
1286 load_trustfile_error:
1287 log_error(LOG_LEVEL_FATAL, "can't load trustfile '%s': %E",
1288 csp->config->trustfile);
1292 #endif /* def FEATURE_TRUST */
1295 /*********************************************************************
1297 * Function : unload_re_filterfile
1299 * Description : Unload the re_filter list by freeing all chained
1300 * re_filterfile specs and their data.
1303 * 1 : f = the data structure associated with the filterfile.
1307 *********************************************************************/
1308 static void unload_re_filterfile(void *f)
1310 struct re_filterfile_spec *a, *b = (struct re_filterfile_spec *)f;
1316 destroy_list(b->patterns);
1317 pcrs_free_joblist(b->joblist);
1319 freez(b->description);
1328 /*********************************************************************
1330 * Function : unload_forward_spec
1332 * Description : Unload the forward spec settings by freeing all
1333 * memory referenced by members and the memory for
1337 * 1 : fwd = the forward spec.
1341 *********************************************************************/
1342 void unload_forward_spec(struct forward_spec *fwd)
1344 free_url_spec(fwd->url);
1345 freez(fwd->gateway_host);
1346 freez(fwd->forward_host);
1353 #ifdef FEATURE_GRACEFUL_TERMINATION
1354 /*********************************************************************
1356 * Function : unload_current_re_filterfile
1358 * Description : Unloads current re_filter file - reset to state at
1359 * beginning of program.
1365 *********************************************************************/
1366 void unload_current_re_filterfile(void)
1370 for (i = 0; i < MAX_AF_FILES; i++)
1372 if (current_re_filterfile[i])
1374 current_re_filterfile[i]->unloader = unload_re_filterfile;
1375 current_re_filterfile[i] = NULL;
1382 /*********************************************************************
1384 * Function : load_re_filterfile
1386 * Description : Load the re_filterfile.
1387 * Generate a chained list of re_filterfile_spec's from
1388 * the "FILTER: " blocks, compiling all their substitutions
1389 * into chained lists of pcrs_job structs.
1392 * 1 : csp = Current client state (buffers, headers, etc...)
1394 * Returns : 0 => Ok, everything else is an error.
1396 *********************************************************************/
1397 int load_re_filterfile(struct client_state *csp)
1402 for (i = 0; i < MAX_AF_FILES; i++)
1404 if (csp->config->re_filterfile[i])
1406 result = load_one_re_filterfile(csp, i);
1412 else if (current_re_filterfile[i])
1414 current_re_filterfile[i]->unloader = unload_re_filterfile;
1415 current_re_filterfile[i] = NULL;
1423 /*********************************************************************
1425 * Function : load_one_re_filterfile
1427 * Description : Load a re_filterfile.
1428 * Generate a chained list of re_filterfile_spec's from
1429 * the "FILTER: " blocks, compiling all their substitutions
1430 * into chained lists of pcrs_job structs.
1433 * 1 : csp = Current client state (buffers, headers, etc...)
1435 * Returns : 0 => Ok, everything else is an error.
1437 *********************************************************************/
1438 int load_one_re_filterfile(struct client_state *csp, int fileid)
1442 struct re_filterfile_spec *new_bl, *bl = NULL;
1443 struct file_list *fs;
1445 char buf[BUFFER_SIZE];
1447 unsigned long linenum = 0;
1448 pcrs_job *dummy, *lastjob = NULL;
1451 * No need to reload if unchanged
1453 if (!check_file_changed(current_re_filterfile[fileid], csp->config->re_filterfile[fileid], &fs))
1457 csp->rlist[fileid] = current_re_filterfile[fileid];
1463 goto load_re_filterfile_error;
1467 * Open the file or fail
1469 if ((fp = fopen(csp->config->re_filterfile[fileid], "r")) == NULL)
1471 goto load_re_filterfile_error;
1477 while (read_config_line(buf, sizeof(buf), fp, &linenum) != NULL)
1479 int new_filter = NO_NEW_FILTER;
1481 if (strncmp(buf, "FILTER:", 7) == 0)
1483 new_filter = FT_CONTENT_FILTER;
1485 else if (strncmp(buf, "SERVER-HEADER-FILTER:", 21) == 0)
1487 new_filter = FT_SERVER_HEADER_FILTER;
1489 else if (strncmp(buf, "CLIENT-HEADER-FILTER:", 21) == 0)
1491 new_filter = FT_CLIENT_HEADER_FILTER;
1493 else if (strncmp(buf, "CLIENT-HEADER-TAGGER:", 21) == 0)
1495 new_filter = FT_CLIENT_HEADER_TAGGER;
1497 else if (strncmp(buf, "SERVER-HEADER-TAGGER:", 21) == 0)
1499 new_filter = FT_SERVER_HEADER_TAGGER;
1503 * If this is the head of a new filter block, make it a
1504 * re_filterfile spec of its own and chain it to the list:
1506 if (new_filter != NO_NEW_FILTER)
1508 new_bl = (struct re_filterfile_spec *)zalloc(sizeof(*bl));
1511 goto load_re_filterfile_error;
1513 if (new_filter == FT_CONTENT_FILTER)
1515 new_bl->name = chomp(buf + 7);
1519 new_bl->name = chomp(buf + 21);
1521 new_bl->type = new_filter;
1524 * If a filter description is available,
1525 * encode it to HTML and save it.
1527 if (NULL != (new_bl->description = strpbrk(new_bl->name, " \t")))
1529 *new_bl->description++ = '\0';
1530 new_bl->description = html_encode(chomp(new_bl->description));
1531 if (NULL == new_bl->description)
1533 new_bl->description = strdup("Out of memory while encoding this filter's description to HTML");
1538 new_bl->description = strdup("No description available for this filter");
1541 new_bl->name = strdup(chomp(new_bl->name));
1544 * If this is the first filter block, chain it
1545 * to the file_list rather than its (nonexistant)
1558 log_error(LOG_LEVEL_RE_FILTER, "Reading in filter \"%s\" (\"%s\")", bl->name, bl->description);
1564 * Else, save the expression, make it a pcrs_job
1565 * and chain it into the current filter's joblist
1569 error = enlist(bl->patterns, buf);
1570 if (JB_ERR_MEMORY == error)
1572 log_error(LOG_LEVEL_FATAL,
1573 "Out of memory while enlisting re_filter job \'%s\' for filter %s.", buf, bl->name);
1575 assert(JB_ERR_OK == error);
1577 if (pcrs_job_is_dynamic(buf))
1580 * Dynamic pattern that might contain variables
1581 * and has to be recompiled for every request
1583 if (bl->joblist != NULL)
1585 pcrs_free_joblist(bl->joblist);
1589 log_error(LOG_LEVEL_RE_FILTER,
1590 "Adding dynamic re_filter job \'%s\' to filter %s succeeded.", buf, bl->name);
1593 else if (bl->dynamic)
1596 * A previous job was dynamic and as we
1597 * recompile the whole filter anyway, it
1598 * makes no sense to compile this job now.
1600 log_error(LOG_LEVEL_RE_FILTER,
1601 "Adding static re_filter job \'%s\' to dynamic filter %s succeeded.", buf, bl->name);
1605 if ((dummy = pcrs_compile_command(buf, &error)) == NULL)
1607 log_error(LOG_LEVEL_ERROR,
1608 "Adding re_filter job \'%s\' to filter %s failed with error %d.", buf, bl->name, error);
1613 if (bl->joblist == NULL)
1615 bl->joblist = dummy;
1619 lastjob->next = dummy;
1622 log_error(LOG_LEVEL_RE_FILTER, "Adding re_filter job \'%s\' to filter %s succeeded.", buf, bl->name);
1627 log_error(LOG_LEVEL_ERROR, "Ignoring job %s outside filter block in %s, line %d",
1628 buf, csp->config->re_filterfile[fileid], linenum);
1635 * Schedule the now-obsolete old data for unloading
1637 if ( NULL != current_re_filterfile[fileid] )
1639 current_re_filterfile[fileid]->unloader = unload_re_filterfile;
1643 * Chain this file into the global list of loaded files
1645 fs->next = files->next;
1647 current_re_filterfile[fileid] = fs;
1651 csp->rlist[fileid] = fs;
1656 load_re_filterfile_error:
1657 log_error(LOG_LEVEL_FATAL, "can't load re_filterfile '%s': %E",
1658 csp->config->re_filterfile[fileid]);
1664 /*********************************************************************
1666 * Function : add_loader
1668 * Description : Called from `load_config'. Called once for each input
1669 * file found in config.
1672 * 1 : loader = pointer to a function that can parse and load
1673 * the appropriate config file.
1674 * 2 : config = The configuration_spec to add the loader to.
1678 *********************************************************************/
1679 void add_loader(int (*loader)(struct client_state *),
1680 struct configuration_spec * config)
1684 for (i=0; i < NLOADERS; i++)
1686 if (config->loaders[i] == NULL)
1688 config->loaders[i] = loader;
1696 /*********************************************************************
1698 * Function : run_loader
1700 * Description : Called from `load_config' and `listen_loop'. This
1701 * function keeps the "csp" current with any file mods
1702 * since the last loop. If a file is unchanged, the
1703 * loader functions do NOT reload the file.
1706 * 1 : csp = Current client state (buffers, headers, etc...)
1707 * Must be non-null. Reads: "csp->config"
1708 * Writes: various data members.
1710 * Returns : 0 => Ok, everything else is an error.
1712 *********************************************************************/
1713 int run_loader(struct client_state *csp)
1718 for (i=0; i < NLOADERS; i++)
1720 if (csp->config->loaders[i] == NULL)
1724 ret |= (csp->config->loaders[i])(csp);