1 const char loaders_rcs[] = "$Id: loaders.c,v 1.63 2007/05/14 10:41:15 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.63 2007/05/14 10:41:15 fabiankeil
39 * Ditch the csp member cookie_list[] which isn't used anymore.
41 * Revision 1.62 2007/04/30 15:02:18 fabiankeil
42 * Introduce dynamic pcrs jobs that can resolve variables.
44 * Revision 1.61 2007/04/15 16:39:21 fabiankeil
45 * Introduce tags as alternative way to specify which
46 * actions apply to a request. At the moment tags can be
47 * created based on client and server headers.
49 * Revision 1.60 2007/03/20 15:16:34 fabiankeil
50 * Use dedicated header filter actions instead of abusing "filter".
51 * Replace "filter-client-headers" and "filter-client-headers"
52 * with "server-header-filter" and "client-header-filter".
54 * Revision 1.59 2007/01/25 13:38:20 fabiankeil
55 * Freez csp->error_message in sweep().
57 * Revision 1.58 2006/12/31 14:25:20 fabiankeil
58 * Fix gcc43 compiler warnings.
60 * Revision 1.57 2006/12/21 12:22:22 fabiankeil
61 * html_encode filter descriptions.
63 * Have "Ignoring job ..." error messages
64 * print the filter file name correctly.
66 * Revision 1.56 2006/09/07 10:40:30 fabiankeil
67 * Turns out trusted referrers above our arbitrary
68 * limit are downgraded too ordinary trusted URLs.
69 * Adjusted error message.
71 * Revision 1.55 2006/09/07 10:25:39 fabiankeil
74 * Revision 1.54 2006/09/07 10:22:20 fabiankeil
75 * If too many trusted referrers are used,
76 * print only one error message instead of logging
77 * every single trusted referrer above the arbitrary
80 * Revision 1.53 2006/08/31 16:25:06 fabiankeil
81 * Work around a buffer overflow that caused Privoxy to
82 * segfault if too many trusted referrers were used. Good
83 * enough for now, but should be replaced with a real
84 * solution after the next release.
86 * Revision 1.52 2006/07/18 14:48:46 david__schmidt
87 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
88 * with what was really the latest development (the v_3_0_branch branch)
90 * Revision 1.50.2.8 2006/01/30 15:16:25 david__schmidt
91 * Remove a little residual debugging info
93 * Revision 1.50.2.7 2006/01/29 23:10:56 david__schmidt
94 * Multiple filter file support
96 * Revision 1.50.2.6 2003/10/24 10:17:54 oes
97 * Nit: Allowed tabs as separators in filter headings
99 * Revision 1.50.2.5 2003/05/08 15:19:15 oes
100 * sweep: Made loop structure of sweep step mirror that of mark step
102 * Revision 1.50.2.4 2003/05/06 15:57:12 oes
103 * Bugfix: Update last_active pointer in sweep() before
104 * leaving an active client. Closes bugs #724395, #727882
106 * Revision 1.50.2.3 2002/11/20 17:12:30 oes
107 * Ooops, forgot one change.
109 * Revision 1.50.2.2 2002/11/20 14:38:15 oes
110 * Fixed delayed/incomplete freeing of client resources and
111 * simplified loop structure in sweep.
112 * Thanks to Oliver Stoeneberg for the hint.
114 * Revision 1.50.2.1 2002/07/26 15:19:24 oes
115 * - PCRS jobs now chained in order of appearance. Previous
116 * reverse chaining was counter-intuitive.
117 * - Changed loglevel of PCRS job compile errors to
120 * Revision 1.50 2002/04/24 02:12:16 oes
121 * Jon's multiple AF patch: Sweep now takes care of all AFs
123 * Revision 1.49 2002/04/19 16:53:25 jongfoster
124 * Optimize away a function call by using an equivalent macro
126 * Revision 1.48 2002/04/05 00:56:09 gliptak
127 * Correcting typo to clean up on realloc failure
129 * Revision 1.47 2002/03/26 22:29:55 swa
130 * we have a new homepage!
132 * Revision 1.46 2002/03/24 13:25:43 swa
133 * name change related issues
135 * Revision 1.45 2002/03/16 23:54:06 jongfoster
136 * Adding graceful termination feature, to help look for memory leaks.
137 * If you enable this (which, by design, has to be done by hand
138 * editing config.h) and then go to http://i.j.b/die, then the program
139 * will exit cleanly after the *next* request. It should free all the
140 * memory that was used.
142 * Revision 1.44 2002/03/16 21:51:00 jongfoster
145 * Revision 1.43 2002/03/16 20:28:34 oes
146 * Added descriptions to the filters so users will know what they select in the cgi editor
148 * Revision 1.42 2002/03/13 00:27:05 jongfoster
151 * Revision 1.41 2002/03/12 01:42:50 oes
152 * Introduced modular filters
154 * Revision 1.40 2002/03/08 17:46:04 jongfoster
155 * Fixing int/size_t warnings
157 * Revision 1.39 2002/03/07 03:46:17 oes
158 * Fixed compiler warnings
160 * Revision 1.38 2002/03/06 22:54:35 jongfoster
161 * Automated function-comment nitpicking.
163 * Revision 1.37 2002/03/03 15:07:49 oes
164 * Re-enabled automatic config reloading
166 * Revision 1.36 2002/01/22 23:46:18 jongfoster
167 * Moving edit_read_line() and simple_read_line() to loaders.c, and
168 * extending them to support reading MS-DOS, Mac and UNIX style files
171 * Modifying read_config_line() (without changing it's prototype) to
172 * be a trivial wrapper for edit_read_line(). This means that we have
173 * one function to read a line and handle comments, which is common
174 * between the initialization code and the edit interface.
176 * Revision 1.35 2002/01/17 21:03:08 jongfoster
177 * Moving all our URL and URL pattern parsing code to urlmatch.c.
179 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
181 * Revision 1.34 2001/12/30 14:07:32 steudten
182 * - Add signal handling (unix)
183 * - Add SIGHUP handler (unix)
184 * - Add creation of pidfile (unix)
185 * - Add action 'top' in rc file (RH)
186 * - Add entry 'SIGNALS' to manpage
187 * - Add exit message to logfile (unix)
189 * Revision 1.33 2001/11/13 00:16:38 jongfoster
190 * Replacing references to malloc.h with the standard stdlib.h
191 * (See ANSI or K&R 2nd Ed)
193 * Revision 1.32 2001/11/07 00:02:13 steudten
194 * Add line number in error output for lineparsing for
195 * actionsfile and configfile.
196 * Special handling for CLF added.
198 * Revision 1.31 2001/10/26 17:39:01 oes
199 * Removed csp->referrer
200 * Moved ijb_isspace and ijb_tolower to project.h
202 * Revision 1.30 2001/10/25 03:40:48 david__schmidt
203 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
204 * threads to call select() simultaneously. So, it's time to do a real, live,
205 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
206 * (native). Both versions will work, but using __OS2__ offers multi-threading.
208 * Revision 1.29 2001/10/23 21:38:53 jongfoster
209 * Adding error-checking to create_url_spec()
211 * Revision 1.28 2001/10/07 15:40:39 oes
212 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
214 * Revision 1.27 2001/09/22 16:36:59 jongfoster
215 * Removing unused parameter fs from read_config_line()
217 * Revision 1.26 2001/09/22 14:05:22 jongfoster
218 * Bugfix: Multiple escaped "#" characters in a configuration
219 * file are now permitted.
220 * Also removing 3 unused headers.
222 * Revision 1.25 2001/09/13 22:44:03 jongfoster
223 * Adding {} to an if statement
225 * Revision 1.24 2001/07/30 22:08:36 jongfoster
226 * Tidying up #defines:
227 * - All feature #defines are now of the form FEATURE_xxx
228 * - Permanently turned off WIN_GUI_EDIT
229 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
231 * Revision 1.23 2001/07/20 15:51:54 oes
232 * Fixed indentation of prepocessor commands
234 * Revision 1.22 2001/07/20 15:16:17 haroon
235 * - per Guy's suggestion, added a while loop in sweep() to catch not just
236 * the last inactive CSP but all other consecutive inactive CSPs after that
239 * Revision 1.21 2001/07/18 17:26:24 oes
240 * Changed to conform to new pcrs interface
242 * Revision 1.20 2001/07/17 13:07:01 oes
243 * Fixed segv when last line in config files
244 * lacked a terminating (\r)\n
246 * Revision 1.19 2001/07/13 14:01:54 oes
247 * Removed all #ifdef PCRS
249 * Revision 1.18 2001/06/29 21:45:41 oes
250 * Indentation, CRLF->LF, Tab-> Space
252 * Revision 1.17 2001/06/29 13:31:51 oes
255 * Revision 1.16 2001/06/09 10:55:28 jongfoster
256 * Changing BUFSIZ ==> BUFFER_SIZE
258 * Revision 1.15 2001/06/07 23:14:14 jongfoster
259 * Removing ACL and forward file loaders - these
260 * files have been merged into the config file.
261 * Cosmetic: Moving unloader funcs next to their
262 * respective loader funcs
264 * Revision 1.14 2001/06/01 03:27:04 oes
265 * Fixed line continuation problem
267 * Revision 1.13 2001/05/31 21:28:49 jongfoster
268 * Removed all permissionsfile code - it's now called the actions
269 * file, and (almost) all the code is in actions.c
271 * Revision 1.12 2001/05/31 17:32:31 oes
273 * - Enhanced domain part globbing with infix and prefix asterisk
274 * matching and optional unanchored operation
276 * Revision 1.11 2001/05/29 23:25:24 oes
278 * - load_config_line() and load_permissions_file() now use chomp()
280 * Revision 1.10 2001/05/29 09:50:24 jongfoster
281 * Unified blocklist/imagelist/permissionslist.
282 * File format is still under discussion, but the internal changes
285 * Also modified interceptor behaviour:
286 * - We now intercept all URLs beginning with one of the following
287 * prefixes (and *only* these prefixes):
289 * * http://ijbswa.sf.net/config/
290 * * http://ijbswa.sourceforge.net/config/
291 * - New interceptors "home page" - go to http://i.j.b/ to see it.
292 * - Internal changes so that intercepted and fast redirect pages
293 * are not replaced with an image.
294 * - Interceptors now have the option to send a binary page direct
295 * to the client. (i.e. ijb-send-banner uses this)
296 * - Implemented show-url-info interceptor. (Which is why I needed
297 * the above interceptors changes - a typical URL is
298 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
299 * The previous mechanism would not have intercepted that, and
300 * if it had been intercepted then it then it would have replaced
303 * Revision 1.9 2001/05/26 17:12:07 jongfoster
304 * Fatal errors loading configuration files now give better error messages.
306 * Revision 1.8 2001/05/26 00:55:20 jongfoster
307 * Removing duplicated code. load_forwardfile() now uses create_url_spec()
309 * Revision 1.7 2001/05/26 00:28:36 jongfoster
310 * Automatic reloading of config file.
311 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
312 * Most of the global variables have been moved to a new
313 * struct configuration_spec, accessed through csp->config->globalname
314 * Most of the globals remaining are used by the Win32 GUI.
316 * Revision 1.6 2001/05/23 12:27:33 oes
318 * Fixed ugly indentation of my last changes
320 * Revision 1.5 2001/05/23 10:39:05 oes
321 * - Added support for escaping the comment character
322 * in config files by a backslash
323 * - Added support for line continuation in config
325 * - Fixed a buffer overflow bug with long config lines
327 * Revision 1.4 2001/05/22 18:56:28 oes
330 * Revision 1.3 2001/05/20 01:21:20 jongfoster
331 * Version 2.9.4 checkin.
332 * - Merged popupfile and cookiefile, and added control over PCRS
333 * filtering, in new "permissionsfile".
334 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
335 * file error you now get a message box (in the Win32 GUI) rather
336 * than the program exiting with no explanation.
337 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
339 * - Removed tabs from "config"
340 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
341 * - Bumped up version number.
343 * Revision 1.2 2001/05/17 23:01:01 oes
344 * - Cleaned CRLF's from the sources and related files
346 * Revision 1.1.1.1 2001/05/15 13:58:59 oes
347 * Initial import of version 2.9.3 source tree
350 *********************************************************************/
357 #include <sys/types.h>
360 #include <sys/stat.h>
364 #if !defined(_WIN32) && !defined(__OS2__)
374 #include "miscutil.h"
377 #include "urlmatch.h"
380 const char loaders_h_rcs[] = LOADERS_H_VERSION;
383 * Currently active files.
384 * These are also entered in the main linked list of files.
388 static struct file_list *current_trustfile = NULL;
389 #endif /* def FEATURE_TRUST */
391 static int load_one_re_filterfile(struct client_state *csp, int fileid);
393 static struct file_list *current_re_filterfile[MAX_AF_FILES] = {
394 NULL, NULL, NULL, NULL, NULL,
395 NULL, NULL, NULL, NULL, NULL
399 * Pseudo filter type for load_one_re_filterfile
401 #define NO_NEW_FILTER -1
404 /*********************************************************************
408 * Description : Basically a mark and sweep garbage collector, it is run
409 * (by the parent thread) every once in a while to reclaim memory.
411 * It uses a mark and sweep strategy:
412 * 1) mark all files as inactive
414 * 2) check with each client:
415 * if it is active, mark its files as active
416 * if it is inactive, free its resources
418 * 3) free the resources of all of the files that
419 * are still marked as inactive (and are obsolete).
421 * N.B. files that are not obsolete don't have an unloader defined.
427 *********************************************************************/
430 struct file_list *fl, *nfl;
431 struct client_state *csp, *last_active;
434 /* clear all of the file's active flags */
435 for ( fl = files->next; NULL != fl; fl = fl->next )
440 last_active = clients;
445 if (csp->flags & CSP_FLAG_ACTIVE)
447 /* Mark this client's files as active */
450 * Always have a configuration file.
451 * (Also note the slightly non-standard extra
454 csp->config->config_file_list->active = 1;
459 for (i = 0; i < MAX_AF_FILES; i++)
461 if (csp->actions_list[i])
463 csp->actions_list[i]->active = 1;
470 for (i = 0; i < MAX_AF_FILES; i++)
474 csp->rlist[i]->active = 1;
484 csp->tlist->active = 1;
486 #endif /* def FEATURE_TRUST */
494 * This client is not active. Free its resources.
497 last_active->next = csp->next;
499 freez(csp->ip_addr_str);
500 freez(csp->my_ip_addr_str);
501 freez(csp->my_hostname);
502 freez(csp->x_forwarded);
503 freez(csp->iob->buf);
504 freez(csp->error_message);
506 if (csp->action->flags & ACTION_FORWARD_OVERRIDE &&
509 unload_forward_spec(csp->fwd);
511 free_http_request(csp->http);
513 destroy_list(csp->headers);
514 destroy_list(csp->tags);
516 free_current_action(csp->action);
518 #ifdef FEATURE_STATISTICS
520 if (csp->flags & CSP_FLAG_REJECTED)
524 #endif /* def FEATURE_STATISTICS */
528 csp = last_active->next;
537 if ( ( 0 == fl->active ) && ( NULL != fl->unloader ) )
539 nfl->next = fl->next;
541 (fl->unloader)(fl->f);
558 /*********************************************************************
560 * Function : check_file_changed
562 * Description : Helper function to check if a file needs reloading.
563 * If "current" is still current, return it. Otherwise
564 * allocates a new (zeroed) "struct file_list", fills
565 * in the disk file name and timestamp, and returns it.
568 * 1 : current = The file_list currently being used - will
569 * be checked to see if it is out of date.
570 * May be NULL (which is treated as out of
572 * 2 : filename = Name of file to check.
573 * 3 : newfl = New file list. [Output only]
574 * This will be set to NULL, OR a struct
575 * file_list newly allocated on the
576 * heap, with the filename and lastmodified
577 * fields filled, and all others zeroed.
579 * Returns : If file unchanged: 0 (and sets newfl == NULL)
580 * If file changed: 1 and sets newfl != NULL
581 * On error: 1 and sets newfl == NULL
583 *********************************************************************/
584 int check_file_changed(const struct file_list * current,
585 const char * filename,
586 struct file_list ** newfl)
588 struct file_list *fs;
589 struct stat statbuf[1];
593 if (stat(filename, statbuf) < 0)
595 /* Error, probably file not found. */
600 && (current->lastmodified == statbuf->st_mtime)
601 && (0 == strcmp(current->filename, filename)))
606 fs = (struct file_list *)zalloc(sizeof(struct file_list));
609 /* Out of memory error */
614 fs->filename = strdup(filename);
615 fs->lastmodified = statbuf->st_mtime;
617 if (fs->filename == NULL)
619 /* Out of memory error */
628 /*********************************************************************
630 * Function : simple_read_line
632 * Description : Read a single line from a file and return it.
633 * This is basically a version of fgets() that malloc()s
634 * it's own line buffer. Note that the buffer will
635 * always be a multiple of BUFFER_SIZE bytes long.
636 * Therefore if you are going to keep the string for
637 * an extended period of time, you should probably
638 * strdup() it and free() the original, to save memory.
642 * 1 : dest = destination for newly malloc'd pointer to
643 * line data. Will be set to NULL on error.
644 * 2 : fp = File to read from
645 * 3 : newline = Standard for newlines in the file.
646 * Will be unchanged if it's value on input is not
648 * On output, may be changed from NEWLINE_UNKNOWN to
649 * actual convention in file.
651 * Returns : JB_ERR_OK on success
652 * JB_ERR_MEMORY on out-of-memory
653 * JB_ERR_FILE on EOF.
655 *********************************************************************/
656 jb_err simple_read_line(FILE *fp, char **dest, int *newline)
659 size_t buflen = BUFFER_SIZE;
663 int realnewline = NEWLINE_UNKNOWN;
665 if (NULL == (buf = malloc(buflen)))
667 return JB_ERR_MEMORY;
673 * Character codes. If you have a wierd compiler and the following are
674 * incorrect, you also need to fix NEWLINE() in loaders.h
676 #define CHAR_CR '\r' /* ASCII 13 */
677 #define CHAR_LF '\n' /* ASCII 10 */
697 else if (ch == CHAR_CR)
702 if (*newline == NEWLINE_UNKNOWN)
704 *newline = NEWLINE_DOS;
713 if (*newline == NEWLINE_UNKNOWN)
715 *newline = NEWLINE_MAC;
720 if (*newline == NEWLINE_UNKNOWN)
722 *newline = realnewline;
726 else if (ch == CHAR_LF)
730 if (*newline == NEWLINE_UNKNOWN)
732 *newline = NEWLINE_UNIX;
747 buflen += BUFFER_SIZE;
748 if (NULL == (p = realloc(buf, buflen)))
751 return JB_ERR_MEMORY;
760 /*********************************************************************
762 * Function : edit_read_line
764 * Description : Read a single non-empty line from a file and return
765 * it. Trims comments, leading and trailing whitespace
766 * and respects escaping of newline and comment char.
767 * Provides the line in 2 alternative forms: raw and
769 * - raw is the raw data read from the file. If the
770 * line is not modified, then this should be written
772 * - prefix is any comments and blank lines that were
773 * read from the file. If the line is modified, then
774 * this should be written out to the file followed
775 * by the modified data. (If this string is non-empty
776 * then it will have a newline at the end).
777 * - data is the actual data that will be parsed
778 * further by appropriate routines.
779 * On EOF, the 3 strings will all be set to NULL and
780 * 0 will be returned.
783 * 1 : fp = File to read from
784 * 2 : raw_out = destination for newly malloc'd pointer to
785 * raw line data. May be NULL if you don't want it.
786 * 3 : prefix_out = destination for newly malloc'd pointer to
787 * comments. May be NULL if you don't want it.
788 * 4 : data_out = destination for newly malloc'd pointer to
789 * line data with comments and leading/trailing spaces
790 * removed, and line continuation performed. May be
791 * NULL if you don't want it.
792 * 5 : newline = Standard for newlines in the file.
793 * On input, set to value to use or NEWLINE_UNKNOWN.
794 * On output, may be changed from NEWLINE_UNKNOWN to
795 * actual convention in file. May be NULL if you
797 * 6 : line_number = Line number in file. In "lines" as
798 * reported by a text editor, not lines containing data.
800 * Returns : JB_ERR_OK on success
801 * JB_ERR_MEMORY on out-of-memory
802 * JB_ERR_FILE on EOF.
804 *********************************************************************/
805 jb_err edit_read_line(FILE *fp,
810 unsigned long *line_number)
812 char *p; /* Temporary pointer */
813 char *linebuf; /* Line read from file */
814 char *linestart; /* Start of linebuf, usually first non-whitespace char */
815 int contflag = 0; /* Nonzero for line continuation - i.e. line ends '\' */
816 int is_empty = 1; /* Flag if not got any data yet */
817 char *raw = NULL; /* String to be stored in raw_out */
818 char *prefix = NULL; /* String to be stored in prefix_out */
819 char *data = NULL; /* String to be stored in data_out */
820 int scrapnewline; /* Used for (*newline) if newline==NULL */
821 jb_err rval = JB_ERR_OK;
824 assert(raw_out || data_out);
825 assert(newline == NULL
826 || *newline == NEWLINE_UNKNOWN
827 || *newline == NEWLINE_UNIX
828 || *newline == NEWLINE_DOS
829 || *newline == NEWLINE_MAC);
833 scrapnewline = NEWLINE_UNKNOWN;
834 newline = &scrapnewline;
837 /* Set output parameters to NULL */
851 /* Set string variables to new, empty strings. */
855 if ((raw = malloc(1)) == NULL)
857 return JB_ERR_MEMORY;
863 if ((prefix = malloc(1)) == NULL)
866 return JB_ERR_MEMORY;
872 if ((data = malloc(1)) == NULL)
876 return JB_ERR_MEMORY;
881 /* Main loop. Loop while we need more data & it's not EOF. */
883 while ( (contflag || is_empty)
884 && (JB_ERR_OK == (rval = simple_read_line(fp, &linebuf, newline))))
892 string_append(&raw,linebuf);
893 if (string_append(&raw,NEWLINE(*newline)))
898 return JB_ERR_MEMORY;
902 /* Line continuation? Trim escape and set flag. */
903 p = linebuf + strlen(linebuf) - 1;
904 contflag = ((*linebuf != '\0') && (*p == '\\'));
910 /* Trim leading spaces if we're at the start of the line */
914 /* Trim leading spaces */
915 while (*linestart && isspace((int)(unsigned char)*linestart))
921 /* Handle comment characters. */
923 while ((p = strchr(p, '#')) != NULL)
925 /* Found a comment char.. */
926 if ((p != linebuf) && (*(p-1) == '\\'))
928 /* ..and it's escaped, left-shift the line over the escape. */
930 while ((*q = *(q + 1)) != '\0')
934 /* Now scan from just after the "#". */
938 /* Real comment. Save it... */
941 /* Special case: Line only contains a comment, so all the
942 * previous whitespace is considered part of the comment.
943 * Undo the whitespace skipping, if any.
950 string_append(&prefix,p);
951 if (string_append(&prefix, NEWLINE(*newline)))
956 return JB_ERR_MEMORY;
960 /* ... and chop off the rest of the line */
963 } /* END while (there's a # character) */
965 /* Write to the buffer */
971 if (string_append(&data, linestart))
976 return JB_ERR_MEMORY;
982 } /* END while(we need more data) */
984 /* Handle simple_read_line() errors - ignore EOF */
985 if ((rval != JB_ERR_OK) && (rval != JB_ERR_FILE))
993 if (raw ? (*raw == '\0') : is_empty)
995 /* EOF and no data there. (Definition of "data" depends on whether
996 * the caller cares about "raw" or just "data").
1007 /* Got at least some data */
1009 /* Remove trailing whitespace */
1022 *prefix_out = prefix;
1041 /*********************************************************************
1043 * Function : read_config_line
1045 * Description : Read a single non-empty line from a file and return
1046 * it. Trims comments, leading and trailing whitespace
1047 * and respects escaping of newline and comment char.
1050 * 1 : buf = Buffer to use.
1051 * 2 : buflen = Size of buffer in bytes.
1052 * 3 : fp = File to read from
1053 * 4 : linenum = linenumber in file
1055 * Returns : NULL on EOF or error
1056 * Otherwise, returns buf.
1058 *********************************************************************/
1059 char *read_config_line(char *buf, size_t buflen, FILE *fp, unsigned long *linenum)
1063 err = edit_read_line(fp, NULL, NULL, &buf2, NULL, linenum);
1066 if (err == JB_ERR_MEMORY)
1068 log_error(LOG_LEVEL_FATAL, "Out of memory loading a config file");
1075 assert(strlen(buf2) + 1U < buflen);
1076 strncpy(buf, buf2, buflen - 1);
1078 buf[buflen - 1] = '\0';
1084 #ifdef FEATURE_TRUST
1085 /*********************************************************************
1087 * Function : unload_trustfile
1089 * Description : Unloads a trustfile.
1092 * 1 : f = the data structure associated with the trustfile.
1096 *********************************************************************/
1097 static void unload_trustfile(void *f)
1099 struct block_spec *cur = (struct block_spec *)f;
1100 struct block_spec *next;
1106 free_url_spec(cur->url);
1115 #ifdef FEATURE_GRACEFUL_TERMINATION
1116 /*********************************************************************
1118 * Function : unload_current_trust_file
1120 * Description : Unloads current trust file - reset to state at
1121 * beginning of program.
1127 *********************************************************************/
1128 void unload_current_trust_file(void)
1130 if (current_trustfile)
1132 current_trustfile->unloader = unload_trustfile;
1133 current_trustfile = NULL;
1136 #endif /* FEATURE_GRACEFUL_TERMINATION */
1139 /*********************************************************************
1141 * Function : load_trustfile
1143 * Description : Read and parse a trustfile and add to files list.
1146 * 1 : csp = Current client state (buffers, headers, etc...)
1148 * Returns : 0 => Ok, everything else is an error.
1150 *********************************************************************/
1151 int load_trustfile(struct client_state *csp)
1155 struct block_spec *b, *bl;
1156 struct url_spec **tl;
1158 char buf[BUFFER_SIZE], *p, *q;
1159 int reject, trusted;
1160 struct file_list *fs;
1161 unsigned long linenum = 0;
1162 int trusted_referrers = 0;
1164 if (!check_file_changed(current_trustfile, csp->config->trustfile, &fs))
1166 /* No need to load */
1169 csp->tlist = current_trustfile;
1175 goto load_trustfile_error;
1178 fs->f = bl = (struct block_spec *)zalloc(sizeof(*bl));
1181 goto load_trustfile_error;
1184 if ((fp = fopen(csp->config->trustfile, "r")) == NULL)
1186 goto load_trustfile_error;
1189 tl = csp->config->trust_list;
1191 while (read_config_line(buf, sizeof(buf), fp, &linenum) != NULL)
1207 while ((*p++ = *q++) != '\0')
1213 /* skip blank lines */
1219 /* allocate a new node */
1220 if ((b = zalloc(sizeof(*b))) == NULL)
1223 goto load_trustfile_error;
1226 /* add it to the list */
1232 /* Save the URL pattern */
1233 if (create_url_spec(b->url, buf))
1236 goto load_trustfile_error;
1240 * save a pointer to URL's spec in the list of trusted URL's, too
1244 if(++trusted_referrers < MAX_TRUSTED_REFERRERS)
1251 if(trusted_referrers >= MAX_TRUSTED_REFERRERS)
1254 * FIXME: ... after Privoxy 3.0.4 is out.
1256 log_error(LOG_LEVEL_ERROR, "Too many trusted referrers. Current limit is %d, you are using %d.\n"
1257 " Additional trusted referrers are treated like ordinary trusted URLs.\n"
1258 " (You can increase this limit by changing MAX_TRUSTED_REFERRERS in project.h and recompiling).",
1259 MAX_TRUSTED_REFERRERS, trusted_referrers);
1266 /* the old one is now obsolete */
1267 if (current_trustfile)
1269 current_trustfile->unloader = unload_trustfile;
1272 fs->next = files->next;
1274 current_trustfile = fs;
1283 load_trustfile_error:
1284 log_error(LOG_LEVEL_FATAL, "can't load trustfile '%s': %E",
1285 csp->config->trustfile);
1289 #endif /* def FEATURE_TRUST */
1292 /*********************************************************************
1294 * Function : unload_re_filterfile
1296 * Description : Unload the re_filter list by freeing all chained
1297 * re_filterfile specs and their data.
1300 * 1 : f = the data structure associated with the filterfile.
1304 *********************************************************************/
1305 static void unload_re_filterfile(void *f)
1307 struct re_filterfile_spec *a, *b = (struct re_filterfile_spec *)f;
1313 destroy_list(b->patterns);
1314 pcrs_free_joblist(b->joblist);
1316 freez(b->description);
1325 /*********************************************************************
1327 * Function : unload_forward_spec
1329 * Description : Unload the forward spec settings by freeing all
1330 * memory referenced by members and the memory for
1334 * 1 : fwd = the forward spec.
1338 *********************************************************************/
1339 void unload_forward_spec(struct forward_spec *fwd)
1341 free_url_spec(fwd->url);
1342 freez(fwd->gateway_host);
1343 freez(fwd->forward_host);
1350 #ifdef FEATURE_GRACEFUL_TERMINATION
1351 /*********************************************************************
1353 * Function : unload_current_re_filterfile
1355 * Description : Unloads current re_filter file - reset to state at
1356 * beginning of program.
1362 *********************************************************************/
1363 void unload_current_re_filterfile(void)
1367 for (i = 0; i < MAX_AF_FILES; i++)
1369 if (current_re_filterfile[i])
1371 current_re_filterfile[i]->unloader = unload_re_filterfile;
1372 current_re_filterfile[i] = NULL;
1379 /*********************************************************************
1381 * Function : load_re_filterfile
1383 * Description : Load the re_filterfile.
1384 * Generate a chained list of re_filterfile_spec's from
1385 * the "FILTER: " blocks, compiling all their substitutions
1386 * into chained lists of pcrs_job structs.
1389 * 1 : csp = Current client state (buffers, headers, etc...)
1391 * Returns : 0 => Ok, everything else is an error.
1393 *********************************************************************/
1394 int load_re_filterfile(struct client_state *csp)
1399 for (i = 0; i < MAX_AF_FILES; i++)
1401 if (csp->config->re_filterfile[i])
1403 result = load_one_re_filterfile(csp, i);
1409 else if (current_re_filterfile[i])
1411 current_re_filterfile[i]->unloader = unload_re_filterfile;
1412 current_re_filterfile[i] = NULL;
1420 /*********************************************************************
1422 * Function : load_one_re_filterfile
1424 * Description : Load a re_filterfile.
1425 * Generate a chained list of re_filterfile_spec's from
1426 * the "FILTER: " blocks, compiling all their substitutions
1427 * into chained lists of pcrs_job structs.
1430 * 1 : csp = Current client state (buffers, headers, etc...)
1432 * Returns : 0 => Ok, everything else is an error.
1434 *********************************************************************/
1435 int load_one_re_filterfile(struct client_state *csp, int fileid)
1439 struct re_filterfile_spec *new_bl, *bl = NULL;
1440 struct file_list *fs;
1442 char buf[BUFFER_SIZE];
1444 unsigned long linenum = 0;
1445 pcrs_job *dummy, *lastjob = NULL;
1448 * No need to reload if unchanged
1450 if (!check_file_changed(current_re_filterfile[fileid], csp->config->re_filterfile[fileid], &fs))
1454 csp->rlist[fileid] = current_re_filterfile[fileid];
1460 goto load_re_filterfile_error;
1464 * Open the file or fail
1466 if ((fp = fopen(csp->config->re_filterfile[fileid], "r")) == NULL)
1468 goto load_re_filterfile_error;
1474 while (read_config_line(buf, sizeof(buf), fp, &linenum) != NULL)
1476 int new_filter = NO_NEW_FILTER;
1478 if (strncmp(buf, "FILTER:", 7) == 0)
1480 new_filter = FT_CONTENT_FILTER;
1482 else if (strncmp(buf, "SERVER-HEADER-FILTER:", 21) == 0)
1484 new_filter = FT_SERVER_HEADER_FILTER;
1486 else if (strncmp(buf, "CLIENT-HEADER-FILTER:", 21) == 0)
1488 new_filter = FT_CLIENT_HEADER_FILTER;
1490 else if (strncmp(buf, "CLIENT-HEADER-TAGGER:", 21) == 0)
1492 new_filter = FT_CLIENT_HEADER_TAGGER;
1494 else if (strncmp(buf, "SERVER-HEADER-TAGGER:", 21) == 0)
1496 new_filter = FT_SERVER_HEADER_TAGGER;
1500 * If this is the head of a new filter block, make it a
1501 * re_filterfile spec of its own and chain it to the list:
1503 if (new_filter != NO_NEW_FILTER)
1505 new_bl = (struct re_filterfile_spec *)zalloc(sizeof(*bl));
1508 goto load_re_filterfile_error;
1510 if (new_filter == FT_CONTENT_FILTER)
1512 new_bl->name = chomp(buf + 7);
1516 new_bl->name = chomp(buf + 21);
1518 new_bl->type = new_filter;
1521 * If a filter description is available,
1522 * encode it to HTML and save it.
1524 if (NULL != (new_bl->description = strpbrk(new_bl->name, " \t")))
1526 *new_bl->description++ = '\0';
1527 new_bl->description = html_encode(chomp(new_bl->description));
1528 if (NULL == new_bl->description)
1530 new_bl->description = strdup("Out of memory while encoding this filter's description to HTML");
1535 new_bl->description = strdup("No description available for this filter");
1538 new_bl->name = strdup(chomp(new_bl->name));
1541 * If this is the first filter block, chain it
1542 * to the file_list rather than its (nonexistant)
1555 log_error(LOG_LEVEL_RE_FILTER, "Reading in filter \"%s\" (\"%s\")", bl->name, bl->description);
1561 * Else, save the expression, make it a pcrs_job
1562 * and chain it into the current filter's joblist
1566 error = enlist(bl->patterns, buf);
1567 if (JB_ERR_MEMORY == error)
1569 log_error(LOG_LEVEL_FATAL,
1570 "Out of memory while enlisting re_filter job \'%s\' for filter %s.", buf, bl->name);
1572 assert(JB_ERR_OK == error);
1574 if (pcrs_job_is_dynamic(buf))
1577 * Dynamic pattern that might contain variables
1578 * and has to be recompiled for every request
1580 if (bl->joblist != NULL)
1582 pcrs_free_joblist(bl->joblist);
1586 log_error(LOG_LEVEL_RE_FILTER,
1587 "Adding dynamic re_filter job \'%s\' to filter %s succeeded.", buf, bl->name);
1590 else if (bl->dynamic)
1593 * A previous job was dynamic and as we
1594 * recompile the whole filter anyway, it
1595 * makes no sense to compile this job now.
1597 log_error(LOG_LEVEL_RE_FILTER,
1598 "Adding static re_filter job \'%s\' to dynamic filter %s succeeded.", buf, bl->name);
1602 if ((dummy = pcrs_compile_command(buf, &error)) == NULL)
1604 log_error(LOG_LEVEL_ERROR,
1605 "Adding re_filter job \'%s\' to filter %s failed with error %d.", buf, bl->name, error);
1610 if (bl->joblist == NULL)
1612 bl->joblist = dummy;
1616 lastjob->next = dummy;
1619 log_error(LOG_LEVEL_RE_FILTER, "Adding re_filter job \'%s\' to filter %s succeeded.", buf, bl->name);
1624 log_error(LOG_LEVEL_ERROR, "Ignoring job %s outside filter block in %s, line %d",
1625 buf, csp->config->re_filterfile[fileid], linenum);
1632 * Schedule the now-obsolete old data for unloading
1634 if ( NULL != current_re_filterfile[fileid] )
1636 current_re_filterfile[fileid]->unloader = unload_re_filterfile;
1640 * Chain this file into the global list of loaded files
1642 fs->next = files->next;
1644 current_re_filterfile[fileid] = fs;
1648 csp->rlist[fileid] = fs;
1653 load_re_filterfile_error:
1654 log_error(LOG_LEVEL_FATAL, "can't load re_filterfile '%s': %E",
1655 csp->config->re_filterfile[fileid]);
1661 /*********************************************************************
1663 * Function : add_loader
1665 * Description : Called from `load_config'. Called once for each input
1666 * file found in config.
1669 * 1 : loader = pointer to a function that can parse and load
1670 * the appropriate config file.
1671 * 2 : config = The configuration_spec to add the loader to.
1675 *********************************************************************/
1676 void add_loader(int (*loader)(struct client_state *),
1677 struct configuration_spec * config)
1681 for (i=0; i < NLOADERS; i++)
1683 if (config->loaders[i] == NULL)
1685 config->loaders[i] = loader;
1693 /*********************************************************************
1695 * Function : run_loader
1697 * Description : Called from `load_config' and `listen_loop'. This
1698 * function keeps the "csp" current with any file mods
1699 * since the last loop. If a file is unchanged, the
1700 * loader functions do NOT reload the file.
1703 * 1 : csp = Current client state (buffers, headers, etc...)
1704 * Must be non-null. Reads: "csp->config"
1705 * Writes: various data members.
1707 * Returns : 0 => Ok, everything else is an error.
1709 *********************************************************************/
1710 int run_loader(struct client_state *csp)
1715 for (i=0; i < NLOADERS; i++)
1717 if (csp->config->loaders[i] == NULL)
1721 ret |= (csp->config->loaders[i])(csp);