1 const char loaders_rcs[] = "$Id: loaders.c,v 1.67 2008/03/30 14:52:08 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.67 2008/03/30 14:52:08 fabiankeil
39 * Rename load_actions_file() and load_re_filterfile()
40 * as they load multiple files "now".
42 * Revision 1.66 2008/03/21 11:16:30 fabiankeil
43 * Garbage-collect csp->my_ip_addr_str and csp->my_hostname.
45 * Revision 1.65 2007/12/07 18:29:23 fabiankeil
46 * Remove now-obsolete csp member x_forwarded.
48 * Revision 1.64 2007/06/01 14:12:38 fabiankeil
49 * Add unload_forward_spec() in preparation for forward-override{}.
51 * Revision 1.63 2007/05/14 10:41:15 fabiankeil
52 * Ditch the csp member cookie_list[] which isn't used anymore.
54 * Revision 1.62 2007/04/30 15:02:18 fabiankeil
55 * Introduce dynamic pcrs jobs that can resolve variables.
57 * Revision 1.61 2007/04/15 16:39:21 fabiankeil
58 * Introduce tags as alternative way to specify which
59 * actions apply to a request. At the moment tags can be
60 * created based on client and server headers.
62 * Revision 1.60 2007/03/20 15:16:34 fabiankeil
63 * Use dedicated header filter actions instead of abusing "filter".
64 * Replace "filter-client-headers" and "filter-client-headers"
65 * with "server-header-filter" and "client-header-filter".
67 * Revision 1.59 2007/01/25 13:38:20 fabiankeil
68 * Freez csp->error_message in sweep().
70 * Revision 1.58 2006/12/31 14:25:20 fabiankeil
71 * Fix gcc43 compiler warnings.
73 * Revision 1.57 2006/12/21 12:22:22 fabiankeil
74 * html_encode filter descriptions.
76 * Have "Ignoring job ..." error messages
77 * print the filter file name correctly.
79 * Revision 1.56 2006/09/07 10:40:30 fabiankeil
80 * Turns out trusted referrers above our arbitrary
81 * limit are downgraded too ordinary trusted URLs.
82 * Adjusted error message.
84 * Revision 1.55 2006/09/07 10:25:39 fabiankeil
87 * Revision 1.54 2006/09/07 10:22:20 fabiankeil
88 * If too many trusted referrers are used,
89 * print only one error message instead of logging
90 * every single trusted referrer above the arbitrary
93 * Revision 1.53 2006/08/31 16:25:06 fabiankeil
94 * Work around a buffer overflow that caused Privoxy to
95 * segfault if too many trusted referrers were used. Good
96 * enough for now, but should be replaced with a real
97 * solution after the next release.
99 * Revision 1.52 2006/07/18 14:48:46 david__schmidt
100 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
101 * with what was really the latest development (the v_3_0_branch branch)
103 * Revision 1.50.2.8 2006/01/30 15:16:25 david__schmidt
104 * Remove a little residual debugging info
106 * Revision 1.50.2.7 2006/01/29 23:10:56 david__schmidt
107 * Multiple filter file support
109 * Revision 1.50.2.6 2003/10/24 10:17:54 oes
110 * Nit: Allowed tabs as separators in filter headings
112 * Revision 1.50.2.5 2003/05/08 15:19:15 oes
113 * sweep: Made loop structure of sweep step mirror that of mark step
115 * Revision 1.50.2.4 2003/05/06 15:57:12 oes
116 * Bugfix: Update last_active pointer in sweep() before
117 * leaving an active client. Closes bugs #724395, #727882
119 * Revision 1.50.2.3 2002/11/20 17:12:30 oes
120 * Ooops, forgot one change.
122 * Revision 1.50.2.2 2002/11/20 14:38:15 oes
123 * Fixed delayed/incomplete freeing of client resources and
124 * simplified loop structure in sweep.
125 * Thanks to Oliver Stoeneberg for the hint.
127 * Revision 1.50.2.1 2002/07/26 15:19:24 oes
128 * - PCRS jobs now chained in order of appearance. Previous
129 * reverse chaining was counter-intuitive.
130 * - Changed loglevel of PCRS job compile errors to
133 * Revision 1.50 2002/04/24 02:12:16 oes
134 * Jon's multiple AF patch: Sweep now takes care of all AFs
136 * Revision 1.49 2002/04/19 16:53:25 jongfoster
137 * Optimize away a function call by using an equivalent macro
139 * Revision 1.48 2002/04/05 00:56:09 gliptak
140 * Correcting typo to clean up on realloc failure
142 * Revision 1.47 2002/03/26 22:29:55 swa
143 * we have a new homepage!
145 * Revision 1.46 2002/03/24 13:25:43 swa
146 * name change related issues
148 * Revision 1.45 2002/03/16 23:54:06 jongfoster
149 * Adding graceful termination feature, to help look for memory leaks.
150 * If you enable this (which, by design, has to be done by hand
151 * editing config.h) and then go to http://i.j.b/die, then the program
152 * will exit cleanly after the *next* request. It should free all the
153 * memory that was used.
155 * Revision 1.44 2002/03/16 21:51:00 jongfoster
158 * Revision 1.43 2002/03/16 20:28:34 oes
159 * Added descriptions to the filters so users will know what they select in the cgi editor
161 * Revision 1.42 2002/03/13 00:27:05 jongfoster
164 * Revision 1.41 2002/03/12 01:42:50 oes
165 * Introduced modular filters
167 * Revision 1.40 2002/03/08 17:46:04 jongfoster
168 * Fixing int/size_t warnings
170 * Revision 1.39 2002/03/07 03:46:17 oes
171 * Fixed compiler warnings
173 * Revision 1.38 2002/03/06 22:54:35 jongfoster
174 * Automated function-comment nitpicking.
176 * Revision 1.37 2002/03/03 15:07:49 oes
177 * Re-enabled automatic config reloading
179 * Revision 1.36 2002/01/22 23:46:18 jongfoster
180 * Moving edit_read_line() and simple_read_line() to loaders.c, and
181 * extending them to support reading MS-DOS, Mac and UNIX style files
184 * Modifying read_config_line() (without changing it's prototype) to
185 * be a trivial wrapper for edit_read_line(). This means that we have
186 * one function to read a line and handle comments, which is common
187 * between the initialization code and the edit interface.
189 * Revision 1.35 2002/01/17 21:03:08 jongfoster
190 * Moving all our URL and URL pattern parsing code to urlmatch.c.
192 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
194 * Revision 1.34 2001/12/30 14:07:32 steudten
195 * - Add signal handling (unix)
196 * - Add SIGHUP handler (unix)
197 * - Add creation of pidfile (unix)
198 * - Add action 'top' in rc file (RH)
199 * - Add entry 'SIGNALS' to manpage
200 * - Add exit message to logfile (unix)
202 * Revision 1.33 2001/11/13 00:16:38 jongfoster
203 * Replacing references to malloc.h with the standard stdlib.h
204 * (See ANSI or K&R 2nd Ed)
206 * Revision 1.32 2001/11/07 00:02:13 steudten
207 * Add line number in error output for lineparsing for
208 * actionsfile and configfile.
209 * Special handling for CLF added.
211 * Revision 1.31 2001/10/26 17:39:01 oes
212 * Removed csp->referrer
213 * Moved ijb_isspace and ijb_tolower to project.h
215 * Revision 1.30 2001/10/25 03:40:48 david__schmidt
216 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
217 * threads to call select() simultaneously. So, it's time to do a real, live,
218 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
219 * (native). Both versions will work, but using __OS2__ offers multi-threading.
221 * Revision 1.29 2001/10/23 21:38:53 jongfoster
222 * Adding error-checking to create_url_spec()
224 * Revision 1.28 2001/10/07 15:40:39 oes
225 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
227 * Revision 1.27 2001/09/22 16:36:59 jongfoster
228 * Removing unused parameter fs from read_config_line()
230 * Revision 1.26 2001/09/22 14:05:22 jongfoster
231 * Bugfix: Multiple escaped "#" characters in a configuration
232 * file are now permitted.
233 * Also removing 3 unused headers.
235 * Revision 1.25 2001/09/13 22:44:03 jongfoster
236 * Adding {} to an if statement
238 * Revision 1.24 2001/07/30 22:08:36 jongfoster
239 * Tidying up #defines:
240 * - All feature #defines are now of the form FEATURE_xxx
241 * - Permanently turned off WIN_GUI_EDIT
242 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
244 * Revision 1.23 2001/07/20 15:51:54 oes
245 * Fixed indentation of prepocessor commands
247 * Revision 1.22 2001/07/20 15:16:17 haroon
248 * - per Guy's suggestion, added a while loop in sweep() to catch not just
249 * the last inactive CSP but all other consecutive inactive CSPs after that
252 * Revision 1.21 2001/07/18 17:26:24 oes
253 * Changed to conform to new pcrs interface
255 * Revision 1.20 2001/07/17 13:07:01 oes
256 * Fixed segv when last line in config files
257 * lacked a terminating (\r)\n
259 * Revision 1.19 2001/07/13 14:01:54 oes
260 * Removed all #ifdef PCRS
262 * Revision 1.18 2001/06/29 21:45:41 oes
263 * Indentation, CRLF->LF, Tab-> Space
265 * Revision 1.17 2001/06/29 13:31:51 oes
268 * Revision 1.16 2001/06/09 10:55:28 jongfoster
269 * Changing BUFSIZ ==> BUFFER_SIZE
271 * Revision 1.15 2001/06/07 23:14:14 jongfoster
272 * Removing ACL and forward file loaders - these
273 * files have been merged into the config file.
274 * Cosmetic: Moving unloader funcs next to their
275 * respective loader funcs
277 * Revision 1.14 2001/06/01 03:27:04 oes
278 * Fixed line continuation problem
280 * Revision 1.13 2001/05/31 21:28:49 jongfoster
281 * Removed all permissionsfile code - it's now called the actions
282 * file, and (almost) all the code is in actions.c
284 * Revision 1.12 2001/05/31 17:32:31 oes
286 * - Enhanced domain part globbing with infix and prefix asterisk
287 * matching and optional unanchored operation
289 * Revision 1.11 2001/05/29 23:25:24 oes
291 * - load_config_line() and load_permissions_file() now use chomp()
293 * Revision 1.10 2001/05/29 09:50:24 jongfoster
294 * Unified blocklist/imagelist/permissionslist.
295 * File format is still under discussion, but the internal changes
298 * Also modified interceptor behaviour:
299 * - We now intercept all URLs beginning with one of the following
300 * prefixes (and *only* these prefixes):
302 * * http://ijbswa.sf.net/config/
303 * * http://ijbswa.sourceforge.net/config/
304 * - New interceptors "home page" - go to http://i.j.b/ to see it.
305 * - Internal changes so that intercepted and fast redirect pages
306 * are not replaced with an image.
307 * - Interceptors now have the option to send a binary page direct
308 * to the client. (i.e. ijb-send-banner uses this)
309 * - Implemented show-url-info interceptor. (Which is why I needed
310 * the above interceptors changes - a typical URL is
311 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
312 * The previous mechanism would not have intercepted that, and
313 * if it had been intercepted then it then it would have replaced
316 * Revision 1.9 2001/05/26 17:12:07 jongfoster
317 * Fatal errors loading configuration files now give better error messages.
319 * Revision 1.8 2001/05/26 00:55:20 jongfoster
320 * Removing duplicated code. load_forwardfile() now uses create_url_spec()
322 * Revision 1.7 2001/05/26 00:28:36 jongfoster
323 * Automatic reloading of config file.
324 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
325 * Most of the global variables have been moved to a new
326 * struct configuration_spec, accessed through csp->config->globalname
327 * Most of the globals remaining are used by the Win32 GUI.
329 * Revision 1.6 2001/05/23 12:27:33 oes
331 * Fixed ugly indentation of my last changes
333 * Revision 1.5 2001/05/23 10:39:05 oes
334 * - Added support for escaping the comment character
335 * in config files by a backslash
336 * - Added support for line continuation in config
338 * - Fixed a buffer overflow bug with long config lines
340 * Revision 1.4 2001/05/22 18:56:28 oes
343 * Revision 1.3 2001/05/20 01:21:20 jongfoster
344 * Version 2.9.4 checkin.
345 * - Merged popupfile and cookiefile, and added control over PCRS
346 * filtering, in new "permissionsfile".
347 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
348 * file error you now get a message box (in the Win32 GUI) rather
349 * than the program exiting with no explanation.
350 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
352 * - Removed tabs from "config"
353 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
354 * - Bumped up version number.
356 * Revision 1.2 2001/05/17 23:01:01 oes
357 * - Cleaned CRLF's from the sources and related files
359 * Revision 1.1.1.1 2001/05/15 13:58:59 oes
360 * Initial import of version 2.9.3 source tree
363 *********************************************************************/
370 #include <sys/types.h>
373 #include <sys/stat.h>
377 #if !defined(_WIN32) && !defined(__OS2__)
387 #include "miscutil.h"
390 #include "urlmatch.h"
393 const char loaders_h_rcs[] = LOADERS_H_VERSION;
396 * Currently active files.
397 * These are also entered in the main linked list of files.
401 static struct file_list *current_trustfile = NULL;
402 #endif /* def FEATURE_TRUST */
404 static int load_one_re_filterfile(struct client_state *csp, int fileid);
406 static struct file_list *current_re_filterfile[MAX_AF_FILES] = {
407 NULL, NULL, NULL, NULL, NULL,
408 NULL, NULL, NULL, NULL, NULL
412 * Pseudo filter type for load_one_re_filterfile
414 #define NO_NEW_FILTER -1
417 /*********************************************************************
421 * Description : Basically a mark and sweep garbage collector, it is run
422 * (by the parent thread) every once in a while to reclaim memory.
424 * It uses a mark and sweep strategy:
425 * 1) mark all files as inactive
427 * 2) check with each client:
428 * if it is active, mark its files as active
429 * if it is inactive, free its resources
431 * 3) free the resources of all of the files that
432 * are still marked as inactive (and are obsolete).
434 * N.B. files that are not obsolete don't have an unloader defined.
440 *********************************************************************/
443 struct file_list *fl, *nfl;
444 struct client_state *csp, *last_active;
447 /* clear all of the file's active flags */
448 for ( fl = files->next; NULL != fl; fl = fl->next )
453 last_active = clients;
458 if (csp->flags & CSP_FLAG_ACTIVE)
460 /* Mark this client's files as active */
463 * Always have a configuration file.
464 * (Also note the slightly non-standard extra
467 csp->config->config_file_list->active = 1;
472 for (i = 0; i < MAX_AF_FILES; i++)
474 if (csp->actions_list[i])
476 csp->actions_list[i]->active = 1;
483 for (i = 0; i < MAX_AF_FILES; i++)
487 csp->rlist[i]->active = 1;
497 csp->tlist->active = 1;
499 #endif /* def FEATURE_TRUST */
507 * This client is not active. Free its resources.
510 last_active->next = csp->next;
512 freez(csp->ip_addr_str);
513 freez(csp->iob->buf);
514 freez(csp->x_forwarded_for);
515 freez(csp->error_message);
517 if (csp->action->flags & ACTION_FORWARD_OVERRIDE &&
520 unload_forward_spec(csp->fwd);
522 free_http_request(csp->http);
524 destroy_list(csp->headers);
525 destroy_list(csp->tags);
527 free_current_action(csp->action);
529 #ifdef FEATURE_STATISTICS
531 if (csp->flags & CSP_FLAG_REJECTED)
535 #endif /* def FEATURE_STATISTICS */
539 csp = last_active->next;
548 if ( ( 0 == fl->active ) && ( NULL != fl->unloader ) )
550 nfl->next = fl->next;
552 (fl->unloader)(fl->f);
569 /*********************************************************************
571 * Function : check_file_changed
573 * Description : Helper function to check if a file needs reloading.
574 * If "current" is still current, return it. Otherwise
575 * allocates a new (zeroed) "struct file_list", fills
576 * in the disk file name and timestamp, and returns it.
579 * 1 : current = The file_list currently being used - will
580 * be checked to see if it is out of date.
581 * May be NULL (which is treated as out of
583 * 2 : filename = Name of file to check.
584 * 3 : newfl = New file list. [Output only]
585 * This will be set to NULL, OR a struct
586 * file_list newly allocated on the
587 * heap, with the filename and lastmodified
588 * fields filled, and all others zeroed.
590 * Returns : If file unchanged: 0 (and sets newfl == NULL)
591 * If file changed: 1 and sets newfl != NULL
592 * On error: 1 and sets newfl == NULL
594 *********************************************************************/
595 int check_file_changed(const struct file_list * current,
596 const char * filename,
597 struct file_list ** newfl)
599 struct file_list *fs;
600 struct stat statbuf[1];
604 if (stat(filename, statbuf) < 0)
606 /* Error, probably file not found. */
611 && (current->lastmodified == statbuf->st_mtime)
612 && (0 == strcmp(current->filename, filename)))
617 fs = (struct file_list *)zalloc(sizeof(struct file_list));
620 /* Out of memory error */
625 fs->filename = strdup(filename);
626 fs->lastmodified = statbuf->st_mtime;
628 if (fs->filename == NULL)
630 /* Out of memory error */
639 /*********************************************************************
641 * Function : simple_read_line
643 * Description : Read a single line from a file and return it.
644 * This is basically a version of fgets() that malloc()s
645 * it's own line buffer. Note that the buffer will
646 * always be a multiple of BUFFER_SIZE bytes long.
647 * Therefore if you are going to keep the string for
648 * an extended period of time, you should probably
649 * strdup() it and free() the original, to save memory.
653 * 1 : dest = destination for newly malloc'd pointer to
654 * line data. Will be set to NULL on error.
655 * 2 : fp = File to read from
656 * 3 : newline = Standard for newlines in the file.
657 * Will be unchanged if it's value on input is not
659 * On output, may be changed from NEWLINE_UNKNOWN to
660 * actual convention in file.
662 * Returns : JB_ERR_OK on success
663 * JB_ERR_MEMORY on out-of-memory
664 * JB_ERR_FILE on EOF.
666 *********************************************************************/
667 jb_err simple_read_line(FILE *fp, char **dest, int *newline)
670 size_t buflen = BUFFER_SIZE;
674 int realnewline = NEWLINE_UNKNOWN;
676 if (NULL == (buf = malloc(buflen)))
678 return JB_ERR_MEMORY;
684 * Character codes. If you have a wierd compiler and the following are
685 * incorrect, you also need to fix NEWLINE() in loaders.h
687 #define CHAR_CR '\r' /* ASCII 13 */
688 #define CHAR_LF '\n' /* ASCII 10 */
708 else if (ch == CHAR_CR)
713 if (*newline == NEWLINE_UNKNOWN)
715 *newline = NEWLINE_DOS;
724 if (*newline == NEWLINE_UNKNOWN)
726 *newline = NEWLINE_MAC;
731 if (*newline == NEWLINE_UNKNOWN)
733 *newline = realnewline;
737 else if (ch == CHAR_LF)
741 if (*newline == NEWLINE_UNKNOWN)
743 *newline = NEWLINE_UNIX;
758 buflen += BUFFER_SIZE;
759 if (NULL == (p = realloc(buf, buflen)))
762 return JB_ERR_MEMORY;
771 /*********************************************************************
773 * Function : edit_read_line
775 * Description : Read a single non-empty line from a file and return
776 * it. Trims comments, leading and trailing whitespace
777 * and respects escaping of newline and comment char.
778 * Provides the line in 2 alternative forms: raw and
780 * - raw is the raw data read from the file. If the
781 * line is not modified, then this should be written
783 * - prefix is any comments and blank lines that were
784 * read from the file. If the line is modified, then
785 * this should be written out to the file followed
786 * by the modified data. (If this string is non-empty
787 * then it will have a newline at the end).
788 * - data is the actual data that will be parsed
789 * further by appropriate routines.
790 * On EOF, the 3 strings will all be set to NULL and
791 * 0 will be returned.
794 * 1 : fp = File to read from
795 * 2 : raw_out = destination for newly malloc'd pointer to
796 * raw line data. May be NULL if you don't want it.
797 * 3 : prefix_out = destination for newly malloc'd pointer to
798 * comments. May be NULL if you don't want it.
799 * 4 : data_out = destination for newly malloc'd pointer to
800 * line data with comments and leading/trailing spaces
801 * removed, and line continuation performed. May be
802 * NULL if you don't want it.
803 * 5 : newline = Standard for newlines in the file.
804 * On input, set to value to use or NEWLINE_UNKNOWN.
805 * On output, may be changed from NEWLINE_UNKNOWN to
806 * actual convention in file. May be NULL if you
808 * 6 : line_number = Line number in file. In "lines" as
809 * reported by a text editor, not lines containing data.
811 * Returns : JB_ERR_OK on success
812 * JB_ERR_MEMORY on out-of-memory
813 * JB_ERR_FILE on EOF.
815 *********************************************************************/
816 jb_err edit_read_line(FILE *fp,
821 unsigned long *line_number)
823 char *p; /* Temporary pointer */
824 char *linebuf; /* Line read from file */
825 char *linestart; /* Start of linebuf, usually first non-whitespace char */
826 int contflag = 0; /* Nonzero for line continuation - i.e. line ends '\' */
827 int is_empty = 1; /* Flag if not got any data yet */
828 char *raw = NULL; /* String to be stored in raw_out */
829 char *prefix = NULL; /* String to be stored in prefix_out */
830 char *data = NULL; /* String to be stored in data_out */
831 int scrapnewline; /* Used for (*newline) if newline==NULL */
832 jb_err rval = JB_ERR_OK;
835 assert(raw_out || data_out);
836 assert(newline == NULL
837 || *newline == NEWLINE_UNKNOWN
838 || *newline == NEWLINE_UNIX
839 || *newline == NEWLINE_DOS
840 || *newline == NEWLINE_MAC);
844 scrapnewline = NEWLINE_UNKNOWN;
845 newline = &scrapnewline;
848 /* Set output parameters to NULL */
862 /* Set string variables to new, empty strings. */
866 if ((raw = malloc(1)) == NULL)
868 return JB_ERR_MEMORY;
874 if ((prefix = malloc(1)) == NULL)
877 return JB_ERR_MEMORY;
883 if ((data = malloc(1)) == NULL)
887 return JB_ERR_MEMORY;
892 /* Main loop. Loop while we need more data & it's not EOF. */
894 while ( (contflag || is_empty)
895 && (JB_ERR_OK == (rval = simple_read_line(fp, &linebuf, newline))))
903 string_append(&raw,linebuf);
904 if (string_append(&raw,NEWLINE(*newline)))
909 return JB_ERR_MEMORY;
913 /* Line continuation? Trim escape and set flag. */
914 p = linebuf + strlen(linebuf) - 1;
915 contflag = ((*linebuf != '\0') && (*p == '\\'));
921 /* Trim leading spaces if we're at the start of the line */
925 /* Trim leading spaces */
926 while (*linestart && isspace((int)(unsigned char)*linestart))
932 /* Handle comment characters. */
934 while ((p = strchr(p, '#')) != NULL)
936 /* Found a comment char.. */
937 if ((p != linebuf) && (*(p-1) == '\\'))
939 /* ..and it's escaped, left-shift the line over the escape. */
941 while ((*q = *(q + 1)) != '\0')
945 /* Now scan from just after the "#". */
949 /* Real comment. Save it... */
952 /* Special case: Line only contains a comment, so all the
953 * previous whitespace is considered part of the comment.
954 * Undo the whitespace skipping, if any.
961 string_append(&prefix,p);
962 if (string_append(&prefix, NEWLINE(*newline)))
967 return JB_ERR_MEMORY;
971 /* ... and chop off the rest of the line */
974 } /* END while (there's a # character) */
976 /* Write to the buffer */
982 if (string_append(&data, linestart))
987 return JB_ERR_MEMORY;
993 } /* END while(we need more data) */
995 /* Handle simple_read_line() errors - ignore EOF */
996 if ((rval != JB_ERR_OK) && (rval != JB_ERR_FILE))
1004 if (raw ? (*raw == '\0') : is_empty)
1006 /* EOF and no data there. (Definition of "data" depends on whether
1007 * the caller cares about "raw" or just "data").
1018 /* Got at least some data */
1020 /* Remove trailing whitespace */
1033 *prefix_out = prefix;
1052 /*********************************************************************
1054 * Function : read_config_line
1056 * Description : Read a single non-empty line from a file and return
1057 * it. Trims comments, leading and trailing whitespace
1058 * and respects escaping of newline and comment char.
1061 * 1 : buf = Buffer to use.
1062 * 2 : buflen = Size of buffer in bytes.
1063 * 3 : fp = File to read from
1064 * 4 : linenum = linenumber in file
1066 * Returns : NULL on EOF or error
1067 * Otherwise, returns buf.
1069 *********************************************************************/
1070 char *read_config_line(char *buf, size_t buflen, FILE *fp, unsigned long *linenum)
1074 err = edit_read_line(fp, NULL, NULL, &buf2, NULL, linenum);
1077 if (err == JB_ERR_MEMORY)
1079 log_error(LOG_LEVEL_FATAL, "Out of memory loading a config file");
1086 assert(strlen(buf2) + 1U < buflen);
1087 strncpy(buf, buf2, buflen - 1);
1089 buf[buflen - 1] = '\0';
1095 #ifdef FEATURE_TRUST
1096 /*********************************************************************
1098 * Function : unload_trustfile
1100 * Description : Unloads a trustfile.
1103 * 1 : f = the data structure associated with the trustfile.
1107 *********************************************************************/
1108 static void unload_trustfile(void *f)
1110 struct block_spec *cur = (struct block_spec *)f;
1111 struct block_spec *next;
1117 free_url_spec(cur->url);
1126 #ifdef FEATURE_GRACEFUL_TERMINATION
1127 /*********************************************************************
1129 * Function : unload_current_trust_file
1131 * Description : Unloads current trust file - reset to state at
1132 * beginning of program.
1138 *********************************************************************/
1139 void unload_current_trust_file(void)
1141 if (current_trustfile)
1143 current_trustfile->unloader = unload_trustfile;
1144 current_trustfile = NULL;
1147 #endif /* FEATURE_GRACEFUL_TERMINATION */
1150 /*********************************************************************
1152 * Function : load_trustfile
1154 * Description : Read and parse a trustfile and add to files list.
1157 * 1 : csp = Current client state (buffers, headers, etc...)
1159 * Returns : 0 => Ok, everything else is an error.
1161 *********************************************************************/
1162 int load_trustfile(struct client_state *csp)
1166 struct block_spec *b, *bl;
1167 struct url_spec **tl;
1169 char buf[BUFFER_SIZE], *p, *q;
1170 int reject, trusted;
1171 struct file_list *fs;
1172 unsigned long linenum = 0;
1173 int trusted_referrers = 0;
1175 if (!check_file_changed(current_trustfile, csp->config->trustfile, &fs))
1177 /* No need to load */
1180 csp->tlist = current_trustfile;
1186 goto load_trustfile_error;
1189 fs->f = bl = (struct block_spec *)zalloc(sizeof(*bl));
1192 goto load_trustfile_error;
1195 if ((fp = fopen(csp->config->trustfile, "r")) == NULL)
1197 goto load_trustfile_error;
1200 tl = csp->config->trust_list;
1202 while (read_config_line(buf, sizeof(buf), fp, &linenum) != NULL)
1218 while ((*p++ = *q++) != '\0')
1224 /* skip blank lines */
1230 /* allocate a new node */
1231 if ((b = zalloc(sizeof(*b))) == NULL)
1234 goto load_trustfile_error;
1237 /* add it to the list */
1243 /* Save the URL pattern */
1244 if (create_url_spec(b->url, buf))
1247 goto load_trustfile_error;
1251 * save a pointer to URL's spec in the list of trusted URL's, too
1255 if(++trusted_referrers < MAX_TRUSTED_REFERRERS)
1262 if(trusted_referrers >= MAX_TRUSTED_REFERRERS)
1265 * FIXME: ... after Privoxy 3.0.4 is out.
1267 log_error(LOG_LEVEL_ERROR, "Too many trusted referrers. Current limit is %d, you are using %d.\n"
1268 " Additional trusted referrers are treated like ordinary trusted URLs.\n"
1269 " (You can increase this limit by changing MAX_TRUSTED_REFERRERS in project.h and recompiling).",
1270 MAX_TRUSTED_REFERRERS, trusted_referrers);
1277 /* the old one is now obsolete */
1278 if (current_trustfile)
1280 current_trustfile->unloader = unload_trustfile;
1283 fs->next = files->next;
1285 current_trustfile = fs;
1294 load_trustfile_error:
1295 log_error(LOG_LEVEL_FATAL, "can't load trustfile '%s': %E",
1296 csp->config->trustfile);
1300 #endif /* def FEATURE_TRUST */
1303 /*********************************************************************
1305 * Function : unload_re_filterfile
1307 * Description : Unload the re_filter list by freeing all chained
1308 * re_filterfile specs and their data.
1311 * 1 : f = the data structure associated with the filterfile.
1315 *********************************************************************/
1316 static void unload_re_filterfile(void *f)
1318 struct re_filterfile_spec *a, *b = (struct re_filterfile_spec *)f;
1324 destroy_list(b->patterns);
1325 pcrs_free_joblist(b->joblist);
1327 freez(b->description);
1336 /*********************************************************************
1338 * Function : unload_forward_spec
1340 * Description : Unload the forward spec settings by freeing all
1341 * memory referenced by members and the memory for
1345 * 1 : fwd = the forward spec.
1349 *********************************************************************/
1350 void unload_forward_spec(struct forward_spec *fwd)
1352 free_url_spec(fwd->url);
1353 freez(fwd->gateway_host);
1354 freez(fwd->forward_host);
1361 #ifdef FEATURE_GRACEFUL_TERMINATION
1362 /*********************************************************************
1364 * Function : unload_current_re_filterfile
1366 * Description : Unloads current re_filter file - reset to state at
1367 * beginning of program.
1373 *********************************************************************/
1374 void unload_current_re_filterfile(void)
1378 for (i = 0; i < MAX_AF_FILES; i++)
1380 if (current_re_filterfile[i])
1382 current_re_filterfile[i]->unloader = unload_re_filterfile;
1383 current_re_filterfile[i] = NULL;
1390 /*********************************************************************
1392 * Function : load_re_filterfiles
1394 * Description : Loads all the filterfiles.
1395 * Generate a chained list of re_filterfile_spec's from
1396 * the "FILTER: " blocks, compiling all their substitutions
1397 * into chained lists of pcrs_job structs.
1400 * 1 : csp = Current client state (buffers, headers, etc...)
1402 * Returns : 0 => Ok, everything else is an error.
1404 *********************************************************************/
1405 int load_re_filterfiles(struct client_state *csp)
1410 for (i = 0; i < MAX_AF_FILES; i++)
1412 if (csp->config->re_filterfile[i])
1414 result = load_one_re_filterfile(csp, i);
1420 else if (current_re_filterfile[i])
1422 current_re_filterfile[i]->unloader = unload_re_filterfile;
1423 current_re_filterfile[i] = NULL;
1431 /*********************************************************************
1433 * Function : load_one_re_filterfile
1435 * Description : Load a re_filterfile.
1436 * Generate a chained list of re_filterfile_spec's from
1437 * the "FILTER: " blocks, compiling all their substitutions
1438 * into chained lists of pcrs_job structs.
1441 * 1 : csp = Current client state (buffers, headers, etc...)
1443 * Returns : 0 => Ok, everything else is an error.
1445 *********************************************************************/
1446 int load_one_re_filterfile(struct client_state *csp, int fileid)
1450 struct re_filterfile_spec *new_bl, *bl = NULL;
1451 struct file_list *fs;
1453 char buf[BUFFER_SIZE];
1455 unsigned long linenum = 0;
1456 pcrs_job *dummy, *lastjob = NULL;
1459 * No need to reload if unchanged
1461 if (!check_file_changed(current_re_filterfile[fileid], csp->config->re_filterfile[fileid], &fs))
1465 csp->rlist[fileid] = current_re_filterfile[fileid];
1471 goto load_re_filterfile_error;
1475 * Open the file or fail
1477 if ((fp = fopen(csp->config->re_filterfile[fileid], "r")) == NULL)
1479 goto load_re_filterfile_error;
1485 while (read_config_line(buf, sizeof(buf), fp, &linenum) != NULL)
1487 int new_filter = NO_NEW_FILTER;
1489 if (strncmp(buf, "FILTER:", 7) == 0)
1491 new_filter = FT_CONTENT_FILTER;
1493 else if (strncmp(buf, "SERVER-HEADER-FILTER:", 21) == 0)
1495 new_filter = FT_SERVER_HEADER_FILTER;
1497 else if (strncmp(buf, "CLIENT-HEADER-FILTER:", 21) == 0)
1499 new_filter = FT_CLIENT_HEADER_FILTER;
1501 else if (strncmp(buf, "CLIENT-HEADER-TAGGER:", 21) == 0)
1503 new_filter = FT_CLIENT_HEADER_TAGGER;
1505 else if (strncmp(buf, "SERVER-HEADER-TAGGER:", 21) == 0)
1507 new_filter = FT_SERVER_HEADER_TAGGER;
1511 * If this is the head of a new filter block, make it a
1512 * re_filterfile spec of its own and chain it to the list:
1514 if (new_filter != NO_NEW_FILTER)
1516 new_bl = (struct re_filterfile_spec *)zalloc(sizeof(*bl));
1519 goto load_re_filterfile_error;
1521 if (new_filter == FT_CONTENT_FILTER)
1523 new_bl->name = chomp(buf + 7);
1527 new_bl->name = chomp(buf + 21);
1529 new_bl->type = new_filter;
1532 * If a filter description is available,
1533 * encode it to HTML and save it.
1535 if (NULL != (new_bl->description = strpbrk(new_bl->name, " \t")))
1537 *new_bl->description++ = '\0';
1538 new_bl->description = html_encode(chomp(new_bl->description));
1539 if (NULL == new_bl->description)
1541 new_bl->description = strdup("Out of memory while encoding this filter's description to HTML");
1546 new_bl->description = strdup("No description available for this filter");
1549 new_bl->name = strdup(chomp(new_bl->name));
1552 * If this is the first filter block, chain it
1553 * to the file_list rather than its (nonexistant)
1566 log_error(LOG_LEVEL_RE_FILTER, "Reading in filter \"%s\" (\"%s\")", bl->name, bl->description);
1572 * Else, save the expression, make it a pcrs_job
1573 * and chain it into the current filter's joblist
1577 error = enlist(bl->patterns, buf);
1578 if (JB_ERR_MEMORY == error)
1580 log_error(LOG_LEVEL_FATAL,
1581 "Out of memory while enlisting re_filter job \'%s\' for filter %s.", buf, bl->name);
1583 assert(JB_ERR_OK == error);
1585 if (pcrs_job_is_dynamic(buf))
1588 * Dynamic pattern that might contain variables
1589 * and has to be recompiled for every request
1591 if (bl->joblist != NULL)
1593 pcrs_free_joblist(bl->joblist);
1597 log_error(LOG_LEVEL_RE_FILTER,
1598 "Adding dynamic re_filter job \'%s\' to filter %s succeeded.", buf, bl->name);
1601 else if (bl->dynamic)
1604 * A previous job was dynamic and as we
1605 * recompile the whole filter anyway, it
1606 * makes no sense to compile this job now.
1608 log_error(LOG_LEVEL_RE_FILTER,
1609 "Adding static re_filter job \'%s\' to dynamic filter %s succeeded.", buf, bl->name);
1613 if ((dummy = pcrs_compile_command(buf, &error)) == NULL)
1615 log_error(LOG_LEVEL_ERROR,
1616 "Adding re_filter job \'%s\' to filter %s failed with error %d.", buf, bl->name, error);
1621 if (bl->joblist == NULL)
1623 bl->joblist = dummy;
1627 lastjob->next = dummy;
1630 log_error(LOG_LEVEL_RE_FILTER, "Adding re_filter job \'%s\' to filter %s succeeded.", buf, bl->name);
1635 log_error(LOG_LEVEL_ERROR, "Ignoring job %s outside filter block in %s, line %d",
1636 buf, csp->config->re_filterfile[fileid], linenum);
1643 * Schedule the now-obsolete old data for unloading
1645 if ( NULL != current_re_filterfile[fileid] )
1647 current_re_filterfile[fileid]->unloader = unload_re_filterfile;
1651 * Chain this file into the global list of loaded files
1653 fs->next = files->next;
1655 current_re_filterfile[fileid] = fs;
1659 csp->rlist[fileid] = fs;
1664 load_re_filterfile_error:
1665 log_error(LOG_LEVEL_FATAL, "can't load re_filterfile '%s': %E",
1666 csp->config->re_filterfile[fileid]);
1672 /*********************************************************************
1674 * Function : add_loader
1676 * Description : Called from `load_config'. Called once for each input
1677 * file found in config.
1680 * 1 : loader = pointer to a function that can parse and load
1681 * the appropriate config file.
1682 * 2 : config = The configuration_spec to add the loader to.
1686 *********************************************************************/
1687 void add_loader(int (*loader)(struct client_state *),
1688 struct configuration_spec * config)
1692 for (i=0; i < NLOADERS; i++)
1694 if (config->loaders[i] == NULL)
1696 config->loaders[i] = loader;
1704 /*********************************************************************
1706 * Function : run_loader
1708 * Description : Called from `load_config' and `listen_loop'. This
1709 * function keeps the "csp" current with any file mods
1710 * since the last loop. If a file is unchanged, the
1711 * loader functions do NOT reload the file.
1714 * 1 : csp = Current client state (buffers, headers, etc...)
1715 * Must be non-null. Reads: "csp->config"
1716 * Writes: various data members.
1718 * Returns : 0 => Ok, everything else is an error.
1720 *********************************************************************/
1721 int run_loader(struct client_state *csp)
1726 for (i=0; i < NLOADERS; i++)
1728 if (csp->config->loaders[i] == NULL)
1732 ret |= (csp->config->loaders[i])(csp);