1 const char loaders_rcs[] = "$Id: loaders.c,v 1.61 2007/04/15 16:39:21 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.61 2007/04/15 16:39:21 fabiankeil
39 * Introduce tags as alternative way to specify which
40 * actions apply to a request. At the moment tags can be
41 * created based on client and server headers.
43 * Revision 1.60 2007/03/20 15:16:34 fabiankeil
44 * Use dedicated header filter actions instead of abusing "filter".
45 * Replace "filter-client-headers" and "filter-client-headers"
46 * with "server-header-filter" and "client-header-filter".
48 * Revision 1.59 2007/01/25 13:38:20 fabiankeil
49 * Freez csp->error_message in sweep().
51 * Revision 1.58 2006/12/31 14:25:20 fabiankeil
52 * Fix gcc43 compiler warnings.
54 * Revision 1.57 2006/12/21 12:22:22 fabiankeil
55 * html_encode filter descriptions.
57 * Have "Ignoring job ..." error messages
58 * print the filter file name correctly.
60 * Revision 1.56 2006/09/07 10:40:30 fabiankeil
61 * Turns out trusted referrers above our arbitrary
62 * limit are downgraded too ordinary trusted URLs.
63 * Adjusted error message.
65 * Revision 1.55 2006/09/07 10:25:39 fabiankeil
68 * Revision 1.54 2006/09/07 10:22:20 fabiankeil
69 * If too many trusted referrers are used,
70 * print only one error message instead of logging
71 * every single trusted referrer above the arbitrary
74 * Revision 1.53 2006/08/31 16:25:06 fabiankeil
75 * Work around a buffer overflow that caused Privoxy to
76 * segfault if too many trusted referrers were used. Good
77 * enough for now, but should be replaced with a real
78 * solution after the next release.
80 * Revision 1.52 2006/07/18 14:48:46 david__schmidt
81 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
82 * with what was really the latest development (the v_3_0_branch branch)
84 * Revision 1.50.2.8 2006/01/30 15:16:25 david__schmidt
85 * Remove a little residual debugging info
87 * Revision 1.50.2.7 2006/01/29 23:10:56 david__schmidt
88 * Multiple filter file support
90 * Revision 1.50.2.6 2003/10/24 10:17:54 oes
91 * Nit: Allowed tabs as separators in filter headings
93 * Revision 1.50.2.5 2003/05/08 15:19:15 oes
94 * sweep: Made loop structure of sweep step mirror that of mark step
96 * Revision 1.50.2.4 2003/05/06 15:57:12 oes
97 * Bugfix: Update last_active pointer in sweep() before
98 * leaving an active client. Closes bugs #724395, #727882
100 * Revision 1.50.2.3 2002/11/20 17:12:30 oes
101 * Ooops, forgot one change.
103 * Revision 1.50.2.2 2002/11/20 14:38:15 oes
104 * Fixed delayed/incomplete freeing of client resources and
105 * simplified loop structure in sweep.
106 * Thanks to Oliver Stoeneberg for the hint.
108 * Revision 1.50.2.1 2002/07/26 15:19:24 oes
109 * - PCRS jobs now chained in order of appearance. Previous
110 * reverse chaining was counter-intuitive.
111 * - Changed loglevel of PCRS job compile errors to
114 * Revision 1.50 2002/04/24 02:12:16 oes
115 * Jon's multiple AF patch: Sweep now takes care of all AFs
117 * Revision 1.49 2002/04/19 16:53:25 jongfoster
118 * Optimize away a function call by using an equivalent macro
120 * Revision 1.48 2002/04/05 00:56:09 gliptak
121 * Correcting typo to clean up on realloc failure
123 * Revision 1.47 2002/03/26 22:29:55 swa
124 * we have a new homepage!
126 * Revision 1.46 2002/03/24 13:25:43 swa
127 * name change related issues
129 * Revision 1.45 2002/03/16 23:54:06 jongfoster
130 * Adding graceful termination feature, to help look for memory leaks.
131 * If you enable this (which, by design, has to be done by hand
132 * editing config.h) and then go to http://i.j.b/die, then the program
133 * will exit cleanly after the *next* request. It should free all the
134 * memory that was used.
136 * Revision 1.44 2002/03/16 21:51:00 jongfoster
139 * Revision 1.43 2002/03/16 20:28:34 oes
140 * Added descriptions to the filters so users will know what they select in the cgi editor
142 * Revision 1.42 2002/03/13 00:27:05 jongfoster
145 * Revision 1.41 2002/03/12 01:42:50 oes
146 * Introduced modular filters
148 * Revision 1.40 2002/03/08 17:46:04 jongfoster
149 * Fixing int/size_t warnings
151 * Revision 1.39 2002/03/07 03:46:17 oes
152 * Fixed compiler warnings
154 * Revision 1.38 2002/03/06 22:54:35 jongfoster
155 * Automated function-comment nitpicking.
157 * Revision 1.37 2002/03/03 15:07:49 oes
158 * Re-enabled automatic config reloading
160 * Revision 1.36 2002/01/22 23:46:18 jongfoster
161 * Moving edit_read_line() and simple_read_line() to loaders.c, and
162 * extending them to support reading MS-DOS, Mac and UNIX style files
165 * Modifying read_config_line() (without changing it's prototype) to
166 * be a trivial wrapper for edit_read_line(). This means that we have
167 * one function to read a line and handle comments, which is common
168 * between the initialization code and the edit interface.
170 * Revision 1.35 2002/01/17 21:03:08 jongfoster
171 * Moving all our URL and URL pattern parsing code to urlmatch.c.
173 * Renaming free_url to free_url_spec, since it frees a struct url_spec.
175 * Revision 1.34 2001/12/30 14:07:32 steudten
176 * - Add signal handling (unix)
177 * - Add SIGHUP handler (unix)
178 * - Add creation of pidfile (unix)
179 * - Add action 'top' in rc file (RH)
180 * - Add entry 'SIGNALS' to manpage
181 * - Add exit message to logfile (unix)
183 * Revision 1.33 2001/11/13 00:16:38 jongfoster
184 * Replacing references to malloc.h with the standard stdlib.h
185 * (See ANSI or K&R 2nd Ed)
187 * Revision 1.32 2001/11/07 00:02:13 steudten
188 * Add line number in error output for lineparsing for
189 * actionsfile and configfile.
190 * Special handling for CLF added.
192 * Revision 1.31 2001/10/26 17:39:01 oes
193 * Removed csp->referrer
194 * Moved ijb_isspace and ijb_tolower to project.h
196 * Revision 1.30 2001/10/25 03:40:48 david__schmidt
197 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
198 * threads to call select() simultaneously. So, it's time to do a real, live,
199 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
200 * (native). Both versions will work, but using __OS2__ offers multi-threading.
202 * Revision 1.29 2001/10/23 21:38:53 jongfoster
203 * Adding error-checking to create_url_spec()
205 * Revision 1.28 2001/10/07 15:40:39 oes
206 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
208 * Revision 1.27 2001/09/22 16:36:59 jongfoster
209 * Removing unused parameter fs from read_config_line()
211 * Revision 1.26 2001/09/22 14:05:22 jongfoster
212 * Bugfix: Multiple escaped "#" characters in a configuration
213 * file are now permitted.
214 * Also removing 3 unused headers.
216 * Revision 1.25 2001/09/13 22:44:03 jongfoster
217 * Adding {} to an if statement
219 * Revision 1.24 2001/07/30 22:08:36 jongfoster
220 * Tidying up #defines:
221 * - All feature #defines are now of the form FEATURE_xxx
222 * - Permanently turned off WIN_GUI_EDIT
223 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
225 * Revision 1.23 2001/07/20 15:51:54 oes
226 * Fixed indentation of prepocessor commands
228 * Revision 1.22 2001/07/20 15:16:17 haroon
229 * - per Guy's suggestion, added a while loop in sweep() to catch not just
230 * the last inactive CSP but all other consecutive inactive CSPs after that
233 * Revision 1.21 2001/07/18 17:26:24 oes
234 * Changed to conform to new pcrs interface
236 * Revision 1.20 2001/07/17 13:07:01 oes
237 * Fixed segv when last line in config files
238 * lacked a terminating (\r)\n
240 * Revision 1.19 2001/07/13 14:01:54 oes
241 * Removed all #ifdef PCRS
243 * Revision 1.18 2001/06/29 21:45:41 oes
244 * Indentation, CRLF->LF, Tab-> Space
246 * Revision 1.17 2001/06/29 13:31:51 oes
249 * Revision 1.16 2001/06/09 10:55:28 jongfoster
250 * Changing BUFSIZ ==> BUFFER_SIZE
252 * Revision 1.15 2001/06/07 23:14:14 jongfoster
253 * Removing ACL and forward file loaders - these
254 * files have been merged into the config file.
255 * Cosmetic: Moving unloader funcs next to their
256 * respective loader funcs
258 * Revision 1.14 2001/06/01 03:27:04 oes
259 * Fixed line continuation problem
261 * Revision 1.13 2001/05/31 21:28:49 jongfoster
262 * Removed all permissionsfile code - it's now called the actions
263 * file, and (almost) all the code is in actions.c
265 * Revision 1.12 2001/05/31 17:32:31 oes
267 * - Enhanced domain part globbing with infix and prefix asterisk
268 * matching and optional unanchored operation
270 * Revision 1.11 2001/05/29 23:25:24 oes
272 * - load_config_line() and load_permissions_file() now use chomp()
274 * Revision 1.10 2001/05/29 09:50:24 jongfoster
275 * Unified blocklist/imagelist/permissionslist.
276 * File format is still under discussion, but the internal changes
279 * Also modified interceptor behaviour:
280 * - We now intercept all URLs beginning with one of the following
281 * prefixes (and *only* these prefixes):
283 * * http://ijbswa.sf.net/config/
284 * * http://ijbswa.sourceforge.net/config/
285 * - New interceptors "home page" - go to http://i.j.b/ to see it.
286 * - Internal changes so that intercepted and fast redirect pages
287 * are not replaced with an image.
288 * - Interceptors now have the option to send a binary page direct
289 * to the client. (i.e. ijb-send-banner uses this)
290 * - Implemented show-url-info interceptor. (Which is why I needed
291 * the above interceptors changes - a typical URL is
292 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
293 * The previous mechanism would not have intercepted that, and
294 * if it had been intercepted then it then it would have replaced
297 * Revision 1.9 2001/05/26 17:12:07 jongfoster
298 * Fatal errors loading configuration files now give better error messages.
300 * Revision 1.8 2001/05/26 00:55:20 jongfoster
301 * Removing duplicated code. load_forwardfile() now uses create_url_spec()
303 * Revision 1.7 2001/05/26 00:28:36 jongfoster
304 * Automatic reloading of config file.
305 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
306 * Most of the global variables have been moved to a new
307 * struct configuration_spec, accessed through csp->config->globalname
308 * Most of the globals remaining are used by the Win32 GUI.
310 * Revision 1.6 2001/05/23 12:27:33 oes
312 * Fixed ugly indentation of my last changes
314 * Revision 1.5 2001/05/23 10:39:05 oes
315 * - Added support for escaping the comment character
316 * in config files by a backslash
317 * - Added support for line continuation in config
319 * - Fixed a buffer overflow bug with long config lines
321 * Revision 1.4 2001/05/22 18:56:28 oes
324 * Revision 1.3 2001/05/20 01:21:20 jongfoster
325 * Version 2.9.4 checkin.
326 * - Merged popupfile and cookiefile, and added control over PCRS
327 * filtering, in new "permissionsfile".
328 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
329 * file error you now get a message box (in the Win32 GUI) rather
330 * than the program exiting with no explanation.
331 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
333 * - Removed tabs from "config"
334 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
335 * - Bumped up version number.
337 * Revision 1.2 2001/05/17 23:01:01 oes
338 * - Cleaned CRLF's from the sources and related files
340 * Revision 1.1.1.1 2001/05/15 13:58:59 oes
341 * Initial import of version 2.9.3 source tree
344 *********************************************************************/
351 #include <sys/types.h>
354 #include <sys/stat.h>
358 #if !defined(_WIN32) && !defined(__OS2__)
368 #include "miscutil.h"
371 #include "urlmatch.h"
374 const char loaders_h_rcs[] = LOADERS_H_VERSION;
377 * Currently active files.
378 * These are also entered in the main linked list of files.
382 static struct file_list *current_trustfile = NULL;
383 #endif /* def FEATURE_TRUST */
385 static int load_one_re_filterfile(struct client_state *csp, int fileid);
387 static struct file_list *current_re_filterfile[MAX_AF_FILES] = {
388 NULL, NULL, NULL, NULL, NULL,
389 NULL, NULL, NULL, NULL, NULL
393 * Pseudo filter type for load_one_re_filterfile
395 #define NO_NEW_FILTER -1
398 /*********************************************************************
402 * Description : Basically a mark and sweep garbage collector, it is run
403 * (by the parent thread) every once in a while to reclaim memory.
405 * It uses a mark and sweep strategy:
406 * 1) mark all files as inactive
408 * 2) check with each client:
409 * if it is active, mark its files as active
410 * if it is inactive, free its resources
412 * 3) free the resources of all of the files that
413 * are still marked as inactive (and are obsolete).
415 * N.B. files that are not obsolete don't have an unloader defined.
421 *********************************************************************/
424 struct file_list *fl, *nfl;
425 struct client_state *csp, *last_active;
428 /* clear all of the file's active flags */
429 for ( fl = files->next; NULL != fl; fl = fl->next )
434 last_active = clients;
439 if (csp->flags & CSP_FLAG_ACTIVE)
441 /* Mark this client's files as active */
444 * Always have a configuration file.
445 * (Also note the slightly non-standard extra
448 csp->config->config_file_list->active = 1;
453 for (i = 0; i < MAX_AF_FILES; i++)
455 if (csp->actions_list[i])
457 csp->actions_list[i]->active = 1;
464 for (i = 0; i < MAX_AF_FILES; i++)
468 csp->rlist[i]->active = 1;
478 csp->tlist->active = 1;
480 #endif /* def FEATURE_TRUST */
488 * This client is not active. Free its resources.
491 last_active->next = csp->next;
493 freez(csp->ip_addr_str);
494 freez(csp->my_ip_addr_str);
495 freez(csp->my_hostname);
496 freez(csp->x_forwarded);
497 freez(csp->iob->buf);
498 freez(csp->error_message);
500 free_http_request(csp->http);
502 destroy_list(csp->headers);
503 destroy_list(csp->tags);
504 destroy_list(csp->cookie_list);
506 free_current_action(csp->action);
508 #ifdef FEATURE_STATISTICS
510 if (csp->flags & CSP_FLAG_REJECTED)
514 #endif /* def FEATURE_STATISTICS */
518 csp = last_active->next;
527 if ( ( 0 == fl->active ) && ( NULL != fl->unloader ) )
529 nfl->next = fl->next;
531 (fl->unloader)(fl->f);
548 /*********************************************************************
550 * Function : check_file_changed
552 * Description : Helper function to check if a file needs reloading.
553 * If "current" is still current, return it. Otherwise
554 * allocates a new (zeroed) "struct file_list", fills
555 * in the disk file name and timestamp, and returns it.
558 * 1 : current = The file_list currently being used - will
559 * be checked to see if it is out of date.
560 * May be NULL (which is treated as out of
562 * 2 : filename = Name of file to check.
563 * 3 : newfl = New file list. [Output only]
564 * This will be set to NULL, OR a struct
565 * file_list newly allocated on the
566 * heap, with the filename and lastmodified
567 * fields filled, and all others zeroed.
569 * Returns : If file unchanged: 0 (and sets newfl == NULL)
570 * If file changed: 1 and sets newfl != NULL
571 * On error: 1 and sets newfl == NULL
573 *********************************************************************/
574 int check_file_changed(const struct file_list * current,
575 const char * filename,
576 struct file_list ** newfl)
578 struct file_list *fs;
579 struct stat statbuf[1];
583 if (stat(filename, statbuf) < 0)
585 /* Error, probably file not found. */
590 && (current->lastmodified == statbuf->st_mtime)
591 && (0 == strcmp(current->filename, filename)))
596 fs = (struct file_list *)zalloc(sizeof(struct file_list));
599 /* Out of memory error */
604 fs->filename = strdup(filename);
605 fs->lastmodified = statbuf->st_mtime;
607 if (fs->filename == NULL)
609 /* Out of memory error */
618 /*********************************************************************
620 * Function : simple_read_line
622 * Description : Read a single line from a file and return it.
623 * This is basically a version of fgets() that malloc()s
624 * it's own line buffer. Note that the buffer will
625 * always be a multiple of BUFFER_SIZE bytes long.
626 * Therefore if you are going to keep the string for
627 * an extended period of time, you should probably
628 * strdup() it and free() the original, to save memory.
632 * 1 : dest = destination for newly malloc'd pointer to
633 * line data. Will be set to NULL on error.
634 * 2 : fp = File to read from
635 * 3 : newline = Standard for newlines in the file.
636 * Will be unchanged if it's value on input is not
638 * On output, may be changed from NEWLINE_UNKNOWN to
639 * actual convention in file.
641 * Returns : JB_ERR_OK on success
642 * JB_ERR_MEMORY on out-of-memory
643 * JB_ERR_FILE on EOF.
645 *********************************************************************/
646 jb_err simple_read_line(FILE *fp, char **dest, int *newline)
649 size_t buflen = BUFFER_SIZE;
653 int realnewline = NEWLINE_UNKNOWN;
655 if (NULL == (buf = malloc(buflen)))
657 return JB_ERR_MEMORY;
663 * Character codes. If you have a wierd compiler and the following are
664 * incorrect, you also need to fix NEWLINE() in loaders.h
666 #define CHAR_CR '\r' /* ASCII 13 */
667 #define CHAR_LF '\n' /* ASCII 10 */
687 else if (ch == CHAR_CR)
692 if (*newline == NEWLINE_UNKNOWN)
694 *newline = NEWLINE_DOS;
703 if (*newline == NEWLINE_UNKNOWN)
705 *newline = NEWLINE_MAC;
710 if (*newline == NEWLINE_UNKNOWN)
712 *newline = realnewline;
716 else if (ch == CHAR_LF)
720 if (*newline == NEWLINE_UNKNOWN)
722 *newline = NEWLINE_UNIX;
737 buflen += BUFFER_SIZE;
738 if (NULL == (p = realloc(buf, buflen)))
741 return JB_ERR_MEMORY;
750 /*********************************************************************
752 * Function : edit_read_line
754 * Description : Read a single non-empty line from a file and return
755 * it. Trims comments, leading and trailing whitespace
756 * and respects escaping of newline and comment char.
757 * Provides the line in 2 alternative forms: raw and
759 * - raw is the raw data read from the file. If the
760 * line is not modified, then this should be written
762 * - prefix is any comments and blank lines that were
763 * read from the file. If the line is modified, then
764 * this should be written out to the file followed
765 * by the modified data. (If this string is non-empty
766 * then it will have a newline at the end).
767 * - data is the actual data that will be parsed
768 * further by appropriate routines.
769 * On EOF, the 3 strings will all be set to NULL and
770 * 0 will be returned.
773 * 1 : fp = File to read from
774 * 2 : raw_out = destination for newly malloc'd pointer to
775 * raw line data. May be NULL if you don't want it.
776 * 3 : prefix_out = destination for newly malloc'd pointer to
777 * comments. May be NULL if you don't want it.
778 * 4 : data_out = destination for newly malloc'd pointer to
779 * line data with comments and leading/trailing spaces
780 * removed, and line continuation performed. May be
781 * NULL if you don't want it.
782 * 5 : newline = Standard for newlines in the file.
783 * On input, set to value to use or NEWLINE_UNKNOWN.
784 * On output, may be changed from NEWLINE_UNKNOWN to
785 * actual convention in file. May be NULL if you
787 * 6 : line_number = Line number in file. In "lines" as
788 * reported by a text editor, not lines containing data.
790 * Returns : JB_ERR_OK on success
791 * JB_ERR_MEMORY on out-of-memory
792 * JB_ERR_FILE on EOF.
794 *********************************************************************/
795 jb_err edit_read_line(FILE *fp,
800 unsigned long *line_number)
802 char *p; /* Temporary pointer */
803 char *linebuf; /* Line read from file */
804 char *linestart; /* Start of linebuf, usually first non-whitespace char */
805 int contflag = 0; /* Nonzero for line continuation - i.e. line ends '\' */
806 int is_empty = 1; /* Flag if not got any data yet */
807 char *raw = NULL; /* String to be stored in raw_out */
808 char *prefix = NULL; /* String to be stored in prefix_out */
809 char *data = NULL; /* String to be stored in data_out */
810 int scrapnewline; /* Used for (*newline) if newline==NULL */
811 jb_err rval = JB_ERR_OK;
814 assert(raw_out || data_out);
815 assert(newline == NULL
816 || *newline == NEWLINE_UNKNOWN
817 || *newline == NEWLINE_UNIX
818 || *newline == NEWLINE_DOS
819 || *newline == NEWLINE_MAC);
823 scrapnewline = NEWLINE_UNKNOWN;
824 newline = &scrapnewline;
827 /* Set output parameters to NULL */
841 /* Set string variables to new, empty strings. */
845 if ((raw = malloc(1)) == NULL)
847 return JB_ERR_MEMORY;
853 if ((prefix = malloc(1)) == NULL)
856 return JB_ERR_MEMORY;
862 if ((data = malloc(1)) == NULL)
866 return JB_ERR_MEMORY;
871 /* Main loop. Loop while we need more data & it's not EOF. */
873 while ( (contflag || is_empty)
874 && (JB_ERR_OK == (rval = simple_read_line(fp, &linebuf, newline))))
882 string_append(&raw,linebuf);
883 if (string_append(&raw,NEWLINE(*newline)))
888 return JB_ERR_MEMORY;
892 /* Line continuation? Trim escape and set flag. */
893 p = linebuf + strlen(linebuf) - 1;
894 contflag = ((*linebuf != '\0') && (*p == '\\'));
900 /* Trim leading spaces if we're at the start of the line */
904 /* Trim leading spaces */
905 while (*linestart && isspace((int)(unsigned char)*linestart))
911 /* Handle comment characters. */
913 while ((p = strchr(p, '#')) != NULL)
915 /* Found a comment char.. */
916 if ((p != linebuf) && (*(p-1) == '\\'))
918 /* ..and it's escaped, left-shift the line over the escape. */
920 while ((*q = *(q + 1)) != '\0')
924 /* Now scan from just after the "#". */
928 /* Real comment. Save it... */
931 /* Special case: Line only contains a comment, so all the
932 * previous whitespace is considered part of the comment.
933 * Undo the whitespace skipping, if any.
940 string_append(&prefix,p);
941 if (string_append(&prefix, NEWLINE(*newline)))
946 return JB_ERR_MEMORY;
950 /* ... and chop off the rest of the line */
953 } /* END while (there's a # character) */
955 /* Write to the buffer */
961 if (string_append(&data, linestart))
966 return JB_ERR_MEMORY;
972 } /* END while(we need more data) */
974 /* Handle simple_read_line() errors - ignore EOF */
975 if ((rval != JB_ERR_OK) && (rval != JB_ERR_FILE))
983 if (raw ? (*raw == '\0') : is_empty)
985 /* EOF and no data there. (Definition of "data" depends on whether
986 * the caller cares about "raw" or just "data").
997 /* Got at least some data */
999 /* Remove trailing whitespace */
1012 *prefix_out = prefix;
1031 /*********************************************************************
1033 * Function : read_config_line
1035 * Description : Read a single non-empty line from a file and return
1036 * it. Trims comments, leading and trailing whitespace
1037 * and respects escaping of newline and comment char.
1040 * 1 : buf = Buffer to use.
1041 * 2 : buflen = Size of buffer in bytes.
1042 * 3 : fp = File to read from
1043 * 4 : linenum = linenumber in file
1045 * Returns : NULL on EOF or error
1046 * Otherwise, returns buf.
1048 *********************************************************************/
1049 char *read_config_line(char *buf, size_t buflen, FILE *fp, unsigned long *linenum)
1053 err = edit_read_line(fp, NULL, NULL, &buf2, NULL, linenum);
1056 if (err == JB_ERR_MEMORY)
1058 log_error(LOG_LEVEL_FATAL, "Out of memory loading a config file");
1065 assert(strlen(buf2) + 1U < buflen);
1066 strncpy(buf, buf2, buflen - 1);
1068 buf[buflen - 1] = '\0';
1074 #ifdef FEATURE_TRUST
1075 /*********************************************************************
1077 * Function : unload_trustfile
1079 * Description : Unloads a trustfile.
1082 * 1 : f = the data structure associated with the trustfile.
1086 *********************************************************************/
1087 static void unload_trustfile(void *f)
1089 struct block_spec *cur = (struct block_spec *)f;
1090 struct block_spec *next;
1096 free_url_spec(cur->url);
1105 #ifdef FEATURE_GRACEFUL_TERMINATION
1106 /*********************************************************************
1108 * Function : unload_current_trust_file
1110 * Description : Unloads current trust file - reset to state at
1111 * beginning of program.
1117 *********************************************************************/
1118 void unload_current_trust_file(void)
1120 if (current_trustfile)
1122 current_trustfile->unloader = unload_trustfile;
1123 current_trustfile = NULL;
1126 #endif /* FEATURE_GRACEFUL_TERMINATION */
1129 /*********************************************************************
1131 * Function : load_trustfile
1133 * Description : Read and parse a trustfile and add to files list.
1136 * 1 : csp = Current client state (buffers, headers, etc...)
1138 * Returns : 0 => Ok, everything else is an error.
1140 *********************************************************************/
1141 int load_trustfile(struct client_state *csp)
1145 struct block_spec *b, *bl;
1146 struct url_spec **tl;
1148 char buf[BUFFER_SIZE], *p, *q;
1149 int reject, trusted;
1150 struct file_list *fs;
1151 unsigned long linenum = 0;
1152 int trusted_referrers = 0;
1154 if (!check_file_changed(current_trustfile, csp->config->trustfile, &fs))
1156 /* No need to load */
1159 csp->tlist = current_trustfile;
1165 goto load_trustfile_error;
1168 fs->f = bl = (struct block_spec *)zalloc(sizeof(*bl));
1171 goto load_trustfile_error;
1174 if ((fp = fopen(csp->config->trustfile, "r")) == NULL)
1176 goto load_trustfile_error;
1179 tl = csp->config->trust_list;
1181 while (read_config_line(buf, sizeof(buf), fp, &linenum) != NULL)
1197 while ((*p++ = *q++) != '\0')
1203 /* skip blank lines */
1209 /* allocate a new node */
1210 if ((b = zalloc(sizeof(*b))) == NULL)
1213 goto load_trustfile_error;
1216 /* add it to the list */
1222 /* Save the URL pattern */
1223 if (create_url_spec(b->url, buf))
1226 goto load_trustfile_error;
1230 * save a pointer to URL's spec in the list of trusted URL's, too
1234 if(++trusted_referrers < MAX_TRUSTED_REFERRERS)
1241 if(trusted_referrers >= MAX_TRUSTED_REFERRERS)
1244 * FIXME: ... after Privoxy 3.0.4 is out.
1246 log_error(LOG_LEVEL_ERROR, "Too many trusted referrers. Current limit is %d, you are using %d.\n"
1247 " Additional trusted referrers are treated like ordinary trusted URLs.\n"
1248 " (You can increase this limit by changing MAX_TRUSTED_REFERRERS in project.h and recompiling).",
1249 MAX_TRUSTED_REFERRERS, trusted_referrers);
1256 /* the old one is now obsolete */
1257 if (current_trustfile)
1259 current_trustfile->unloader = unload_trustfile;
1262 fs->next = files->next;
1264 current_trustfile = fs;
1273 load_trustfile_error:
1274 log_error(LOG_LEVEL_FATAL, "can't load trustfile '%s': %E",
1275 csp->config->trustfile);
1279 #endif /* def FEATURE_TRUST */
1282 /*********************************************************************
1284 * Function : unload_re_filterfile
1286 * Description : Unload the re_filter list by freeing all chained
1287 * re_filterfile specs and their data.
1290 * 1 : f = the data structure associated with the filterfile.
1294 *********************************************************************/
1295 static void unload_re_filterfile(void *f)
1297 struct re_filterfile_spec *a, *b = (struct re_filterfile_spec *)f;
1303 destroy_list(b->patterns);
1304 pcrs_free_joblist(b->joblist);
1306 freez(b->description);
1316 #ifdef FEATURE_GRACEFUL_TERMINATION
1317 /*********************************************************************
1319 * Function : unload_current_re_filterfile
1321 * Description : Unloads current re_filter file - reset to state at
1322 * beginning of program.
1328 *********************************************************************/
1329 void unload_current_re_filterfile(void)
1333 for (i = 0; i < MAX_AF_FILES; i++)
1335 if (current_re_filterfile[i])
1337 current_re_filterfile[i]->unloader = unload_re_filterfile;
1338 current_re_filterfile[i] = NULL;
1345 /*********************************************************************
1347 * Function : load_re_filterfile
1349 * Description : Load the re_filterfile.
1350 * Generate a chained list of re_filterfile_spec's from
1351 * the "FILTER: " blocks, compiling all their substitutions
1352 * into chained lists of pcrs_job structs.
1355 * 1 : csp = Current client state (buffers, headers, etc...)
1357 * Returns : 0 => Ok, everything else is an error.
1359 *********************************************************************/
1360 int load_re_filterfile(struct client_state *csp)
1365 for (i = 0; i < MAX_AF_FILES; i++)
1367 if (csp->config->re_filterfile[i])
1369 result = load_one_re_filterfile(csp, i);
1375 else if (current_re_filterfile[i])
1377 current_re_filterfile[i]->unloader = unload_re_filterfile;
1378 current_re_filterfile[i] = NULL;
1386 /*********************************************************************
1388 * Function : load_one_re_filterfile
1390 * Description : Load a re_filterfile.
1391 * Generate a chained list of re_filterfile_spec's from
1392 * the "FILTER: " blocks, compiling all their substitutions
1393 * into chained lists of pcrs_job structs.
1396 * 1 : csp = Current client state (buffers, headers, etc...)
1398 * Returns : 0 => Ok, everything else is an error.
1400 *********************************************************************/
1401 int load_one_re_filterfile(struct client_state *csp, int fileid)
1405 struct re_filterfile_spec *new_bl, *bl = NULL;
1406 struct file_list *fs;
1408 char buf[BUFFER_SIZE];
1410 unsigned long linenum = 0;
1411 pcrs_job *dummy, *lastjob = NULL;
1414 * No need to reload if unchanged
1416 if (!check_file_changed(current_re_filterfile[fileid], csp->config->re_filterfile[fileid], &fs))
1420 csp->rlist[fileid] = current_re_filterfile[fileid];
1426 goto load_re_filterfile_error;
1430 * Open the file or fail
1432 if ((fp = fopen(csp->config->re_filterfile[fileid], "r")) == NULL)
1434 goto load_re_filterfile_error;
1440 while (read_config_line(buf, sizeof(buf), fp, &linenum) != NULL)
1442 int new_filter = NO_NEW_FILTER;
1444 if (strncmp(buf, "FILTER:", 7) == 0)
1446 new_filter = FT_CONTENT_FILTER;
1448 else if (strncmp(buf, "SERVER-HEADER-FILTER:", 21) == 0)
1450 new_filter = FT_SERVER_HEADER_FILTER;
1452 else if (strncmp(buf, "CLIENT-HEADER-FILTER:", 21) == 0)
1454 new_filter = FT_CLIENT_HEADER_FILTER;
1456 else if (strncmp(buf, "CLIENT-HEADER-TAGGER:", 21) == 0)
1458 new_filter = FT_CLIENT_HEADER_TAGGER;
1460 else if (strncmp(buf, "SERVER-HEADER-TAGGER:", 21) == 0)
1462 new_filter = FT_SERVER_HEADER_TAGGER;
1466 * If this is the head of a new filter block, make it a
1467 * re_filterfile spec of its own and chain it to the list:
1469 if (new_filter != NO_NEW_FILTER)
1471 new_bl = (struct re_filterfile_spec *)zalloc(sizeof(*bl));
1474 goto load_re_filterfile_error;
1476 if (new_filter == FT_CONTENT_FILTER)
1478 new_bl->name = chomp(buf + 7);
1482 new_bl->name = chomp(buf + 21);
1484 new_bl->type = new_filter;
1487 * If a filter description is available,
1488 * encode it to HTML and save it.
1490 if (NULL != (new_bl->description = strpbrk(new_bl->name, " \t")))
1492 *new_bl->description++ = '\0';
1493 new_bl->description = html_encode(chomp(new_bl->description));
1494 if (NULL == new_bl->description)
1496 new_bl->description = strdup("Out of memory while encoding this filter's description to HTML");
1501 new_bl->description = strdup("No description available for this filter");
1504 new_bl->name = strdup(chomp(new_bl->name));
1507 * If this is the first filter block, chain it
1508 * to the file_list rather than its (nonexistant)
1521 log_error(LOG_LEVEL_RE_FILTER, "Reading in filter \"%s\" (\"%s\")", bl->name, bl->description);
1527 * Else, save the expression, make it a pcrs_job
1528 * and chain it into the current filter's joblist
1532 error = enlist(bl->patterns, buf);
1533 if (JB_ERR_MEMORY == error)
1535 log_error(LOG_LEVEL_FATAL,
1536 "Out of memory while enlisting re_filter job \'%s\' for filter %s.", buf, bl->name);
1538 assert(JB_ERR_OK == error);
1540 if (pcrs_job_is_dynamic(buf))
1543 * Dynamic pattern that might contain variables
1544 * and has to be recompiled for every request
1546 if (bl->joblist != NULL)
1548 pcrs_free_joblist(bl->joblist);
1552 log_error(LOG_LEVEL_RE_FILTER,
1553 "Adding dynamic re_filter job \'%s\' to filter %s succeeded.", buf, bl->name);
1556 else if (bl->dynamic)
1559 * A previous job was dynamic and as we
1560 * recompile the whole filter anyway, it
1561 * makes no sense to compile this job now.
1563 log_error(LOG_LEVEL_RE_FILTER,
1564 "Adding static re_filter job \'%s\' to dynamic filter %s succeeded.", buf, bl->name);
1568 if ((dummy = pcrs_compile_command(buf, &error)) == NULL)
1570 log_error(LOG_LEVEL_ERROR,
1571 "Adding re_filter job \'%s\' to filter %s failed with error %d.", buf, bl->name, error);
1576 if (bl->joblist == NULL)
1578 bl->joblist = dummy;
1582 lastjob->next = dummy;
1585 log_error(LOG_LEVEL_RE_FILTER, "Adding re_filter job \'%s\' to filter %s succeeded.", buf, bl->name);
1590 log_error(LOG_LEVEL_ERROR, "Ignoring job %s outside filter block in %s, line %d",
1591 buf, csp->config->re_filterfile[fileid], linenum);
1598 * Schedule the now-obsolete old data for unloading
1600 if ( NULL != current_re_filterfile[fileid] )
1602 current_re_filterfile[fileid]->unloader = unload_re_filterfile;
1606 * Chain this file into the global list of loaded files
1608 fs->next = files->next;
1610 current_re_filterfile[fileid] = fs;
1614 csp->rlist[fileid] = fs;
1619 load_re_filterfile_error:
1620 log_error(LOG_LEVEL_FATAL, "can't load re_filterfile '%s': %E",
1621 csp->config->re_filterfile[fileid]);
1627 /*********************************************************************
1629 * Function : add_loader
1631 * Description : Called from `load_config'. Called once for each input
1632 * file found in config.
1635 * 1 : loader = pointer to a function that can parse and load
1636 * the appropriate config file.
1637 * 2 : config = The configuration_spec to add the loader to.
1641 *********************************************************************/
1642 void add_loader(int (*loader)(struct client_state *),
1643 struct configuration_spec * config)
1647 for (i=0; i < NLOADERS; i++)
1649 if (config->loaders[i] == NULL)
1651 config->loaders[i] = loader;
1659 /*********************************************************************
1661 * Function : run_loader
1663 * Description : Called from `load_config' and `listen_loop'. This
1664 * function keeps the "csp" current with any file mods
1665 * since the last loop. If a file is unchanged, the
1666 * loader functions do NOT reload the file.
1669 * 1 : csp = Current client state (buffers, headers, etc...)
1670 * Must be non-null. Reads: "csp->config"
1671 * Writes: various data members.
1673 * Returns : 0 => Ok, everything else is an error.
1675 *********************************************************************/
1676 int run_loader(struct client_state *csp)
1681 for (i=0; i < NLOADERS; i++)
1683 if (csp->config->loaders[i] == NULL)
1687 ret |= (csp->config->loaders[i])(csp);