workaround for user error: some people were putting "Address " in their
[tor.git] / src / or / config.c
blob0f2e395242b570f31349ae3f2366d3159045d0a9
1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char config_c_id[] = "$Id$";
8 /**
9 * \file config.c
11 * \brief Code to parse and interpret configuration files.
12 **/
14 #include "or.h"
15 #ifdef MS_WINDOWS
16 #include <shlobj.h>
17 #endif
18 #include "../common/aes.h"
20 /** Enumeration of types which option values can take */
21 typedef enum config_type_t {
22 CONFIG_TYPE_STRING = 0, /**< An arbitrary string. */
23 CONFIG_TYPE_UINT, /**< A non-negative integer less than MAX_INT */
24 CONFIG_TYPE_INTERVAL, /**< A number of seconds, with optional units*/
25 CONFIG_TYPE_MEMUNIT, /**< A number of bytes, with optional units*/
26 CONFIG_TYPE_DOUBLE, /**< A floating-point value */
27 CONFIG_TYPE_BOOL, /**< A boolean value, expressed as 0 or 1. */
28 CONFIG_TYPE_CSV, /**< A list of strings, separated by commas and optional
29 * whitespace. */
30 CONFIG_TYPE_LINELIST, /**< Uninterpreted config lines */
31 CONFIG_TYPE_LINELIST_S, /**< Uninterpreted, context-sensitive config lines,
32 * mixed with other keywords. */
33 CONFIG_TYPE_LINELIST_V, /**< Catch-all "virtual" option to summarize
34 * context-sensitive config lines when fetching.
36 CONFIG_TYPE_OBSOLETE, /**< Obsolete (ignored) option. */
37 } config_type_t;
39 /* An abbreviation for a configuration option allowed on the command line */
40 typedef struct config_abbrev_t {
41 const char *abbreviated;
42 const char *full;
43 int commandline_only;
44 } config_abbrev_t;
46 /* Handy macro for declaring "In the config file or on the command line,
47 * you can abbreviate <b>tok</b>s as <b>tok</b>". */
48 #define PLURAL(tok) { #tok, #tok "s", 0 }
50 /* A list of command-line abbreviations. */
51 static config_abbrev_t config_abbrevs[] = {
52 PLURAL(ExitNode),
53 PLURAL(EntryNode),
54 PLURAL(ExcludeNode),
55 PLURAL(FirewallPort),
56 PLURAL(LongLivedPort),
57 PLURAL(HiddenServiceNode),
58 PLURAL(HiddenServiceExcludeNode),
59 PLURAL(NumCpu),
60 PLURAL(RendNode),
61 PLURAL(RendExcludeNode),
62 PLURAL(StrictEntryNode),
63 PLURAL(StrictExitNode),
64 { "l", "Log", 1},
65 { "BandwidthRateBytes", "BandwidthRate", 0},
66 { "BandwidthBurstBytes", "BandwidthBurst", 0},
67 { "DirFetchPostPeriod", "StatusFetchPeriod", 0},
68 { "MaxConn", "ConnLimit", 0},
69 { NULL, NULL , 0},
71 #undef PLURAL
73 /** A variable allowed in the configuration file or on the command line. */
74 typedef struct config_var_t {
75 const char *name; /**< The full keyword (case insensitive). */
76 config_type_t type; /**< How to interpret the type and turn it into a value. */
77 off_t var_offset; /**< Offset of the corresponding member of or_options_t. */
78 const char *initvalue; /**< String (or null) describing initial value. */
79 } config_var_t;
81 /** Return the offset of <b>member</b> within the type <b>tp</b>, in bytes */
82 #define STRUCT_OFFSET(tp, member) ((off_t) (((char*)&((tp*)0)->member)-(char*)0))
83 /** An entry for config_vars: "The option <b>name</b> has type
84 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
85 * or_options_t.<b>member</b>"
87 #define VAR(name,conftype,member,initvalue) \
88 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), initvalue }
89 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
90 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
92 /** Array of configuration options. Until we disallow nonstandard
93 * abbreviations, order is significant, since the first matching option will
94 * be chosen first.
96 static config_var_t config_vars[] = {
97 VAR("Address", STRING, Address, NULL),
98 VAR("AccountingStart", STRING, AccountingStart, NULL),
99 VAR("AllowUnverifiedNodes",CSV, AllowUnverifiedNodes, "middle,rendezvous"),
100 VAR("AuthoritativeDirectory",BOOL, AuthoritativeDir, "0"),
101 VAR("BandwidthRate", MEMUNIT, BandwidthRate, "2 MB"),
102 VAR("BandwidthBurst", MEMUNIT, BandwidthBurst, "5 MB"),
103 VAR("MaxAdvertisedBandwidth",MEMUNIT,MaxAdvertisedBandwidth,"128 TB"),
104 VAR("ClientOnly", BOOL, ClientOnly, "0"),
105 VAR("ContactInfo", STRING, ContactInfo, NULL),
106 VAR("ControlPort", UINT, ControlPort, "0"),
107 VAR("CookieAuthentication",BOOL, CookieAuthentication, "0"),
108 VAR("DebugLogFile", STRING, DebugLogFile, NULL),
109 VAR("DataDirectory", STRING, DataDirectory, NULL),
110 VAR("DirAllowPrivateAddresses",BOOL, DirAllowPrivateAddresses, NULL),
111 VAR("DirPort", UINT, DirPort, "0"),
112 VAR("DirBindAddress", LINELIST, DirBindAddress, NULL),
113 /** DOCDOC **/
114 VAR("DirFetchPeriod", INTERVAL, DirFetchPeriod, "0 seconds"),
115 VAR("DirPostPeriod", INTERVAL, DirPostPeriod, "20 minutes"),
116 VAR("RendPostPeriod", INTERVAL, RendPostPeriod, "20 minutes"),
117 VAR("DirPolicy", LINELIST, DirPolicy, NULL),
118 VAR("DirServer", LINELIST, DirServers, NULL),
119 VAR("ExitNodes", STRING, ExitNodes, NULL),
120 VAR("EntryNodes", STRING, EntryNodes, NULL),
121 VAR("StrictExitNodes", BOOL, StrictExitNodes, "0"),
122 VAR("StrictEntryNodes", BOOL, StrictEntryNodes, "0"),
123 VAR("ExitPolicy", LINELIST, ExitPolicy, NULL),
124 VAR("ExcludeNodes", STRING, ExcludeNodes, NULL),
125 VAR("TrackHostExits", CSV, TrackHostExits, NULL),
126 VAR("TrackHostExitsExpire",INTERVAL, TrackHostExitsExpire, "30 minutes"),
127 VAR("MapAddress", LINELIST, AddressMap, NULL),
128 VAR("FascistFirewall", BOOL, FascistFirewall, "0"),
129 VAR("FirewallPorts", CSV, FirewallPorts, "80,443"),
130 VAR("MyFamily", STRING, MyFamily, NULL),
131 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
132 VAR("NoPublish", BOOL, NoPublish, "0"),
133 VAR("Group", STRING, Group, NULL),
134 VAR("HashedControlPassword",STRING, HashedControlPassword, NULL),
135 VAR("HttpProxy", STRING, HttpProxy, NULL),
136 VAR("HttpsProxy", STRING, HttpsProxy, NULL),
137 VAR("HttpsProxyAuthenticator",STRING,HttpsProxyAuthenticator,NULL),
138 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
139 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
140 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
141 VAR("HiddenServiceNodes", LINELIST_S, RendConfigLines, NULL),
142 VAR("HiddenServiceExcludeNodes", LINELIST_S, RendConfigLines, NULL),
143 VAR("IgnoreVersion", BOOL, IgnoreVersion, "0"),
144 VAR("KeepalivePeriod", INTERVAL, KeepalivePeriod, "5 minutes"),
145 VAR("Log", LINELIST, Logs, NULL),
146 VAR("LogLevel", LINELIST_S, OldLogOptions, NULL),
147 VAR("LogFile", LINELIST_S, OldLogOptions, NULL),
148 OBSOLETE("LinkPadding"),
149 VAR("ConnLimit", UINT, ConnLimit, "1024"),
150 VAR("MaxOnionsPending", UINT, MaxOnionsPending, "100"),
151 VAR("MonthlyAccountingStart",UINT, _MonthlyAccountingStart,"0"),
152 VAR("AccountingMaxKB", UINT, _AccountingMaxKB, "0"),
153 VAR("AccountingMax", MEMUNIT, AccountingMax, "0 bytes"),
154 VAR("Nickname", STRING, Nickname, NULL),
155 VAR("NewCircuitPeriod", INTERVAL, NewCircuitPeriod, "30 seconds"),
156 VAR("MaxCircuitDirtiness", INTERVAL, MaxCircuitDirtiness, "10 minutes"),
157 VAR("NumCpus", UINT, NumCpus, "1"),
158 VAR("ORPort", UINT, ORPort, "0"),
159 VAR("ORBindAddress", LINELIST, ORBindAddress, NULL),
160 VAR("OutboundBindAddress", STRING, OutboundBindAddress, NULL),
161 VAR("PidFile", STRING, PidFile, NULL),
162 VAR("LongLivedPorts", CSV, LongLivedPorts, "21,22,706,1863,5050,5190,5222,5223,6667,8300,8888"),
163 VAR("PathlenCoinWeight", DOUBLE, PathlenCoinWeight, "0.3"),
164 VAR("RedirectExit", LINELIST, RedirectExit, NULL),
165 OBSOLETE("RouterFile"),
166 VAR("RunAsDaemon", BOOL, RunAsDaemon, "0"),
167 VAR("RunTesting", BOOL, RunTesting, "0"),
168 VAR("RecommendedVersions", LINELIST, RecommendedVersions, NULL),
169 VAR("RendNodes", STRING, RendNodes, NULL),
170 VAR("RendExcludeNodes", STRING, RendExcludeNodes, NULL),
171 VAR("ShutdownWaitLength", INTERVAL, ShutdownWaitLength, "30 seconds"),
172 VAR("SocksPort", UINT, SocksPort, "9050"),
173 VAR("SocksBindAddress", LINELIST, SocksBindAddress, NULL),
174 VAR("SocksPolicy", LINELIST, SocksPolicy, NULL),
175 /** DOCDOC */
176 VAR("StatusFetchPeriod", INTERVAL, StatusFetchPeriod, "0 seconds"),
177 VAR("SysLog", LINELIST_S, OldLogOptions, NULL),
178 OBSOLETE("TrafficShaping"),
179 VAR("User", STRING, User, NULL),
180 VAR("__LeaveStreamsUnattached", BOOL,LeaveStreamsUnattached, "0"),
181 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
183 #undef VAR
184 #undef OBSOLETE
186 /** Largest allowed config line */
187 #define CONFIG_LINE_T_MAXLEN 4096
189 static void config_line_append(struct config_line_t **lst,
190 const char *key, const char *val);
191 static void option_reset(or_options_t *options, config_var_t *var);
192 static void options_free(or_options_t *options);
193 static int option_is_same(or_options_t *o1, or_options_t *o2,const char *name);
194 static or_options_t *options_dup(or_options_t *old);
195 static int options_validate(or_options_t *options);
196 static int options_transition_allowed(or_options_t *old, or_options_t *new);
197 static int check_nickname_list(const char *lst, const char *name);
198 static void config_register_addressmaps(or_options_t *options);
200 static int parse_dir_server_line(const char *line, int validate_only);
201 static int parse_redirect_line(smartlist_t *result,
202 struct config_line_t *line);
203 static int parse_log_severity_range(const char *range, int *min_out,
204 int *max_out);
205 static int convert_log_option(or_options_t *options,
206 struct config_line_t *level_opt,
207 struct config_line_t *file_opt, int isDaemon);
208 static int add_single_log_option(or_options_t *options, int minSeverity,
209 int maxSeverity,
210 const char *type, const char *fname);
211 static int normalize_log_options(or_options_t *options);
212 static int validate_data_directory(or_options_t *options);
213 static int write_configuration_file(const char *fname, or_options_t *options);
215 static uint64_t config_parse_memunit(const char *s, int *ok);
216 static int config_parse_interval(const char *s, int *ok);
217 static void print_cvs_version(void);
220 * Functions to read and write the global options pointer.
223 /** Command-line and config-file options. */
224 static or_options_t *global_options=NULL;
225 /** Name of most recently read torrc file. */
226 static char *config_fname = NULL;
228 /** Return the currently configured options. */
229 or_options_t *
230 get_options(void) {
231 tor_assert(global_options);
232 return global_options;
235 /** Change the current global options to contain <b>new_val</b> instead
236 * of their current value; free the old value as necessary.
238 void
239 set_options(or_options_t *new_val) {
240 if (global_options)
241 options_free(global_options);
242 global_options = new_val;
245 void
246 config_free_all(void)
248 options_free(global_options);
249 tor_free(config_fname);
252 /** Fetch the active option list, and take actions based on it. All
253 * of the things we do should survive being done repeatedly.
254 * Return 0 if all goes well, return -1 if it's time to die.
256 * Note 1: <b>new_val</b> must have previously been validated with
257 * options_validate(), or Tor may freak out and exit.
259 * Note 2: We haven't moved all the "act on new configuration" logic
260 * here yet. Some is still in do_hup() and other places.
263 options_act(void) {
264 struct config_line_t *cl;
265 or_options_t *options = get_options();
266 static int libevent_initialized = 0;
268 /* XXXX009 We once had a reason to separate start_daemon and finish_daemon:
269 * It let us have the parent process stick around until we were sure Tor
270 * was started. Should we make start_daemon get called earlier? -NM */
271 if (options->RunAsDaemon) {
272 start_daemon();
274 if (!libevent_initialized) {
275 configure_libevent_logging();
276 suppress_libevent_log_msg("function not implemented");
277 event_init();
278 suppress_libevent_log_msg(NULL);
279 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
280 /* Making this a NOTICE for now so we can link bugs to a libevent versions
281 * or methods better. */
282 log_fn(LOG_NOTICE, "Initialized libevent version %s using method %s",
283 event_get_version(), event_get_method());
284 #else
285 log_fn(LOG_NOTICE, "Initialized old libevent (version 1.0b or earlier)");
286 #endif
287 libevent_initialized = 1;
290 clear_trusted_dir_servers();
291 for (cl = options->DirServers; cl; cl = cl->next) {
292 if (parse_dir_server_line(cl->value, 0)<0) {
293 log_fn(LOG_ERR,
294 "Bug: Previously validated DirServer line could not be added!");
295 return -1;
299 if (rend_config_services(options, 0)<0) {
300 log_fn(LOG_ERR,
301 "Bug: Previously validated hidden services line could not be added!");
302 return -1;
305 /* Setuid/setgid as appropriate */
306 if (options->User || options->Group) {
307 if (switch_id(options->User, options->Group) != 0) {
308 return -1;
312 /* Ensure data directory is private; create if possible. */
313 if (check_private_dir(options->DataDirectory, CPD_CREATE) != 0) {
314 log_fn(LOG_ERR, "Couldn't access/create private data directory %s",
315 options->DataDirectory);
316 return -1;
319 /* Bail out at this point if we're not going to be a server: we want
320 * to not fork, and to log stuff to stderr. */
321 if (options->command != CMD_RUN_TOR)
322 return 0;
324 mark_logs_temp(); /* Close current logs once new logs are open. */
325 if (config_init_logs(options, 0)<0) /* Configure the log(s) */
326 return -1;
327 /* Close the temporary log we used while starting up, if it isn't already
328 * gone. */
329 close_temp_logs();
330 add_callback_log(LOG_ERR, LOG_ERR, control_event_logmsg);
331 adjust_event_log_severity();
333 options->_ConnLimit =
334 set_max_file_descriptors((unsigned)options->ConnLimit, MAXCONNECTIONS);
335 if (options->_ConnLimit < 0)
336 return -1;
339 smartlist_t *sl = smartlist_create();
340 for (cl = options->RedirectExit; cl; cl = cl->next) {
341 if (parse_redirect_line(sl, cl)<0)
342 return -1;
344 set_exit_redirects(sl);
347 /* Finish backgrounding the process */
348 if (options->RunAsDaemon) {
349 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
350 finish_daemon(options->DataDirectory);
353 /* Write our pid to the pid file. If we do not have write permissions we
354 * will log a warning */
355 if (options->PidFile)
356 write_pidfile(options->PidFile);
358 /* Register addressmap directives */
359 config_register_addressmaps(options);
361 /* Update address policies. */
362 parse_socks_policy();
363 parse_dir_policy();
365 init_cookie_authentication(options->CookieAuthentication);
367 /* reload keys as needed for rendezvous services. */
368 if (rend_service_load_keys()<0) {
369 log_fn(LOG_ERR,"Error loading rendezvous service keys");
370 return -1;
373 /* Set up accounting */
374 if (accounting_parse_options(options, 0)<0) {
375 log_fn(LOG_ERR,"Error in accounting options");
376 return -1;
378 if (accounting_is_enabled(options))
379 configure_accounting(time(NULL));
381 if (!we_are_hibernating() && retry_all_listeners(1) < 0) {
382 log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
383 return -1;
386 #if 0
388 char *smin, *smax;
389 smin = config_dump_options(options, 1);
390 smax = config_dump_options(options, 0);
391 log_fn(LOG_DEBUG, "These are our options:\n%s",smax);
392 log_fn(LOG_DEBUG, "We changed these options:\n%s",smin);
393 tor_free(smin);
394 tor_free(smax);
396 #endif
398 /* Since our options changed, we might need to regenerate and upload our
399 * server descriptor. (We could probably be more clever about only calling
400 * this when something significant changed.)
402 mark_my_descriptor_dirty();
404 return 0;
408 * Functions to parse config options
411 /** If <b>option</b> is an official abbreviation for a longer option,
412 * return the longer option. Otherwise return <b>option</b>.
413 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
414 * apply abbreviations that work for the config file and the command line. */
415 static const char *
416 expand_abbrev(const char *option, int command_line)
418 int i;
419 for (i=0; config_abbrevs[i].abbreviated; ++i) {
420 /* Abbreviations aren't casei. */
421 if (!strcasecmp(option,config_abbrevs[i].abbreviated) &&
422 (command_line || !config_abbrevs[i].commandline_only)) {
423 return config_abbrevs[i].full;
426 return option;
429 /** Helper: Read a list of configuration options from the command line. */
430 static struct config_line_t *
431 config_get_commandlines(int argc, char **argv)
433 struct config_line_t *new;
434 struct config_line_t *front = NULL;
435 char *s;
436 int i = 1;
438 while (i < argc-1) {
439 if (!strcmp(argv[i],"-f") ||
440 !strcmp(argv[i],"--hash-password")) {
441 i += 2; /* command-line option with argument. ignore them. */
442 continue;
443 } else if (!strcmp(argv[i],"--list-fingerprint")) {
444 i += 1; /* command-line option. ignore it. */
445 continue;
446 } else if (!strcmp(argv[i],"--nt-service")) {
447 i += 1;
448 continue;
451 new = tor_malloc(sizeof(struct config_line_t));
452 s = argv[i];
454 while (*s == '-')
455 s++;
457 new->key = tor_strdup(expand_abbrev(s, 1));
458 new->value = tor_strdup(argv[i+1]);
460 log(LOG_DEBUG,"Commandline: parsed keyword '%s', value '%s'",
461 new->key, new->value);
462 new->next = front;
463 front = new;
464 i += 2;
466 return front;
469 /** Helper: allocate a new configuration option mapping 'key' to 'val',
470 * append it to *<b>lst</b>. */
471 static void
472 config_line_append(struct config_line_t **lst,
473 const char *key,
474 const char *val)
476 struct config_line_t *newline;
478 newline = tor_malloc(sizeof(struct config_line_t));
479 newline->key = tor_strdup(key);
480 newline->value = tor_strdup(val);
481 newline->next = NULL;
482 while (*lst)
483 lst = &((*lst)->next);
485 (*lst) = newline;
488 /** Helper: parse the config string and strdup into key/value
489 * strings. Set *result to the list, or NULL if parsing the string
490 * failed. Return 0 on success, -1 on failure. Warn and ignore any
491 * misformatted lines. */
493 config_get_lines(char *string, struct config_line_t **result)
495 struct config_line_t *list = NULL, **next;
496 char *k, *v;
498 next = &list;
499 do {
500 string = parse_line_from_str(string, &k, &v);
501 if (!string) {
502 config_free_lines(list);
503 return -1;
505 if (k && v) {
506 /* This list can get long, so we keep a pointer to the end of it
507 * rather than using config_line_append over and over and getting n^2
508 * performance. This is the only really long list. */
509 *next = tor_malloc(sizeof(struct config_line_t));
510 (*next)->key = tor_strdup(k);
511 (*next)->value = tor_strdup(v);
512 (*next)->next = NULL;
513 next = &((*next)->next);
515 } while (*string);
517 *result = list;
518 return 0;
522 * Free all the configuration lines on the linked list <b>front</b>.
524 void
525 config_free_lines(struct config_line_t *front)
527 struct config_line_t *tmp;
529 while (front) {
530 tmp = front;
531 front = tmp->next;
533 tor_free(tmp->key);
534 tor_free(tmp->value);
535 tor_free(tmp);
539 /** If <b>key</b> is a configuration option, return the corresponding
540 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
541 * warn, and return the corresponding config_var_t. Otherwise return NULL.
543 static config_var_t *config_find_option(const char *key)
545 int i;
546 size_t keylen = strlen(key);
547 if (!keylen)
548 return NULL; /* if they say "--" on the commandline, it's not an option */
549 /* First, check for an exact (case-insensitive) match */
550 for (i=0; config_vars[i].name; ++i) {
551 if (!strcasecmp(key, config_vars[i].name))
552 return &config_vars[i];
554 /* If none, check for an abbreviated match */
555 for (i=0; config_vars[i].name; ++i) {
556 if (!strncasecmp(key, config_vars[i].name, keylen)) {
557 log_fn(LOG_WARN, "The abbreviation '%s' is deprecated. "
558 "Tell Nick and Roger to make it official, or just use '%s' instead",
559 key, config_vars[i].name);
560 return &config_vars[i];
563 /* Okay, unrecognized options */
564 return NULL;
567 /** If <b>c</b> is a syntactically valid configuration line, update
568 * <b>options</b> with its value and return 0. Otherwise return -1 for bad key,
569 * -2 for bad value.
571 * If 'reset' is set, and we get a line containing no value, restore the
572 * option to its default value.
574 static int
575 config_assign_line(or_options_t *options, struct config_line_t *c, int reset)
577 int i, ok;
578 config_var_t *var;
579 void *lvalue;
581 var = config_find_option(c->key);
582 if (!var) {
583 log_fn(LOG_WARN, "Unknown option '%s'. Failing.", c->key);
584 return -1;
586 /* Put keyword into canonical case. */
587 if (strcmp(var->name, c->key)) {
588 tor_free(c->key);
589 c->key = tor_strdup(var->name);
592 if (reset && !strlen(c->value)) {
593 option_reset(options, var);
594 return 0;
597 lvalue = ((char*)options) + var->var_offset;
598 switch (var->type) {
600 case CONFIG_TYPE_UINT:
601 i = tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
602 if (!ok) {
603 log(LOG_WARN, "Int keyword '%s %s' is malformed or out of bounds.",
604 c->key,c->value);
605 return -2;
607 *(int *)lvalue = i;
608 break;
610 case CONFIG_TYPE_INTERVAL: {
611 i = config_parse_interval(c->value, &ok);
612 if (!ok) {
613 return -2;
615 *(int *)lvalue = i;
616 break;
619 case CONFIG_TYPE_MEMUNIT: {
620 uint64_t u64 = config_parse_memunit(c->value, &ok);
621 if (!ok) {
622 return -2;
624 *(uint64_t *)lvalue = u64;
625 break;
628 case CONFIG_TYPE_BOOL:
629 i = tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
630 if (!ok) {
631 log(LOG_WARN, "Boolean keyword '%s' expects 0 or 1.", c->key);
632 return -2;
634 *(int *)lvalue = i;
635 break;
637 case CONFIG_TYPE_STRING:
638 tor_free(*(char **)lvalue);
639 *(char **)lvalue = tor_strdup(c->value);
640 break;
642 case CONFIG_TYPE_DOUBLE:
643 *(double *)lvalue = atof(c->value);
644 break;
646 case CONFIG_TYPE_CSV:
647 if (*(smartlist_t**)lvalue) {
648 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
649 smartlist_clear(*(smartlist_t**)lvalue);
650 } else {
651 *(smartlist_t**)lvalue = smartlist_create();
654 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
655 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
656 break;
658 case CONFIG_TYPE_LINELIST:
659 case CONFIG_TYPE_LINELIST_S:
660 config_line_append((struct config_line_t**)lvalue, c->key, c->value);
661 break;
663 case CONFIG_TYPE_OBSOLETE:
664 log_fn(LOG_WARN, "Skipping obsolete configuration option '%s'", c->key);
665 break;
666 case CONFIG_TYPE_LINELIST_V:
667 log_fn(LOG_WARN, "Can't provide value for virtual option '%s'", c->key);
668 return -2;
669 default:
670 tor_assert(0);
671 break;
673 return 0;
676 /** restore the option named <b>key</b> in options to its default value. */
677 static void
678 config_reset_line(or_options_t *options, const char *key)
680 config_var_t *var;
682 var = config_find_option(key);
683 if (!var)
684 return; /* give error on next pass. */
686 option_reset(options, var);
689 /** Return true iff key is a valid configuration option. */
691 config_option_is_recognized(const char *key)
693 config_var_t *var = config_find_option(key);
694 return (var != NULL);
697 /** Return a canonicalized list of the options assigned for key.
699 struct config_line_t *
700 config_get_assigned_option(or_options_t *options, const char *key)
702 config_var_t *var;
703 const void *value;
704 char buf[32];
705 struct config_line_t *result;
706 tor_assert(options && key);
708 var = config_find_option(key);
709 if (!var) {
710 log_fn(LOG_WARN, "Unknown option '%s'. Failing.", key);
711 return NULL;
712 } else if (var->type == CONFIG_TYPE_LINELIST_S) {
713 log_fn(LOG_WARN, "Can't return context-sensitive '%s' on its own", key);
714 return NULL;
716 value = ((char*)options) + var->var_offset;
718 if (var->type == CONFIG_TYPE_LINELIST ||
719 var->type == CONFIG_TYPE_LINELIST_V) {
720 /* Linelist requires special handling: we just copy and return it. */
721 const struct config_line_t *next_in = *(const struct config_line_t**)value;
722 struct config_line_t **next_out = &result;
723 while (next_in) {
724 *next_out = tor_malloc(sizeof(struct config_line_t));
725 (*next_out)->key = tor_strdup(next_in->key);
726 (*next_out)->value = tor_strdup(next_in->value);
727 next_in = next_in->next;
728 next_out = &((*next_out)->next);
730 (*next_out) = NULL;
731 return result;
734 result = tor_malloc_zero(sizeof(struct config_line_t));
735 result->key = tor_strdup(var->name);
736 switch (var->type)
738 case CONFIG_TYPE_STRING:
739 if (*(char**)value) {
740 result->value = tor_strdup(*(char**)value);
741 } else {
742 tor_free(result->key);
743 tor_free(result);
744 return NULL;
746 break;
747 case CONFIG_TYPE_INTERVAL:
748 case CONFIG_TYPE_UINT:
749 /* This means every or_options_t uint or bool element
750 * needs to be an int. Not, say, a uint16_t or char. */
751 tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
752 result->value = tor_strdup(buf);
753 break;
754 case CONFIG_TYPE_MEMUNIT:
755 tor_snprintf(buf, sizeof(buf), U64_FORMAT,
756 U64_PRINTF_ARG(*(uint64_t*)value));
757 result->value = tor_strdup(buf);
758 break;
759 case CONFIG_TYPE_DOUBLE:
760 tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
761 result->value = tor_strdup(buf);
762 break;
763 case CONFIG_TYPE_BOOL:
764 result->value = tor_strdup(*(int*)value ? "1" : "0");
765 break;
766 case CONFIG_TYPE_CSV:
767 if (*(smartlist_t**)value)
768 result->value = smartlist_join_strings(*(smartlist_t**)value,",",0,NULL);
769 else
770 result->value = tor_strdup("");
771 break;
772 case CONFIG_TYPE_OBSOLETE:
773 log_fn(LOG_WARN,"You asked me for the value of an obsolete config option %s.", key);
774 tor_free(result->key);
775 tor_free(result);
776 return NULL;
777 default:
778 tor_free(result->key);
779 tor_free(result);
780 log_fn(LOG_WARN,"Bug: unknown type %d for known key %s", var->type, key);
781 return NULL;
784 return result;
787 /** Iterate through the linked list of requested options <b>list</b>.
788 * For each item, convert as appropriate and assign to <b>options</b>.
789 * If an item is unrecognized, return -1 immediately,
790 * else return 0 for success.
792 * If <b>reset</b>, then interpret empty lines as meaning "restore to
793 * default value", and interpret LINELIST* options as replacing (not
794 * extending) their previous values. Return 0 on success, -1 on bad key,
795 * -2 on bad value.
797 static int
798 config_assign(or_options_t *options, struct config_line_t *list, int reset)
800 struct config_line_t *p;
801 tor_assert(options);
803 /* pass 1: normalize keys */
804 for (p = list; p; p = p->next) {
805 const char *full = expand_abbrev(p->key, 0);
806 if (strcmp(full,p->key)) {
807 tor_free(p->key);
808 p->key = tor_strdup(full);
812 /* pass 2: if we're reading from a resetting source, clear all mentioned
813 * linelists. */
814 if (reset) {
815 for (p = list; p; p = p->next)
816 config_reset_line(options, p->key);
819 /* pass 3: assign. */
820 while (list) {
821 int r;
822 if ((r=config_assign_line(options, list, reset)))
823 return r;
824 list = list->next;
826 return 0;
829 /** Try assigning <b>list</b> to the global options. You do this by duping
830 * options, assigning list to the new one, then validating it. If it's
831 * ok, then throw out the old one and stick with the new one. Else,
832 * revert to old and return failure. Return 0 on success, -1 on bad
833 * keys, -2 on bad values, -3 on bad transition.
836 config_trial_assign(struct config_line_t *list, int reset)
838 int r;
839 or_options_t *trial_options = options_dup(get_options());
841 if ((r=config_assign(trial_options, list, reset)) < 0) {
842 options_free(trial_options);
843 return r;
846 if (options_validate(trial_options) < 0) {
847 options_free(trial_options);
848 return -2;
851 if (options_transition_allowed(get_options(), trial_options) < 0) {
852 options_free(trial_options);
853 return -3;
856 set_options(trial_options); /* we liked it. put it in place. */
857 return 0;
860 /** Replace the option indexed by <b>var</b> in <b>options</b> with its
861 * default value. */
862 static void
863 option_reset(or_options_t *options, config_var_t *var)
865 struct config_line_t *c;
866 void *lvalue;
868 lvalue = ((char*)options) + var->var_offset;
869 switch (var->type) {
870 case CONFIG_TYPE_STRING:
871 tor_free(*(char**)lvalue);
872 break;
873 case CONFIG_TYPE_DOUBLE:
874 *(double*)lvalue = 0.0;
875 break;
876 case CONFIG_TYPE_INTERVAL:
877 case CONFIG_TYPE_UINT:
878 case CONFIG_TYPE_BOOL:
879 *(int*)lvalue = 0;
880 break;
881 case CONFIG_TYPE_MEMUNIT:
882 *(uint64_t*)lvalue = 0;
883 break;
884 case CONFIG_TYPE_CSV:
885 if (*(smartlist_t**)lvalue) {
886 SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
887 smartlist_free(*(smartlist_t **)lvalue);
888 *(smartlist_t **)lvalue = NULL;
890 break;
891 case CONFIG_TYPE_LINELIST:
892 case CONFIG_TYPE_LINELIST_S:
893 config_free_lines(*(struct config_line_t **)lvalue);
894 *(struct config_line_t **)lvalue = NULL;
895 break;
896 case CONFIG_TYPE_LINELIST_V:
897 /* handled by linelist_s. */
898 break;
899 case CONFIG_TYPE_OBSOLETE:
900 break;
902 if (var->initvalue) {
903 c = tor_malloc_zero(sizeof(struct config_line_t));
904 c->key = tor_strdup(var->name);
905 c->value = tor_strdup(var->initvalue);
906 config_assign_line(options,c,0);
907 config_free_lines(c);
911 /** Set <b>options</b>-&gt;DirServers to contain the default directory
912 * servers. */
913 static void
914 add_default_trusted_dirservers(or_options_t *options)
916 /* moria1 */
917 config_line_append(&options->DirServers, "DirServer",
918 "18.244.0.188:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441");
919 /* moria2 */
920 config_line_append(&options->DirServers, "DirServer",
921 "18.244.0.114:80 719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF");
922 /* tor26 */
923 config_line_append(&options->DirServers, "DirServer",
924 "62.116.124.106:9030 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D");
925 // "tor.noreply.org:9030 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D");
928 /** Print a usage message for tor. */
929 static void
930 print_usage(void)
932 printf(
933 "Copyright 2001-2004 Roger Dingledine, Nick Mathewson, Matej Pfajfar.\n\n"
934 "tor -f <torrc> [args]\n"
935 "See man page for options, or http://tor.eff.org/ for documentation.\n");
939 * Based on <b>address</b>, guess our public IP address and put it
940 * in <b>addr</b>.
943 resolve_my_address(const char *address, uint32_t *addr)
945 struct in_addr in;
946 struct hostent *rent;
947 char hostname[256];
948 int explicit_ip=1;
949 char tmpbuf[INET_NTOA_BUF_LEN];
950 static uint32_t old_addr=0;
952 tor_assert(addr);
954 /* workaround: some people were leaving "Address " in their torrc,
955 * and they had a buggy resolver that resolved " " to 0.0.0.0. Oops.
957 if (address)
958 while (TOR_ISSPACE(*address))
959 address++;
961 if (address && *address) {
962 strlcpy(hostname, address, sizeof(hostname));
963 } else { /* then we need to guess our address */
964 explicit_ip = 0; /* it's implicit */
966 if (gethostname(hostname, sizeof(hostname)) < 0) {
967 log_fn(LOG_WARN,"Error obtaining local hostname");
968 return -1;
970 log_fn(LOG_DEBUG,"Guessed local host name as '%s'",hostname);
973 /* now we know hostname. resolve it and keep only the IP */
975 if (tor_inet_aton(hostname, &in) == 0) {
976 /* then we have to resolve it */
977 explicit_ip = 0;
978 rent = (struct hostent *)gethostbyname(hostname);
979 if (!rent) {
980 log_fn(LOG_WARN,"Could not resolve local Address %s. Failing.", hostname);
981 return -1;
983 tor_assert(rent->h_length == 4);
984 memcpy(&in.s_addr, rent->h_addr, rent->h_length);
987 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
988 if (!explicit_ip && is_internal_IP(htonl(in.s_addr))) {
989 log_fn(LOG_WARN,"Address '%s' resolves to private IP '%s'. "
990 "Please set the Address config option to be the IP you want to use.",
991 hostname, tmpbuf);
992 return -1;
995 log_fn(LOG_DEBUG, "Resolved Address to %s.", tmpbuf);
996 *addr = ntohl(in.s_addr);
997 if (old_addr && old_addr != *addr) {
998 log_fn(LOG_NOTICE,"Your IP seems to have changed. Updating.");
999 server_has_changed_ip();
1001 old_addr = *addr;
1002 return 0;
1005 /** Called when we don't have a nickname set. Try to guess a good
1006 * nickname based on the hostname, and return it in a newly allocated string. */
1007 static char *
1008 get_default_nickname(void)
1010 char localhostname[256];
1011 char *cp, *out, *outp;
1013 if (gethostname(localhostname, sizeof(localhostname)) < 0) {
1014 log_fn(LOG_WARN,"Error obtaining local hostname");
1015 return NULL;
1018 /* Put it in lowercase; stop at the first dot. */
1019 for (cp = localhostname; *cp; ++cp) {
1020 if (*cp == '.') {
1021 *cp = '\0';
1022 break;
1024 *cp = tolower(*cp);
1027 /* Strip invalid characters. */
1028 cp = localhostname;
1029 out = outp = tor_malloc(strlen(localhostname) + 1);
1030 while (*cp) {
1031 if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
1032 *outp++ = *cp++;
1033 else
1034 cp++;
1036 *outp = '\0';
1038 /* Enforce length. */
1039 if (strlen(out) > MAX_NICKNAME_LEN)
1040 out[MAX_NICKNAME_LEN]='\0';
1042 return out;
1045 /** Release storage held by <b>options</b> */
1046 static void
1047 options_free(or_options_t *options)
1049 int i;
1050 void *lvalue;
1052 tor_assert(options);
1054 for (i=0; config_vars[i].name; ++i) {
1055 lvalue = ((char*)options) + config_vars[i].var_offset;
1056 switch (config_vars[i].type) {
1057 case CONFIG_TYPE_MEMUNIT:
1058 case CONFIG_TYPE_INTERVAL:
1059 case CONFIG_TYPE_UINT:
1060 case CONFIG_TYPE_BOOL:
1061 case CONFIG_TYPE_DOUBLE:
1062 case CONFIG_TYPE_OBSOLETE:
1063 break; /* nothing to free for these config types */
1064 case CONFIG_TYPE_STRING:
1065 tor_free(*(char **)lvalue);
1066 break;
1067 case CONFIG_TYPE_LINELIST:
1068 case CONFIG_TYPE_LINELIST_V:
1069 config_free_lines(*(struct config_line_t**)lvalue);
1070 *(struct config_line_t**)lvalue = NULL;
1071 break;
1072 case CONFIG_TYPE_CSV:
1073 if (*(smartlist_t**)lvalue) {
1074 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
1075 smartlist_free(*(smartlist_t**)lvalue);
1076 *(smartlist_t**)lvalue = NULL;
1078 break;
1079 case CONFIG_TYPE_LINELIST_S:
1080 /* will be freed by corresponding LINELIST_V. */
1081 break;
1084 tor_free(options);
1087 /** Return true iff the option <b>var</b> has the same value in <b>o1</b>
1088 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
1090 static int
1091 option_is_same(or_options_t *o1, or_options_t *o2, const char *name)
1093 struct config_line_t *c1, *c2;
1094 int r = 1;
1095 c1 = config_get_assigned_option(o1, name);
1096 c2 = config_get_assigned_option(o2, name);
1097 while (c1 && c2) {
1098 if (strcasecmp(c1->key, c2->key) ||
1099 strcmp(c1->value, c2->value)) {
1100 r = 0;
1101 break;
1103 c1 = c1->next;
1104 c2 = c2->next;
1106 if (r && (c1 || c2)) {
1107 r = 0;
1109 config_free_lines(c1);
1110 config_free_lines(c2);
1111 return r;
1114 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
1115 static or_options_t *
1116 options_dup(or_options_t *old)
1118 or_options_t *newopts;
1119 int i;
1120 struct config_line_t *line;
1122 newopts = tor_malloc_zero(sizeof(or_options_t));
1123 for (i=0; config_vars[i].name; ++i) {
1124 if (config_vars[i].type == CONFIG_TYPE_LINELIST_S)
1125 continue;
1126 if (config_vars[i].type == CONFIG_TYPE_OBSOLETE)
1127 continue;
1128 line = config_get_assigned_option(old, config_vars[i].name);
1129 if (line) {
1130 if (config_assign(newopts, line, 0) < 0) {
1131 log_fn(LOG_WARN,"Bug: config_get_assigned_option() generated "
1132 "something we couldn't config_assign().");
1133 tor_assert(0);
1136 config_free_lines(line);
1138 return newopts;
1141 /** Set <b>options</b> to hold reasonable defaults for most options.
1142 * Each option defaults to zero. */
1143 void
1144 options_init(or_options_t *options)
1146 int i;
1147 config_var_t *var;
1149 for (i=0; config_vars[i].name; ++i) {
1150 var = &config_vars[i];
1151 if (!var->initvalue)
1152 continue; /* defaults to NULL or 0 */
1153 option_reset(options, var);
1157 /** Return a string containing a possible configuration file that would give
1158 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
1159 * include options that are the same as Tor's defaults.
1161 char *
1162 config_dump_options(or_options_t *options, int minimal)
1164 smartlist_t *elements;
1165 or_options_t *defaults;
1166 struct config_line_t *line;
1167 char *result;
1168 int i;
1170 defaults = tor_malloc_zero(sizeof(or_options_t));
1171 options_init(defaults);
1172 options_validate(defaults); /* ??? will this work? */
1174 elements = smartlist_create();
1175 for (i=0; config_vars[i].name; ++i) {
1176 if (config_vars[i].type == CONFIG_TYPE_OBSOLETE ||
1177 config_vars[i].type == CONFIG_TYPE_LINELIST_S)
1178 continue;
1179 /* Don't save 'hidden' control variables. */
1180 if (!strcmpstart(config_vars[i].name, "__"))
1181 continue;
1182 if (minimal && option_is_same(options, defaults, config_vars[i].name))
1183 continue;
1184 line = config_get_assigned_option(options, config_vars[i].name);
1185 for (; line; line = line->next) {
1186 size_t len = strlen(line->key) + strlen(line->value) + 3;
1187 char *tmp;
1188 tmp = tor_malloc(len);
1189 if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
1190 log_fn(LOG_ERR, "Internal error writing log option");
1191 tor_assert(0);
1193 smartlist_add(elements, tmp);
1195 config_free_lines(line);
1198 result = smartlist_join_strings(elements, "", 0, NULL);
1199 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
1200 smartlist_free(elements);
1201 return result;
1204 static int
1205 validate_ports_csv(smartlist_t *sl, const char *name) {
1206 int i;
1207 int result = 0;
1208 tor_assert(name);
1210 if (!sl)
1211 return 0;
1213 SMARTLIST_FOREACH(sl, const char *, cp,
1215 i = atoi(cp);
1216 if (i < 1 || i > 65535) {
1217 log(LOG_WARN, "Port '%s' out of range in %s", cp, name);
1218 result=-1;
1221 return result;
1224 /** Return 0 if every setting in <b>options</b> is reasonable. Else
1225 * warn and return -1. Should have no side effects, except for
1226 * normalizing the contents of <b>options</b>. */
1227 static int
1228 options_validate(or_options_t *options)
1230 int result = 0;
1231 struct config_line_t *cl;
1232 addr_policy_t *addr_policy=NULL;
1234 if (options->ORPort < 0 || options->ORPort > 65535) {
1235 log(LOG_WARN, "ORPort option out of bounds.");
1236 result = -1;
1239 /* XXX might similarly want to check the other *BindAddress options */
1240 if (options->ORPort == 0 && options->ORBindAddress != NULL) {
1241 log(LOG_WARN, "ORPort must be defined if ORBindAddress is defined.");
1242 result = -1;
1245 if (validate_data_directory(options)<0) {
1246 log(LOG_WARN, "Invalid DataDirectory");
1247 result = -1;
1250 if (options->Nickname == NULL) {
1251 if (server_mode(options)) {
1252 if (!(options->Nickname = get_default_nickname()))
1253 return -1;
1254 log_fn(LOG_NOTICE, "Choosing default nickname %s", options->Nickname);
1256 } else {
1257 if (strspn(options->Nickname, LEGAL_NICKNAME_CHARACTERS) !=
1258 strlen(options->Nickname)) {
1259 log_fn(LOG_WARN, "Nickname '%s' contains illegal characters.", options->Nickname);
1260 result = -1;
1262 if (strlen(options->Nickname) == 0) {
1263 log_fn(LOG_WARN, "Nickname must have at least one character");
1264 result = -1;
1266 if (strlen(options->Nickname) > MAX_NICKNAME_LEN) {
1267 log_fn(LOG_WARN, "Nickname '%s' has more than %d characters.",
1268 options->Nickname, MAX_NICKNAME_LEN);
1269 result = -1;
1273 if (normalize_log_options(options))
1274 return -1;
1276 /* Special case if no options are given. */
1277 if (!options->Logs) {
1278 config_line_append(&options->Logs, "Log", "notice stdout");
1281 if (config_init_logs(options, 1)<0) /* Validate the log(s) */
1282 return -1;
1284 if (server_mode(options)) {
1285 /* confirm that our address isn't broken, so we can complain now */
1286 uint32_t tmp;
1287 if (resolve_my_address(options->Address, &tmp) < 0)
1288 result = -1;
1291 if (options->SocksPort < 0 || options->SocksPort > 65535) {
1292 log(LOG_WARN, "SocksPort option out of bounds.");
1293 result = -1;
1296 if (options->SocksPort == 0 && options->ORPort == 0) {
1297 log(LOG_WARN, "SocksPort and ORPort are both undefined? Quitting.");
1298 result = -1;
1301 if (options->ControlPort < 0 || options->ControlPort > 65535) {
1302 log(LOG_WARN, "ControlPort option out of bounds.");
1303 result = -1;
1306 if (options->DirPort < 0 || options->DirPort > 65535) {
1307 log(LOG_WARN, "DirPort option out of bounds.");
1308 result = -1;
1311 if (options->StrictExitNodes &&
1312 (!options->ExitNodes || !strlen(options->ExitNodes))) {
1313 log(LOG_WARN, "StrictExitNodes set, but no ExitNodes listed.");
1316 if (options->StrictEntryNodes &&
1317 (!options->EntryNodes || !strlen(options->EntryNodes))) {
1318 log(LOG_WARN, "StrictEntryNodes set, but no EntryNodes listed.");
1321 if (options->AuthoritativeDir && options->RecommendedVersions == NULL) {
1322 log(LOG_WARN, "Directory servers must configure RecommendedVersions.");
1323 result = -1;
1326 if (options->AuthoritativeDir && !options->DirPort) {
1327 log(LOG_WARN, "Running as authoritative directory, but no DirPort set.");
1328 result = -1;
1331 if (options->AuthoritativeDir && !options->ORPort) {
1332 log(LOG_WARN, "Running as authoritative directory, but no ORPort set.");
1333 result = -1;
1336 if (options->AuthoritativeDir && options->ClientOnly) {
1337 log(LOG_WARN, "Running as authoritative directory, but ClientOnly also set.");
1338 result = -1;
1341 if (options->AuthoritativeDir && options->NoPublish) {
1342 log(LOG_WARN, "You cannot set both AuthoritativeDir and NoPublish.");
1343 result = -1;
1346 if (options->ConnLimit <= 0) {
1347 log(LOG_WARN, "ConnLimit must be greater than 0, but was set to %d",
1348 options->ConnLimit);
1349 result = -1;
1352 if (options->_AccountingMaxKB) {
1353 log(LOG_WARN, "AccountingMaxKB is deprecated. Say 'AccountingMax %d KB' instead.", options->_AccountingMaxKB);
1354 options->AccountingMax = U64_LITERAL(1024)*options->_AccountingMaxKB;
1355 options->_AccountingMaxKB = 0;
1358 if (validate_ports_csv(options->FirewallPorts,
1359 "FirewallPorts") < 0)
1360 result = -1;
1362 if (validate_ports_csv(options->LongLivedPorts,
1363 "LongLivedPorts") < 0)
1364 result = -1;
1366 options->_AllowUnverified = 0;
1367 if (options->AllowUnverifiedNodes) {
1368 SMARTLIST_FOREACH(options->AllowUnverifiedNodes, const char *, cp, {
1369 if (!strcasecmp(cp, "entry"))
1370 options->_AllowUnverified |= ALLOW_UNVERIFIED_ENTRY;
1371 else if (!strcasecmp(cp, "exit"))
1372 options->_AllowUnverified |= ALLOW_UNVERIFIED_EXIT;
1373 else if (!strcasecmp(cp, "middle"))
1374 options->_AllowUnverified |= ALLOW_UNVERIFIED_MIDDLE;
1375 else if (!strcasecmp(cp, "introduction"))
1376 options->_AllowUnverified |= ALLOW_UNVERIFIED_INTRODUCTION;
1377 else if (!strcasecmp(cp, "rendezvous"))
1378 options->_AllowUnverified |= ALLOW_UNVERIFIED_RENDEZVOUS;
1379 else {
1380 log(LOG_WARN, "Unrecognized value '%s' in AllowUnverifiedNodes",
1381 cp);
1382 result = -1;
1387 if (options->SocksPort >= 1 &&
1388 (options->PathlenCoinWeight < 0.0 || options->PathlenCoinWeight >= 1.0)) {
1389 log(LOG_WARN, "PathlenCoinWeight option must be >=0.0 and <1.0.");
1390 result = -1;
1393 #define MIN_DIR_FETCH_PERIOD 600
1394 #define MIN_DIR_POST_PERIOD 300
1395 #define MIN_REND_POST_PERIOD 300
1396 #define MIN_STATUS_FETCH_PERIOD 60
1398 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
1399 #define MAX_CACHE_DIR_FETCH_PERIOD 3600
1400 #define MAX_CACHE_STATUS_FETCH_PERIOD 900
1402 if (options->DirFetchPeriod &&
1403 options->DirFetchPeriod < MIN_DIR_FETCH_PERIOD) {
1404 log(LOG_WARN, "DirFetchPeriod option must be at least %d seconds. Clipping.", MIN_DIR_FETCH_PERIOD);
1405 options->DirFetchPeriod = MIN_DIR_FETCH_PERIOD;
1407 if (options->StatusFetchPeriod &&
1408 options->StatusFetchPeriod < MIN_STATUS_FETCH_PERIOD) {
1409 log(LOG_WARN, "StatusFetchPeriod option must be at least %d seconds. Clipping.", MIN_STATUS_FETCH_PERIOD);
1410 options->StatusFetchPeriod = MIN_STATUS_FETCH_PERIOD;
1412 if (options->DirPostPeriod < MIN_DIR_POST_PERIOD) {
1413 log(LOG_WARN, "DirPostPeriod option must be at least %d seconds. Clipping.",
1414 MIN_DIR_POST_PERIOD);
1415 options->DirPostPeriod = MIN_DIR_POST_PERIOD;
1417 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
1418 log(LOG_WARN,"RendPostPeriod option must be at least %d seconds. Clipping.",
1419 MIN_REND_POST_PERIOD);
1420 options->RendPostPeriod = MIN_REND_POST_PERIOD;
1423 if (options->DirPort && ! options->AuthoritativeDir) {
1424 if (options->DirFetchPeriod > MAX_CACHE_DIR_FETCH_PERIOD) {
1425 log(LOG_WARN, "Caching directory servers must have DirFetchPeriod less than %d seconds. Clipping.", MAX_CACHE_DIR_FETCH_PERIOD);
1426 options->DirFetchPeriod = MAX_CACHE_DIR_FETCH_PERIOD;
1428 if (options->StatusFetchPeriod > MAX_CACHE_STATUS_FETCH_PERIOD) {
1429 log(LOG_WARN, "Caching directory servers must have StatusFetchPeriod less than %d seconds. Clipping.", MAX_CACHE_STATUS_FETCH_PERIOD);
1430 options->StatusFetchPeriod = MAX_CACHE_STATUS_FETCH_PERIOD;
1434 if (options->DirFetchPeriod > MAX_DIR_PERIOD) {
1435 log(LOG_WARN, "DirFetchPeriod is too large; clipping.");
1436 options->DirFetchPeriod = MAX_DIR_PERIOD;
1438 if (options->DirPostPeriod > MAX_DIR_PERIOD) {
1439 log(LOG_WARN, "DirPostPeriod is too large; clipping.");
1440 options->DirPostPeriod = MAX_DIR_PERIOD;
1442 if (options->StatusFetchPeriod > MAX_DIR_PERIOD) {
1443 log(LOG_WARN, "StatusFetchPeriod is too large; clipping.");
1444 options->StatusFetchPeriod = MAX_DIR_PERIOD;
1446 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
1447 log(LOG_WARN, "RendPostPeriod is too large; clipping.");
1448 options->RendPostPeriod = MAX_DIR_PERIOD;
1451 if (options->KeepalivePeriod < 1) {
1452 log(LOG_WARN,"KeepalivePeriod option must be positive.");
1453 result = -1;
1456 if (options->BandwidthRate > INT_MAX) {
1457 log(LOG_WARN,"BandwidthRate must be less than %d",INT_MAX);
1458 result = -1;
1460 if (options->BandwidthBurst > INT_MAX) {
1461 log(LOG_WARN,"BandwidthBurst must be less than %d",INT_MAX);
1462 result = -1;
1464 if (server_mode(options) &&
1465 options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH*2) {
1466 log(LOG_WARN,"BandwidthRate is set to %d bytes/second. For servers, it must be at least %d.", (int)options->BandwidthRate, ROUTER_REQUIRED_MIN_BANDWIDTH*2);
1467 result = -1;
1469 if (options->BandwidthRate > options->BandwidthBurst) {
1470 log(LOG_WARN,"BandwidthBurst must be at least equal to BandwidthRate.");
1471 result = -1;
1473 #if 0
1474 if (2*options->BandwidthRate > options->BandwidthBurst) {
1475 log(LOG_NOTICE,"You have chosen a BandwidthBurst less than twice BandwidthRate. Please consider setting your BandwidthBurst higher (at least %d), to provide better service to the Tor network.", (int)(2*options->BandwidthRate));
1477 #endif
1479 if (options->_MonthlyAccountingStart) {
1480 if (options->AccountingStart) {
1481 log(LOG_WARN,"Can't specify AccountingStart and MonthlyAccountingStart");
1482 result = -1;
1483 } else {
1484 options->AccountingStart = tor_malloc(32);
1485 if (tor_snprintf(options->AccountingStart, 32, "month %d 0:00",
1486 options->_MonthlyAccountingStart)<0) {
1487 log_fn(LOG_WARN,"Error translating MonthlyAccountingStart");
1488 result = -1;
1489 } else {
1490 log_fn(LOG_WARN,"MonthlyAccountingStart is deprecated. Use 'AccountingStart %s' instead.", options->AccountingStart);
1495 if (accounting_parse_options(options, 1)<0) {
1496 result = -1;
1499 if (options->HttpProxy) { /* parse it now */
1500 if (parse_addr_port(options->HttpProxy, NULL,
1501 &options->HttpProxyAddr, &options->HttpProxyPort) < 0) {
1502 log(LOG_WARN,"HttpProxy failed to parse or resolve. Please fix.");
1503 result = -1;
1505 if (options->HttpProxyPort == 0) { /* give it a default */
1506 options->HttpProxyPort = 80;
1510 if (options->HttpsProxy) { /* parse it now */
1511 if (parse_addr_port(options->HttpsProxy, NULL,
1512 &options->HttpsProxyAddr, &options->HttpsProxyPort) < 0) {
1513 log(LOG_WARN,"HttpsProxy failed to parse or resolve. Please fix.");
1514 result = -1;
1516 if (options->HttpsProxyPort == 0) { /* give it a default */
1517 options->HttpsProxyPort = 443;
1521 if (options->HttpsProxyAuthenticator) {
1522 if (strlen(options->HttpsProxyAuthenticator) >= 48) {
1523 log(LOG_WARN, "HttpsProxyAuthenticator is too long (>= 48 chars).");
1524 result = -1;
1528 if (options->HashedControlPassword) {
1529 if (decode_hashed_password(NULL, options->HashedControlPassword)<0) {
1530 log_fn(LOG_WARN,"Bad HashedControlPassword: wrong length or bad base64");
1531 result = -1;
1534 if (options->HashedControlPassword && options->CookieAuthentication) {
1535 log_fn(LOG_WARN,"Cannot enable both HashedControlPassword and CookieAuthentication");
1536 result = -1;
1539 if (check_nickname_list(options->ExitNodes, "ExitNodes"))
1540 result = -1;
1541 if (check_nickname_list(options->EntryNodes, "EntryNodes"))
1542 result = -1;
1543 if (check_nickname_list(options->ExcludeNodes, "ExcludeNodes"))
1544 result = -1;
1545 if (check_nickname_list(options->RendNodes, "RendNodes"))
1546 result = -1;
1547 if (check_nickname_list(options->RendNodes, "RendExcludeNodes"))
1548 result = -1;
1549 if (check_nickname_list(options->MyFamily, "MyFamily"))
1550 result = -1;
1551 for (cl = options->NodeFamilies; cl; cl = cl->next) {
1552 if (check_nickname_list(cl->value, "NodeFamily"))
1553 result = -1;
1556 if (config_parse_addr_policy(options->ExitPolicy, &addr_policy)) {
1557 log_fn(LOG_WARN, "Error in Exit Policy entry.");
1558 result = -1;
1560 if (server_mode(options)) {
1561 exit_policy_implicitly_allows_local_networks(addr_policy, 1);
1563 /* The rest of these calls *append* to addr_policy. So don't actually
1564 * use the results for anything other than checking if they parse! */
1565 if (config_parse_addr_policy(options->DirPolicy, &addr_policy)) {
1566 log_fn(LOG_WARN, "Error in DirPolicy entry.");
1567 result = -1;
1569 if (config_parse_addr_policy(options->SocksPolicy, &addr_policy)) {
1570 log_fn(LOG_WARN, "Error in SocksPolicy entry.");
1571 result = -1;
1573 addr_policy_free(addr_policy);
1575 for (cl = options->RedirectExit; cl; cl = cl->next) {
1576 if (parse_redirect_line(NULL, cl)<0)
1577 result = -1;
1580 if (!options->DirServers) {
1581 add_default_trusted_dirservers(options);
1582 } else {
1583 for (cl = options->DirServers; cl; cl = cl->next) {
1584 if (parse_dir_server_line(cl->value, 1)<0)
1585 result = -1;
1589 if (rend_config_services(options, 1) < 0)
1590 result = -1;
1592 return result;
1595 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
1596 * equal strings. */
1597 static int
1598 opt_streq(const char *s1, const char *s2)
1600 if (!s1 && !s2)
1601 return 1;
1602 else if (s1 && s2 && !strcmp(s1,s2))
1603 return 1;
1604 else
1605 return 0;
1608 /** Check if any of the previous options have changed but aren't allowed to. */
1609 static int
1610 options_transition_allowed(or_options_t *old, or_options_t *new_val) {
1612 if (!old)
1613 return 0;
1615 if (!opt_streq(old->PidFile, new_val->PidFile)) {
1616 log_fn(LOG_WARN,"PidFile is not allowed to change. Failing.");
1617 return -1;
1620 if (old->RunAsDaemon && !new_val->RunAsDaemon) {
1621 log_fn(LOG_WARN,"During reload, change from RunAsDaemon=1 to =0 not allowed. Failing.");
1622 return -1;
1625 if (old->ORPort != new_val->ORPort) {
1626 log_fn(LOG_WARN,"During reload, changing ORPort is not allowed. Failing.");
1627 return -1;
1630 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
1631 log_fn(LOG_WARN,"During reload, changing DataDirectory (%s->%s) is not allowed. Failing.", old->DataDirectory, new_val->DataDirectory);
1632 return -1;
1635 if (!opt_streq(old->User, new_val->User)) {
1636 log_fn(LOG_WARN,"During reload, changing User is not allowed. Failing.");
1637 return -1;
1640 if (!opt_streq(old->Group, new_val->Group)) {
1641 log_fn(LOG_WARN,"During reload, changing User is not allowed. Failing.");
1642 return -1;
1645 return 0;
1648 #ifdef MS_WINDOWS
1649 /** Return the directory on windows where we expect to find our application
1650 * data. */
1651 static char *get_windows_conf_root(void)
1653 static int is_set = 0;
1654 static char path[MAX_PATH+1];
1656 LPITEMIDLIST idl;
1657 IMalloc *m;
1658 HRESULT result;
1660 if (is_set)
1661 return path;
1663 /* Find X:\documents and settings\username\application data\ .
1664 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
1666 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA,
1667 &idl))) {
1668 GetCurrentDirectory(MAX_PATH, path);
1669 is_set = 1;
1670 log_fn(LOG_WARN, "I couldn't find your application data folder: are you running an ancient version of Windows 95? Defaulting to '%s'", path);
1671 return path;
1673 /* Convert the path from an "ID List" (whatever that is!) to a path. */
1674 result = SHGetPathFromIDList(idl, path);
1675 /* Now we need to free the */
1676 SHGetMalloc(&m);
1677 if (m) {
1678 m->lpVtbl->Free(m, idl);
1679 m->lpVtbl->Release(m);
1681 if (!SUCCEEDED(result)) {
1682 return NULL;
1684 strlcat(path,"\\tor",MAX_PATH);
1685 is_set = 1;
1686 return path;
1688 #endif
1690 /** Return the default location for our torrc file. */
1691 static char *
1692 get_default_conf_file(void)
1694 #ifdef MS_WINDOWS
1695 char *path = tor_malloc(MAX_PATH);
1696 strlcpy(path, get_windows_conf_root(), MAX_PATH);
1697 strlcat(path,"\\torrc",MAX_PATH);
1698 return path;
1699 #else
1700 return tor_strdup(CONFDIR "/torrc");
1701 #endif
1704 /** Verify whether lst is a string containing valid-looking space-separated
1705 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
1707 static int check_nickname_list(const char *lst, const char *name)
1709 int r = 0;
1710 smartlist_t *sl;
1712 if (!lst)
1713 return 0;
1714 sl = smartlist_create();
1715 smartlist_split_string(sl, lst, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1716 SMARTLIST_FOREACH(sl, const char *, s,
1718 if (!is_legal_nickname_or_hexdigest(s)) {
1719 log_fn(LOG_WARN, "Invalid nickname '%s' in %s line", s, name);
1720 r = -1;
1723 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
1724 smartlist_free(sl);
1725 return r;
1728 /** Read a configuration file into <b>options</b>, finding the configuration
1729 * file location based on the command line. After loading the options,
1730 * validate them for consistency, then take actions based on them.
1731 * Return 0 if success, -1 if failure. */
1733 init_from_config(int argc, char **argv)
1735 or_options_t *oldoptions, *newoptions;
1736 struct config_line_t *cl;
1737 char *cf=NULL, *fname=NULL;
1738 int i, retval;
1739 int using_default_torrc;
1740 static char **backup_argv;
1741 static int backup_argc;
1743 if (argv) { /* first time we're called. save commandline args */
1744 backup_argv = argv;
1745 backup_argc = argc;
1746 oldoptions = NULL;
1747 } else { /* we're reloading. need to clean up old options first. */
1748 argv = backup_argv;
1749 argc = backup_argc;
1750 oldoptions = get_options();
1752 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
1753 print_usage();
1754 exit(0);
1757 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
1758 printf("Tor version %s.\n",VERSION);
1759 if (argc > 2 && (!strcmp(argv[2],"--version"))) {
1760 print_cvs_version();
1762 exit(0);
1765 newoptions = tor_malloc_zero(sizeof(or_options_t));
1766 options_init(newoptions);
1768 /* learn config file name, get config lines, assign them */
1769 fname = NULL;
1770 using_default_torrc = 1;
1771 newoptions->command = CMD_RUN_TOR;
1772 for (i = 1; i < argc; ++i) {
1773 if (i < argc-1 && !strcmp(argv[i],"-f")) {
1774 if (fname) {
1775 log(LOG_WARN, "Duplicate -f options on command line.");
1776 tor_free(fname);
1778 fname = tor_strdup(argv[i+1]);
1779 using_default_torrc = 0;
1780 ++i;
1781 } else if (!strcmp(argv[i],"--list-fingerprint")) {
1782 newoptions->command = CMD_LIST_FINGERPRINT;
1783 } else if (!strcmp(argv[i],"--hash-password")) {
1784 newoptions->command = CMD_HASH_PASSWORD;
1785 newoptions->command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
1786 ++i;
1790 if (using_default_torrc) {
1791 /* didn't find one, try CONFDIR */
1792 char *fn;
1793 fn = get_default_conf_file();
1794 if (fn && file_status(fn) == FN_FILE) {
1795 fname = fn;
1796 } else {
1797 tor_free(fn);
1798 #ifndef MS_WINDOWS
1799 fn = expand_filename("~/.torrc");
1800 if (fn && file_status(fn) == FN_FILE) {
1801 fname = fn;
1802 } else {
1803 tor_free(fn);
1804 fname = get_default_conf_file();
1806 #else
1807 fname = get_default_conf_file();
1808 #endif
1811 tor_assert(fname);
1812 log(LOG_DEBUG, "Opening config file '%s'", fname);
1814 if (file_status(fname) != FN_FILE ||
1815 !(cf = read_file_to_str(fname,0))) {
1816 if (using_default_torrc == 1) {
1817 log(LOG_NOTICE, "Configuration file '%s' not present, "
1818 "using reasonable defaults.", fname);
1819 tor_free(fname); /* sets fname to NULL */
1820 } else {
1821 log(LOG_WARN, "Unable to open configuration file '%s'.", fname);
1822 tor_free(fname);
1823 goto err;
1825 } else { /* it opened successfully. use it. */
1826 retval = config_get_lines(cf, &cl);
1827 tor_free(cf);
1828 if (retval < 0)
1829 goto err;
1830 retval = config_assign(newoptions, cl, 0);
1831 config_free_lines(cl);
1832 if (retval < 0)
1833 goto err;
1836 /* Go through command-line variables too */
1837 cl = config_get_commandlines(argc,argv);
1838 retval = config_assign(newoptions,cl,0);
1839 config_free_lines(cl);
1840 if (retval < 0)
1841 goto err;
1843 /* Validate newoptions */
1844 if (options_validate(newoptions) < 0)
1845 goto err;
1847 if (options_transition_allowed(oldoptions, newoptions) < 0)
1848 goto err;
1850 set_options(newoptions); /* frees and replaces old options */
1851 if (options_act() < 0) { /* acting on them failed. die. */
1852 log_fn(LOG_ERR,"Acting on config options left us in a broken state. Dying.");
1853 exit(1);
1855 tor_free(config_fname);
1856 config_fname = fname;
1857 return 0;
1858 err:
1859 tor_free(fname);
1860 options_free(newoptions);
1861 return -1;
1864 static void
1865 config_register_addressmaps(or_options_t *options) {
1866 smartlist_t *elts;
1867 struct config_line_t *opt;
1868 char *from, *to;
1870 addressmap_clear_configured();
1871 elts = smartlist_create();
1872 for (opt = options->AddressMap; opt; opt = opt->next) {
1873 smartlist_split_string(elts, opt->value, NULL,
1874 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
1875 if (smartlist_len(elts) >= 2) {
1876 from = smartlist_get(elts,0);
1877 to = smartlist_get(elts,1);
1878 if (!is_plausible_address(from)) {
1879 log_fn(LOG_WARN,"Skipping invalid argument '%s' to MapAddress",from);
1880 } else if (!is_plausible_address(to)) {
1881 log_fn(LOG_WARN,"Skipping invalid argument '%s' to MapAddress",to);
1882 } else {
1883 addressmap_register(from, tor_strdup(to), 0);
1884 if (smartlist_len(elts)>2) {
1885 log_fn(LOG_WARN,"Ignoring extra arguments to MapAddress.");
1888 } else {
1889 log_fn(LOG_WARN,"MapAddress '%s' has too few arguments. Ignoring.", opt->value);
1891 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
1892 smartlist_clear(elts);
1894 smartlist_free(elts);
1897 /** If <b>range</b> is of the form MIN-MAX, for MIN and MAX both
1898 * recognized log severity levels, set *<b>min_out</b> to MIN and
1899 * *<b>max_out</b> to MAX and return 0. Else, if <b>range<b> is of
1900 * the form MIN, act as if MIN-err had been specified. Else, warn and
1901 * return -1.
1903 static int
1904 parse_log_severity_range(const char *range, int *min_out, int *max_out)
1906 int levelMin, levelMax;
1907 const char *cp;
1908 cp = strchr(range, '-');
1909 if (cp) {
1910 if (cp == range) {
1911 levelMin = LOG_DEBUG;
1912 } else {
1913 char *tmp_sev = tor_strndup(range, cp - range);
1914 levelMin = parse_log_level(tmp_sev);
1915 if (levelMin < 0) {
1916 log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
1917 "err|warn|notice|info|debug", tmp_sev);
1918 tor_free(tmp_sev);
1919 return -1;
1921 tor_free(tmp_sev);
1923 if (!*(cp+1)) {
1924 levelMax = LOG_ERR;
1925 } else {
1926 levelMax = parse_log_level(cp+1);
1927 if (levelMax < 0) {
1928 log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
1929 "err|warn|notice|info|debug", cp+1);
1930 return -1;
1933 } else {
1934 levelMin = parse_log_level(range);
1935 if (levelMin < 0) {
1936 log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
1937 "err|warn|notice|info|debug", range);
1938 return -1;
1940 levelMax = LOG_ERR;
1943 *min_out = levelMin;
1944 *max_out = levelMax;
1946 return 0;
1949 /** Try to convert a pair of old-style logging options [LogLevel, and
1950 * (LogFile/Syslog)] to a new-style option, and add the new option to
1951 * options->Logs. */
1952 static int
1953 convert_log_option(or_options_t *options, struct config_line_t *level_opt,
1954 struct config_line_t *file_opt, int isDaemon)
1956 int levelMin = -1, levelMax = -1;
1958 if (level_opt) {
1959 if (parse_log_severity_range(level_opt->value, &levelMin, &levelMax))
1960 return -1;
1962 if (levelMin < 0 && levelMax < 0) {
1963 levelMin = LOG_NOTICE;
1964 levelMax = LOG_ERR;
1965 } else if (levelMin < 0) {
1966 levelMin = levelMax;
1967 } else {
1968 levelMax = LOG_ERR;
1971 if (file_opt && !strcasecmp(file_opt->key, "LogFile")) {
1972 if (add_single_log_option(options, levelMin, levelMax, "file", file_opt->value) < 0) {
1973 log_fn(LOG_WARN, "Cannot write to LogFile '%s': %s.", file_opt->value,
1974 strerror(errno));
1975 return -1;
1977 } else if (file_opt && !strcasecmp(file_opt->key, "SysLog")) {
1978 if (add_single_log_option(options, levelMin, levelMax, "syslog", NULL) < 0)
1979 return -1;
1980 } else if (!isDaemon) {
1981 add_single_log_option(options, levelMin, levelMax, "stdout", NULL);
1983 return 0;
1987 * Initialize the logs based on the configuration file.
1990 config_init_logs(or_options_t *options, int validate_only)
1992 struct config_line_t *opt;
1993 int ok;
1994 smartlist_t *elts;
1996 ok = 1;
1997 elts = smartlist_create();
1998 for (opt = options->Logs; opt; opt = opt->next) {
1999 int levelMin=LOG_DEBUG, levelMax=LOG_ERR;
2000 smartlist_split_string(elts, opt->value, NULL,
2001 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
2002 if (smartlist_len(elts) == 0) {
2003 log_fn(LOG_WARN, "Bad syntax on Log option 'Log %s'", opt->value);
2004 ok = 0; goto cleanup;
2006 if (parse_log_severity_range(smartlist_get(elts,0), &levelMin, &levelMax)) {
2007 ok = 0; goto cleanup;
2009 if (smartlist_len(elts) < 2) { /* only loglevels were provided */
2010 if (!validate_only)
2011 add_stream_log(levelMin, levelMax, "<stdout>", stdout);
2012 goto cleanup;
2014 if (!strcasecmp(smartlist_get(elts,1), "file")) {
2015 if (smartlist_len(elts) != 3) {
2016 log_fn(LOG_WARN, "Bad syntax on Log option 'Log %s'", opt->value);
2017 ok = 0; goto cleanup;
2019 if (!validate_only)
2020 add_file_log(levelMin, levelMax, smartlist_get(elts, 2));
2021 goto cleanup;
2023 if (smartlist_len(elts) != 2) {
2024 log_fn(LOG_WARN, "Bad syntax on Log option 'Log %s'", opt->value);
2025 ok = 0; goto cleanup;
2027 if (!strcasecmp(smartlist_get(elts,1), "stdout")) {
2028 if (!validate_only) {
2029 add_stream_log(levelMin, levelMax, "<stdout>", stdout);
2030 close_temp_logs();
2032 } else if (!strcasecmp(smartlist_get(elts,1), "stderr")) {
2033 if (!validate_only) {
2034 add_stream_log(levelMin, levelMax, "<stderr>", stderr);
2035 close_temp_logs();
2037 } else if (!strcasecmp(smartlist_get(elts,1), "syslog")) {
2038 #ifdef HAVE_SYSLOG_H
2039 if (!validate_only)
2040 add_syslog_log(levelMin, levelMax);
2041 #else
2042 log_fn(LOG_WARN, "Syslog is not supported in this compilation.");
2043 #endif
2044 } else {
2045 log_fn(LOG_WARN, "Unrecognized log type %s",
2046 (const char*)smartlist_get(elts,1));
2047 if (strchr(smartlist_get(elts,1), '/')) {
2048 log_fn(LOG_WARN, "Did you mean to say 'Log file %s' ?",
2049 (const char *)smartlist_get(elts,1));
2051 ok = 0; goto cleanup;
2053 cleanup:
2054 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
2055 smartlist_clear(elts);
2057 smartlist_free(elts);
2058 if (!validate_only)
2059 close_temp_logs();
2061 return ok?0:-1;
2064 /** Add a single option of the form Log min-max <type> [fname] to options. */
2065 static int
2066 add_single_log_option(or_options_t *options, int minSeverity, int maxSeverity,
2067 const char *type, const char *fname)
2069 char buf[512];
2070 int n;
2072 n = tor_snprintf(buf, sizeof(buf), "%s%s%s %s%s%s",
2073 log_level_to_string(minSeverity),
2074 maxSeverity == LOG_ERR ? "" : "-",
2075 maxSeverity == LOG_ERR ? "" : log_level_to_string(maxSeverity),
2076 type, fname?" ":"", fname?fname:"");
2077 if (n<0) {
2078 log_fn(LOG_WARN, "Normalized log option too long.");
2079 return -1;
2082 log(LOG_WARN, "The old LogLevel/LogFile/DebugLogFile/SysLog options are deprecated, and will go away soon. Your new torrc line should be: 'Log %s'", buf);
2083 config_line_append(&options->Logs, "Log", buf);
2084 return 0;
2087 /** Convert all old-style logging options to new-style Log options. Return 0
2088 * on success, -1 on failure. */
2089 static int
2090 normalize_log_options(or_options_t *options)
2092 /* The order of options is: Level? (File Level?)+
2094 struct config_line_t *opt = options->OldLogOptions;
2096 /* Special case for if first option is LogLevel. */
2097 if (opt && !strcasecmp(opt->key, "LogLevel")) {
2098 if (opt->next && (!strcasecmp(opt->next->key, "LogFile") ||
2099 !strcasecmp(opt->next->key, "SysLog"))) {
2100 if (convert_log_option(options, opt, opt->next, options->RunAsDaemon) < 0)
2101 return -1;
2102 opt = opt->next->next;
2103 } else if (!opt->next) {
2104 if (convert_log_option(options, opt, NULL, options->RunAsDaemon) < 0)
2105 return -1;
2106 opt = opt->next;
2107 } else {
2108 ; /* give warning below */
2112 while (opt) {
2113 if (!strcasecmp(opt->key, "LogLevel")) {
2114 log_fn(LOG_WARN, "Two LogLevel options in a row without intervening LogFile or SysLog");
2115 opt = opt->next;
2116 } else {
2117 tor_assert(!strcasecmp(opt->key, "LogFile") ||
2118 !strcasecmp(opt->key, "SysLog"));
2119 if (opt->next && !strcasecmp(opt->next->key, "LogLevel")) {
2120 /* LogFile/SysLog followed by LogLevel */
2121 if (convert_log_option(options,opt->next,opt, options->RunAsDaemon) < 0)
2122 return -1;
2123 opt = opt->next->next;
2124 } else {
2125 /* LogFile/SysLog followed by LogFile/SysLog or end of list. */
2126 if (convert_log_option(options,NULL, opt, options->RunAsDaemon) < 0)
2127 return -1;
2128 opt = opt->next;
2133 if (options->DebugLogFile) {
2134 if (add_single_log_option(options, LOG_DEBUG, LOG_ERR, "file", options->DebugLogFile) < 0)
2135 return -1;
2138 tor_free(options->DebugLogFile);
2139 config_free_lines(options->OldLogOptions);
2140 options->OldLogOptions = NULL;
2142 return 0;
2146 * Given a linked list of config lines containing "allow" and "deny" tokens,
2147 * parse them and append the result to <b>dest</b>. Return -1 if any tokens
2148 * are malformed, else return 0.
2151 config_parse_addr_policy(struct config_line_t *cfg,
2152 addr_policy_t **dest)
2154 addr_policy_t **nextp;
2155 smartlist_t *entries;
2156 int r = 0;
2158 if (!cfg)
2159 return 0;
2161 nextp = dest;
2163 while (*nextp)
2164 nextp = &((*nextp)->next);
2166 entries = smartlist_create();
2167 for (; cfg; cfg = cfg->next) {
2168 smartlist_split_string(entries, cfg->value, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2169 SMARTLIST_FOREACH(entries, const char *, ent,
2171 log_fn(LOG_DEBUG,"Adding new entry '%s'",ent);
2172 *nextp = router_parse_addr_policy_from_string(ent);
2173 if (*nextp) {
2174 nextp = &((*nextp)->next);
2175 } else {
2176 log_fn(LOG_WARN,"Malformed policy %s.", ent);
2177 r = -1;
2180 SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
2181 smartlist_clear(entries);
2183 smartlist_free(entries);
2184 return r;
2187 /** Release all storage held by <b>p</b> */
2188 void
2189 addr_policy_free(addr_policy_t *p) {
2190 addr_policy_t *e;
2192 while (p) {
2193 e = p;
2194 p = p->next;
2195 tor_free(e->string);
2196 tor_free(e);
2200 /** Parse a single RedirectExit line's contents from <b>line</b>. If
2201 * they are valid, and <b>result</b> is not NULL, add an element to
2202 * <b>result</b> and return 0. Else if they are valid, return 0.
2203 * Else return -1. */
2204 static int
2205 parse_redirect_line(smartlist_t *result, struct config_line_t *line)
2207 smartlist_t *elements = NULL;
2208 exit_redirect_t *r;
2210 tor_assert(line);
2212 r = tor_malloc_zero(sizeof(exit_redirect_t));
2213 elements = smartlist_create();
2214 smartlist_split_string(elements, line->value, NULL,
2215 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2216 if (smartlist_len(elements) != 2) {
2217 log_fn(LOG_WARN, "Wrong number of elements in RedirectExit line");
2218 goto err;
2220 if (parse_addr_and_port_range(smartlist_get(elements,0),&r->addr,&r->mask,
2221 &r->port_min,&r->port_max)) {
2222 log_fn(LOG_WARN, "Error parsing source address in RedirectExit line");
2223 goto err;
2225 if (0==strcasecmp(smartlist_get(elements,1), "pass")) {
2226 r->is_redirect = 0;
2227 } else {
2228 if (parse_addr_port(smartlist_get(elements,1),NULL,&r->addr_dest,
2229 &r->port_dest)) {
2230 log_fn(LOG_WARN, "Error parsing dest address in RedirectExit line");
2231 goto err;
2233 r->is_redirect = 1;
2236 goto done;
2237 err:
2238 tor_free(r);
2239 done:
2240 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2241 smartlist_free(elements);
2242 if (r) {
2243 if (result)
2244 smartlist_add(result, r);
2245 else
2246 tor_free(r);
2247 return 0;
2248 } else {
2249 return -1;
2253 /** Read the contents of a DirServer line from <b>line</b>. Return 0
2254 * if the line is well-formed, and 0 if it isn't. If
2255 * <b>validate_only</b> is 0, and the line is well-formed, then add
2256 * the dirserver described in the line as a valid server. */
2257 static int
2258 parse_dir_server_line(const char *line, int validate_only)
2260 smartlist_t *items = NULL;
2261 int r;
2262 char *addrport, *address=NULL;
2263 uint16_t port;
2264 char digest[DIGEST_LEN];
2266 items = smartlist_create();
2267 smartlist_split_string(items, line, NULL,
2268 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
2269 if (smartlist_len(items) < 2) {
2270 log_fn(LOG_WARN, "Too few arguments to DirServer line.");
2271 goto err;
2273 addrport = smartlist_get(items, 0);
2274 if (parse_addr_port(addrport, &address, NULL, &port)<0) {
2275 log_fn(LOG_WARN, "Error parsing DirServer address '%s'", addrport);
2276 goto err;
2278 if (!port) {
2279 log_fn(LOG_WARN, "Missing port in DirServer address '%s'",addrport);
2280 goto err;
2283 tor_strstrip(smartlist_get(items, 1), " ");
2284 if (strlen(smartlist_get(items, 1)) != HEX_DIGEST_LEN) {
2285 log_fn(LOG_WARN, "Key digest for DirServer is wrong length.");
2286 goto err;
2288 if (base16_decode(digest, DIGEST_LEN,
2289 smartlist_get(items,1), HEX_DIGEST_LEN)<0) {
2290 log_fn(LOG_WARN, "Unable to decode DirServer key digest.");
2291 goto err;
2294 if (!validate_only) {
2295 log_fn(LOG_DEBUG, "Trusted dirserver at %s:%d (%s)", address, (int)port,
2296 (char*)smartlist_get(items,1));
2297 add_trusted_dir_server(address, port, digest);
2300 r = 0;
2301 goto done;
2303 err:
2304 r = -1;
2306 done:
2307 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
2308 smartlist_free(items);
2309 tor_free(address);
2310 return r;
2313 /** Adjust the value of options->DataDirectory, or fill it in if it's
2314 * absent. Return 0 on success, -1 on failure. */
2315 static int
2316 normalize_data_directory(or_options_t *options) {
2317 #ifdef MS_WINDOWS
2318 char *p;
2319 if (options->DataDirectory)
2320 return 0; /* all set */
2321 p = tor_malloc(MAX_PATH);
2322 strlcpy(p,get_windows_conf_root(),MAX_PATH);
2323 options->DataDirectory = p;
2324 return 0;
2325 #else
2326 const char *d = options->DataDirectory;
2327 if (!d)
2328 d = "~/.tor";
2330 if (strncmp(d,"~/",2) == 0) {
2331 char *fn = expand_filename(d);
2332 if (!fn) {
2333 log_fn(LOG_ERR,"Failed to expand filename '%s'.", d);
2334 return -1;
2336 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
2337 /* If our homedir is /, we probably don't want to use it. */
2338 /* XXXX Default to /var/lib/tor? */
2339 log_fn(LOG_WARN, "Defaulting to 'DataDirectory %s', which may not be what you want", fn);
2341 tor_free(options->DataDirectory);
2342 options->DataDirectory = fn;
2344 return 0;
2345 #endif
2348 /** Check and normalize the value of options->DataDirectory; return 0 if it
2349 * sane, -1 otherwise. */
2350 static int
2351 validate_data_directory(or_options_t *options) {
2352 if (normalize_data_directory(options) < 0)
2353 return -1;
2354 tor_assert(options->DataDirectory);
2355 if (strlen(options->DataDirectory) > (512-128)) {
2356 log_fn(LOG_ERR, "DataDirectory is too long.");
2357 return -1;
2359 #if 0
2360 if (check_private_dir(options->DataDirectory, CPD_CHECK != 0)) {
2361 log_fn(LOG_WARN, "Can't create directory %s", options->DataDirectory);
2362 return -1;
2364 #endif
2365 return 0;
2368 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; if you edit it, comments will not be preserved"
2370 /** Save a configuration file for the configuration in <b>options</b>
2371 * into the file <b>fname</b>. If the file already exists, and
2372 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
2373 * replace it. Return 0 on success, -1 on failure. */
2374 static int
2375 write_configuration_file(const char *fname, or_options_t *options)
2377 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
2378 int rename_old = 0, r;
2379 size_t len;
2381 if (fname) {
2382 switch (file_status(fname)) {
2383 case FN_FILE:
2384 old_val = read_file_to_str(fname, 0);
2385 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
2386 rename_old = 1;
2388 tor_free(old_val);
2389 break;
2390 case FN_NOENT:
2391 break;
2392 default:
2393 log_fn(LOG_WARN,"Config file %s is not a file? Failing.", fname);
2394 return -1;
2398 if (!(new_conf = config_dump_options(options, 1))) {
2399 log_fn(LOG_WARN, "Couldn't get configuration string");
2400 goto err;
2403 len = strlen(new_conf)+128;
2404 new_val = tor_malloc(len);
2405 tor_snprintf(new_val, len, "%s\n\n%s", GENERATED_FILE_PREFIX, new_conf);
2407 if (rename_old) {
2408 int i = 1;
2409 size_t fn_tmp_len = strlen(fname)+32;
2410 char *fn_tmp;
2411 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
2412 fn_tmp = tor_malloc(fn_tmp_len);
2413 while (1) {
2414 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
2415 log_fn(LOG_WARN, "tor_snprintf failed inexplicably");
2416 tor_free(fn_tmp);
2417 goto err;
2419 if (file_status(fn_tmp) == FN_NOENT)
2420 break;
2421 ++i;
2423 log_fn(LOG_NOTICE, "Renaming old configuration file to %s", fn_tmp);
2424 rename(fname, fn_tmp);
2425 tor_free(fn_tmp);
2428 write_str_to_file(fname, new_val, 0);
2430 r = 0;
2431 goto done;
2432 err:
2433 r = -1;
2434 done:
2435 tor_free(new_val);
2436 tor_free(new_conf);
2437 return r;
2441 * Save the current configuration file value to disk. Return 0 on
2442 * success, -1 on failure.
2445 save_current_config(void)
2447 char *fn;
2448 if (config_fname) {
2449 /* XXX This fails if we can't write to our configuration file.
2450 * Arguably, we should try falling back to datadirectory or something.
2451 * But just as arguably, we shouldn't. */
2452 return write_configuration_file(config_fname, get_options());
2454 fn = get_default_conf_file();
2455 return write_configuration_file(fn, get_options());
2458 struct unit_table_t {
2459 const char *unit;
2460 uint64_t multiplier;
2463 static struct unit_table_t memory_units[] = {
2464 { "", 1 },
2465 { "b", 1<< 0 },
2466 { "byte", 1<< 0 },
2467 { "bytes", 1<< 0 },
2468 { "kb", 1<<10 },
2469 { "kilobyte", 1<<10 },
2470 { "kilobytes", 1<<10 },
2471 { "m", 1<<20 },
2472 { "mb", 1<<20 },
2473 { "megabyte", 1<<20 },
2474 { "megabytes", 1<<20 },
2475 { "gb", 1<<30 },
2476 { "gigabyte", 1<<30 },
2477 { "gigabytes", 1<<30 },
2478 { "tb", U64_LITERAL(1)<<40 },
2479 { "terabyte", U64_LITERAL(1)<<40 },
2480 { "terabytes", U64_LITERAL(1)<<40 },
2481 { NULL, 0 },
2484 static struct unit_table_t time_units[] = {
2485 { "", 1 },
2486 { "second", 1 },
2487 { "seconds", 1 },
2488 { "minute", 60 },
2489 { "minutes", 60 },
2490 { "hour", 60*60 },
2491 { "hours", 60*60 },
2492 { "day", 24*60*60 },
2493 { "days", 24*60*60 },
2494 { "week", 7*24*60*60 },
2495 { "weeks", 7*24*60*60 },
2496 { NULL, 0 },
2499 /** Parse a string <b>val</b> containing a number, zero or more
2500 * spaces, and an optional unit string. If the unit appears in the
2501 * table <b>u</b>, then multiply the number by the unit multiplier.
2502 * On success, set *<b>ok</b> to 1 and return this product.
2503 * Otherwise, set *<b>ok</b> to 0.
2505 static uint64_t
2506 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
2508 uint64_t v;
2509 char *cp;
2511 tor_assert(ok);
2513 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
2514 if (!*ok)
2515 return 0;
2516 if (!cp) {
2517 *ok = 1;
2518 return v;
2520 while (TOR_ISSPACE(*cp))
2521 ++cp;
2522 for ( ;u->unit;++u) {
2523 if (!strcasecmp(u->unit, cp)) {
2524 v *= u->multiplier;
2525 *ok = 1;
2526 return v;
2529 log_fn(LOG_WARN, "Unknown unit '%s'.", cp);
2530 *ok = 0;
2531 return 0;
2534 /** Parse a string in the format "number unit", where unit is a unit of
2535 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
2536 * and return the number of bytes specified. Otherwise, set
2537 * *<b>ok</b> to false and return 0. */
2538 static uint64_t
2539 config_parse_memunit(const char *s, int *ok) {
2540 return config_parse_units(s, memory_units, ok);
2543 /** Parse a string in the format "number unit", where unit is a unit of time.
2544 * On success, set *<b>ok</b> to true and return the number of seconds in
2545 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
2547 static int
2548 config_parse_interval(const char *s, int *ok) {
2549 uint64_t r;
2550 r = config_parse_units(s, time_units, ok);
2551 if (!ok)
2552 return -1;
2553 if (r > INT_MAX) {
2554 log_fn(LOG_WARN, "Interval '%s' is too long", s);
2555 *ok = 0;
2556 return -1;
2558 return (int)r;
2561 static void
2562 print_cvs_version(void)
2564 extern const char aes_c_id[];
2565 extern const char compat_c_id[];
2566 extern const char container_c_id[];
2567 extern const char crypto_c_id[];
2568 extern const char log_c_id[];
2569 extern const char torgzip_c_id[];
2570 extern const char tortls_c_id[];
2571 extern const char util_c_id[];
2573 extern const char buffers_c_id[];
2574 extern const char circuitbuild_c_id[];
2575 extern const char circuitlist_c_id[];
2576 extern const char circuituse_c_id[];
2577 extern const char command_c_id[];
2578 // extern const char config_c_id[];
2579 extern const char connection_c_id[];
2580 extern const char connection_edge_c_id[];
2581 extern const char connection_or_c_id[];
2582 extern const char control_c_id[];
2583 extern const char cpuworker_c_id[];
2584 extern const char directory_c_id[];
2585 extern const char dirserv_c_id[];
2586 extern const char dns_c_id[];
2587 extern const char hibernate_c_id[];
2588 extern const char main_c_id[];
2589 extern const char onion_c_id[];
2590 extern const char relay_c_id[];
2591 extern const char rendclient_c_id[];
2592 extern const char rendcommon_c_id[];
2593 extern const char rendmid_c_id[];
2594 extern const char rendservice_c_id[];
2595 extern const char rephist_c_id[];
2596 extern const char router_c_id[];
2597 extern const char routerlist_c_id[];
2598 extern const char routerparse_c_id[];
2600 puts(AES_H_ID);
2601 puts(COMPAT_H_ID);
2602 puts(CONTAINER_H_ID);
2603 puts(CRYPTO_H_ID);
2604 puts(LOG_H_ID);
2605 puts(TORGZIP_H_ID);
2606 puts(TORINT_H_ID);
2607 puts(TORTLS_H_ID);
2608 puts(UTIL_H_ID);
2609 puts(aes_c_id);
2610 puts(compat_c_id);
2611 puts(container_c_id);
2612 puts(crypto_c_id);
2613 puts(log_c_id);
2614 puts(torgzip_c_id);
2615 puts(tortls_c_id);
2616 puts(util_c_id);
2618 puts(OR_H_ID);
2619 puts(buffers_c_id);
2620 puts(circuitbuild_c_id);
2621 puts(circuitlist_c_id);
2622 puts(circuituse_c_id);
2623 puts(command_c_id);
2624 puts(config_c_id);
2625 puts(connection_c_id);
2626 puts(connection_edge_c_id);
2627 puts(connection_or_c_id);
2628 puts(control_c_id);
2629 puts(cpuworker_c_id);
2630 puts(directory_c_id);
2631 puts(dirserv_c_id);
2632 puts(dns_c_id);
2633 puts(hibernate_c_id);
2634 puts(main_c_id);
2635 puts(onion_c_id);
2636 puts(relay_c_id);
2637 puts(rendclient_c_id);
2638 puts(rendcommon_c_id);
2639 puts(rendmid_c_id);
2640 puts(rendservice_c_id);
2641 puts(rephist_c_id);
2642 puts(router_c_id);
2643 puts(routerlist_c_id);
2644 puts(routerparse_c_id);