1 const char loaders_rcs[] = "$Id: loaders.c,v 1.68 2008/09/19 15:26:28 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.68 2008/09/19 15:26:28 fabiankeil
39 * Add change-x-forwarded-for{} action to block or add
40 * X-Forwarded-For headers. Mostly based on code removed
43 * Revision 1.67 2008/03/30 14:52:08 fabiankeil
44 * Rename load_actions_file() and load_re_filterfile()
45 * as they load multiple files "now".
47 * Revision 1.66 2008/03/21 11:16:30 fabiankeil
48 * Garbage-collect csp->my_ip_addr_str and csp->my_hostname.
50 * Revision 1.65 2007/12/07 18:29:23 fabiankeil
51 * Remove now-obsolete csp member x_forwarded.
53 * Revision 1.64 2007/06/01 14:12:38 fabiankeil
54 * Add unload_forward_spec() in preparation for forward-override{}.
56 * Revision 1.63 2007/05/14 10:41:15 fabiankeil
57 * Ditch the csp member cookie_list[] which isn't used anymore.
59 * Revision 1.62 2007/04/30 15:02:18 fabiankeil
60 * Introduce dynamic pcrs jobs that can resolve variables.
62 * Revision 1.61 2007/04/15 16:39:21 fabiankeil
63 * Introduce tags as alternative way to specify which
64 * actions apply to a request. At the moment tags can be
65 * created based on client and server headers.
67 * Revision 1.60 2007/03/20 15:16:34 fabiankeil
68 * Use dedicated header filter actions instead of abusing "filter".
69 * Replace "filter-client-headers" and "filter-client-headers"
70 * with "server-header-filter" and "client-header-filter".
72 * Revision 1.59 2007/01/25 13:38:20 fabiankeil
73 * Freez csp->error_message in sweep().
75 * Revision 1.58 2006/12/31 14:25:20 fabiankeil
76 * Fix gcc43 compiler warnings.
78 * Revision 1.57 2006/12/21 12:22:22 fabiankeil
79 * html_encode filter descriptions.
81 * Have "Ignoring job ..." error messages
82 * print the filter file name correctly.
84 * Revision 1.56 2006/09/07 10:40:30 fabiankeil
85 * Turns out trusted referrers above our arbitrary
86 * limit are downgraded too ordinary trusted URLs.
87 * Adjusted error message.
89 * Revision 1.55 2006/09/07 10:25:39 fabiankeil
92 * Revision 1.54 2006/09/07 10:22:20 fabiankeil
93 * If too many trusted referrers are used,
94 * print only one error message instead of logging
95 * every single trusted referrer above the arbitrary
98 * Revision 1.53 2006/08/31 16:25:06 fabiankeil
99 * Work around a buffer overflow that caused Privoxy to
100 * segfault if too many trusted referrers were used. Good
101 * enough for now, but should be replaced with a real
102 * solution after the next release.
104 * Revision 1.52 2006/07/18 14:48:46 david__schmidt
105 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
106 * with what was really the latest development (the v_3_0_branch branch)
108 * Revision 1.50.2.8 2006/01/30 15:16:25 david__schmidt
109 * Remove a little residual debugging info
111 * Revision 1.50.2.7 2006/01/29 23:10:56 david__schmidt
112 * Multiple filter file support
114 * Revision 1.50.2.6 2003/10/24 10:17:54 oes
115 * Nit: Allowed tabs as separators in filter headings
117 * Revision 1.50.2.5 2003/05/08 15:19:15 oes
118 * sweep: Made loop structure of sweep step mirror that of mark step
120 * Revision 1.50.2.4 2003/05/06 15:57:12 oes
121 * Bugfix: Update last_active pointer in sweep() before
122 * leaving an active client. Closes bugs #724395, #727882
124 * Revision 1.50.2.3 2002/11/20 17:12:30 oes
125 * Ooops, forgot one change.
127 * Revision 1.50.2.2 2002/11/20 14:38:15 oes
128 * Fixed delayed/incomplete freeing of client resources and
129 * simplified loop structure in sweep.
130 * Thanks to Oliver Stoeneberg for the hint.
132 * Revision 1.50.2.1 2002/07/26 15:19:24 oes
133 * - PCRS jobs now chained in order of appearance. Previous
134 * reverse chaining was counter-intuitive.
135 * - Changed loglevel of PCRS job compile errors to
138 * Revision 1.50 2002/04/24 02:12:16 oes
139 * Jon's multiple AF patch: Sweep now takes care of all AFs
141 * Revision 1.49 2002/04/19 16:53:25 jongfoster
142 * Optimize away a function call by using an equivalent macro
144 * Revision 1.48 2002/04/05 00:56:09 gliptak
145 * Correcting typo to clean up on realloc failure
147 * Revision 1.47 2002/03/26 22:29:55 swa
148 * we have a new homepage!
150 * Revision 1.46 2002/03/24 13:25:43 swa
151 * name change related issues
153 * Revision 1.45 2002/03/16 23:54:06 jongfoster
154 * Adding graceful termination feature, to help look for memory leaks.
155 * If you enable this (which, by design, has to be done by hand
156 * editing config.h) and then go to http://i.j.b/die, then the program
157 * will exit cleanly after the *next* request. It should free all the
158 * memory that was used.
160 * Revision 1.44 2002/03/16 21:51:00 jongfoster
163 * Revision 1.43 2002/03/16 20:28:34 oes
164 * Added descriptions to the filters so users will know what they select in the cgi editor
166 * Revision 1.42 2002/03/13 00:27:05 jongfoster
169 * Revision 1.41 2002/03/12 01:42:50 oes
170 * Introduced modular filters
172 * Revision 1.40 2002/03/08 17:46:04 jongfoster
173 * Fixing int/size_t warnings
175 * Revision 1.39 2002/03/07 03:46:17 oes
176 * Fixed compiler warnings
178 * Revision 1.38 2002/03/06 22:54:35 jongfoster
179 * Automated function-comment nitpicking.
181 * Revision 1.37 2002/03/03 15:07:49 oes
182 * Re-enabled automatic config reloading
184 * Revision 1.36 2002/01/22 23:46:18 jongfoster
185 * Moving edit_read_line() and simple_read_line() to loaders.c, and
186 * extending them to support reading MS-DOS, Mac and UNIX style files
189 * Modifying read_config_line() (without changing it's prototype) to
190 * be a trivial wrapper for edit_read_line(). This means that we have
191 * one function to read a line and handle comments, which is common
192 * between the initialization code and the edit interface.
194 * Revision 1.35 2002/01/17 21:03:08 jongfoster
195 * Moving all our URL and URL pattern parsing code to urlmatch.c.
197 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
199 * Revision 1.34 2001/12/30 14:07:32 steudten
200 * - Add signal handling (unix)
201 * - Add SIGHUP handler (unix)
202 * - Add creation of pidfile (unix)
203 * - Add action 'top' in rc file (RH)
204 * - Add entry 'SIGNALS' to manpage
205 * - Add exit message to logfile (unix)
207 * Revision 1.33 2001/11/13 00:16:38 jongfoster
208 * Replacing references to malloc.h with the standard stdlib.h
209 * (See ANSI or K&R 2nd Ed)
211 * Revision 1.32 2001/11/07 00:02:13 steudten
212 * Add line number in error output for lineparsing for
213 * actionsfile and configfile.
214 * Special handling for CLF added.
216 * Revision 1.31 2001/10/26 17:39:01 oes
217 * Removed csp->referrer
218 * Moved ijb_isspace and ijb_tolower to project.h
220 * Revision 1.30 2001/10/25 03:40:48 david__schmidt
221 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
222 * threads to call select() simultaneously. So, it's time to do a real, live,
223 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
224 * (native). Both versions will work, but using __OS2__ offers multi-threading.
226 * Revision 1.29 2001/10/23 21:38:53 jongfoster
227 * Adding error-checking to create_url_spec()
229 * Revision 1.28 2001/10/07 15:40:39 oes
230 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
232 * Revision 1.27 2001/09/22 16:36:59 jongfoster
233 * Removing unused parameter fs from read_config_line()
235 * Revision 1.26 2001/09/22 14:05:22 jongfoster
236 * Bugfix: Multiple escaped "#" characters in a configuration
237 * file are now permitted.
238 * Also removing 3 unused headers.
240 * Revision 1.25 2001/09/13 22:44:03 jongfoster
241 * Adding {} to an if statement
243 * Revision 1.24 2001/07/30 22:08:36 jongfoster
244 * Tidying up #defines:
245 * - All feature #defines are now of the form FEATURE_xxx
246 * - Permanently turned off WIN_GUI_EDIT
247 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
249 * Revision 1.23 2001/07/20 15:51:54 oes
250 * Fixed indentation of prepocessor commands
252 * Revision 1.22 2001/07/20 15:16:17 haroon
253 * - per Guy's suggestion, added a while loop in sweep() to catch not just
254 * the last inactive CSP but all other consecutive inactive CSPs after that
257 * Revision 1.21 2001/07/18 17:26:24 oes
258 * Changed to conform to new pcrs interface
260 * Revision 1.20 2001/07/17 13:07:01 oes
261 * Fixed segv when last line in config files
262 * lacked a terminating (\r)\n
264 * Revision 1.19 2001/07/13 14:01:54 oes
265 * Removed all #ifdef PCRS
267 * Revision 1.18 2001/06/29 21:45:41 oes
268 * Indentation, CRLF->LF, Tab-> Space
270 * Revision 1.17 2001/06/29 13:31:51 oes
273 * Revision 1.16 2001/06/09 10:55:28 jongfoster
274 * Changing BUFSIZ ==> BUFFER_SIZE
276 * Revision 1.15 2001/06/07 23:14:14 jongfoster
277 * Removing ACL and forward file loaders - these
278 * files have been merged into the config file.
279 * Cosmetic: Moving unloader funcs next to their
280 * respective loader funcs
282 * Revision 1.14 2001/06/01 03:27:04 oes
283 * Fixed line continuation problem
285 * Revision 1.13 2001/05/31 21:28:49 jongfoster
286 * Removed all permissionsfile code - it's now called the actions
287 * file, and (almost) all the code is in actions.c
289 * Revision 1.12 2001/05/31 17:32:31 oes
291 * - Enhanced domain part globbing with infix and prefix asterisk
292 * matching and optional unanchored operation
294 * Revision 1.11 2001/05/29 23:25:24 oes
296 * - load_config_line() and load_permissions_file() now use chomp()
298 * Revision 1.10 2001/05/29 09:50:24 jongfoster
299 * Unified blocklist/imagelist/permissionslist.
300 * File format is still under discussion, but the internal changes
303 * Also modified interceptor behaviour:
304 * - We now intercept all URLs beginning with one of the following
305 * prefixes (and *only* these prefixes):
307 * * http://ijbswa.sf.net/config/
308 * * http://ijbswa.sourceforge.net/config/
309 * - New interceptors "home page" - go to http://i.j.b/ to see it.
310 * - Internal changes so that intercepted and fast redirect pages
311 * are not replaced with an image.
312 * - Interceptors now have the option to send a binary page direct
313 * to the client. (i.e. ijb-send-banner uses this)
314 * - Implemented show-url-info interceptor. (Which is why I needed
315 * the above interceptors changes - a typical URL is
316 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
317 * The previous mechanism would not have intercepted that, and
318 * if it had been intercepted then it then it would have replaced
321 * Revision 1.9 2001/05/26 17:12:07 jongfoster
322 * Fatal errors loading configuration files now give better error messages.
324 * Revision 1.8 2001/05/26 00:55:20 jongfoster
325 * Removing duplicated code. load_forwardfile() now uses create_url_spec()
327 * Revision 1.7 2001/05/26 00:28:36 jongfoster
328 * Automatic reloading of config file.
329 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
330 * Most of the global variables have been moved to a new
331 * struct configuration_spec, accessed through csp->config->globalname
332 * Most of the globals remaining are used by the Win32 GUI.
334 * Revision 1.6 2001/05/23 12:27:33 oes
336 * Fixed ugly indentation of my last changes
338 * Revision 1.5 2001/05/23 10:39:05 oes
339 * - Added support for escaping the comment character
340 * in config files by a backslash
341 * - Added support for line continuation in config
343 * - Fixed a buffer overflow bug with long config lines
345 * Revision 1.4 2001/05/22 18:56:28 oes
348 * Revision 1.3 2001/05/20 01:21:20 jongfoster
349 * Version 2.9.4 checkin.
350 * - Merged popupfile and cookiefile, and added control over PCRS
351 * filtering, in new "permissionsfile".
352 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
353 * file error you now get a message box (in the Win32 GUI) rather
354 * than the program exiting with no explanation.
355 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
357 * - Removed tabs from "config"
358 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
359 * - Bumped up version number.
361 * Revision 1.2 2001/05/17 23:01:01 oes
362 * - Cleaned CRLF's from the sources and related files
364 * Revision 1.1.1.1 2001/05/15 13:58:59 oes
365 * Initial import of version 2.9.3 source tree
368 *********************************************************************/
375 #include <sys/types.h>
378 #include <sys/stat.h>
382 #if !defined(_WIN32) && !defined(__OS2__)
392 #include "miscutil.h"
395 #include "urlmatch.h"
398 const char loaders_h_rcs[] = LOADERS_H_VERSION;
401 * Currently active files.
402 * These are also entered in the main linked list of files.
406 static struct file_list *current_trustfile = NULL;
407 #endif /* def FEATURE_TRUST */
409 static int load_one_re_filterfile(struct client_state *csp, int fileid);
411 static struct file_list *current_re_filterfile[MAX_AF_FILES] = {
412 NULL, NULL, NULL, NULL, NULL,
413 NULL, NULL, NULL, NULL, NULL
417 * Pseudo filter type for load_one_re_filterfile
419 #define NO_NEW_FILTER -1
422 /*********************************************************************
426 * Description : Basically a mark and sweep garbage collector, it is run
427 * (by the parent thread) every once in a while to reclaim memory.
429 * It uses a mark and sweep strategy:
430 * 1) mark all files as inactive
432 * 2) check with each client:
433 * if it is active, mark its files as active
434 * if it is inactive, free its resources
436 * 3) free the resources of all of the files that
437 * are still marked as inactive (and are obsolete).
439 * N.B. files that are not obsolete don't have an unloader defined.
445 *********************************************************************/
448 struct file_list *fl, *nfl;
449 struct client_state *csp, *last_active;
452 /* clear all of the file's active flags */
453 for ( fl = files->next; NULL != fl; fl = fl->next )
458 last_active = clients;
463 if (csp->flags & CSP_FLAG_ACTIVE)
465 /* Mark this client's files as active */
468 * Always have a configuration file.
469 * (Also note the slightly non-standard extra
472 csp->config->config_file_list->active = 1;
477 for (i = 0; i < MAX_AF_FILES; i++)
479 if (csp->actions_list[i])
481 csp->actions_list[i]->active = 1;
488 for (i = 0; i < MAX_AF_FILES; i++)
492 csp->rlist[i]->active = 1;
502 csp->tlist->active = 1;
504 #endif /* def FEATURE_TRUST */
512 * This client is not active. Free its resources.
515 last_active->next = csp->next;
517 freez(csp->ip_addr_str);
518 freez(csp->iob->buf);
519 freez(csp->error_message);
521 if (csp->action->flags & ACTION_FORWARD_OVERRIDE &&
524 unload_forward_spec(csp->fwd);
526 free_http_request(csp->http);
528 destroy_list(csp->headers);
529 destroy_list(csp->tags);
531 free_current_action(csp->action);
533 #ifdef FEATURE_STATISTICS
535 if (csp->flags & CSP_FLAG_REJECTED)
539 #endif /* def FEATURE_STATISTICS */
543 csp = last_active->next;
552 if ( ( 0 == fl->active ) && ( NULL != fl->unloader ) )
554 nfl->next = fl->next;
556 (fl->unloader)(fl->f);
573 /*********************************************************************
575 * Function : check_file_changed
577 * Description : Helper function to check if a file needs reloading.
578 * If "current" is still current, return it. Otherwise
579 * allocates a new (zeroed) "struct file_list", fills
580 * in the disk file name and timestamp, and returns it.
583 * 1 : current = The file_list currently being used - will
584 * be checked to see if it is out of date.
585 * May be NULL (which is treated as out of
587 * 2 : filename = Name of file to check.
588 * 3 : newfl = New file list. [Output only]
589 * This will be set to NULL, OR a struct
590 * file_list newly allocated on the
591 * heap, with the filename and lastmodified
592 * fields filled, and all others zeroed.
594 * Returns : If file unchanged: 0 (and sets newfl == NULL)
595 * If file changed: 1 and sets newfl != NULL
596 * On error: 1 and sets newfl == NULL
598 *********************************************************************/
599 int check_file_changed(const struct file_list * current,
600 const char * filename,
601 struct file_list ** newfl)
603 struct file_list *fs;
604 struct stat statbuf[1];
608 if (stat(filename, statbuf) < 0)
610 /* Error, probably file not found. */
615 && (current->lastmodified == statbuf->st_mtime)
616 && (0 == strcmp(current->filename, filename)))
621 fs = (struct file_list *)zalloc(sizeof(struct file_list));
624 /* Out of memory error */
629 fs->filename = strdup(filename);
630 fs->lastmodified = statbuf->st_mtime;
632 if (fs->filename == NULL)
634 /* Out of memory error */
643 /*********************************************************************
645 * Function : simple_read_line
647 * Description : Read a single line from a file and return it.
648 * This is basically a version of fgets() that malloc()s
649 * it's own line buffer. Note that the buffer will
650 * always be a multiple of BUFFER_SIZE bytes long.
651 * Therefore if you are going to keep the string for
652 * an extended period of time, you should probably
653 * strdup() it and free() the original, to save memory.
657 * 1 : dest = destination for newly malloc'd pointer to
658 * line data. Will be set to NULL on error.
659 * 2 : fp = File to read from
660 * 3 : newline = Standard for newlines in the file.
661 * Will be unchanged if it's value on input is not
663 * On output, may be changed from NEWLINE_UNKNOWN to
664 * actual convention in file.
666 * Returns : JB_ERR_OK on success
667 * JB_ERR_MEMORY on out-of-memory
668 * JB_ERR_FILE on EOF.
670 *********************************************************************/
671 jb_err simple_read_line(FILE *fp, char **dest, int *newline)
674 size_t buflen = BUFFER_SIZE;
678 int realnewline = NEWLINE_UNKNOWN;
680 if (NULL == (buf = malloc(buflen)))
682 return JB_ERR_MEMORY;
688 * Character codes. If you have a wierd compiler and the following are
689 * incorrect, you also need to fix NEWLINE() in loaders.h
691 #define CHAR_CR '\r' /* ASCII 13 */
692 #define CHAR_LF '\n' /* ASCII 10 */
712 else if (ch == CHAR_CR)
717 if (*newline == NEWLINE_UNKNOWN)
719 *newline = NEWLINE_DOS;
728 if (*newline == NEWLINE_UNKNOWN)
730 *newline = NEWLINE_MAC;
735 if (*newline == NEWLINE_UNKNOWN)
737 *newline = realnewline;
741 else if (ch == CHAR_LF)
745 if (*newline == NEWLINE_UNKNOWN)
747 *newline = NEWLINE_UNIX;
762 buflen += BUFFER_SIZE;
763 if (NULL == (p = realloc(buf, buflen)))
766 return JB_ERR_MEMORY;
775 /*********************************************************************
777 * Function : edit_read_line
779 * Description : Read a single non-empty line from a file and return
780 * it. Trims comments, leading and trailing whitespace
781 * and respects escaping of newline and comment char.
782 * Provides the line in 2 alternative forms: raw and
784 * - raw is the raw data read from the file. If the
785 * line is not modified, then this should be written
787 * - prefix is any comments and blank lines that were
788 * read from the file. If the line is modified, then
789 * this should be written out to the file followed
790 * by the modified data. (If this string is non-empty
791 * then it will have a newline at the end).
792 * - data is the actual data that will be parsed
793 * further by appropriate routines.
794 * On EOF, the 3 strings will all be set to NULL and
795 * 0 will be returned.
798 * 1 : fp = File to read from
799 * 2 : raw_out = destination for newly malloc'd pointer to
800 * raw line data. May be NULL if you don't want it.
801 * 3 : prefix_out = destination for newly malloc'd pointer to
802 * comments. May be NULL if you don't want it.
803 * 4 : data_out = destination for newly malloc'd pointer to
804 * line data with comments and leading/trailing spaces
805 * removed, and line continuation performed. May be
806 * NULL if you don't want it.
807 * 5 : newline = Standard for newlines in the file.
808 * On input, set to value to use or NEWLINE_UNKNOWN.
809 * On output, may be changed from NEWLINE_UNKNOWN to
810 * actual convention in file. May be NULL if you
812 * 6 : line_number = Line number in file. In "lines" as
813 * reported by a text editor, not lines containing data.
815 * Returns : JB_ERR_OK on success
816 * JB_ERR_MEMORY on out-of-memory
817 * JB_ERR_FILE on EOF.
819 *********************************************************************/
820 jb_err edit_read_line(FILE *fp,
825 unsigned long *line_number)
827 char *p; /* Temporary pointer */
828 char *linebuf; /* Line read from file */
829 char *linestart; /* Start of linebuf, usually first non-whitespace char */
830 int contflag = 0; /* Nonzero for line continuation - i.e. line ends '\' */
831 int is_empty = 1; /* Flag if not got any data yet */
832 char *raw = NULL; /* String to be stored in raw_out */
833 char *prefix = NULL; /* String to be stored in prefix_out */
834 char *data = NULL; /* String to be stored in data_out */
835 int scrapnewline; /* Used for (*newline) if newline==NULL */
836 jb_err rval = JB_ERR_OK;
839 assert(raw_out || data_out);
840 assert(newline == NULL
841 || *newline == NEWLINE_UNKNOWN
842 || *newline == NEWLINE_UNIX
843 || *newline == NEWLINE_DOS
844 || *newline == NEWLINE_MAC);
848 scrapnewline = NEWLINE_UNKNOWN;
849 newline = &scrapnewline;
852 /* Set output parameters to NULL */
866 /* Set string variables to new, empty strings. */
870 if ((raw = malloc(1)) == NULL)
872 return JB_ERR_MEMORY;
878 if ((prefix = malloc(1)) == NULL)
881 return JB_ERR_MEMORY;
887 if ((data = malloc(1)) == NULL)
891 return JB_ERR_MEMORY;
896 /* Main loop. Loop while we need more data & it's not EOF. */
898 while ( (contflag || is_empty)
899 && (JB_ERR_OK == (rval = simple_read_line(fp, &linebuf, newline))))
907 string_append(&raw,linebuf);
908 if (string_append(&raw,NEWLINE(*newline)))
913 return JB_ERR_MEMORY;
917 /* Line continuation? Trim escape and set flag. */
918 p = linebuf + strlen(linebuf) - 1;
919 contflag = ((*linebuf != '\0') && (*p == '\\'));
925 /* Trim leading spaces if we're at the start of the line */
929 /* Trim leading spaces */
930 while (*linestart && isspace((int)(unsigned char)*linestart))
936 /* Handle comment characters. */
938 while ((p = strchr(p, '#')) != NULL)
940 /* Found a comment char.. */
941 if ((p != linebuf) && (*(p-1) == '\\'))
943 /* ..and it's escaped, left-shift the line over the escape. */
945 while ((*q = *(q + 1)) != '\0')
949 /* Now scan from just after the "#". */
953 /* Real comment. Save it... */
956 /* Special case: Line only contains a comment, so all the
957 * previous whitespace is considered part of the comment.
958 * Undo the whitespace skipping, if any.
965 string_append(&prefix,p);
966 if (string_append(&prefix, NEWLINE(*newline)))
971 return JB_ERR_MEMORY;
975 /* ... and chop off the rest of the line */
978 } /* END while (there's a # character) */
980 /* Write to the buffer */
986 if (string_append(&data, linestart))
991 return JB_ERR_MEMORY;
997 } /* END while(we need more data) */
999 /* Handle simple_read_line() errors - ignore EOF */
1000 if ((rval != JB_ERR_OK) && (rval != JB_ERR_FILE))
1008 if (raw ? (*raw == '\0') : is_empty)
1010 /* EOF and no data there. (Definition of "data" depends on whether
1011 * the caller cares about "raw" or just "data").
1022 /* Got at least some data */
1024 /* Remove trailing whitespace */
1037 *prefix_out = prefix;
1056 /*********************************************************************
1058 * Function : read_config_line
1060 * Description : Read a single non-empty line from a file and return
1061 * it. Trims comments, leading and trailing whitespace
1062 * and respects escaping of newline and comment char.
1065 * 1 : buf = Buffer to use.
1066 * 2 : buflen = Size of buffer in bytes.
1067 * 3 : fp = File to read from
1068 * 4 : linenum = linenumber in file
1070 * Returns : NULL on EOF or error
1071 * Otherwise, returns buf.
1073 *********************************************************************/
1074 char *read_config_line(char *buf, size_t buflen, FILE *fp, unsigned long *linenum)
1078 err = edit_read_line(fp, NULL, NULL, &buf2, NULL, linenum);
1081 if (err == JB_ERR_MEMORY)
1083 log_error(LOG_LEVEL_FATAL, "Out of memory loading a config file");
1090 assert(strlen(buf2) + 1U < buflen);
1091 strncpy(buf, buf2, buflen - 1);
1093 buf[buflen - 1] = '\0';
1099 #ifdef FEATURE_TRUST
1100 /*********************************************************************
1102 * Function : unload_trustfile
1104 * Description : Unloads a trustfile.
1107 * 1 : f = the data structure associated with the trustfile.
1111 *********************************************************************/
1112 static void unload_trustfile(void *f)
1114 struct block_spec *cur = (struct block_spec *)f;
1115 struct block_spec *next;
1121 free_url_spec(cur->url);
1130 #ifdef FEATURE_GRACEFUL_TERMINATION
1131 /*********************************************************************
1133 * Function : unload_current_trust_file
1135 * Description : Unloads current trust file - reset to state at
1136 * beginning of program.
1142 *********************************************************************/
1143 void unload_current_trust_file(void)
1145 if (current_trustfile)
1147 current_trustfile->unloader = unload_trustfile;
1148 current_trustfile = NULL;
1151 #endif /* FEATURE_GRACEFUL_TERMINATION */
1154 /*********************************************************************
1156 * Function : load_trustfile
1158 * Description : Read and parse a trustfile and add to files list.
1161 * 1 : csp = Current client state (buffers, headers, etc...)
1163 * Returns : 0 => Ok, everything else is an error.
1165 *********************************************************************/
1166 int load_trustfile(struct client_state *csp)
1170 struct block_spec *b, *bl;
1171 struct url_spec **tl;
1173 char buf[BUFFER_SIZE], *p, *q;
1174 int reject, trusted;
1175 struct file_list *fs;
1176 unsigned long linenum = 0;
1177 int trusted_referrers = 0;
1179 if (!check_file_changed(current_trustfile, csp->config->trustfile, &fs))
1181 /* No need to load */
1184 csp->tlist = current_trustfile;
1190 goto load_trustfile_error;
1193 fs->f = bl = (struct block_spec *)zalloc(sizeof(*bl));
1196 goto load_trustfile_error;
1199 if ((fp = fopen(csp->config->trustfile, "r")) == NULL)
1201 goto load_trustfile_error;
1204 tl = csp->config->trust_list;
1206 while (read_config_line(buf, sizeof(buf), fp, &linenum) != NULL)
1222 while ((*p++ = *q++) != '\0')
1228 /* skip blank lines */
1234 /* allocate a new node */
1235 if ((b = zalloc(sizeof(*b))) == NULL)
1238 goto load_trustfile_error;
1241 /* add it to the list */
1247 /* Save the URL pattern */
1248 if (create_url_spec(b->url, buf))
1251 goto load_trustfile_error;
1255 * save a pointer to URL's spec in the list of trusted URL's, too
1259 if(++trusted_referrers < MAX_TRUSTED_REFERRERS)
1266 if(trusted_referrers >= MAX_TRUSTED_REFERRERS)
1269 * FIXME: ... after Privoxy 3.0.4 is out.
1271 log_error(LOG_LEVEL_ERROR, "Too many trusted referrers. Current limit is %d, you are using %d.\n"
1272 " Additional trusted referrers are treated like ordinary trusted URLs.\n"
1273 " (You can increase this limit by changing MAX_TRUSTED_REFERRERS in project.h and recompiling).",
1274 MAX_TRUSTED_REFERRERS, trusted_referrers);
1281 /* the old one is now obsolete */
1282 if (current_trustfile)
1284 current_trustfile->unloader = unload_trustfile;
1287 fs->next = files->next;
1289 current_trustfile = fs;
1298 load_trustfile_error:
1299 log_error(LOG_LEVEL_FATAL, "can't load trustfile '%s': %E",
1300 csp->config->trustfile);
1304 #endif /* def FEATURE_TRUST */
1307 /*********************************************************************
1309 * Function : unload_re_filterfile
1311 * Description : Unload the re_filter list by freeing all chained
1312 * re_filterfile specs and their data.
1315 * 1 : f = the data structure associated with the filterfile.
1319 *********************************************************************/
1320 static void unload_re_filterfile(void *f)
1322 struct re_filterfile_spec *a, *b = (struct re_filterfile_spec *)f;
1328 destroy_list(b->patterns);
1329 pcrs_free_joblist(b->joblist);
1331 freez(b->description);
1340 /*********************************************************************
1342 * Function : unload_forward_spec
1344 * Description : Unload the forward spec settings by freeing all
1345 * memory referenced by members and the memory for
1349 * 1 : fwd = the forward spec.
1353 *********************************************************************/
1354 void unload_forward_spec(struct forward_spec *fwd)
1356 free_url_spec(fwd->url);
1357 freez(fwd->gateway_host);
1358 freez(fwd->forward_host);
1365 #ifdef FEATURE_GRACEFUL_TERMINATION
1366 /*********************************************************************
1368 * Function : unload_current_re_filterfile
1370 * Description : Unloads current re_filter file - reset to state at
1371 * beginning of program.
1377 *********************************************************************/
1378 void unload_current_re_filterfile(void)
1382 for (i = 0; i < MAX_AF_FILES; i++)
1384 if (current_re_filterfile[i])
1386 current_re_filterfile[i]->unloader = unload_re_filterfile;
1387 current_re_filterfile[i] = NULL;
1394 /*********************************************************************
1396 * Function : load_re_filterfiles
1398 * Description : Loads all the filterfiles.
1399 * Generate a chained list of re_filterfile_spec's from
1400 * the "FILTER: " blocks, compiling all their substitutions
1401 * into chained lists of pcrs_job structs.
1404 * 1 : csp = Current client state (buffers, headers, etc...)
1406 * Returns : 0 => Ok, everything else is an error.
1408 *********************************************************************/
1409 int load_re_filterfiles(struct client_state *csp)
1414 for (i = 0; i < MAX_AF_FILES; i++)
1416 if (csp->config->re_filterfile[i])
1418 result = load_one_re_filterfile(csp, i);
1424 else if (current_re_filterfile[i])
1426 current_re_filterfile[i]->unloader = unload_re_filterfile;
1427 current_re_filterfile[i] = NULL;
1435 /*********************************************************************
1437 * Function : load_one_re_filterfile
1439 * Description : Load a re_filterfile.
1440 * Generate a chained list of re_filterfile_spec's from
1441 * the "FILTER: " blocks, compiling all their substitutions
1442 * into chained lists of pcrs_job structs.
1445 * 1 : csp = Current client state (buffers, headers, etc...)
1447 * Returns : 0 => Ok, everything else is an error.
1449 *********************************************************************/
1450 int load_one_re_filterfile(struct client_state *csp, int fileid)
1454 struct re_filterfile_spec *new_bl, *bl = NULL;
1455 struct file_list *fs;
1457 char buf[BUFFER_SIZE];
1459 unsigned long linenum = 0;
1460 pcrs_job *dummy, *lastjob = NULL;
1463 * No need to reload if unchanged
1465 if (!check_file_changed(current_re_filterfile[fileid], csp->config->re_filterfile[fileid], &fs))
1469 csp->rlist[fileid] = current_re_filterfile[fileid];
1475 goto load_re_filterfile_error;
1479 * Open the file or fail
1481 if ((fp = fopen(csp->config->re_filterfile[fileid], "r")) == NULL)
1483 goto load_re_filterfile_error;
1489 while (read_config_line(buf, sizeof(buf), fp, &linenum) != NULL)
1491 int new_filter = NO_NEW_FILTER;
1493 if (strncmp(buf, "FILTER:", 7) == 0)
1495 new_filter = FT_CONTENT_FILTER;
1497 else if (strncmp(buf, "SERVER-HEADER-FILTER:", 21) == 0)
1499 new_filter = FT_SERVER_HEADER_FILTER;
1501 else if (strncmp(buf, "CLIENT-HEADER-FILTER:", 21) == 0)
1503 new_filter = FT_CLIENT_HEADER_FILTER;
1505 else if (strncmp(buf, "CLIENT-HEADER-TAGGER:", 21) == 0)
1507 new_filter = FT_CLIENT_HEADER_TAGGER;
1509 else if (strncmp(buf, "SERVER-HEADER-TAGGER:", 21) == 0)
1511 new_filter = FT_SERVER_HEADER_TAGGER;
1515 * If this is the head of a new filter block, make it a
1516 * re_filterfile spec of its own and chain it to the list:
1518 if (new_filter != NO_NEW_FILTER)
1520 new_bl = (struct re_filterfile_spec *)zalloc(sizeof(*bl));
1523 goto load_re_filterfile_error;
1525 if (new_filter == FT_CONTENT_FILTER)
1527 new_bl->name = chomp(buf + 7);
1531 new_bl->name = chomp(buf + 21);
1533 new_bl->type = new_filter;
1536 * If a filter description is available,
1537 * encode it to HTML and save it.
1539 if (NULL != (new_bl->description = strpbrk(new_bl->name, " \t")))
1541 *new_bl->description++ = '\0';
1542 new_bl->description = html_encode(chomp(new_bl->description));
1543 if (NULL == new_bl->description)
1545 new_bl->description = strdup("Out of memory while encoding this filter's description to HTML");
1550 new_bl->description = strdup("No description available for this filter");
1553 new_bl->name = strdup(chomp(new_bl->name));
1556 * If this is the first filter block, chain it
1557 * to the file_list rather than its (nonexistant)
1570 log_error(LOG_LEVEL_RE_FILTER, "Reading in filter \"%s\" (\"%s\")", bl->name, bl->description);
1576 * Else, save the expression, make it a pcrs_job
1577 * and chain it into the current filter's joblist
1581 error = enlist(bl->patterns, buf);
1582 if (JB_ERR_MEMORY == error)
1584 log_error(LOG_LEVEL_FATAL,
1585 "Out of memory while enlisting re_filter job \'%s\' for filter %s.", buf, bl->name);
1587 assert(JB_ERR_OK == error);
1589 if (pcrs_job_is_dynamic(buf))
1592 * Dynamic pattern that might contain variables
1593 * and has to be recompiled for every request
1595 if (bl->joblist != NULL)
1597 pcrs_free_joblist(bl->joblist);
1601 log_error(LOG_LEVEL_RE_FILTER,
1602 "Adding dynamic re_filter job \'%s\' to filter %s succeeded.", buf, bl->name);
1605 else if (bl->dynamic)
1608 * A previous job was dynamic and as we
1609 * recompile the whole filter anyway, it
1610 * makes no sense to compile this job now.
1612 log_error(LOG_LEVEL_RE_FILTER,
1613 "Adding static re_filter job \'%s\' to dynamic filter %s succeeded.", buf, bl->name);
1617 if ((dummy = pcrs_compile_command(buf, &error)) == NULL)
1619 log_error(LOG_LEVEL_ERROR,
1620 "Adding re_filter job \'%s\' to filter %s failed with error %d.", buf, bl->name, error);
1625 if (bl->joblist == NULL)
1627 bl->joblist = dummy;
1631 lastjob->next = dummy;
1634 log_error(LOG_LEVEL_RE_FILTER, "Adding re_filter job \'%s\' to filter %s succeeded.", buf, bl->name);
1639 log_error(LOG_LEVEL_ERROR, "Ignoring job %s outside filter block in %s, line %d",
1640 buf, csp->config->re_filterfile[fileid], linenum);
1647 * Schedule the now-obsolete old data for unloading
1649 if ( NULL != current_re_filterfile[fileid] )
1651 current_re_filterfile[fileid]->unloader = unload_re_filterfile;
1655 * Chain this file into the global list of loaded files
1657 fs->next = files->next;
1659 current_re_filterfile[fileid] = fs;
1663 csp->rlist[fileid] = fs;
1668 load_re_filterfile_error:
1669 log_error(LOG_LEVEL_FATAL, "can't load re_filterfile '%s': %E",
1670 csp->config->re_filterfile[fileid]);
1676 /*********************************************************************
1678 * Function : add_loader
1680 * Description : Called from `load_config'. Called once for each input
1681 * file found in config.
1684 * 1 : loader = pointer to a function that can parse and load
1685 * the appropriate config file.
1686 * 2 : config = The configuration_spec to add the loader to.
1690 *********************************************************************/
1691 void add_loader(int (*loader)(struct client_state *),
1692 struct configuration_spec * config)
1696 for (i=0; i < NLOADERS; i++)
1698 if (config->loaders[i] == NULL)
1700 config->loaders[i] = loader;
1708 /*********************************************************************
1710 * Function : run_loader
1712 * Description : Called from `load_config' and `listen_loop'. This
1713 * function keeps the "csp" current with any file mods
1714 * since the last loop. If a file is unchanged, the
1715 * loader functions do NOT reload the file.
1718 * 1 : csp = Current client state (buffers, headers, etc...)
1719 * Must be non-null. Reads: "csp->config"
1720 * Writes: various data members.
1722 * Returns : 0 => Ok, everything else is an error.
1724 *********************************************************************/
1725 int run_loader(struct client_state *csp)
1730 for (i=0; i < NLOADERS; i++)
1732 if (csp->config->loaders[i] == NULL)
1736 ret |= (csp->config->loaders[i])(csp);