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