- Add Matthias Drochner for providing the patch to
[privoxy.git] / loadcfg.c
1 const char loadcfg_rcs[] = "$Id: loadcfg.c,v 1.84 2009/01/14 16:14:36 fabiankeil Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/loadcfg.c,v $
5  *
6  * Purpose     :  Loads settings from the configuration file into
7  *                global variables.  This file contains both the
8  *                routine to load the configuration and the global
9  *                variables it writes to.
10  *
11  * Copyright   :  Written by and Copyright (C) 2001-2008 the SourceForge
12  *                Privoxy team. http://www.privoxy.org/
13  *
14  *                Based on the Internet Junkbuster originally written
15  *                by and Copyright (C) 1997 Anonymous Coders and
16  *                Junkbusters Corporation.  http://www.junkbusters.com
17  *
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.
23  *
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.
29  *
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.
35  *
36  * Revisions   :
37  *    $Log: loadcfg.c,v $
38  *    Revision 1.84  2009/01/14 16:14:36  fabiankeil
39  *    Due to the standard.action file removal, the other action
40  *    files changed their position in config->actions_file[].
41  *    Update mingw32 kludge accordingly.
42  *
43  *    Revision 1.83  2008/12/20 14:53:55  fabiankeil
44  *    Add config option socket-timeout to control the time
45  *    Privoxy waits for data to arrive on a socket. Useful
46  *    in case of stale ssh tunnels or when fuzz-testing.
47  *
48  *    Revision 1.82  2008/11/16 12:43:49  fabiankeil
49  *    Turn keep-alive support into a runtime feature
50  *    that is disabled by setting keep-alive-timeout
51  *    to a negative value.
52  *
53  *    Revision 1.81  2008/11/13 09:08:42  fabiankeil
54  *    Add new config option: keep-alive-timeout.
55  *
56  *    Revision 1.80  2008/08/31 15:59:03  fabiankeil
57  *    There's no reason to let remote toggling support depend
58  *    on FEATURE_CGI_EDIT_ACTIONS, so make sure it doesn't.
59  *
60  *    Revision 1.79  2008/08/30 12:03:07  fabiankeil
61  *    Remove FEATURE_COOKIE_JAR.
62  *
63  *    Revision 1.78  2008/08/02 08:23:22  fabiankeil
64  *    If the enforce-blocks directive is used with FEATURE_FORCE_LOAD
65  *    disabled, log a message that blocks will always be enforced
66  *    instead of complaining about an unrecognized directive.
67  *    Reported by Pietro Leone.
68  *
69  *    Revision 1.77  2008/05/26 16:13:22  fabiankeil
70  *    Reuse directive_hash and don't hash the same directive twice.
71  *
72  *    Revision 1.76  2008/05/10 09:03:16  fabiankeil
73  *    - Merge three string_append() calls.
74  *    - Remove useless assertion.
75  *
76  *    Revision 1.75  2008/03/30 14:52:05  fabiankeil
77  *    Rename load_actions_file() and load_re_filterfile()
78  *    as they load multiple files "now".
79  *
80  *    Revision 1.74  2008/03/26 18:07:07  fabiankeil
81  *    Add hostname directive. Closes PR#1918189.
82  *
83  *    Revision 1.73  2008/02/16 16:54:51  fabiankeil
84  *    Fix typo.
85  *
86  *    Revision 1.72  2008/02/03 13:46:15  fabiankeil
87  *    Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
88  *
89  *    Revision 1.71  2007/12/23 15:24:56  fabiankeil
90  *    Reword "unrecognized directive" warning, use better
91  *    mark up and add a <br>. Fixes parts of #1856559.
92  *
93  *    Revision 1.70  2007/12/15 14:24:05  fabiankeil
94  *    Plug memory leak if listen-address only specifies the port.
95  *
96  *    Revision 1.69  2007/10/27 13:02:27  fabiankeil
97  *    Relocate daemon-mode-related log messages to make sure
98  *    they aren't shown again in case of configuration reloads.
99  *
100  *    Revision 1.68  2007/10/19 16:32:34  fabiankeil
101  *    Plug memory leak introduced with my last commit.
102  *
103  *    Revision 1.67  2007/10/14 14:12:41  fabiankeil
104  *    When in daemon mode, close stderr after the configuration file has been
105  *    parsed the first time. If logfile isn't set, stop logging. Fixes BR#897436.
106  *
107  *    Revision 1.66  2007/08/05 14:02:09  fabiankeil
108  *    #1763173 from Stefan Huehner: declare unload_configfile() static.
109  *
110  *    Revision 1.65  2007/07/21 11:51:36  fabiankeil
111  *    As Hal noticed, checking dispatch_cgi() as the last cruncher
112  *    looks like a bug if CGI requests are blocked unintentionally,
113  *    so don't do it unless the user enabled the new config option
114  *    "allow-cgi-request-crunching".
115  *
116  *    Revision 1.64  2007/05/21 10:44:08  fabiankeil
117  *    - Use strlcpy() instead of strcpy().
118  *    - Stop treating actions files special. Expect a complete file name
119  *      (with or without path) like it's done for the rest of the files.
120  *      Closes FR#588084.
121  *    - Remove an unnecessary temporary memory allocation.
122  *    - Don't log anything to the console when running as
123  *      daemon and no errors occurred.
124  *
125  *    Revision 1.63  2007/04/09 18:11:36  fabiankeil
126  *    Don't mistake VC++'s _snprintf() for a snprintf() replacement.
127  *
128  *    Revision 1.62  2007/03/17 15:20:05  fabiankeil
129  *    New config option: enforce-blocks.
130  *
131  *    Revision 1.61  2007/03/16 16:47:35  fabiankeil
132  *    - Mention other reasons why acl directive loading might have failed.
133  *    - Don't log the acl source if the acl destination is to blame.
134  *
135  *    Revision 1.60  2007/01/27 13:09:16  fabiankeil
136  *    Add new config option "templdir" to
137  *    change the templates directory.
138  *
139  *    Revision 1.59  2006/12/31 17:56:38  fabiankeil
140  *    Added config option accept-intercepted-requests
141  *    and disabled it by default.
142  *
143  *    Revision 1.58  2006/12/31 14:24:29  fabiankeil
144  *    Fix gcc43 compiler warnings.
145  *
146  *    Revision 1.57  2006/12/21 12:57:48  fabiankeil
147  *    Add config option "split-large-forms"
148  *    to work around the browser bug reported
149  *    in BR #1570678.
150  *
151  *    Revision 1.56  2006/12/17 17:04:51  fabiankeil
152  *    Move the <br> in the generated HTML for the config
153  *    options from the beginning of the string to its end.
154  *    Keeps the white space in balance.
155  *
156  *    Revision 1.55  2006/11/28 15:31:52  fabiankeil
157  *    Fix memory leak in case of config file reloads.
158  *
159  *    Revision 1.54  2006/10/21 16:04:22  fabiankeil
160  *    Modified kludge for win32 to make ming32 menu
161  *    "Options/Edit Filters" (sort of) work again.
162  *    Same limitations as for the action files apply.
163  *    Fixes BR 1567373.
164  *
165  *    Revision 1.53  2006/09/06 18:45:03  fabiankeil
166  *    Incorporate modified version of Roland Rosenfeld's patch to
167  *    optionally access the user-manual via Privoxy. Closes patch 679075.
168  *
169  *    Formatting changed to Privoxy style, added call to
170  *    cgi_error_no_template if the requested file doesn't
171  *    exist and modified check whether or not Privoxy itself
172  *    should serve the manual. Should work cross-platform now.
173  *
174  *    Revision 1.52  2006/09/06 10:43:32  fabiankeil
175  *    Added config option enable-remote-http-toggle
176  *    to specify if Privoxy should recognize special
177  *    headers (currently only X-Filter) to change its
178  *    behaviour. Disabled by default.
179  *
180  *    Revision 1.51  2006/09/06 09:23:37  fabiankeil
181  *    Make number of retries in case of forwarded-connect problems
182  *    a config file option (forwarded-connect-retries) and use 0 as
183  *    default.
184  *
185  *    Revision 1.50  2006/07/18 14:48:46  david__schmidt
186  *    Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
187  *    with what was really the latest development (the v_3_0_branch branch)
188  *
189  *    Revision 1.48.2.7  2006/02/02 17:29:16  david__schmidt
190  *    Don't forget to malloc space for the null terminator...
191  *
192  *    Revision 1.48.2.6  2006/01/29 23:10:56  david__schmidt
193  *    Multiple filter file support
194  *
195  *    Revision 1.48.2.5  2003/05/08 15:17:25  oes
196  *    Closed two memory leaks; hopefully the last remaining ones
197  *    (in the main execution paths, anyway).
198  *
199  *    Revision 1.48.2.4  2003/04/11 12:06:14  oes
200  *    Addressed bug #719435
201  *     - Extraneous filterfile directives now logged as errors
202  *     - This and unrecnonised directives now really obvious on status page
203  *
204  *    Revision 1.48.2.3  2003/03/11 11:53:59  oes
205  *    Cosmetic: Renamed cryptic variable
206  *
207  *    Revision 1.48.2.2  2002/11/12 16:28:20  oes
208  *    Move unrelated variable declaration out of #ifdef FEATURE_ACL; fixes bug #636655
209  *
210  *    Revision 1.48.2.1  2002/08/21 17:58:05  oes
211  *    Temp kludge to let user and default action file be edited through win32 GUI (FR 592080)
212  *
213  *    Revision 1.48  2002/05/14 21:30:38  oes
214  *    savearg now uses own linking code instead of (now special-cased) add_help_link
215  *
216  *    Revision 1.47  2002/05/12 21:36:29  jongfoster
217  *    Correcting function comments
218  *
219  *    Revision 1.46  2002/04/26 12:55:14  oes
220  *     - New option "user-manual", defaults to our site
221  *       via project.h #define
222  *     - savearg now embeds option names in help links
223  *
224  *    Revision 1.45  2002/04/24 02:11:54  oes
225  *    Jon's multiple AF patch: Allow up to MAX_AF_FILES actionsfile options
226  *
227  *    Revision 1.44  2002/04/08 20:37:13  swa
228  *    fixed JB spelling
229  *
230  *    Revision 1.43  2002/04/08 20:36:50  swa
231  *    fixed JB spelling
232  *
233  *    Revision 1.42  2002/04/05 15:50:15  oes
234  *    fix for invalid HTML proxy_args
235  *
236  *    Revision 1.41  2002/03/31 17:19:00  jongfoster
237  *    Win32 only: Enabling STRICT to fix a VC++ compile warning.
238  *
239  *    Revision 1.40  2002/03/26 22:29:55  swa
240  *    we have a new homepage!
241  *
242  *    Revision 1.39  2002/03/24 13:25:43  swa
243  *    name change related issues
244  *
245  *    Revision 1.38  2002/03/24 13:05:48  jongfoster
246  *    Renaming re_filterfile to filterfile
247  *
248  *    Revision 1.37  2002/03/16 23:54:06  jongfoster
249  *    Adding graceful termination feature, to help look for memory leaks.
250  *    If you enable this (which, by design, has to be done by hand
251  *    editing config.h) and then go to http://i.j.b/die, then the program
252  *    will exit cleanly after the *next* request.  It should free all the
253  *    memory that was used.
254  *
255  *    Revision 1.36  2002/03/13 00:27:05  jongfoster
256  *    Killing warnings
257  *
258  *    Revision 1.35  2002/03/07 03:52:44  oes
259  *    Set logging to tty for --no-daemon mode
260  *
261  *    Revision 1.34  2002/03/06 23:14:35  jongfoster
262  *    Trivial cosmetic changes to make function comments easier to find.
263  *
264  *    Revision 1.33  2002/03/05 04:52:42  oes
265  *    Deleted non-errlog debugging code
266  *
267  *    Revision 1.32  2002/03/04 18:24:53  oes
268  *    Re-enabled output of unknown config directive hash
269  *
270  *    Revision 1.31  2002/03/03 15:07:20  oes
271  *    Re-enabled automatic config reloading
272  *
273  *    Revision 1.30  2002/01/22 23:31:43  jongfoster
274  *    Replacing strsav() with string_append()
275  *
276  *    Revision 1.29  2002/01/17 21:02:30  jongfoster
277  *    Moving all our URL and URL pattern parsing code to urlmatch.c.
278  *
279  *    Renaming free_url to free_url_spec, since it frees a struct url_spec.
280  *
281  *    Revision 1.28  2001/12/30 14:07:32  steudten
282  *    - Add signal handling (unix)
283  *    - Add SIGHUP handler (unix)
284  *    - Add creation of pidfile (unix)
285  *    - Add action 'top' in rc file (RH)
286  *    - Add entry 'SIGNALS' to manpage
287  *    - Add exit message to logfile (unix)
288  *
289  *    Revision 1.27  2001/11/07 00:02:13  steudten
290  *    Add line number in error output for lineparsing for
291  *    actionsfile and configfile.
292  *    Special handling for CLF added.
293  *
294  *    Revision 1.26  2001/11/05 21:41:43  steudten
295  *    Add changes to be a real daemon just for unix os.
296  *    (change cwd to /, detach from controlling tty, set
297  *    process group and session leader to the own process.
298  *    Add DBG() Macro.
299  *    Add some fatal-error log message for failed malloc().
300  *    Add '-d' if compiled with 'configure --with-debug' to
301  *    enable debug output.
302  *
303  *    Revision 1.25  2001/10/25 03:40:48  david__schmidt
304  *    Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
305  *    threads to call select() simultaneously.  So, it's time to do a real, live,
306  *    native OS/2 port.  See defines for __EMX__ (the porting layer) vs. __OS2__
307  *    (native). Both versions will work, but using __OS2__ offers multi-threading.
308  *
309  *    Revision 1.24  2001/10/23 21:40:30  jongfoster
310  *    Added support for enable-edit-actions and enable-remote-toggle config
311  *    file options.
312  *
313  *    Revision 1.23  2001/10/07 15:36:00  oes
314  *    Introduced new config option "buffer-limit"
315  *
316  *    Revision 1.22  2001/09/22 16:36:59  jongfoster
317  *    Removing unused parameter fs from read_config_line()
318  *
319  *    Revision 1.21  2001/09/16 17:10:43  jongfoster
320  *    Moving function savearg() here, since it was the only thing left in
321  *    showargs.c.
322  *
323  *    Revision 1.20  2001/07/30 22:08:36  jongfoster
324  *    Tidying up #defines:
325  *    - All feature #defines are now of the form FEATURE_xxx
326  *    - Permanently turned off WIN_GUI_EDIT
327  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
328  *
329  *    Revision 1.19  2001/07/15 17:45:16  jongfoster
330  *    Removing some unused #includes
331  *
332  *    Revision 1.18  2001/07/13 14:01:14  oes
333  *     - Removed all #ifdef PCRS
334  *     - Removed vim-settings
335  *
336  *    Revision 1.17  2001/06/29 13:31:03  oes
337  *    - Improved comments
338  *    - Fixed (actionsfile) and sorted hashes
339  *    - Introduced admin_address and proxy-info-url
340  *      as config parameters
341  *    - Renamed config->proxy_args_invocation (which didn't have
342  *      the invocation but the options!) to config->proxy_args
343  *    - Various adaptions
344  *    - Removed logentry from cancelled commit
345  *
346  *    Revision 1.16  2001/06/09 10:55:28  jongfoster
347  *    Changing BUFSIZ ==> BUFFER_SIZE
348  *
349  *    Revision 1.15  2001/06/07 23:13:40  jongfoster
350  *    Merging ACL and forward files into config file.
351  *    Cosmetic: Sorting config file options alphabetically.
352  *    Cosmetic: Adding brief syntax comments to config file options.
353  *
354  *    Revision 1.14  2001/06/07 14:46:25  joergs
355  *    Missing make_path() added for re_filterfile.
356  *
357  *    Revision 1.13  2001/06/05 22:33:54  jongfoster
358  *
359  *    Fixed minor memory leak.
360  *    Also now uses make_path to prepend the pathnames.
361  *
362  *    Revision 1.12  2001/06/05 20:04:09  jongfoster
363  *    Now uses _snprintf() in place of snprintf() under Win32.
364  *
365  *    Revision 1.11  2001/06/04 18:31:58  swa
366  *    files are now prefixed with either `confdir' or `logdir'.
367  *    `make redhat-dist' replaces both entries confdir and logdir
368  *    with redhat values
369  *
370  *    Revision 1.10  2001/06/03 19:11:54  oes
371  *    introduced confdir option
372  *
373  *    Revision 1.9  2001/06/01 20:06:24  jongfoster
374  *    Removed support for "tinygif" option - moved to actions file.
375  *
376  *    Revision 1.8  2001/05/31 21:27:13  jongfoster
377  *    Removed many options from the config file and into the
378  *    "actions" file: add_forwarded, suppress_vanilla_wafer,
379  *    wafer, add_header, user_agent, referer, from
380  *    Also globally replaced "permission" with "action".
381  *
382  *    Revision 1.7  2001/05/29 09:50:24  jongfoster
383  *    Unified blocklist/imagelist/permissionslist.
384  *    File format is still under discussion, but the internal changes
385  *    are (mostly) done.
386  *
387  *    Also modified interceptor behaviour:
388  *    - We now intercept all URLs beginning with one of the following
389  *      prefixes (and *only* these prefixes):
390  *        * http://i.j.b/
391  *        * http://ijbswa.sf.net/config/
392  *        * http://ijbswa.sourceforge.net/config/
393  *    - New interceptors "home page" - go to http://i.j.b/ to see it.
394  *    - Internal changes so that intercepted and fast redirect pages
395  *      are not replaced with an image.
396  *    - Interceptors now have the option to send a binary page direct
397  *      to the client. (i.e. ijb-send-banner uses this)
398  *    - Implemented show-url-info interceptor.  (Which is why I needed
399  *      the above interceptors changes - a typical URL is
400  *      "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
401  *      The previous mechanism would not have intercepted that, and
402  *      if it had been intercepted then it then it would have replaced
403  *      it with an image.)
404  *
405  *    Revision 1.6  2001/05/26 00:28:36  jongfoster
406  *    Automatic reloading of config file.
407  *    Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
408  *    Most of the global variables have been moved to a new
409  *    struct configuration_spec, accessed through csp->config->globalname
410  *    Most of the globals remaining are used by the Win32 GUI.
411  *
412  *    Revision 1.5  2001/05/25 22:34:30  jongfoster
413  *    Hard tabs->Spaces
414  *
415  *    Revision 1.4  2001/05/22 18:46:04  oes
416  *
417  *    - Enabled filtering banners by size rather than URL
418  *      by adding patterns that replace all standard banner
419  *      sizes with the "Junkbuster" gif to the re_filterfile
420  *
421  *    - Enabled filtering WebBugs by providing a pattern
422  *      which kills all 1x1 images
423  *
424  *    - Added support for PCRE_UNGREEDY behaviour to pcrs,
425  *      which is selected by the (nonstandard and therefore
426  *      capital) letter 'U' in the option string.
427  *      It causes the quantifiers to be ungreedy by default.
428  *      Appending a ? turns back to greedy (!).
429  *
430  *    - Added a new interceptor ijb-send-banner, which
431  *      sends back the "Junkbuster" gif. Without imagelist or
432  *      MSIE detection support, or if tinygif = 1, or the
433  *      URL isn't recognized as an imageurl, a lame HTML
434  *      explanation is sent instead.
435  *
436  *    - Added new feature, which permits blocking remote
437  *      script redirects and firing back a local redirect
438  *      to the browser.
439  *      The feature is conditionally compiled, i.e. it
440  *      can be disabled with --disable-fast-redirects,
441  *      plus it must be activated by a "fast-redirects"
442  *      line in the config file, has its own log level
443  *      and of course wants to be displayed by show-proxy-args
444  *      Note: Boy, all the #ifdefs in 1001 locations and
445  *      all the fumbling with configure.in and acconfig.h
446  *      were *way* more work than the feature itself :-(
447  *
448  *    - Because a generic redirect template was needed for
449  *      this, tinygif = 3 now uses the same.
450  *
451  *    - Moved GIFs, and other static HTTP response templates
452  *      to project.h
453  *
454  *    - Some minor fixes
455  *
456  *    - Removed some >400 CRs again (Jon, you really worked
457  *      a lot! ;-)
458  *
459  *    Revision 1.3  2001/05/20 01:21:20  jongfoster
460  *    Version 2.9.4 checkin.
461  *    - Merged popupfile and cookiefile, and added control over PCRS
462  *      filtering, in new "permissionsfile".
463  *    - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
464  *      file error you now get a message box (in the Win32 GUI) rather
465  *      than the program exiting with no explanation.
466  *    - Made killpopup use the PCRS MIME-type checking and HTTP-header
467  *      skipping.
468  *    - Removed tabs from "config"
469  *    - Moved duplicated url parsing code in "loaders.c" to a new funcition.
470  *    - Bumped up version number.
471  *
472  *    Revision 1.2  2001/05/17 23:01:01  oes
473  *     - Cleaned CRLF's from the sources and related files
474  *
475  *    Revision 1.1.1.1  2001/05/15 13:58:58  oes
476  *    Initial import of version 2.9.3 source tree
477  *
478  *
479  *********************************************************************/
480 \f
481
482 #include "config.h"
483
484 #include <stdio.h>
485 #include <sys/types.h>
486 #include <stdlib.h>
487 #include <string.h>
488 #include <signal.h>
489 #include <fcntl.h>
490 #include <errno.h>
491 #include <ctype.h>
492 #include <assert.h>
493
494 #ifdef _WIN32
495
496 # ifndef STRICT
497 #  define STRICT
498 # endif
499 # include <windows.h>
500
501 # include "win32.h"
502 # ifndef _WIN_CONSOLE
503 #  include "w32log.h"
504 # endif /* ndef _WIN_CONSOLE */
505
506 #else /* ifndef _WIN32 */
507
508 #ifndef __OS2__
509 # include <unistd.h>
510 # include <sys/wait.h>
511 #endif
512 # include <sys/time.h>
513 # include <sys/stat.h>
514 # include <signal.h>
515
516 #endif
517
518 #include "loadcfg.h"
519 #include "list.h"
520 #include "jcc.h"
521 #include "filters.h"
522 #include "loaders.h"
523 #include "miscutil.h"
524 #include "errlog.h"
525 #include "ssplit.h"
526 #include "encode.h"
527 #include "urlmatch.h"
528 #include "cgi.h"
529 #include "gateway.h"
530
531 const char loadcfg_h_rcs[] = LOADCFG_H_VERSION;
532
533 /*
534  * Fix a problem with Solaris.  There should be no effect on other
535  * platforms.
536  * Solaris's isspace() is a macro which uses it's argument directly
537  * as an array index.  Therefore we need to make sure that high-bit
538  * characters generate +ve values, and ideally we also want to make
539  * the argument match the declared parameter type of "int".
540  */
541 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
542 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
543
544 #ifdef FEATURE_TOGGLE
545 /* Privoxy is enabled by default. */
546 int global_toggle_state = 1;
547 #endif /* def FEATURE_TOGGLE */
548
549 /* The filename of the configfile */
550 const char *configfile  = NULL;
551
552 /*
553  * CGI functions will later need access to the invocation args,
554  * so we will make argc and argv global.
555  */
556 int Argc = 0;
557 const char **Argv = NULL;
558
559 static struct file_list *current_configfile = NULL;
560
561
562 /*
563  * This takes the "cryptic" hash of each keyword and aliases them to
564  * something a little more readable.  This also makes changing the
565  * hash values easier if they should change or the hash algorthm changes.
566  * Use the included "hash" program to find out what the hash will be
567  * for any string supplied on the command line.  (Or just put it in the
568  * config file and read the number from the error message in the log).
569  *
570  * Please keep this list sorted alphabetically (but with the Windows
571  * console and GUI specific options last).
572  */
573
574 #define hash_actions_file                1196306641ul /* "actionsfile" */
575 #define hash_accept_intercepted_requests 1513024973ul /* "accept-intercepted-requests" */
576 #define hash_admin_address               4112573064ul /* "admin-address" */
577 #define hash_allow_cgi_request_crunching  258915987ul /* "allow-cgi-request-crunching" */
578 #define hash_buffer_limit                1881726070ul /* "buffer-limit */
579 #define hash_confdir                        1978389ul /* "confdir" */
580 #define hash_debug                            78263ul /* "debug" */
581 #define hash_deny_access                 1227333715ul /* "deny-access" */
582 #define hash_enable_edit_actions         2517097536ul /* "enable-edit-actions" */
583 #define hash_enable_remote_toggle        2979744683ul /* "enable-remote-toggle" */
584 #define hash_enable_remote_http_toggle    110543988ul /* "enable-remote-http-toggle" */
585 #define hash_enforce_blocks              1862427469ul /* "enforce-blocks" */
586 #define hash_filterfile                   250887266ul /* "filterfile" */
587 #define hash_forward                        2029845ul /* "forward" */
588 #define hash_forward_socks4              3963965521ul /* "forward-socks4" */
589 #define hash_forward_socks4a             2639958518ul /* "forward-socks4a" */
590 #define hash_forward_socks5              3963965522ul /* "forward-socks5" */
591 #define hash_forwarded_connect_retries    101465292ul /* "forwarded-connect-retries" */
592 #define hash_hostname                      10308071ul /* "hostname" */
593 #define hash_keep_alive_timeout          3878599515ul /* "keep-alive-timeout" */
594 #define hash_listen_address              1255650842ul /* "listen-address" */
595 #define hash_logdir                          422889ul /* "logdir" */
596 #define hash_logfile                        2114766ul /* "logfile" */
597 #define hash_permit_access               3587953268ul /* "permit-access" */
598 #define hash_proxy_info_url              3903079059ul /* "proxy-info-url" */
599 #define hash_single_threaded             4250084780ul /* "single-threaded" */
600 #define hash_socket_timeout              1809001761ul /* "socket-timeout" */
601 #define hash_split_large_cgi_forms        671658948ul /* "split-large-cgi-forms" */
602 #define hash_suppress_blocklists         1948693308ul /* "suppress-blocklists" */
603 #define hash_templdir                      11067889ul /* "templdir" */
604 #define hash_toggle                          447966ul /* "toggle" */
605 #define hash_trust_info_url               430331967ul /* "trust-info-url" */
606 #define hash_trustfile                     56494766ul /* "trustfile" */
607 #define hash_usermanual                  1416668518ul /* "user-manual" */
608 #define hash_activity_animation          1817904738ul /* "activity-animation" */
609 #define hash_close_button_minimizes      3651284693ul /* "close-button-minimizes" */
610 #define hash_hide_console                2048809870ul /* "hide-console" */
611 #define hash_log_buffer_size             2918070425ul /* "log-buffer-size" */
612 #define hash_log_font_name               2866730124ul /* "log-font-name" */
613 #define hash_log_font_size               2866731014ul /* "log-font-size" */
614 #define hash_log_highlight_messages      4032101240ul /* "log-highlight-messages" */
615 #define hash_log_max_lines               2868344173ul /* "log-max-lines" */
616 #define hash_log_messages                2291744899ul /* "log-messages" */
617 #define hash_show_on_task_bar             215410365ul /* "show-on-task-bar" */
618
619
620 static void savearg(char *command, char *argument, struct configuration_spec * config);
621
622 /*********************************************************************
623  *
624  * Function    :  unload_configfile
625  *
626  * Description :  Free the config structure and all components.
627  *
628  * Parameters  :
629  *          1  :  data: struct configuration_spec to unload
630  *
631  * Returns     :  N/A
632  *
633  *********************************************************************/
634 static void unload_configfile (void * data)
635 {
636    struct configuration_spec * config = (struct configuration_spec *)data;
637    struct forward_spec *cur_fwd = config->forward;
638    int i;
639
640 #ifdef FEATURE_ACL
641    struct access_control_list *cur_acl = config->acl;
642
643    while (cur_acl != NULL)
644    {
645       struct access_control_list * next_acl = cur_acl->next;
646       free(cur_acl);
647       cur_acl = next_acl;
648    }
649    config->acl = NULL;
650 #endif /* def FEATURE_ACL */
651
652    while (cur_fwd != NULL)
653    {
654       struct forward_spec * next_fwd = cur_fwd->next;
655       free_url_spec(cur_fwd->url);
656
657       freez(cur_fwd->gateway_host);
658       freez(cur_fwd->forward_host);
659       free(cur_fwd);
660       cur_fwd = next_fwd;
661    }
662    config->forward = NULL;
663
664    freez(config->confdir);
665    freez(config->logdir);
666    freez(config->templdir);
667    freez(config->hostname);
668
669    freez(config->haddr);
670    freez(config->logfile);
671
672    for (i = 0; i < MAX_AF_FILES; i++)
673    {
674       freez(config->actions_file_short[i]);
675       freez(config->actions_file[i]);
676       freez(config->re_filterfile_short[i]);
677       freez(config->re_filterfile[i]);
678    }
679
680    freez(config->admin_address);
681    freez(config->proxy_info_url);
682    freez(config->proxy_args);
683    freez(config->usermanual);
684
685 #ifdef FEATURE_TRUST
686    freez(config->trustfile);
687    list_remove_all(config->trust_info);
688 #endif /* def FEATURE_TRUST */
689
690    for (i = 0; i < MAX_AF_FILES; i++)
691    {
692       freez(config->re_filterfile[i]);
693    }
694
695    freez(config);
696 }
697
698
699 #ifdef FEATURE_GRACEFUL_TERMINATION
700 /*********************************************************************
701  *
702  * Function    :  unload_current_config_file
703  *
704  * Description :  Unloads current config file - reset to state at
705  *                beginning of program.
706  *
707  * Parameters  :  None
708  *
709  * Returns     :  N/A
710  *
711  *********************************************************************/
712 void unload_current_config_file(void)
713 {
714    if (current_configfile)
715    {
716       current_configfile->unloader = unload_configfile;
717       current_configfile = NULL;
718    }
719 }
720 #endif
721
722
723 /*********************************************************************
724  *
725  * Function    :  load_config
726  *
727  * Description :  Load the config file and all parameters.
728  *
729  *                XXX: more than thousand lines long
730  *                and thus in serious need of refactoring.
731  *
732  * Parameters  :  None
733  *
734  * Returns     :  The configuration_spec, or NULL on error.
735  *
736  *********************************************************************/
737 struct configuration_spec * load_config(void)
738 {
739    char buf[BUFFER_SIZE];
740    char *p, *q;
741    FILE *configfp = NULL;
742    struct configuration_spec * config = NULL;
743    struct client_state * fake_csp;
744    struct file_list *fs;
745    unsigned long linenum = 0;
746    int i;
747    char *logfile = NULL;
748 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
749    int keep_alive_timeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
750 #endif
751
752    if ( !check_file_changed(current_configfile, configfile, &fs))
753    {
754       /* No need to load */
755       return ((struct configuration_spec *)current_configfile->f);
756    }
757    if (!fs)
758    {
759       log_error(LOG_LEVEL_FATAL, "can't check configuration file '%s':  %E",
760                 configfile);
761    }
762
763    if (NULL != current_configfile)
764    {
765       log_error(LOG_LEVEL_INFO, "Reloading configuration file '%s'", configfile);
766    }
767
768 #ifdef FEATURE_TOGGLE
769    global_toggle_state      = 1;
770 #endif /* def FEATURE_TOGGLE */
771
772    fs->f = config = (struct configuration_spec *)zalloc(sizeof(*config));
773
774    if (config==NULL)
775    {
776       freez(fs->filename);
777       freez(fs);
778       log_error(LOG_LEVEL_FATAL, "can't allocate memory for configuration");
779       /* Never get here - LOG_LEVEL_FATAL causes program exit */
780    }
781
782    /*
783     * This is backwards from how it's usually done.
784     * Following the usual pattern, "fs" would be stored in a member
785     * variable in "csp", and then we'd access "config" from "fs->f",
786     * using a cast.  However, "config" is used so often that a
787     * cast each time would be very ugly, and the extra indirection
788     * would waste CPU cycles.  Therefore we store "config" in
789     * "csp->config", and "fs" in "csp->config->config_file_list".
790     */
791    config->config_file_list = fs;
792
793    /*
794     * Set to defaults
795     */
796    config->multi_threaded            = 1;
797    config->hport                     = HADDR_PORT;
798    config->buffer_limit              = 4096 * 1024;
799    config->usermanual                = strdup(USER_MANUAL_URL);
800    config->proxy_args                = strdup("");
801    config->forwarded_connect_retries = 0;
802    config->socket_timeout            = 180;
803    config->feature_flags            &= ~RUNTIME_FEATURE_CGI_TOGGLE;
804    config->feature_flags            &= ~RUNTIME_FEATURE_SPLIT_LARGE_FORMS;
805    config->feature_flags            &= ~RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS;
806
807    if ((configfp = fopen(configfile, "r")) == NULL)
808    {
809       log_error(LOG_LEVEL_FATAL, "can't open configuration file '%s':  %E",
810               configfile);
811       /* Never get here - LOG_LEVEL_FATAL causes program exit */
812    }
813
814    while (read_config_line(buf, sizeof(buf), configfp, &linenum) != NULL)
815    {
816       char cmd[BUFFER_SIZE];
817       char arg[BUFFER_SIZE];
818       char tmp[BUFFER_SIZE];
819 #ifdef FEATURE_ACL
820       struct access_control_list *cur_acl;
821 #endif /* def FEATURE_ACL */
822       struct forward_spec *cur_fwd;
823       int vec_count;
824       char *vec[3];
825       unsigned long directive_hash;
826
827       strlcpy(tmp, buf, sizeof(tmp));
828
829       /* Copy command (i.e. up to space or tab) into cmd */
830       p = buf;
831       q = cmd;
832       while (*p && (*p != ' ') && (*p != '\t'))
833       {
834          *q++ = *p++;
835       }
836       *q = '\0';
837
838       /* Skip over the whitespace in buf */
839       while (*p && ((*p == ' ') || (*p == '\t')))
840       {
841          p++;
842       }
843
844       /* Copy the argument into arg */
845       strlcpy(arg, p, sizeof(arg));
846
847       /* Should never happen, but check this anyway */
848       if (*cmd == '\0')
849       {
850          continue;
851       }
852
853       /* Make sure the command field is lower case */
854       for (p=cmd; *p; p++)
855       {
856          if (ijb_isupper(*p))
857          {
858             *p = (char)ijb_tolower(*p);
859          }
860       }
861
862       /* Save the argument for show-proxy-args */
863       savearg(cmd, arg, config);
864
865       directive_hash = hash_string(cmd);
866       switch (directive_hash)
867       {
868 /* *************************************************************************
869  * actionsfile actions-file-name
870  * In confdir by default
871  * *************************************************************************/
872          case hash_actions_file :
873             i = 0;
874             while ((i < MAX_AF_FILES) && (NULL != config->actions_file[i]))
875             {
876                i++;
877             }
878
879             if (i >= MAX_AF_FILES)
880             {
881                log_error(LOG_LEVEL_FATAL, "Too many 'actionsfile' directives in config file - limit is %d.\n"
882                   "(You can increase this limit by changing MAX_AF_FILES in project.h and recompiling).",
883                   MAX_AF_FILES);
884             }
885             config->actions_file_short[i] = strdup(arg);
886             config->actions_file[i] = make_path(config->confdir, arg);
887
888             continue;
889 /* *************************************************************************
890  * accept-intercepted-requests
891  * *************************************************************************/
892          case hash_accept_intercepted_requests:
893             if ((*arg != '\0') && (0 != atoi(arg)))
894             {
895                config->feature_flags |= RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS;
896             }
897             else
898             {
899                config->feature_flags &= ~RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS;
900             }
901             continue;
902
903 /* *************************************************************************
904  * admin-address email-address
905  * *************************************************************************/
906          case hash_admin_address :
907             freez(config->admin_address);
908             config->admin_address = strdup(arg);
909             continue;
910
911 /* *************************************************************************
912  * allow-cgi-request-crunching
913  * *************************************************************************/
914          case hash_allow_cgi_request_crunching:
915             if ((*arg != '\0') && (0 != atoi(arg)))
916             {
917                config->feature_flags |= RUNTIME_FEATURE_CGI_CRUNCHING;
918             }
919             else
920             {
921                config->feature_flags &= ~RUNTIME_FEATURE_CGI_CRUNCHING;
922             }
923             continue;
924
925 /* *************************************************************************
926  * buffer-limit n
927  * *************************************************************************/
928          case hash_buffer_limit :
929             config->buffer_limit = (size_t)(1024 * atoi(arg));
930             continue;
931
932 /* *************************************************************************
933  * confdir directory-name
934  * *************************************************************************/
935          case hash_confdir :
936             freez(config->confdir);
937             config->confdir = make_path( NULL, arg);
938             continue;
939
940 /* *************************************************************************
941  * debug n
942  * Specifies debug level, multiple values are ORed together.
943  * *************************************************************************/
944          case hash_debug :
945             config->debug |= atoi(arg);
946             continue;
947
948 /* *************************************************************************
949  * deny-access source-ip[/significant-bits] [dest-ip[/significant-bits]]
950  * *************************************************************************/
951 #ifdef FEATURE_ACL
952          case hash_deny_access:
953             vec_count = ssplit(arg, " \t", vec, SZ(vec), 1, 1);
954
955             if ((vec_count != 1) && (vec_count != 2))
956             {
957                log_error(LOG_LEVEL_ERROR, "Wrong number of parameters for "
958                      "deny-access directive in configuration file.");
959                string_append(&config->proxy_args,
960                   "<br>\nWARNING: Wrong number of parameters for "
961                   "deny-access directive in configuration file.<br><br>\n");
962                continue;
963             }
964
965             /* allocate a new node */
966             cur_acl = (struct access_control_list *) zalloc(sizeof(*cur_acl));
967
968             if (cur_acl == NULL)
969             {
970                log_error(LOG_LEVEL_FATAL, "can't allocate memory for configuration");
971                /* Never get here - LOG_LEVEL_FATAL causes program exit */
972                continue;
973             }
974             cur_acl->action = ACL_DENY;
975
976             if (acl_addr(vec[0], cur_acl->src) < 0)
977             {
978                log_error(LOG_LEVEL_ERROR, "Invalid source address, port or netmask "
979                   "for deny-access directive in configuration file: \"%s\"", vec[0]);
980                string_append(&config->proxy_args,
981                   "<br>\nWARNING: Invalid source address, port or netmask "
982                   "for deny-access directive in configuration file: \"");
983                string_append(&config->proxy_args,
984                   vec[0]);
985                string_append(&config->proxy_args,
986                   "\"<br><br>\n");
987                freez(cur_acl);
988                continue;
989             }
990             if (vec_count == 2)
991             {
992                if (acl_addr(vec[1], cur_acl->dst) < 0)
993                {
994                   log_error(LOG_LEVEL_ERROR, "Invalid destination address, port or netmask "
995                      "for deny-access directive in configuration file: \"%s\"", vec[1]);
996                   string_append(&config->proxy_args,
997                      "<br>\nWARNING: Invalid destination address, port or netmask "
998                      "for deny-access directive in configuration file: \"");
999                   string_append(&config->proxy_args,
1000                      vec[1]);
1001                   string_append(&config->proxy_args,
1002                      "\"<br><br>\n");
1003                   freez(cur_acl);
1004                   continue;
1005                }
1006             }
1007
1008             /*
1009              * Add it to the list.  Note we reverse the list to get the
1010              * behaviour the user expects.  With both the ACL and
1011              * actions file, the last match wins.  However, the internal
1012              * implementations are different:  The actions file is stored
1013              * in the same order as the file, and scanned completely.
1014              * With the ACL, we reverse the order as we load it, then
1015              * when we scan it we stop as soon as we get a match.
1016              */
1017             cur_acl->next  = config->acl;
1018             config->acl = cur_acl;
1019
1020             continue;
1021 #endif /* def FEATURE_ACL */
1022
1023 /* *************************************************************************
1024  * enable-edit-actions 0|1
1025  * *************************************************************************/
1026 #ifdef FEATURE_CGI_EDIT_ACTIONS
1027          case hash_enable_edit_actions:
1028             if ((*arg != '\0') && (0 != atoi(arg)))
1029             {
1030                config->feature_flags |= RUNTIME_FEATURE_CGI_EDIT_ACTIONS;
1031             }
1032             else
1033             {
1034                config->feature_flags &= ~RUNTIME_FEATURE_CGI_EDIT_ACTIONS;
1035             }
1036             continue;
1037 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
1038
1039 /* *************************************************************************
1040  * enable-remote-toggle 0|1
1041  * *************************************************************************/
1042 #ifdef FEATURE_TOGGLE
1043          case hash_enable_remote_toggle:
1044             if ((*arg != '\0') && (0 != atoi(arg)))
1045             {
1046                config->feature_flags |= RUNTIME_FEATURE_CGI_TOGGLE;
1047             }
1048             else
1049             {
1050                config->feature_flags &= ~RUNTIME_FEATURE_CGI_TOGGLE;
1051             }
1052             continue;
1053 #endif /* def FEATURE_TOGGLE */
1054
1055 /* *************************************************************************
1056  * enable-remote-http-toggle 0|1
1057  * *************************************************************************/
1058          case hash_enable_remote_http_toggle:
1059             if ((*arg != '\0') && (0 != atoi(arg)))
1060             {
1061                config->feature_flags |= RUNTIME_FEATURE_HTTP_TOGGLE;
1062             }
1063             else
1064             {
1065                config->feature_flags &= ~RUNTIME_FEATURE_HTTP_TOGGLE;
1066             }
1067             continue;
1068
1069 /* *************************************************************************
1070  * enforce-blocks 0|1
1071  * *************************************************************************/
1072          case hash_enforce_blocks:
1073 #ifdef FEATURE_FORCE_LOAD
1074             if ((*arg != '\0') && (0 != atoi(arg)))
1075             {
1076                config->feature_flags |= RUNTIME_FEATURE_ENFORCE_BLOCKS;
1077             }
1078             else
1079             {
1080                config->feature_flags &= ~RUNTIME_FEATURE_ENFORCE_BLOCKS;
1081             }
1082 #else
1083             log_error(LOG_LEVEL_ERROR, "Ignoring directive 'enforce-blocks'. "
1084                "FEATURE_FORCE_LOAD is disabled, blocks will always be enforced.");
1085 #endif /* def FEATURE_FORCE_LOAD */
1086             continue;
1087
1088 /* *************************************************************************
1089  * filterfile file-name
1090  * In confdir by default.
1091  * *************************************************************************/
1092          case hash_filterfile :
1093             i = 0;
1094             while ((i < MAX_AF_FILES) && (NULL != config->re_filterfile[i]))
1095             {
1096                i++;
1097             }
1098
1099             if (i >= MAX_AF_FILES)
1100             {
1101                log_error(LOG_LEVEL_FATAL, "Too many 'filterfile' directives in config file - limit is %d.\n"
1102                   "(You can increase this limit by changing MAX_AF_FILES in project.h and recompiling).",
1103                   MAX_AF_FILES);
1104             }
1105             config->re_filterfile_short[i] = strdup(arg);
1106             config->re_filterfile[i] = make_path(config->confdir, arg);
1107
1108             continue;
1109
1110 /* *************************************************************************
1111  * forward url-pattern (.|http-proxy-host[:port])
1112  * *************************************************************************/
1113          case hash_forward:
1114             vec_count = ssplit(arg, " \t", vec, SZ(vec), 1, 1);
1115
1116             if (vec_count != 2)
1117             {
1118                log_error(LOG_LEVEL_ERROR, "Wrong number of parameters for forward "
1119                      "directive in configuration file.");
1120                string_append(&config->proxy_args,
1121                   "<br>\nWARNING: Wrong number of parameters for "
1122                   "forward directive in configuration file.");
1123                continue;
1124             }
1125
1126             /* allocate a new node */
1127             cur_fwd = zalloc(sizeof(*cur_fwd));
1128             if (cur_fwd == NULL)
1129             {
1130                log_error(LOG_LEVEL_FATAL, "can't allocate memory for configuration");
1131                /* Never get here - LOG_LEVEL_FATAL causes program exit */
1132                continue;
1133             }
1134
1135             cur_fwd->type = SOCKS_NONE;
1136
1137             /* Save the URL pattern */
1138             if (create_url_spec(cur_fwd->url, vec[0]))
1139             {
1140                log_error(LOG_LEVEL_ERROR, "Bad URL specifier for forward "
1141                      "directive in configuration file.");
1142                string_append(&config->proxy_args,
1143                   "<br>\nWARNING: Bad URL specifier for "
1144                   "forward directive in configuration file.");
1145                continue;
1146             }
1147
1148             /* Parse the parent HTTP proxy host:port */
1149             p = vec[1];
1150
1151             if (strcmp(p, ".") != 0)
1152             {
1153                cur_fwd->forward_host = strdup(p);
1154
1155                if (NULL != (p = strchr(cur_fwd->forward_host, ':')))
1156                {
1157                   *p++ = '\0';
1158                   cur_fwd->forward_port = atoi(p);
1159                }
1160
1161                if (cur_fwd->forward_port <= 0)
1162                {
1163                   cur_fwd->forward_port = 8000;
1164                }
1165             }
1166
1167             /* Add to list. */
1168             cur_fwd->next = config->forward;
1169             config->forward = cur_fwd;
1170
1171             continue;
1172
1173 /* *************************************************************************
1174  * forward-socks4 url-pattern socks-proxy[:port] (.|http-proxy[:port])
1175  * *************************************************************************/
1176          case hash_forward_socks4:
1177             vec_count = ssplit(arg, " \t", vec, SZ(vec), 1, 1);
1178
1179             if (vec_count != 3)
1180             {
1181                log_error(LOG_LEVEL_ERROR, "Wrong number of parameters for "
1182                      "forward-socks4 directive in configuration file.");
1183                string_append(&config->proxy_args,
1184                   "<br>\nWARNING: Wrong number of parameters for "
1185                   "forward-socks4 directive in configuration file.");
1186                continue;
1187             }
1188
1189             /* allocate a new node */
1190             cur_fwd = zalloc(sizeof(*cur_fwd));
1191             if (cur_fwd == NULL)
1192             {
1193                log_error(LOG_LEVEL_FATAL, "can't allocate memory for configuration");
1194                /* Never get here - LOG_LEVEL_FATAL causes program exit */
1195                continue;
1196             }
1197
1198             cur_fwd->type = SOCKS_4;
1199
1200             /* Save the URL pattern */
1201             if (create_url_spec(cur_fwd->url, vec[0]))
1202             {
1203                log_error(LOG_LEVEL_ERROR, "Bad URL specifier for forward-socks4 "
1204                      "directive in configuration file.");
1205                string_append(&config->proxy_args,
1206                   "<br>\nWARNING: Bad URL specifier for "
1207                   "forward-socks4 directive in configuration file.");
1208                continue;
1209             }
1210
1211             /* Parse the SOCKS proxy host[:port] */
1212             p = vec[1];
1213
1214             if (strcmp(p, ".") != 0)
1215             {
1216                cur_fwd->gateway_host = strdup(p);
1217
1218                if (NULL != (p = strchr(cur_fwd->gateway_host, ':')))
1219                {
1220                   *p++ = '\0';
1221                   cur_fwd->gateway_port = atoi(p);
1222                }
1223                if (cur_fwd->gateway_port <= 0)
1224                {
1225                   cur_fwd->gateway_port = 1080;
1226                }
1227             }
1228
1229             /* Parse the parent HTTP proxy host[:port] */
1230             p = vec[2];
1231
1232             if (strcmp(p, ".") != 0)
1233             {
1234                cur_fwd->forward_host = strdup(p);
1235
1236                if (NULL != (p = strchr(cur_fwd->forward_host, ':')))
1237                {
1238                   *p++ = '\0';
1239                   cur_fwd->forward_port = atoi(p);
1240                }
1241
1242                if (cur_fwd->forward_port <= 0)
1243                {
1244                   cur_fwd->forward_port = 8000;
1245                }
1246             }
1247
1248             /* Add to list. */
1249             cur_fwd->next = config->forward;
1250             config->forward = cur_fwd;
1251
1252             continue;
1253
1254 /* *************************************************************************
1255  * forward-socks4a url-pattern socks-proxy[:port] (.|http-proxy[:port])
1256  * *************************************************************************/
1257          case hash_forward_socks4a:
1258          case hash_forward_socks5:
1259             vec_count = ssplit(arg, " \t", vec, SZ(vec), 1, 1);
1260
1261             if (vec_count != 3)
1262             {
1263                log_error(LOG_LEVEL_ERROR, "Wrong number of parameters for "
1264                      "forward-socks4a directive in configuration file.");
1265                string_append(&config->proxy_args,
1266                   "<br>\nWARNING: Wrong number of parameters for "
1267                   "forward-socks4a directive in configuration file.");
1268                continue;
1269             }
1270
1271             /* allocate a new node */
1272             cur_fwd = zalloc(sizeof(*cur_fwd));
1273             if (cur_fwd == NULL)
1274             {
1275                log_error(LOG_LEVEL_FATAL, "can't allocate memory for configuration");
1276                /* Never get here - LOG_LEVEL_FATAL causes program exit */
1277                continue;
1278             }
1279
1280             if (directive_hash == hash_forward_socks4a)
1281             {
1282                cur_fwd->type = SOCKS_4A;
1283             }
1284             else
1285             {
1286                cur_fwd->type = SOCKS_5;
1287             }
1288
1289             /* Save the URL pattern */
1290             if (create_url_spec(cur_fwd->url, vec[0]))
1291             {
1292                log_error(LOG_LEVEL_ERROR, "Bad URL specifier for forward-socks4a "
1293                      "directive in configuration file.");
1294                string_append(&config->proxy_args,
1295                   "<br>\nWARNING: Bad URL specifier for "
1296                   "forward-socks4a directive in configuration file.");
1297                continue;
1298             }
1299
1300             /* Parse the SOCKS proxy host[:port] */
1301             p = vec[1];
1302
1303             cur_fwd->gateway_host = strdup(p);
1304
1305             if (NULL != (p = strchr(cur_fwd->gateway_host, ':')))
1306             {
1307                *p++ = '\0';
1308                cur_fwd->gateway_port = atoi(p);
1309             }
1310             if (cur_fwd->gateway_port <= 0)
1311             {
1312                cur_fwd->gateway_port = 1080;
1313             }
1314
1315             /* Parse the parent HTTP proxy host[:port] */
1316             p = vec[2];
1317
1318             if (strcmp(p, ".") != 0)
1319             {
1320                cur_fwd->forward_host = strdup(p);
1321
1322                if (NULL != (p = strchr(cur_fwd->forward_host, ':')))
1323                {
1324                   *p++ = '\0';
1325                   cur_fwd->forward_port = atoi(p);
1326                }
1327
1328                if (cur_fwd->forward_port <= 0)
1329                {
1330                   cur_fwd->forward_port = 8000;
1331                }
1332             }
1333
1334             /* Add to list. */
1335             cur_fwd->next = config->forward;
1336             config->forward = cur_fwd;
1337
1338             continue;
1339
1340 /* *************************************************************************
1341  * forwarded-connect-retries n
1342  * *************************************************************************/
1343          case hash_forwarded_connect_retries :
1344             config->forwarded_connect_retries = atoi(arg);
1345             continue;
1346
1347 /* *************************************************************************
1348  * hostname hostname-to-show-on-cgi-pages
1349  * *************************************************************************/
1350          case hash_hostname :
1351             freez(config->hostname);
1352             config->hostname = strdup(arg);
1353             if (NULL == config->hostname)
1354             {
1355                log_error(LOG_LEVEL_FATAL, "Out of memory saving hostname.");
1356             }
1357             continue;
1358
1359 /* *************************************************************************
1360  * keep-alive-timeout timeout
1361  * *************************************************************************/
1362 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1363          case hash_keep_alive_timeout :
1364             if (*arg != '\0')
1365             {
1366                int timeout = atoi(arg);
1367                if (0 <= timeout)
1368                {
1369                   config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
1370                   keep_alive_timeout = timeout;
1371                }
1372                else
1373                {
1374                   config->feature_flags &= ~RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
1375                }
1376             }
1377             continue;
1378 #endif
1379
1380 /* *************************************************************************
1381  * listen-address [ip][:port]
1382  * *************************************************************************/
1383          case hash_listen_address :
1384             freez(config->haddr);
1385             config->haddr = strdup(arg);
1386             continue;
1387
1388 /* *************************************************************************
1389  * logdir directory-name
1390  * *************************************************************************/
1391          case hash_logdir :
1392             freez(config->logdir);
1393             config->logdir = make_path(NULL, arg);
1394             continue;
1395
1396 /* *************************************************************************
1397  * logfile log-file-name
1398  * In logdir by default
1399  * *************************************************************************/
1400          case hash_logfile :
1401             if (!no_daemon)
1402             {
1403                logfile = make_path(config->logdir, arg);
1404                if (NULL == logfile)
1405                {
1406                   log_error(LOG_LEVEL_FATAL, "Out of memory while creating logfile path");
1407                }
1408             }
1409             continue;
1410
1411 /* *************************************************************************
1412  * permit-access source-ip[/significant-bits] [dest-ip[/significant-bits]]
1413  * *************************************************************************/
1414 #ifdef FEATURE_ACL
1415          case hash_permit_access:
1416             vec_count = ssplit(arg, " \t", vec, SZ(vec), 1, 1);
1417
1418             if ((vec_count != 1) && (vec_count != 2))
1419             {
1420                log_error(LOG_LEVEL_ERROR, "Wrong number of parameters for "
1421                      "permit-access directive in configuration file.");
1422                string_append(&config->proxy_args,
1423                   "<br>\nWARNING: Wrong number of parameters for "
1424                   "permit-access directive in configuration file.<br><br>\n");
1425
1426                continue;
1427             }
1428
1429             /* allocate a new node */
1430             cur_acl = (struct access_control_list *) zalloc(sizeof(*cur_acl));
1431
1432             if (cur_acl == NULL)
1433             {
1434                log_error(LOG_LEVEL_FATAL, "can't allocate memory for configuration");
1435                /* Never get here - LOG_LEVEL_FATAL causes program exit */
1436                continue;
1437             }
1438             cur_acl->action = ACL_PERMIT;
1439
1440             if (acl_addr(vec[0], cur_acl->src) < 0)
1441             {
1442                log_error(LOG_LEVEL_ERROR, "Invalid source address, port or netmask "
1443                   "for permit-access directive in configuration file: \"%s\"", vec[0]);
1444                string_append(&config->proxy_args,
1445                   "<br>\nWARNING: Invalid source address, port or netmask for "
1446                   "permit-access directive in configuration file: \"");
1447                string_append(&config->proxy_args,
1448                   vec[0]);
1449                string_append(&config->proxy_args,
1450                   "\"<br><br>\n");
1451                freez(cur_acl);
1452                continue;
1453             }
1454             if (vec_count == 2)
1455             {
1456                if (acl_addr(vec[1], cur_acl->dst) < 0)
1457                {
1458                   log_error(LOG_LEVEL_ERROR, "Invalid destination address, port or netmask "
1459                      "for permit-access directive in configuration file: \"%s\"", vec[1]);
1460                   string_append(&config->proxy_args,
1461                      "<br>\nWARNING: Invalid destination address, port or netmask for "
1462                      "permit-access directive in configuration file: \"");
1463                   string_append(&config->proxy_args,
1464                      vec[1]);
1465                   string_append(&config->proxy_args,
1466                      "\"<br><br>\n");
1467                   freez(cur_acl);
1468                   continue;
1469                }
1470             }
1471
1472             /*
1473              * Add it to the list.  Note we reverse the list to get the
1474              * behaviour the user expects.  With both the ACL and
1475              * actions file, the last match wins.  However, the internal
1476              * implementations are different:  The actions file is stored
1477              * in the same order as the file, and scanned completely.
1478              * With the ACL, we reverse the order as we load it, then
1479              * when we scan it we stop as soon as we get a match.
1480              */
1481             cur_acl->next  = config->acl;
1482             config->acl = cur_acl;
1483
1484             continue;
1485 #endif /* def FEATURE_ACL */
1486
1487 /* *************************************************************************
1488  * proxy-info-url url
1489  * *************************************************************************/
1490          case hash_proxy_info_url :
1491             freez(config->proxy_info_url);
1492             config->proxy_info_url = strdup(arg);
1493             continue;
1494
1495 /* *************************************************************************
1496  * single-threaded
1497  * *************************************************************************/
1498          case hash_single_threaded :
1499             config->multi_threaded = 0;
1500             continue;
1501
1502 /* *************************************************************************
1503  * socket-timeout numer_of_seconds
1504  * *************************************************************************/
1505          case hash_socket_timeout :
1506             if (*arg != '\0')
1507             {
1508                int socket_timeout = atoi(arg);
1509                if (0 < socket_timeout)
1510                {
1511                   config->socket_timeout = socket_timeout;
1512                }
1513                else
1514                {
1515                   log_error(LOG_LEVEL_FATAL,
1516                      "Invalid socket-timeout: '%s'", arg);
1517                }
1518             }
1519             continue;
1520
1521 /* *************************************************************************
1522  * split-large-cgi-forms
1523  * *************************************************************************/
1524          case hash_split_large_cgi_forms :
1525             if ((*arg != '\0') && (0 != atoi(arg)))
1526             {
1527                config->feature_flags |= RUNTIME_FEATURE_SPLIT_LARGE_FORMS;
1528             }
1529             else
1530             {
1531                config->feature_flags &= ~RUNTIME_FEATURE_SPLIT_LARGE_FORMS;
1532             }
1533             continue;
1534
1535 /* *************************************************************************
1536  * templdir directory-name
1537  * *************************************************************************/
1538          case hash_templdir :
1539             freez(config->templdir);
1540             config->templdir = make_path(NULL, arg);
1541             continue;
1542
1543 /* *************************************************************************
1544  * toggle (0|1)
1545  * *************************************************************************/
1546 #ifdef FEATURE_TOGGLE
1547          case hash_toggle :
1548             global_toggle_state = atoi(arg);
1549             continue;
1550 #endif /* def FEATURE_TOGGLE */
1551
1552 /* *************************************************************************
1553  * trust-info-url url
1554  * *************************************************************************/
1555 #ifdef FEATURE_TRUST
1556          case hash_trust_info_url :
1557             enlist(config->trust_info, arg);
1558             continue;
1559 #endif /* def FEATURE_TRUST */
1560
1561 /* *************************************************************************
1562  * trustfile filename
1563  * (In confdir by default.)
1564  * *************************************************************************/
1565 #ifdef FEATURE_TRUST
1566          case hash_trustfile :
1567             freez(config->trustfile);
1568             config->trustfile = make_path(config->confdir, arg);
1569             continue;
1570 #endif /* def FEATURE_TRUST */
1571
1572 /* *************************************************************************
1573  * usermanual url
1574  * *************************************************************************/
1575          case hash_usermanual :
1576             freez(config->usermanual);
1577             config->usermanual = strdup(arg);
1578             continue;
1579
1580 /* *************************************************************************
1581  * Win32 Console options:
1582  * *************************************************************************/
1583
1584 /* *************************************************************************
1585  * hide-console
1586  * *************************************************************************/
1587 #ifdef _WIN_CONSOLE
1588          case hash_hide_console :
1589             hideConsole = 1;
1590             continue;
1591 #endif /*def _WIN_CONSOLE*/
1592
1593
1594 /* *************************************************************************
1595  * Win32 GUI options:
1596  * *************************************************************************/
1597
1598 #if defined(_WIN32) && ! defined(_WIN_CONSOLE)
1599 /* *************************************************************************
1600  * activity-animation (0|1)
1601  * *************************************************************************/
1602          case hash_activity_animation :
1603             g_bShowActivityAnimation = atoi(arg);
1604             continue;
1605
1606 /* *************************************************************************
1607  *  close-button-minimizes (0|1)
1608  * *************************************************************************/
1609          case hash_close_button_minimizes :
1610             g_bCloseHidesWindow = atoi(arg);
1611             continue;
1612
1613 /* *************************************************************************
1614  * log-buffer-size (0|1)
1615  * *************************************************************************/
1616          case hash_log_buffer_size :
1617             g_bLimitBufferSize = atoi(arg);
1618             continue;
1619
1620 /* *************************************************************************
1621  * log-font-name fontnane
1622  * *************************************************************************/
1623          case hash_log_font_name :
1624             strcpy( g_szFontFaceName, arg );
1625             continue;
1626
1627 /* *************************************************************************
1628  * log-font-size n
1629  * *************************************************************************/
1630          case hash_log_font_size :
1631             g_nFontSize = atoi(arg);
1632             continue;
1633
1634 /* *************************************************************************
1635  * log-highlight-messages (0|1)
1636  * *************************************************************************/
1637          case hash_log_highlight_messages :
1638             g_bHighlightMessages = atoi(arg);
1639             continue;
1640
1641 /* *************************************************************************
1642  * log-max-lines n
1643  * *************************************************************************/
1644          case hash_log_max_lines :
1645             g_nMaxBufferLines = atoi(arg);
1646             continue;
1647
1648 /* *************************************************************************
1649  * log-messages (0|1)
1650  * *************************************************************************/
1651          case hash_log_messages :
1652             g_bLogMessages = atoi(arg);
1653             continue;
1654
1655 /* *************************************************************************
1656  * show-on-task-bar (0|1)
1657  * *************************************************************************/
1658          case hash_show_on_task_bar :
1659             g_bShowOnTaskBar = atoi(arg);
1660             continue;
1661
1662 #endif /* defined(_WIN32) && ! defined(_WIN_CONSOLE) */
1663
1664
1665 /* *************************************************************************
1666  * Warnings about unsupported features
1667  * *************************************************************************/
1668 #ifndef FEATURE_ACL
1669          case hash_deny_access:
1670 #endif /* ndef FEATURE_ACL */
1671 #ifndef FEATURE_CGI_EDIT_ACTIONS
1672          case hash_enable_edit_actions:
1673 #endif /* ndef FEATURE_CGI_EDIT_ACTIONS */
1674 #ifndef FEATURE_TOGGLE
1675          case hash_enable_remote_toggle:
1676 #endif /* ndef FEATURE_TOGGLE */
1677 #ifndef FEATURE_ACL
1678          case hash_permit_access:
1679 #endif /* ndef FEATURE_ACL */
1680 #ifndef FEATURE_TOGGLE
1681          case hash_toggle :
1682 #endif /* ndef FEATURE_TOGGLE */
1683 #ifndef FEATURE_TRUST
1684          case hash_trustfile :
1685          case hash_trust_info_url :
1686 #endif /* ndef FEATURE_TRUST */
1687
1688 #ifndef _WIN_CONSOLE
1689          case hash_hide_console :
1690 #endif /* ndef _WIN_CONSOLE */
1691
1692 #if defined(_WIN_CONSOLE) || ! defined(_WIN32)
1693          case hash_activity_animation :
1694          case hash_close_button_minimizes :
1695          case hash_log_buffer_size :
1696          case hash_log_font_name :
1697          case hash_log_font_size :
1698          case hash_log_highlight_messages :
1699          case hash_log_max_lines :
1700          case hash_log_messages :
1701          case hash_show_on_task_bar :
1702 #endif /* defined(_WIN_CONSOLE) || ! defined(_WIN32) */
1703             /* These warnings are annoying - so hide them. -- Jon */
1704             /* log_error(LOG_LEVEL_INFO, "Unsupported directive \"%s\" ignored.", cmd); */
1705             continue;
1706
1707 /* *************************************************************************/
1708          default :
1709 /* *************************************************************************/
1710             /*
1711              * I decided that I liked this better as a warning than an
1712              * error.  To change back to an error, just change log level
1713              * to LOG_LEVEL_FATAL.
1714              */
1715             log_error(LOG_LEVEL_ERROR, "Ignoring unrecognized directive '%s' (%luul) in line %lu "
1716                   "in configuration file (%s).",  buf, directive_hash, linenum, configfile);
1717             string_append(&config->proxy_args,
1718                " <strong class='warning'>Warning: ignored unrecognized directive above.</strong><br>");
1719             continue;
1720
1721 /* *************************************************************************/
1722       } /* end switch( hash_string(cmd) ) */
1723    } /* end while ( read_config_line(...) ) */
1724
1725    fclose(configfp);
1726
1727    set_debug_level(config->debug);
1728
1729    freez(config->logfile);
1730
1731    if (!no_daemon)
1732    {
1733       if (NULL != logfile)
1734       {
1735          config->logfile = logfile;
1736          init_error_log(Argv[0], config->logfile);
1737       }
1738       else
1739       {
1740          disable_logging();
1741       }
1742    }
1743
1744 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1745    if (config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1746    {
1747       if (config->multi_threaded)
1748       {
1749          set_keep_alive_timeout(keep_alive_timeout);
1750       }
1751       else
1752       {
1753          /*
1754           * While we could use keep-alive without multiple threads
1755           * if we didn't bother with enforcing the connection timeout,
1756           * that might make Tor users sad, even though they shouldn't
1757           * enable the single-threaded option anyway.
1758           */
1759          config->feature_flags &= ~RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
1760          log_error(LOG_LEVEL_ERROR,
1761             "Config option single-threaded disables connection keep-alive.");
1762       }
1763    }
1764 #endif
1765
1766    if (NULL == config->proxy_args)
1767    {
1768       log_error(LOG_LEVEL_FATAL, "Out of memory loading config - insufficient memory for config->proxy_args");
1769    }
1770
1771    if (config->actions_file[0])
1772    {
1773       add_loader(load_action_files, config);
1774    }
1775
1776    if (config->re_filterfile[0])
1777    {
1778       add_loader(load_re_filterfiles, config);
1779    }
1780
1781 #ifdef FEATURE_TRUST
1782    if (config->trustfile)
1783    {
1784       add_loader(load_trustfile, config);
1785    }
1786 #endif /* def FEATURE_TRUST */
1787
1788    if ( NULL == config->haddr )
1789    {
1790       config->haddr = strdup( HADDR_DEFAULT );
1791    }
1792
1793    if ( NULL != config->haddr )
1794    {
1795       if (NULL != (p = strchr(config->haddr, ':')))
1796       {
1797          *p++ = '\0';
1798          if (*p)
1799          {
1800             config->hport = atoi(p);
1801          }
1802       }
1803
1804       if (config->hport <= 0)
1805       {
1806          *--p = ':';
1807          log_error(LOG_LEVEL_FATAL, "invalid bind port spec %s", config->haddr);
1808          /* Never get here - LOG_LEVEL_FATAL causes program exit */
1809       }
1810       if (*config->haddr == '\0')
1811       {
1812          /*
1813           * Only the port specified. We stored it in config->hport
1814           * and don't need its text representation anymore.
1815           */
1816          freez(config->haddr);
1817       }
1818    }
1819
1820    /*
1821     * Want to run all the loaders once now.
1822     *
1823     * Need to set up a fake csp, so they can get to the config.
1824     */
1825    fake_csp = (struct client_state *) zalloc (sizeof(*fake_csp));
1826    fake_csp->config = config;
1827
1828    if (run_loader(fake_csp))
1829    {
1830       freez(fake_csp);
1831       log_error(LOG_LEVEL_FATAL, "A loader failed while loading config file. Exiting.");
1832       /* Never get here - LOG_LEVEL_FATAL causes program exit */
1833    }
1834    freez(fake_csp);
1835
1836 /* FIXME: this is a kludge for win32 */
1837 #if defined(_WIN32) && !defined (_WIN_CONSOLE)
1838
1839    g_default_actions_file  = config->actions_file[0]; /* FIXME Hope this is default.action */
1840    g_user_actions_file = config->actions_file[1]; /* FIXME Hope this is user.action */
1841    g_re_filterfile    = config->re_filterfile[0]; /* FIXME Hope this is default.filter */
1842
1843 #ifdef FEATURE_TRUST
1844    g_trustfile        = config->trustfile;
1845 #endif /* def FEATURE_TRUST */
1846
1847
1848 #endif /* defined(_WIN32) && !defined (_WIN_CONSOLE) */
1849 /* FIXME: end kludge */
1850
1851
1852    config->need_bind = 1;
1853
1854    if (current_configfile)
1855    {
1856       struct configuration_spec * oldcfg = (struct configuration_spec *)
1857                                            current_configfile->f;
1858       /*
1859        * Check if config->haddr,hport == oldcfg->haddr,hport
1860        *
1861        * The following could be written more compactly as a single,
1862        * (unreadably long) if statement.
1863        */
1864       config->need_bind = 0;
1865       if (config->hport != oldcfg->hport)
1866       {
1867          config->need_bind = 1;
1868       }
1869       else if (config->haddr == NULL)
1870       {
1871          if (oldcfg->haddr != NULL)
1872          {
1873             config->need_bind = 1;
1874          }
1875       }
1876       else if (oldcfg->haddr == NULL)
1877       {
1878          config->need_bind = 1;
1879       }
1880       else if (0 != strcmp(config->haddr, oldcfg->haddr))
1881       {
1882          config->need_bind = 1;
1883       }
1884
1885       current_configfile->unloader = unload_configfile;
1886    }
1887
1888    fs->next = files->next;
1889    files->next = fs;
1890
1891    current_configfile = fs;
1892
1893    return (config);
1894 }
1895
1896
1897 /*********************************************************************
1898  *
1899  * Function    :  savearg
1900  *
1901  * Description :  Called from `load_config'.  It saves each non-empty
1902  *                and non-comment line from config into
1903  *                config->proxy_args.  This is used to create the
1904  *                show-proxy-args page.  On error, frees
1905  *                config->proxy_args and sets it to NULL
1906  *
1907  * Parameters  :
1908  *          1  :  command = config setting that was found
1909  *          2  :  argument = the setting's argument (if any)
1910  *          3  :  config = Configuration to save into.
1911  *
1912  * Returns     :  N/A
1913  *
1914  *********************************************************************/
1915 static void savearg(char *command, char *argument, struct configuration_spec * config)
1916 {
1917    char * buf;
1918    char * s;
1919
1920    assert(command);
1921    assert(argument);
1922
1923    /*
1924     * Add config option name embedded in
1925     * link to its section in the user-manual
1926     */
1927    buf = strdup("\n<a href=\"");
1928    if (!strncmpic(config->usermanual, "file://", 7) ||
1929        !strncmpic(config->usermanual, "http", 4))
1930    {
1931       string_append(&buf, config->usermanual);
1932    }
1933    else
1934    {
1935       string_append(&buf, "http://" CGI_SITE_2_HOST "/user-manual/");
1936    }
1937    string_append(&buf, CONFIG_HELP_PREFIX);
1938    string_join  (&buf, string_toupper(command));
1939    string_append(&buf, "\">");
1940    string_append(&buf, command);
1941    string_append(&buf, "</a> ");
1942
1943    if (NULL == buf)
1944    {
1945       freez(config->proxy_args);
1946       return;
1947    }
1948
1949    if ( (NULL != argument) && ('\0' != *argument) )
1950    {
1951       s = html_encode(argument);
1952       if (NULL == s)
1953       {
1954          freez(buf);
1955          freez(config->proxy_args);
1956          return;
1957       }
1958
1959       if (strncmpic(argument, "http://", 7) == 0)
1960       {
1961          string_append(&buf, "<a href=\"");
1962          string_append(&buf, s);
1963          string_append(&buf, "\">");
1964          string_join  (&buf, s);
1965          string_append(&buf, "</a>");
1966       }
1967       else
1968       {
1969          string_join  (&buf, s);
1970       }
1971    }
1972
1973    string_append(&buf, "<br>");
1974    string_join(&config->proxy_args, buf);
1975 }
1976
1977
1978 /*
1979   Local Variables:
1980   tab-width: 3
1981   end:
1982 */