add more chat and interactive protocols to LongLivedPorts
[tor.git] / src / or / config.c
blob6e9ca1d71e99a016a8d9c8166650a43f74fb2349
1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004 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(RendNode),
60 PLURAL(RendExcludeNode),
61 PLURAL(StrictEntryNode),
62 PLURAL(StrictExitNode),
63 { "l", "Log", 1},
64 { "BandwidthRateBytes", "BandwidthRate", 0},
65 { "BandwidthBurstBytes", "BandwidthBurst", 0},
66 { "DirFetchPostPeriod", "StatusFetchPeriod", 0},
67 { NULL, NULL , 0},
69 #undef PLURAL
71 /** A variable allowed in the configuration file or on the command line. */
72 typedef struct config_var_t {
73 const char *name; /**< The full keyword (case insensitive). */
74 config_type_t type; /**< How to interpret the type and turn it into a value. */
75 off_t var_offset; /**< Offset of the corresponding member of or_options_t. */
76 const char *initvalue; /**< String (or null) describing initial value. */
77 } config_var_t;
79 /** Return the offset of <b>member</b> within the type <b>tp</b>, in bytes */
80 #define STRUCT_OFFSET(tp, member) ((off_t) (((char*)&((tp*)0)->member)-(char*)0))
81 /** An entry for config_vars: "The option <b>name</b> has type
82 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
83 * or_options_t.<b>member</b>"
85 #define VAR(name,conftype,member,initvalue) \
86 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), initvalue }
87 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
88 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
90 /** Array of configuration options. Until we disallow nonstandard
91 * abbreviations, order is significant, since the first matching option will
92 * be chosen first.
94 static config_var_t config_vars[] = {
95 VAR("Address", STRING, Address, NULL),
96 VAR("AccountingStart", STRING, AccountingStart, NULL),
97 VAR("AllowUnverifiedNodes",CSV, AllowUnverifiedNodes, "middle,rendezvous"),
98 VAR("AuthoritativeDirectory",BOOL, AuthoritativeDir, "0"),
99 VAR("BandwidthRate", MEMUNIT, BandwidthRate, "780 KB"),
100 VAR("BandwidthBurst", MEMUNIT, BandwidthBurst, "48 MB"),
101 VAR("ClientOnly", BOOL, ClientOnly, "0"),
102 VAR("ContactInfo", STRING, ContactInfo, NULL),
103 VAR("ControlPort", UINT, ControlPort, "0"),
104 VAR("CookieAuthentication",BOOL, CookieAuthentication, "0"),
105 VAR("DebugLogFile", STRING, DebugLogFile, NULL),
106 VAR("DataDirectory", STRING, DataDirectory, NULL),
107 VAR("DirAllowPrivateAddresses",BOOL, DirAllowPrivateAddresses, NULL),
108 VAR("DirPort", UINT, DirPort, "0"),
109 VAR("DirBindAddress", LINELIST, DirBindAddress, NULL),
110 /* XXX we'd like dirfetchperiod to be higher for people with dirport not
111 * set, but low for people with dirport set. how to have two defaults? */
112 VAR("DirFetchPeriod", INTERVAL, DirFetchPeriod, "1 hour"),
113 VAR("DirPostPeriod", INTERVAL, DirPostPeriod, "20 minutes"),
114 VAR("RendPostPeriod", INTERVAL, RendPostPeriod, "20 minutes"),
115 VAR("DirPolicy", LINELIST, DirPolicy, NULL),
116 VAR("DirServer", LINELIST, DirServers, NULL),
117 VAR("ExitNodes", STRING, ExitNodes, NULL),
118 VAR("EntryNodes", STRING, EntryNodes, NULL),
119 VAR("StrictExitNodes", BOOL, StrictExitNodes, "0"),
120 VAR("StrictEntryNodes", BOOL, StrictEntryNodes, "0"),
121 VAR("ExitPolicy", LINELIST, ExitPolicy, NULL),
122 VAR("ExcludeNodes", STRING, ExcludeNodes, NULL),
123 VAR("FascistFirewall", BOOL, FascistFirewall, "0"),
124 VAR("FirewallPorts", CSV, FirewallPorts, "80,443"),
125 VAR("MyFamily", STRING, MyFamily, NULL),
126 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
127 VAR("Group", STRING, Group, NULL),
128 VAR("HashedControlPassword",STRING, HashedControlPassword, NULL),
129 VAR("HttpProxy", STRING, HttpProxy, NULL),
130 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
131 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
132 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
133 VAR("HiddenServiceNodes", LINELIST_S, RendConfigLines, NULL),
134 VAR("HiddenServiceExcludeNodes", LINELIST_S, RendConfigLines, NULL),
135 VAR("IgnoreVersion", BOOL, IgnoreVersion, "0"),
136 VAR("KeepalivePeriod", INTERVAL, KeepalivePeriod, "5 minutes"),
137 VAR("Log", LINELIST, Logs, NULL),
138 VAR("LogLevel", LINELIST_S, OldLogOptions, NULL),
139 VAR("LogFile", LINELIST_S, OldLogOptions, NULL),
140 OBSOLETE("LinkPadding"),
141 VAR("MaxConn", UINT, MaxConn, "1024"),
142 VAR("MaxOnionsPending", UINT, MaxOnionsPending, "100"),
143 VAR("MonthlyAccountingStart",UINT, _MonthlyAccountingStart,"0"),
144 VAR("AccountingMaxKB", UINT, _AccountingMaxKB, "0"),
145 VAR("AccountingMax", MEMUNIT, AccountingMax, "0 bytes"),
146 VAR("Nickname", STRING, Nickname, NULL),
147 VAR("NewCircuitPeriod", INTERVAL, NewCircuitPeriod, "30 seconds"),
148 VAR("NumCpus", UINT, NumCpus, "1"),
149 VAR("ORPort", UINT, ORPort, "0"),
150 VAR("ORBindAddress", LINELIST, ORBindAddress, NULL),
151 VAR("OutboundBindAddress", STRING, OutboundBindAddress, NULL),
152 VAR("PidFile", STRING, PidFile, NULL),
153 VAR("LongLivedPorts", CSV, LongLivedPorts, "21,22,706,1863,5050,5190,5222,5223,6667,8300,8888"),
154 VAR("PathlenCoinWeight", DOUBLE, PathlenCoinWeight, "0.3"),
155 VAR("RedirectExit", LINELIST, RedirectExit, NULL),
156 OBSOLETE("RouterFile"),
157 VAR("RunAsDaemon", BOOL, RunAsDaemon, "0"),
158 VAR("RunTesting", BOOL, RunTesting, "0"),
159 VAR("RecommendedVersions", LINELIST, RecommendedVersions, NULL),
160 VAR("RendNodes", STRING, RendNodes, NULL),
161 VAR("RendExcludeNodes", STRING, RendExcludeNodes, NULL),
162 VAR("SocksPort", UINT, SocksPort, "9050"),
163 VAR("SocksBindAddress", LINELIST, SocksBindAddress, NULL),
164 VAR("SocksPolicy", LINELIST, SocksPolicy, NULL),
165 /* XXX as with dirfetchperiod, we want this to be 15 minutes for people
166 * with a dirport open, but higher for people without a dirport open. */
167 VAR("StatusFetchPeriod", INTERVAL, StatusFetchPeriod, "15 minutes"),
168 VAR("SysLog", LINELIST_S, OldLogOptions, NULL),
169 OBSOLETE("TrafficShaping"),
170 VAR("User", STRING, User, NULL),
171 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
173 #undef VAR
174 #undef OBSOLETE
176 /** Largest allowed config line */
177 #define CONFIG_LINE_T_MAXLEN 4096
179 static void config_line_append(struct config_line_t **lst,
180 const char *key, const char *val);
181 static void option_reset(or_options_t *options, config_var_t *var);
182 static void options_free(or_options_t *options);
183 static int option_is_same(or_options_t *o1, or_options_t *o2,const char *name);
184 static or_options_t *options_dup(or_options_t *old);
185 static int options_validate(or_options_t *options);
186 static int options_transition_allowed(or_options_t *old, or_options_t *new);
187 static int check_nickname_list(const char *lst, const char *name);
189 static int parse_dir_server_line(const char *line, int validate_only);
190 static int parse_redirect_line(smartlist_t *result,
191 struct config_line_t *line);
192 static int parse_log_severity_range(const char *range, int *min_out,
193 int *max_out);
194 static int convert_log_option(or_options_t *options,
195 struct config_line_t *level_opt,
196 struct config_line_t *file_opt, int isDaemon);
197 static int add_single_log_option(or_options_t *options, int minSeverity,
198 int maxSeverity,
199 const char *type, const char *fname);
200 static int normalize_log_options(or_options_t *options);
201 static int validate_data_directory(or_options_t *options);
202 static int write_configuration_file(const char *fname, or_options_t *options);
204 static uint64_t config_parse_memunit(const char *s, int *ok);
205 static int config_parse_interval(const char *s, int *ok);
206 static void print_cvs_version(void);
209 * Functions to read and write the global options pointer.
212 /** Command-line and config-file options. */
213 static or_options_t *global_options=NULL;
214 /** Name of most recently read torrc file. */
215 static char *config_fname = NULL;
217 /** Return the currently configured options. */
218 or_options_t *
219 get_options(void) {
220 tor_assert(global_options);
221 return global_options;
224 /** Change the current global options to contain <b>new_val</b> instead
225 * of their current value; free the old value as necessary.
227 void
228 set_options(or_options_t *new_val) {
229 if (global_options)
230 options_free(global_options);
231 global_options = new_val;
234 /** Fetch the active option list, and take actions based on it. All
235 * of the things we do should survive being done repeatedly.
236 * Return 0 if all goes well, return -1 if it's time to die.
238 * Note 1: <b>new_val</b> must have previously been validated with
239 * options_validate(), or Tor may freak out and exit.
241 * Note 2: We haven't moved all the "act on new configuration" logic
242 * here yet. Some is still in do_hup() and other places.
245 options_act(void) {
246 struct config_line_t *cl;
247 or_options_t *options = get_options();
249 clear_trusted_dir_servers();
250 for (cl = options->DirServers; cl; cl = cl->next) {
251 if (parse_dir_server_line(cl->value, 0)<0) {
252 log_fn(LOG_ERR,
253 "Bug: Previously validated DirServer line could not be added!");
254 return -1;
258 if (rend_config_services(options, 0)<0) {
259 log_fn(LOG_ERR,
260 "Bug: Previously validated hidden services line could not be added!");
261 return -1;
264 /* Setuid/setgid as appropriate */
265 if (options->User || options->Group) {
266 if (switch_id(options->User, options->Group) != 0) {
267 return -1;
271 /* Ensure data directory is private; create if possible. */
272 if (check_private_dir(options->DataDirectory, CPD_CREATE) != 0) {
273 log_fn(LOG_ERR, "Couldn't access/create private data directory %s",
274 options->DataDirectory);
275 return -1;
278 /* Bail out at this point if we're not going to be a server: we want
279 * to not fork, and to log stuff to stderr. */
280 if (options->command != CMD_RUN_TOR)
281 return 0;
283 mark_logs_temp(); /* Close current logs once new logs are open. */
284 if (config_init_logs(options, 0)<0) /* Configure the log(s) */
285 return -1;
286 /* Close the temporary log we used while starting up, if it isn't already
287 * gone. */
288 close_temp_logs();
289 add_callback_log(LOG_NOTICE, LOG_ERR, control_event_logmsg);
291 if (set_max_file_descriptors(options->MaxConn) < 0)
292 return -1;
295 smartlist_t *sl = smartlist_create();
296 for (cl = options->RedirectExit; cl; cl = cl->next) {
297 if (parse_redirect_line(sl, cl)<0)
298 return -1;
300 set_exit_redirects(sl);
303 /* Start backgrounding the process, if requested. */
305 /* XXXX009 We once had a reason to separate start_daemon and finish_daemon:
306 * It let us have the parent process stick around until we were sure Tor
307 * was started. Should we make start_daemon get called earlier? -NM */
308 if (options->RunAsDaemon) {
309 start_daemon(options->DataDirectory);
312 /* Finish backgrounding the process */
313 if (options->RunAsDaemon) {
314 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
315 finish_daemon();
318 /* Write our pid to the pid file. If we do not have write permissions we
319 * will log a warning */
320 if (options->PidFile)
321 write_pidfile(options->PidFile);
323 /* Update address policies. */
324 parse_socks_policy();
325 parse_dir_policy();
327 init_cookie_authentication(options->CookieAuthentication);
329 /* reload keys as needed for rendezvous services. */
330 if (rend_service_load_keys()<0) {
331 log_fn(LOG_ERR,"Error loading rendezvous service keys");
332 return -1;
335 /* Set up accounting */
336 if (accounting_parse_options(options, 0)<0) {
337 log_fn(LOG_ERR,"Error in accounting options");
338 return -1;
340 if (accounting_is_enabled(options))
341 configure_accounting(time(NULL));
343 if (!we_are_hibernating() && retry_all_listeners(1) < 0) {
344 log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
345 return -1;
348 #if 0
350 char *smin, *smax;
351 smin = config_dump_options(options, 1);
352 smax = config_dump_options(options, 0);
353 log_fn(LOG_DEBUG, "These are our options:\n%s",smax);
354 log_fn(LOG_DEBUG, "We changed these options:\n%s",smin);
355 tor_free(smin);
356 tor_free(smax);
358 #endif
360 /* Since our options changed, we might need to regenerate and upload our
361 * server descriptor. (We could probably be more clever about only calling
362 * this when something significant changed.)
364 mark_my_descriptor_dirty();
366 return 0;
370 * Functions to parse config options
373 /** If <b>option</b> is an official abbreviation for a longer option,
374 * return the longer option. Otherwise return <b>option</b>.
375 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
376 * apply abbreviations that work for the config file and the command line. */
377 static const char *
378 expand_abbrev(const char *option, int command_line)
380 int i;
381 for (i=0; config_abbrevs[i].abbreviated; ++i) {
382 /* Abbreviations aren't casei. */
383 if (!strcasecmp(option,config_abbrevs[i].abbreviated) &&
384 (command_line || !config_abbrevs[i].commandline_only)) {
385 return config_abbrevs[i].full;
388 return option;
391 /** Helper: Read a list of configuration options from the command line. */
392 static struct config_line_t *
393 config_get_commandlines(int argc, char **argv)
395 struct config_line_t *new;
396 struct config_line_t *front = NULL;
397 char *s;
398 int i = 1;
400 while (i < argc-1) {
401 if (!strcmp(argv[i],"-f") ||
402 !strcmp(argv[i],"--hash-password")) {
403 i += 2; /* command-line option with argument. ignore them. */
404 continue;
405 } else if (!strcmp(argv[i],"--list-fingerprint")) {
406 i += 1; /* command-line option. ignore it. */
407 continue;
410 new = tor_malloc(sizeof(struct config_line_t));
411 s = argv[i];
413 while (*s == '-')
414 s++;
416 new->key = tor_strdup(expand_abbrev(s, 1));
417 new->value = tor_strdup(argv[i+1]);
419 log(LOG_DEBUG,"Commandline: parsed keyword '%s', value '%s'",
420 new->key, new->value);
421 new->next = front;
422 front = new;
423 i += 2;
425 return front;
428 /** Helper: allocate a new configuration option mapping 'key' to 'val',
429 * append it to *<b>lst</b>. */
430 static void
431 config_line_append(struct config_line_t **lst,
432 const char *key,
433 const char *val)
435 struct config_line_t *newline;
437 newline = tor_malloc(sizeof(struct config_line_t));
438 newline->key = tor_strdup(key);
439 newline->value = tor_strdup(val);
440 newline->next = NULL;
441 while (*lst)
442 lst = &((*lst)->next);
444 (*lst) = newline;
447 /** Helper: parse the config string and strdup into key/value
448 * strings. Set *result to the list, or NULL if parsing the string
449 * failed. Return 0 on success, -1 on failure. Warn and ignore any
450 * misformatted lines. */
452 config_get_lines(char *string, struct config_line_t **result)
454 struct config_line_t *list = NULL, **next;
455 char *k, *v;
457 next = &list;
458 do {
459 string = parse_line_from_str(string, &k, &v);
460 if (!string) {
461 config_free_lines(list);
462 return -1;
464 if (k && v) {
465 /* This list can get long, so we keep a pointer to the end of it
466 * rather than using config_line_append over and over and getting n^2
467 * performance. This is the only really long list. */
468 *next = tor_malloc(sizeof(struct config_line_t));
469 (*next)->key = tor_strdup(k);
470 (*next)->value = tor_strdup(v);
471 (*next)->next = NULL;
472 next = &((*next)->next);
474 } while (*string);
476 *result = list;
477 return 0;
481 * Free all the configuration lines on the linked list <b>front</b>.
483 void
484 config_free_lines(struct config_line_t *front)
486 struct config_line_t *tmp;
488 while (front) {
489 tmp = front;
490 front = tmp->next;
492 tor_free(tmp->key);
493 tor_free(tmp->value);
494 tor_free(tmp);
498 /** If <b>key</b> is a configuration option, return the corresponding
499 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
500 * warn, and return the corresponding config_var_t. Otherwise return NULL.
502 static config_var_t *config_find_option(const char *key)
504 int i;
505 /* First, check for an exact (case-insensitive) match */
506 for (i=0; config_vars[i].name; ++i) {
507 if (!strcasecmp(key, config_vars[i].name))
508 return &config_vars[i];
510 /* If none, check for an abbreviated match */
511 for (i=0; config_vars[i].name; ++i) {
512 if (!strncasecmp(key, config_vars[i].name, strlen(key))) {
513 log_fn(LOG_WARN, "The abbreviation '%s' is deprecated. "
514 "Tell Nick and Roger to make it official, or just use '%s' instead",
515 key, config_vars[i].name);
516 return &config_vars[i];
519 /* Okay, unrecognized options */
520 return NULL;
523 /** If <b>c</b> is a syntactically valid configuration line, update
524 * <b>options</b> with its value and return 0. Otherwise return -1 for bad key,
525 * -2 for bad value.
527 * If 'reset' is set, and we get a line containing no value, restore the
528 * option to its default value.
530 static int
531 config_assign_line(or_options_t *options, struct config_line_t *c, int reset)
533 int i, ok;
534 config_var_t *var;
535 void *lvalue;
537 var = config_find_option(c->key);
538 if (!var) {
539 log_fn(LOG_WARN, "Unknown option '%s'. Failing.", c->key);
540 return -1;
542 /* Put keyword into canonical case. */
543 if (strcmp(var->name, c->key)) {
544 tor_free(c->key);
545 c->key = tor_strdup(var->name);
548 if (reset && !strlen(c->value)) {
549 option_reset(options, var);
550 return 0;
553 lvalue = ((char*)options) + var->var_offset;
554 switch (var->type) {
556 case CONFIG_TYPE_UINT:
557 i = tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
558 if (!ok) {
559 log(LOG_WARN, "Int keyword '%s %s' is malformed or out of bounds.",
560 c->key,c->value);
561 return -2;
563 *(int *)lvalue = i;
564 break;
566 case CONFIG_TYPE_INTERVAL: {
567 i = config_parse_interval(c->value, &ok);
568 if (!ok) {
569 return -2;
571 *(int *)lvalue = i;
572 break;
575 case CONFIG_TYPE_MEMUNIT: {
576 uint64_t u64 = config_parse_memunit(c->value, &ok);
577 if (!ok) {
578 return -2;
580 *(uint64_t *)lvalue = u64;
581 break;
584 case CONFIG_TYPE_BOOL:
585 i = tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
586 if (!ok) {
587 log(LOG_WARN, "Boolean keyword '%s' expects 0 or 1.", c->key);
588 return -2;
590 *(int *)lvalue = i;
591 break;
593 case CONFIG_TYPE_STRING:
594 tor_free(*(char **)lvalue);
595 *(char **)lvalue = tor_strdup(c->value);
596 break;
598 case CONFIG_TYPE_DOUBLE:
599 *(double *)lvalue = atof(c->value);
600 break;
602 case CONFIG_TYPE_CSV:
603 if (*(smartlist_t**)lvalue) {
604 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
605 smartlist_clear(*(smartlist_t**)lvalue);
606 } else {
607 *(smartlist_t**)lvalue = smartlist_create();
610 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
611 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
612 break;
614 case CONFIG_TYPE_LINELIST:
615 case CONFIG_TYPE_LINELIST_S:
616 config_line_append((struct config_line_t**)lvalue, c->key, c->value);
617 break;
619 case CONFIG_TYPE_OBSOLETE:
620 log_fn(LOG_WARN, "Skipping obsolete configuration option '%s'", c->key);
621 break;
622 case CONFIG_TYPE_LINELIST_V:
623 log_fn(LOG_WARN, "Can't provide value for virtual option '%s'", c->key);
624 return -2;
625 default:
626 tor_assert(0);
627 break;
629 return 0;
632 /** restore the option named <b>key</b> in options to its default value. */
633 static void
634 config_reset_line(or_options_t *options, const char *key)
636 config_var_t *var;
638 var = config_find_option(key);
639 if (!var)
640 return; /* give error on next pass. */
642 option_reset(options, var);
645 /** Return true iff key is a valid configuration option. */
647 config_option_is_recognized(const char *key)
649 config_var_t *var = config_find_option(key);
650 return (var != NULL);
653 /** Return a canonicalized list of the options assigned for key.
655 struct config_line_t *
656 config_get_assigned_option(or_options_t *options, const char *key)
658 config_var_t *var;
659 const void *value;
660 char buf[32];
661 struct config_line_t *result;
662 tor_assert(options && key);
664 var = config_find_option(key);
665 if (!var) {
666 log_fn(LOG_WARN, "Unknown option '%s'. Failing.", key);
667 return NULL;
668 } else if (var->type == CONFIG_TYPE_LINELIST_S) {
669 log_fn(LOG_WARN, "Can't return context-sensitive '%s' on its own", key);
670 return NULL;
672 value = ((char*)options) + var->var_offset;
674 if (var->type == CONFIG_TYPE_LINELIST ||
675 var->type == CONFIG_TYPE_LINELIST_V) {
676 /* Linelist requires special handling: we just copy and return it. */
677 const struct config_line_t *next_in = *(const struct config_line_t**)value;
678 struct config_line_t **next_out = &result;
679 while (next_in) {
680 *next_out = tor_malloc(sizeof(struct config_line_t));
681 (*next_out)->key = tor_strdup(next_in->key);
682 (*next_out)->value = tor_strdup(next_in->value);
683 next_in = next_in->next;
684 next_out = &((*next_out)->next);
686 (*next_out) = NULL;
687 return result;
690 result = tor_malloc_zero(sizeof(struct config_line_t));
691 result->key = tor_strdup(var->name);
692 switch (var->type)
694 case CONFIG_TYPE_STRING:
695 if (*(char**)value) {
696 result->value = tor_strdup(*(char**)value);
697 } else {
698 tor_free(result->key);
699 tor_free(result);
700 return NULL;
702 break;
703 case CONFIG_TYPE_INTERVAL:
704 case CONFIG_TYPE_UINT:
705 /* This means every or_options_t uint or bool element
706 * needs to be an int. Not, say, a uint16_t or char. */
707 tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
708 result->value = tor_strdup(buf);
709 break;
710 case CONFIG_TYPE_MEMUNIT:
711 tor_snprintf(buf, sizeof(buf), U64_FORMAT,
712 U64_PRINTF_ARG(*(uint64_t*)value));
713 result->value = tor_strdup(buf);
714 break;
715 case CONFIG_TYPE_DOUBLE:
716 tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
717 result->value = tor_strdup(buf);
718 break;
719 case CONFIG_TYPE_BOOL:
720 result->value = tor_strdup(*(int*)value ? "1" : "0");
721 break;
722 case CONFIG_TYPE_CSV:
723 if (*(smartlist_t**)value)
724 result->value = smartlist_join_strings(*(smartlist_t**)value,",",0,NULL);
725 else
726 result->value = tor_strdup("");
727 break;
728 case CONFIG_TYPE_OBSOLETE:
729 log_fn(LOG_WARN,"You asked me for the value of an obsolete config option %s.", key);
730 tor_free(result->key);
731 tor_free(result);
732 return NULL;
733 default:
734 tor_free(result->key);
735 tor_free(result);
736 log_fn(LOG_WARN,"Bug: unknown type %d for known key %s", var->type, key);
737 return NULL;
740 return result;
743 /** Iterate through the linked list of requested options <b>list</b>.
744 * For each item, convert as appropriate and assign to <b>options</b>.
745 * If an item is unrecognized, return -1 immediately,
746 * else return 0 for success.
748 * If <b>reset</b>, then interpret empty lines as meaning "restore to
749 * default value", and interpret LINELIST* options as replacing (not
750 * extending) their previous values. Return 0 on success, -1 on bad key,
751 * -2 on bad value.
753 static int
754 config_assign(or_options_t *options, struct config_line_t *list, int reset)
756 struct config_line_t *p;
757 tor_assert(options);
759 /* pass 1: normalize keys */
760 for (p = list; p; p = p->next) {
761 const char *full = expand_abbrev(p->key, 0);
762 if (strcmp(full,p->key)) {
763 tor_free(p->key);
764 p->key = tor_strdup(full);
768 /* pass 2: if we're reading from a resetting source, clear all mentioned
769 * linelists. */
770 if (reset) {
771 for (p = list; p; p = p->next)
772 config_reset_line(options, p->key);
775 /* pass 3: assign. */
776 while (list) {
777 int r;
778 if ((r=config_assign_line(options, list, reset)))
779 return r;
780 list = list->next;
782 return 0;
785 /** Try assigning <b>list</b> to the global options. You do this by duping
786 * options, assigning list to the new one, then validating it. If it's
787 * ok, then throw out the old one and stick with the new one. Else,
788 * revert to old and return failure. Return 0 on success, -1 on bad
789 * keys, -2 on bad values, -3 on bad transition.
792 config_trial_assign(struct config_line_t *list, int reset)
794 int r;
795 or_options_t *trial_options = options_dup(get_options());
797 if ((r=config_assign(trial_options, list, reset)) < 0) {
798 options_free(trial_options);
799 return r;
802 if (options_validate(trial_options) < 0) {
803 options_free(trial_options);
804 return -2;
807 if (options_transition_allowed(get_options(), trial_options) < 0) {
808 options_free(trial_options);
809 return -3;
812 set_options(trial_options); /* we liked it. put it in place. */
813 return 0;
816 /** Replace the option indexed by <b>var</b> in <b>options</b> with its
817 * default value. */
818 static void
819 option_reset(or_options_t *options, config_var_t *var)
821 struct config_line_t *c;
822 void *lvalue;
824 lvalue = ((char*)options) + var->var_offset;
825 switch (var->type) {
826 case CONFIG_TYPE_STRING:
827 tor_free(*(char**)lvalue);
828 break;
829 case CONFIG_TYPE_DOUBLE:
830 *(double*)lvalue = 0.0;
831 break;
832 case CONFIG_TYPE_INTERVAL:
833 case CONFIG_TYPE_UINT:
834 case CONFIG_TYPE_BOOL:
835 *(int*)lvalue = 0;
836 break;
837 case CONFIG_TYPE_MEMUNIT:
838 *(uint64_t*)lvalue = 0;
839 break;
840 case CONFIG_TYPE_CSV:
841 if (*(smartlist_t**)lvalue) {
842 SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
843 smartlist_free(*(smartlist_t **)lvalue);
844 *(smartlist_t **)lvalue = NULL;
846 break;
847 case CONFIG_TYPE_LINELIST:
848 case CONFIG_TYPE_LINELIST_S:
849 config_free_lines(*(struct config_line_t **)lvalue);
850 *(struct config_line_t **)lvalue = NULL;
851 break;
852 case CONFIG_TYPE_LINELIST_V:
853 /* handled by linelist_s. */
854 break;
855 case CONFIG_TYPE_OBSOLETE:
856 break;
858 if (var->initvalue) {
859 c = tor_malloc_zero(sizeof(struct config_line_t));
860 c->key = tor_strdup(var->name);
861 c->value = tor_strdup(var->initvalue);
862 config_assign_line(options,c,0);
863 config_free_lines(c);
867 /** Set <b>options</b>-&gt;DirServers to contain the default directory
868 * servers. */
869 static void
870 add_default_trusted_dirservers(or_options_t *options)
872 /* moria1 */
873 config_line_append(&options->DirServers, "DirServer",
874 "18.244.0.188:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441");
875 /* moria2 */
876 config_line_append(&options->DirServers, "DirServer",
877 "18.244.0.114:80 719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF");
878 /* tor26 */
879 config_line_append(&options->DirServers, "DirServer",
880 "62.116.124.106:9030 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D");
881 // "tor.noreply.org:9030 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D");
884 /** Print a usage message for tor. */
885 static void
886 print_usage(void)
888 printf(
889 "Copyright 2001-2004 Roger Dingledine, Nick Mathewson, Matej Pfajfar.\n\n"
890 "tor -f <torrc> [args]\n"
891 "See man page for options, or http://tor.eff.org/ for documentation.\n");
895 * Based on <b>address</b>, guess our public IP address and put it
896 * in <b>addr</b>.
899 resolve_my_address(const char *address, uint32_t *addr)
901 struct in_addr in;
902 struct hostent *rent;
903 char hostname[256];
904 int explicit_ip=1;
906 tor_assert(addr);
908 if (address) {
909 strlcpy(hostname, address, sizeof(hostname));
910 } else { /* then we need to guess our address */
911 explicit_ip = 0; /* it's implicit */
913 if (gethostname(hostname, sizeof(hostname)) < 0) {
914 log_fn(LOG_WARN,"Error obtaining local hostname");
915 return -1;
917 log_fn(LOG_DEBUG,"Guessed local host name as '%s'",hostname);
920 /* now we know hostname. resolve it and keep only the IP */
922 if (tor_inet_aton(hostname, &in) == 0) {
923 /* then we have to resolve it */
924 explicit_ip = 0;
925 rent = (struct hostent *)gethostbyname(hostname);
926 if (!rent) {
927 log_fn(LOG_WARN,"Could not resolve local Address %s. Failing.", hostname);
928 return -1;
930 tor_assert(rent->h_length == 4);
931 memcpy(&in.s_addr, rent->h_addr, rent->h_length);
934 if (!explicit_ip && is_internal_IP(htonl(in.s_addr))) {
935 log_fn(LOG_WARN,"Address '%s' resolves to private IP '%s'. "
936 "Please set the Address config option to be the IP you want to use.",
937 hostname, inet_ntoa(in));
938 return -1;
941 log_fn(LOG_DEBUG, "Resolved Address to %s.", inet_ntoa(in));
942 *addr = ntohl(in.s_addr);
943 return 0;
946 /** Called when we don't have a nickname set. Try to guess a good
947 * nickname based on the hostname, and return it in a newly allocated string. */
948 static char *
949 get_default_nickname(void)
951 char localhostname[256];
952 char *cp, *out, *outp;
954 if (gethostname(localhostname, sizeof(localhostname)) < 0) {
955 log_fn(LOG_WARN,"Error obtaining local hostname");
956 return NULL;
959 /* Put it in lowercase; stop at the first dot. */
960 for (cp = localhostname; *cp; ++cp) {
961 if (*cp == '.') {
962 *cp = '\0';
963 break;
965 *cp = tolower(*cp);
968 /* Strip invalid characters. */
969 cp = localhostname;
970 out = outp = tor_malloc(strlen(localhostname) + 1);
971 while (*cp) {
972 if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
973 *outp++ = *cp++;
974 else
975 cp++;
977 *outp = '\0';
979 /* Enforce length. */
980 if (strlen(out) > MAX_NICKNAME_LEN)
981 out[MAX_NICKNAME_LEN]='\0';
983 return out;
986 /** Release storage held by <b>options</b> */
987 static void
988 options_free(or_options_t *options)
990 int i;
991 void *lvalue;
993 tor_assert(options);
995 for (i=0; config_vars[i].name; ++i) {
996 lvalue = ((char*)options) + config_vars[i].var_offset;
997 switch (config_vars[i].type) {
998 case CONFIG_TYPE_MEMUNIT:
999 case CONFIG_TYPE_INTERVAL:
1000 case CONFIG_TYPE_UINT:
1001 case CONFIG_TYPE_BOOL:
1002 case CONFIG_TYPE_DOUBLE:
1003 case CONFIG_TYPE_OBSOLETE:
1004 break; /* nothing to free for these config types */
1005 case CONFIG_TYPE_STRING:
1006 tor_free(*(char **)lvalue);
1007 break;
1008 case CONFIG_TYPE_LINELIST:
1009 case CONFIG_TYPE_LINELIST_V:
1010 config_free_lines(*(struct config_line_t**)lvalue);
1011 *(struct config_line_t**)lvalue = NULL;
1012 break;
1013 case CONFIG_TYPE_CSV:
1014 if (*(smartlist_t**)lvalue) {
1015 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
1016 smartlist_free(*(smartlist_t**)lvalue);
1017 *(smartlist_t**)lvalue = NULL;
1019 break;
1020 case CONFIG_TYPE_LINELIST_S:
1021 /* will be freed by corresponding LINELIST_V. */
1022 break;
1025 tor_free(options);
1028 /** Return true iff the option <b>var</b> has the same value in <b>o1</b>
1029 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
1031 static int
1032 option_is_same(or_options_t *o1, or_options_t *o2, const char *name)
1034 struct config_line_t *c1, *c2;
1035 int r = 1;
1036 c1 = config_get_assigned_option(o1, name);
1037 c2 = config_get_assigned_option(o2, name);
1038 while (c1 && c2) {
1039 if (strcasecmp(c1->key, c2->key) ||
1040 strcmp(c1->value, c2->value)) {
1041 r = 0;
1042 break;
1044 c1 = c1->next;
1045 c2 = c2->next;
1047 if (r && (c1 || c2)) {
1048 r = 0;
1050 config_free_lines(c1);
1051 config_free_lines(c2);
1052 return r;
1055 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
1056 static or_options_t *
1057 options_dup(or_options_t *old)
1059 or_options_t *newopts;
1060 int i;
1061 struct config_line_t *line;
1063 newopts = tor_malloc_zero(sizeof(or_options_t));
1064 for (i=0; config_vars[i].name; ++i) {
1065 if (config_vars[i].type == CONFIG_TYPE_LINELIST_S)
1066 continue;
1067 if (config_vars[i].type == CONFIG_TYPE_OBSOLETE)
1068 continue;
1069 line = config_get_assigned_option(old, config_vars[i].name);
1070 if (line) {
1071 if (config_assign(newopts, line, 0) < 0) {
1072 log_fn(LOG_WARN,"Bug: config_get_assigned_option() generated "
1073 "something we couldn't config_assign().");
1074 tor_assert(0);
1077 config_free_lines(line);
1079 return newopts;
1082 /** Set <b>options</b> to hold reasonable defaults for most options.
1083 * Each option defaults to zero. */
1084 void
1085 options_init(or_options_t *options)
1087 int i;
1088 config_var_t *var;
1090 for (i=0; config_vars[i].name; ++i) {
1091 var = &config_vars[i];
1092 if (!var->initvalue)
1093 continue; /* defaults to NULL or 0 */
1094 option_reset(options, var);
1098 /** Return a string containing a possible configuration file that would give
1099 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
1100 * include options that are the same as Tor's defaults.
1102 char *
1103 config_dump_options(or_options_t *options, int minimal)
1105 smartlist_t *elements;
1106 or_options_t *defaults;
1107 struct config_line_t *line;
1108 char *result;
1109 int i;
1111 defaults = tor_malloc_zero(sizeof(or_options_t));
1112 options_init(defaults);
1113 options_validate(defaults); /* ??? will this work? */
1115 elements = smartlist_create();
1116 for (i=0; config_vars[i].name; ++i) {
1117 if (config_vars[i].type == CONFIG_TYPE_OBSOLETE ||
1118 config_vars[i].type == CONFIG_TYPE_LINELIST_S)
1119 continue;
1120 if (minimal && option_is_same(options, defaults, config_vars[i].name))
1121 continue;
1122 line = config_get_assigned_option(options, config_vars[i].name);
1123 for (; line; line = line->next) {
1124 size_t len = strlen(line->key) + strlen(line->value) + 3;
1125 char *tmp;
1126 tmp = tor_malloc(len);
1127 if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
1128 log_fn(LOG_ERR, "Internal error writing log option");
1129 tor_assert(0);
1131 smartlist_add(elements, tmp);
1133 config_free_lines(line);
1136 result = smartlist_join_strings(elements, "", 0, NULL);
1137 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
1138 smartlist_free(elements);
1139 return result;
1142 static int
1143 validate_ports_csv(smartlist_t *sl, char *name) {
1144 int i;
1145 int result = 0;
1146 tor_assert(name);
1148 if(!sl)
1149 return 0;
1151 SMARTLIST_FOREACH(sl, const char *, cp,
1153 i = atoi(cp);
1154 if (i < 1 || i > 65535) {
1155 log(LOG_WARN, "Port '%s' out of range in %s", cp, name);
1156 result=-1;
1159 return result;
1162 /** Return 0 if every setting in <b>options</b> is reasonable. Else
1163 * warn and return -1. Should have no side effects, except for
1164 * normalizing the contents of <b>options</b>. */
1165 static int
1166 options_validate(or_options_t *options)
1168 int result = 0;
1169 struct config_line_t *cl;
1170 addr_policy_t *addr_policy=NULL;
1172 if (options->ORPort < 0 || options->ORPort > 65535) {
1173 log(LOG_WARN, "ORPort option out of bounds.");
1174 result = -1;
1177 /* XXX might similarly want to check the other *BindAddress options */
1178 if (options->ORPort == 0 && options->ORBindAddress != NULL) {
1179 log(LOG_WARN, "ORPort must be defined if ORBindAddress is defined.");
1180 result = -1;
1183 if (validate_data_directory(options)<0) {
1184 log(LOG_WARN, "Invalid DataDirectory");
1185 result = -1;
1188 if (options->Nickname == NULL) {
1189 if (server_mode(options)) {
1190 if (!(options->Nickname = get_default_nickname()))
1191 return -1;
1192 log_fn(LOG_NOTICE, "Choosing default nickname %s", options->Nickname);
1194 } else {
1195 if (strspn(options->Nickname, LEGAL_NICKNAME_CHARACTERS) !=
1196 strlen(options->Nickname)) {
1197 log_fn(LOG_WARN, "Nickname '%s' contains illegal characters.", options->Nickname);
1198 result = -1;
1200 if (strlen(options->Nickname) == 0) {
1201 log_fn(LOG_WARN, "Nickname must have at least one character");
1202 result = -1;
1204 if (strlen(options->Nickname) > MAX_NICKNAME_LEN) {
1205 log_fn(LOG_WARN, "Nickname '%s' has more than %d characters.",
1206 options->Nickname, MAX_NICKNAME_LEN);
1207 result = -1;
1211 if (normalize_log_options(options))
1212 return -1;
1214 /* Special case if no options are given. */
1215 if (!options->Logs) {
1216 config_line_append(&options->Logs, "Log", "notice stdout");
1219 if (config_init_logs(options, 1)<0) /* Validate the log(s) */
1220 return -1;
1222 if (server_mode(options)) {
1223 /* confirm that our address isn't broken, so we can complain now */
1224 uint32_t tmp;
1225 if (resolve_my_address(options->Address, &tmp) < 0)
1226 result = -1;
1229 if (options->SocksPort < 0 || options->SocksPort > 65535) {
1230 log(LOG_WARN, "SocksPort option out of bounds.");
1231 result = -1;
1234 if (options->SocksPort == 0 && options->ORPort == 0) {
1235 log(LOG_WARN, "SocksPort and ORPort are both undefined? Quitting.");
1236 result = -1;
1239 if (options->ControlPort < 0 || options->ControlPort > 65535) {
1240 log(LOG_WARN, "ControlPort option out of bounds.");
1241 result = -1;
1244 if (options->DirPort < 0 || options->DirPort > 65535) {
1245 log(LOG_WARN, "DirPort option out of bounds.");
1246 result = -1;
1249 if (options->StrictExitNodes &&
1250 (!options->ExitNodes || !strlen(options->ExitNodes))) {
1251 log(LOG_WARN, "StrictExitNodes set, but no ExitNodes listed.");
1254 if (options->StrictEntryNodes &&
1255 (!options->EntryNodes || !strlen(options->EntryNodes))) {
1256 log(LOG_WARN, "StrictEntryNodes set, but no EntryNodes listed.");
1259 if (options->AuthoritativeDir && options->RecommendedVersions == NULL) {
1260 log(LOG_WARN, "Directory servers must configure RecommendedVersions.");
1261 result = -1;
1264 if (options->AuthoritativeDir && !options->DirPort) {
1265 log(LOG_WARN, "Running as authoritative directory, but no DirPort set.");
1266 result = -1;
1269 if (options->AuthoritativeDir && !options->ORPort) {
1270 log(LOG_WARN, "Running as authoritative directory, but no ORPort set.");
1271 result = -1;
1274 if (options->AuthoritativeDir && options->ClientOnly) {
1275 log(LOG_WARN, "Running as authoritative directory, but ClientOnly also set.");
1276 result = -1;
1279 if (options->_AccountingMaxKB) {
1280 log(LOG_WARN, "AccountingMaxKB is deprecated. Say 'AccountingMax %d KB' instead.", options->_AccountingMaxKB);
1281 options->AccountingMax = U64_LITERAL(1024)*options->_AccountingMaxKB;
1282 options->_AccountingMaxKB = 0;
1285 if (validate_ports_csv(options->FirewallPorts,
1286 "FirewallPorts") < 0)
1287 result = -1;
1289 if (validate_ports_csv(options->LongLivedPorts,
1290 "LongLivedPorts") < 0)
1291 result = -1;
1293 options->_AllowUnverified = 0;
1294 if (options->AllowUnverifiedNodes) {
1295 SMARTLIST_FOREACH(options->AllowUnverifiedNodes, const char *, cp, {
1296 if (!strcasecmp(cp, "entry"))
1297 options->_AllowUnverified |= ALLOW_UNVERIFIED_ENTRY;
1298 else if (!strcasecmp(cp, "exit"))
1299 options->_AllowUnverified |= ALLOW_UNVERIFIED_EXIT;
1300 else if (!strcasecmp(cp, "middle"))
1301 options->_AllowUnverified |= ALLOW_UNVERIFIED_MIDDLE;
1302 else if (!strcasecmp(cp, "introduction"))
1303 options->_AllowUnverified |= ALLOW_UNVERIFIED_INTRODUCTION;
1304 else if (!strcasecmp(cp, "rendezvous"))
1305 options->_AllowUnverified |= ALLOW_UNVERIFIED_RENDEZVOUS;
1306 else {
1307 log(LOG_WARN, "Unrecognized value '%s' in AllowUnverifiedNodes",
1308 cp);
1309 result = -1;
1314 if (options->SocksPort >= 1 &&
1315 (options->PathlenCoinWeight < 0.0 || options->PathlenCoinWeight >= 1.0)) {
1316 log(LOG_WARN, "PathlenCoinWeight option must be >=0.0 and <1.0.");
1317 result = -1;
1320 if (options->MaxConn < 1) {
1321 log(LOG_WARN, "MaxConn option must be a non-zero positive integer.");
1322 result = -1;
1325 if (options->MaxConn >= MAXCONNECTIONS) {
1326 log(LOG_WARN, "MaxConn option must be less than %d.", MAXCONNECTIONS);
1327 result = -1;
1330 #define MIN_DIR_FETCH_PERIOD 600
1331 #define MIN_DIR_POST_PERIOD 300
1332 #define MIN_REND_POST_PERIOD 300
1333 #define MIN_STATUS_FETCH_PERIOD 60
1335 /* After 0.0.8 is dead, change this to MIN_ONION_KEY_LIFETIME. */
1336 #define MAX_DIR_PERIOD (OLD_MIN_ONION_KEY_LIFETIME/2)
1337 #define MAX_CACHE_DIR_FETCH_PERIOD 3600
1338 #define MAX_CACHE_STATUS_FETCH_PERIOD 900
1340 if (options->DirFetchPeriod < MIN_DIR_FETCH_PERIOD) {
1341 log(LOG_WARN, "DirFetchPeriod option must be at least %d seconds. Clipping.", MIN_DIR_FETCH_PERIOD);
1342 options->DirFetchPeriod = MIN_DIR_FETCH_PERIOD;
1344 if (options->StatusFetchPeriod < MIN_STATUS_FETCH_PERIOD) {
1345 log(LOG_WARN, "StatusFetchPeriod option must be at least %d seconds. Clipping.", MIN_STATUS_FETCH_PERIOD);
1346 options->StatusFetchPeriod = MIN_STATUS_FETCH_PERIOD;
1348 if (options->DirPostPeriod < MIN_DIR_POST_PERIOD) {
1349 log(LOG_WARN, "DirPostPeriod option must be at least %d seconds. Clipping.",
1350 MIN_DIR_POST_PERIOD);
1351 options->DirPostPeriod = MIN_DIR_POST_PERIOD;
1353 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
1354 log(LOG_WARN,"RendPostPeriod option must be at least %d seconds. Clipping.",
1355 MIN_REND_POST_PERIOD);
1356 options->RendPostPeriod = MIN_REND_POST_PERIOD;
1359 if (options->DirPort && ! options->AuthoritativeDir) {
1360 if (options->DirFetchPeriod > MAX_CACHE_DIR_FETCH_PERIOD) {
1361 log(LOG_WARN, "Caching directory servers must have DirFetchPeriod less than %d seconds. Clipping.", MAX_CACHE_DIR_FETCH_PERIOD);
1362 options->DirFetchPeriod = MAX_CACHE_DIR_FETCH_PERIOD;
1364 if (options->StatusFetchPeriod > MAX_CACHE_STATUS_FETCH_PERIOD) {
1365 log(LOG_WARN, "Caching directory servers must have StatusFetchPeriod less than %d seconds. Clipping.", MAX_CACHE_STATUS_FETCH_PERIOD);
1366 options->StatusFetchPeriod = MAX_CACHE_STATUS_FETCH_PERIOD;
1370 if (options->DirFetchPeriod > MAX_DIR_PERIOD) {
1371 log(LOG_WARN, "DirFetchPeriod is too large; clipping.");
1372 options->DirFetchPeriod = MAX_DIR_PERIOD;
1374 if (options->DirPostPeriod > MAX_DIR_PERIOD) {
1375 log(LOG_WARN, "DirPostPeriod is too large; clipping.");
1376 options->DirPostPeriod = MAX_DIR_PERIOD;
1378 if (options->StatusFetchPeriod > MAX_DIR_PERIOD) {
1379 log(LOG_WARN, "StatusFetchPeriod is too large; clipping.");
1380 options->StatusFetchPeriod = MAX_DIR_PERIOD;
1382 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
1383 log(LOG_WARN, "RendPostPeriod is too large; clipping.");
1384 options->RendPostPeriod = MAX_DIR_PERIOD;
1387 if (options->KeepalivePeriod < 1) {
1388 log(LOG_WARN,"KeepalivePeriod option must be positive.");
1389 result = -1;
1392 if (2*options->BandwidthRate >= options->BandwidthBurst) {
1393 log(LOG_WARN,"BandwidthBurst must be more than twice BandwidthRate.");
1394 result = -1;
1396 if (options->BandwidthRate > INT_MAX) {
1397 log(LOG_WARN,"BandwidthRate must be less than %d",INT_MAX);
1398 result = -1;
1400 if (options->BandwidthBurst > INT_MAX) {
1401 log(LOG_WARN,"BandwidthBurst must be less than %d",INT_MAX);
1402 result = -1;
1404 if (server_mode(options) &&
1405 options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH*2) {
1406 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);
1407 result = -1;
1410 if (options->_MonthlyAccountingStart) {
1411 if (options->AccountingStart) {
1412 log(LOG_WARN,"Can't specify AccountingStart and MonthlyAccountingStart");
1413 result = -1;
1414 } else {
1415 options->AccountingStart = tor_malloc(32);
1416 if (tor_snprintf(options->AccountingStart, 32, "month %d 0:00",
1417 options->_MonthlyAccountingStart)<0) {
1418 log_fn(LOG_WARN,"Error translating MonthlyAccountingStart");
1419 result = -1;
1420 } else {
1421 log_fn(LOG_WARN,"MonthlyAccountingStart is deprecated. Use 'AccountingStart %s' instead.", options->AccountingStart);
1426 if (accounting_parse_options(options, 1)<0) {
1427 result = -1;
1430 if (options->HttpProxy) { /* parse it now */
1431 if (parse_addr_port(options->HttpProxy, NULL,
1432 &options->HttpProxyAddr, &options->HttpProxyPort) < 0) {
1433 log(LOG_WARN,"HttpProxy failed to parse or resolve. Please fix.");
1434 result = -1;
1436 if (options->HttpProxyPort == 0) { /* give it a default */
1437 options->HttpProxyPort = 80;
1441 if (options->HashedControlPassword) {
1442 if (decode_hashed_password(NULL, options->HashedControlPassword)<0) {
1443 log_fn(LOG_WARN,"Bad HashedControlPassword: wrong length or bad base64");
1444 result = -1;
1447 if (options->HashedControlPassword && options->CookieAuthentication) {
1448 log_fn(LOG_WARN,"Cannot enable both HashedControlPassword and CookieAuthentication");
1449 result = -1;
1452 if (check_nickname_list(options->ExitNodes, "ExitNodes"))
1453 result = -1;
1454 if (check_nickname_list(options->EntryNodes, "EntryNodes"))
1455 result = -1;
1456 if (check_nickname_list(options->ExcludeNodes, "ExcludeNodes"))
1457 result = -1;
1458 if (check_nickname_list(options->RendNodes, "RendNodes"))
1459 result = -1;
1460 if (check_nickname_list(options->RendNodes, "RendExcludeNodes"))
1461 result = -1;
1462 if (check_nickname_list(options->MyFamily, "MyFamily"))
1463 result = -1;
1464 for (cl = options->NodeFamilies; cl; cl = cl->next) {
1465 if (check_nickname_list(cl->value, "NodeFamily"))
1466 result = -1;
1469 if (config_parse_addr_policy(options->ExitPolicy, &addr_policy)) {
1470 log_fn(LOG_WARN, "Error in Exit Policy entry.");
1471 result = -1;
1473 if (config_parse_addr_policy(options->DirPolicy, &addr_policy)) {
1474 log_fn(LOG_WARN, "Error in DirPolicy entry.");
1475 result = -1;
1477 if (config_parse_addr_policy(options->SocksPolicy, &addr_policy)) {
1478 log_fn(LOG_WARN, "Error in SocksPolicy entry.");
1479 result = -1;
1481 addr_policy_free(addr_policy);
1483 for (cl = options->RedirectExit; cl; cl = cl->next) {
1484 if (parse_redirect_line(NULL, cl)<0)
1485 result = -1;
1488 if (!options->DirServers) {
1489 add_default_trusted_dirservers(options);
1490 } else {
1491 for (cl = options->DirServers; cl; cl = cl->next) {
1492 if (parse_dir_server_line(cl->value, 1)<0)
1493 result = -1;
1497 if (rend_config_services(options, 1) < 0)
1498 result = -1;
1500 return result;
1503 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
1504 * equal strings. */
1505 static int
1506 opt_streq(const char *s1, const char *s2)
1508 if (!s1 && !s2)
1509 return 1;
1510 else if (s1 && s2 && !strcmp(s1,s2))
1511 return 1;
1512 else
1513 return 0;
1516 /** Check if any of the previous options have changed but aren't allowed to. */
1517 static int
1518 options_transition_allowed(or_options_t *old, or_options_t *new_val) {
1520 if (!old)
1521 return 0;
1523 if (!opt_streq(old->PidFile, new_val->PidFile)) {
1524 log_fn(LOG_WARN,"PidFile is not allowed to change. Failing.");
1525 return -1;
1528 if (old->RunAsDaemon && !new_val->RunAsDaemon) {
1529 log_fn(LOG_WARN,"During reload, change from RunAsDaemon=1 to =0 not allowed. Failing.");
1530 return -1;
1533 if (old->ORPort != new_val->ORPort) {
1534 log_fn(LOG_WARN,"During reload, changing ORPort is not allowed. Failing.");
1535 return -1;
1538 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
1539 log_fn(LOG_WARN,"During reload, changing DataDirectory (%s->%s) is not allowed. Failing.", old->DataDirectory, new_val->DataDirectory);
1540 return -1;
1543 if (!opt_streq(old->User, new_val->User)) {
1544 log_fn(LOG_WARN,"During reload, changing User is not allowed. Failing.");
1545 return -1;
1548 if (!opt_streq(old->Group, new_val->Group)) {
1549 log_fn(LOG_WARN,"During reload, changing User is not allowed. Failing.");
1550 return -1;
1553 return 0;
1556 #ifdef MS_WINDOWS
1557 /** Return the directory on windows where we expect to find our application
1558 * data. */
1559 static char *get_windows_conf_root(void)
1561 static int is_set = 0;
1562 static char path[MAX_PATH+1];
1564 LPITEMIDLIST idl;
1565 IMalloc *m;
1566 HRESULT result;
1568 if (is_set)
1569 return path;
1571 /* Find X:\documents and settings\username\application data\ .
1572 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
1574 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA,
1575 &idl))) {
1576 GetCurrentDirectory(MAX_PATH, path);
1577 is_set = 1;
1578 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);
1579 return path;
1581 /* Convert the path from an "ID List" (whatever that is!) to a path. */
1582 result = SHGetPathFromIDList(idl, path);
1583 /* Now we need to free the */
1584 SHGetMalloc(&m);
1585 if (m) {
1586 m->lpVtbl->Free(m, idl);
1587 m->lpVtbl->Release(m);
1589 if (!SUCCEEDED(result)) {
1590 return NULL;
1592 strlcat(path,"\\tor",MAX_PATH);
1593 is_set = 1;
1594 return path;
1596 #endif
1598 /** Return the default location for our torrc file. */
1599 static char *
1600 get_default_conf_file(void)
1602 #ifdef MS_WINDOWS
1603 char *path = tor_malloc(MAX_PATH);
1604 strlcpy(path, get_windows_conf_root(), MAX_PATH);
1605 strlcat(path,"\\torrc",MAX_PATH);
1606 return path;
1607 #else
1608 return tor_strdup(CONFDIR "/torrc");
1609 #endif
1612 /** Verify whether lst is a string containing valid-looking space-separated
1613 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
1615 static int check_nickname_list(const char *lst, const char *name)
1617 int r = 0;
1618 smartlist_t *sl;
1620 if (!lst)
1621 return 0;
1622 sl = smartlist_create();
1623 smartlist_split_string(sl, lst, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1624 SMARTLIST_FOREACH(sl, const char *, s,
1626 if (!is_legal_nickname_or_hexdigest(s)) {
1627 log_fn(LOG_WARN, "Invalid nickname '%s' in %s line", s, name);
1628 r = -1;
1631 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
1632 smartlist_free(sl);
1633 return r;
1636 /** Read a configuration file into <b>options</b>, finding the configuration
1637 * file location based on the command line. After loading the options,
1638 * validate them for consistency, then take actions based on them.
1639 * Return 0 if success, -1 if failure. */
1641 init_from_config(int argc, char **argv)
1643 or_options_t *oldoptions, *newoptions;
1644 struct config_line_t *cl;
1645 char *cf=NULL, *fname=NULL;
1646 int i, retval;
1647 int using_default_torrc;
1648 static char **backup_argv;
1649 static int backup_argc;
1651 if (argv) { /* first time we're called. save commandline args */
1652 backup_argv = argv;
1653 backup_argc = argc;
1654 oldoptions = NULL;
1655 } else { /* we're reloading. need to clean up old options first. */
1656 argv = backup_argv;
1657 argc = backup_argc;
1658 oldoptions = get_options();
1660 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
1661 print_usage();
1662 exit(0);
1665 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
1666 printf("Tor version %s.\n",VERSION);
1667 if (argc > 2 && (!strcmp(argv[2],"--version"))) {
1668 print_cvs_version();
1670 exit(0);
1673 newoptions = tor_malloc_zero(sizeof(or_options_t));
1674 options_init(newoptions);
1676 /* learn config file name, get config lines, assign them */
1677 fname = NULL;
1678 using_default_torrc = 1;
1679 newoptions->command = CMD_RUN_TOR;
1680 for (i = 1; i < argc; ++i) {
1681 if (i < argc-1 && !strcmp(argv[i],"-f")) {
1682 if (fname) {
1683 log(LOG_WARN, "Duplicate -f options on command line.");
1684 tor_free(fname);
1686 fname = tor_strdup(argv[i+1]);
1687 using_default_torrc = 0;
1688 ++i;
1689 } else if (!strcmp(argv[i],"--list-fingerprint")) {
1690 newoptions->command = CMD_LIST_FINGERPRINT;
1691 } else if (!strcmp(argv[i],"--hash-password")) {
1692 newoptions->command = CMD_HASH_PASSWORD;
1693 newoptions->command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
1694 ++i;
1698 if (using_default_torrc) {
1699 /* didn't find one, try CONFDIR */
1700 char *fn;
1701 fn = get_default_conf_file();
1702 if (fn && file_status(fn) == FN_FILE) {
1703 fname = fn;
1704 } else {
1705 tor_free(fn);
1706 #ifndef MS_WINDOWS
1707 fn = expand_filename("~/.torrc");
1708 if (fn && file_status(fn) == FN_FILE) {
1709 fname = fn;
1710 } else {
1711 tor_free(fn);
1712 fname = get_default_conf_file();
1714 #else
1715 fname = get_default_conf_file();
1716 #endif
1719 tor_assert(fname);
1720 log(LOG_DEBUG, "Opening config file '%s'", fname);
1722 if (file_status(fname) != FN_FILE ||
1723 !(cf = read_file_to_str(fname,0))) {
1724 if (using_default_torrc == 1) {
1725 log(LOG_NOTICE, "Configuration file '%s' not present, "
1726 "using reasonable defaults.", fname);
1727 tor_free(fname); /* sets fname to NULL */
1728 } else {
1729 log(LOG_WARN, "Unable to open configuration file '%s'.", fname);
1730 tor_free(fname);
1731 goto err;
1733 } else { /* it opened successfully. use it. */
1734 retval = config_get_lines(cf, &cl);
1735 tor_free(cf);
1736 if (retval < 0)
1737 goto err;
1738 retval = config_assign(newoptions, cl, 0);
1739 config_free_lines(cl);
1740 if (retval < 0)
1741 goto err;
1744 /* Go through command-line variables too */
1745 cl = config_get_commandlines(argc,argv);
1746 retval = config_assign(newoptions,cl,0);
1747 config_free_lines(cl);
1748 if (retval < 0)
1749 goto err;
1751 /* Validate newoptions */
1752 if (options_validate(newoptions) < 0)
1753 goto err;
1755 if (options_transition_allowed(oldoptions, newoptions) < 0)
1756 goto err;
1758 set_options(newoptions); /* frees and replaces old options */
1759 if (options_act() < 0) { /* acting on them failed. die. */
1760 log_fn(LOG_ERR,"Acting on config options left us in a broken state. Dying.");
1761 exit(1);
1763 tor_free(config_fname);
1764 config_fname = fname;
1765 return 0;
1766 err:
1767 tor_free(fname);
1768 options_free(newoptions);
1769 return -1;
1772 /** If <b>range</b> is of the form MIN-MAX, for MIN and MAX both
1773 * recognized log severity levels, set *<b>min_out</b> to MIN and
1774 * *<b>max_out</b> to MAX and return 0. Else, if <b>range<b> is of
1775 * the form MIN, act as if MIN-err had been specified. Else, warn and
1776 * return -1.
1778 static int
1779 parse_log_severity_range(const char *range, int *min_out, int *max_out)
1781 int levelMin, levelMax;
1782 const char *cp;
1783 cp = strchr(range, '-');
1784 if (cp) {
1785 if (cp == range) {
1786 levelMin = LOG_DEBUG;
1787 } else {
1788 char *tmp_sev = tor_strndup(range, cp - range);
1789 levelMin = parse_log_level(tmp_sev);
1790 if (levelMin < 0) {
1791 log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
1792 "err|warn|notice|info|debug", tmp_sev);
1793 tor_free(tmp_sev);
1794 return -1;
1796 tor_free(tmp_sev);
1798 if (!*(cp+1)) {
1799 levelMax = LOG_ERR;
1800 } else {
1801 levelMax = parse_log_level(cp+1);
1802 if (levelMax < 0) {
1803 log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
1804 "err|warn|notice|info|debug", cp+1);
1805 return -1;
1808 } else {
1809 levelMin = parse_log_level(range);
1810 if (levelMin < 0) {
1811 log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
1812 "err|warn|notice|info|debug", range);
1813 return -1;
1815 levelMax = LOG_ERR;
1818 *min_out = levelMin;
1819 *max_out = levelMax;
1821 return 0;
1824 /** Try to convert a pair of old-style logging options [LogLevel, and
1825 * (LogFile/Syslog)] to a new-style option, and add the new option to
1826 * options->Logs. */
1827 static int
1828 convert_log_option(or_options_t *options, struct config_line_t *level_opt,
1829 struct config_line_t *file_opt, int isDaemon)
1831 int levelMin = -1, levelMax = -1;
1833 if (level_opt) {
1834 if (parse_log_severity_range(level_opt->value, &levelMin, &levelMax))
1835 return -1;
1837 if (levelMin < 0 && levelMax < 0) {
1838 levelMin = LOG_NOTICE;
1839 levelMax = LOG_ERR;
1840 } else if (levelMin < 0) {
1841 levelMin = levelMax;
1842 } else {
1843 levelMax = LOG_ERR;
1846 if (file_opt && !strcasecmp(file_opt->key, "LogFile")) {
1847 if (add_single_log_option(options, levelMin, levelMax, "file", file_opt->value) < 0) {
1848 log_fn(LOG_WARN, "Cannot write to LogFile '%s': %s.", file_opt->value,
1849 strerror(errno));
1850 return -1;
1852 } else if (file_opt && !strcasecmp(file_opt->key, "SysLog")) {
1853 if (add_single_log_option(options, levelMin, levelMax, "syslog", NULL) < 0)
1854 return -1;
1855 } else if (!isDaemon) {
1856 add_single_log_option(options, levelMin, levelMax, "stdout", NULL);
1858 return 0;
1862 * Initialize the logs based on the configuration file.
1865 config_init_logs(or_options_t *options, int validate_only)
1867 struct config_line_t *opt;
1868 int ok;
1869 smartlist_t *elts;
1871 ok = 1;
1872 elts = smartlist_create();
1873 for (opt = options->Logs; opt; opt = opt->next) {
1874 int levelMin=LOG_DEBUG, levelMax=LOG_ERR;
1875 smartlist_split_string(elts, opt->value, NULL,
1876 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
1877 if (smartlist_len(elts) == 0) {
1878 log_fn(LOG_WARN, "Bad syntax on Log option 'Log %s'", opt->value);
1879 ok = 0; goto cleanup;
1881 if (parse_log_severity_range(smartlist_get(elts,0), &levelMin, &levelMax)) {
1882 ok = 0; goto cleanup;
1884 if (smartlist_len(elts) < 2) { /* only loglevels were provided */
1885 if (!validate_only)
1886 add_stream_log(levelMin, levelMax, "<stdout>", stdout);
1887 goto cleanup;
1889 if (!strcasecmp(smartlist_get(elts,1), "file")) {
1890 if (smartlist_len(elts) != 3) {
1891 log_fn(LOG_WARN, "Bad syntax on Log option 'Log %s'", opt->value);
1892 ok = 0; goto cleanup;
1894 if (!validate_only)
1895 add_file_log(levelMin, levelMax, smartlist_get(elts, 2));
1896 goto cleanup;
1898 if (smartlist_len(elts) != 2) {
1899 log_fn(LOG_WARN, "Bad syntax on Log option 'Log %s'", opt->value);
1900 ok = 0; goto cleanup;
1902 if (!strcasecmp(smartlist_get(elts,1), "stdout")) {
1903 if (!validate_only) {
1904 add_stream_log(levelMin, levelMax, "<stdout>", stdout);
1905 close_temp_logs();
1907 } else if (!strcasecmp(smartlist_get(elts,1), "stderr")) {
1908 if (!validate_only) {
1909 add_stream_log(levelMin, levelMax, "<stderr>", stderr);
1910 close_temp_logs();
1912 } else if (!strcasecmp(smartlist_get(elts,1), "syslog")) {
1913 #ifdef HAVE_SYSLOG_H
1914 if (!validate_only)
1915 add_syslog_log(levelMin, levelMax);
1916 #else
1917 log_fn(LOG_WARN, "Syslog is not supported in this compilation.");
1918 #endif
1919 } else {
1920 log_fn(LOG_WARN, "Unrecognized log type %s",
1921 (const char*)smartlist_get(elts,1));
1922 if (strchr(smartlist_get(elts,1), '/')) {
1923 log_fn(LOG_WARN, "Did you mean to say 'Log file %s' ?",
1924 (const char *)smartlist_get(elts,1));
1926 ok = 0; goto cleanup;
1928 cleanup:
1929 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
1930 smartlist_clear(elts);
1932 smartlist_free(elts);
1933 if (!validate_only)
1934 close_temp_logs();
1936 return ok?0:-1;
1939 /** Add a single option of the form Log min-max <type> [fname] to options. */
1940 static int
1941 add_single_log_option(or_options_t *options, int minSeverity, int maxSeverity,
1942 const char *type, const char *fname)
1944 char buf[512];
1945 int n;
1947 n = tor_snprintf(buf, sizeof(buf), "%s%s%s %s%s%s",
1948 log_level_to_string(minSeverity),
1949 maxSeverity == LOG_ERR ? "" : "-",
1950 maxSeverity == LOG_ERR ? "" : log_level_to_string(maxSeverity),
1951 type, fname?" ":"", fname?fname:"");
1952 if (n<0) {
1953 log_fn(LOG_WARN, "Normalized log option too long.");
1954 return -1;
1957 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);
1958 config_line_append(&options->Logs, "Log", buf);
1959 return 0;
1962 /** Convert all old-style logging options to new-style Log options. Return 0
1963 * on success, -1 on failure. */
1964 static int
1965 normalize_log_options(or_options_t *options)
1967 /* The order of options is: Level? (File Level?)+
1969 struct config_line_t *opt = options->OldLogOptions;
1971 /* Special case for if first option is LogLevel. */
1972 if (opt && !strcasecmp(opt->key, "LogLevel")) {
1973 if (opt->next && (!strcasecmp(opt->next->key, "LogFile") ||
1974 !strcasecmp(opt->next->key, "SysLog"))) {
1975 if (convert_log_option(options, opt, opt->next, options->RunAsDaemon) < 0)
1976 return -1;
1977 opt = opt->next->next;
1978 } else if (!opt->next) {
1979 if (convert_log_option(options, opt, NULL, options->RunAsDaemon) < 0)
1980 return -1;
1981 opt = opt->next;
1982 } else {
1983 ; /* give warning below */
1987 while (opt) {
1988 if (!strcasecmp(opt->key, "LogLevel")) {
1989 log_fn(LOG_WARN, "Two LogLevel options in a row without intervening LogFile or SysLog");
1990 opt = opt->next;
1991 } else {
1992 tor_assert(!strcasecmp(opt->key, "LogFile") ||
1993 !strcasecmp(opt->key, "SysLog"));
1994 if (opt->next && !strcasecmp(opt->next->key, "LogLevel")) {
1995 /* LogFile/SysLog followed by LogLevel */
1996 if (convert_log_option(options,opt->next,opt, options->RunAsDaemon) < 0)
1997 return -1;
1998 opt = opt->next->next;
1999 } else {
2000 /* LogFile/SysLog followed by LogFile/SysLog or end of list. */
2001 if (convert_log_option(options,NULL, opt, options->RunAsDaemon) < 0)
2002 return -1;
2003 opt = opt->next;
2008 if (options->DebugLogFile) {
2009 if (add_single_log_option(options, LOG_DEBUG, LOG_ERR, "file", options->DebugLogFile) < 0)
2010 return -1;
2013 tor_free(options->DebugLogFile);
2014 config_free_lines(options->OldLogOptions);
2015 options->OldLogOptions = NULL;
2017 return 0;
2021 * Given a linked list of config lines containing "allow" and "deny" tokens,
2022 * parse them and append the result to <b>dest</b>. Return -1 if any tokens
2023 * are malformed, else return 0.
2026 config_parse_addr_policy(struct config_line_t *cfg,
2027 addr_policy_t **dest)
2029 addr_policy_t **nextp;
2030 smartlist_t *entries;
2031 int r = 0;
2033 if (!cfg)
2034 return 0;
2036 nextp = dest;
2038 while (*nextp)
2039 nextp = &((*nextp)->next);
2041 entries = smartlist_create();
2042 for (; cfg; cfg = cfg->next) {
2043 smartlist_split_string(entries, cfg->value, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2044 SMARTLIST_FOREACH(entries, const char *, ent,
2046 log_fn(LOG_DEBUG,"Adding new entry '%s'",ent);
2047 *nextp = router_parse_addr_policy_from_string(ent);
2048 if (*nextp) {
2049 nextp = &((*nextp)->next);
2050 } else {
2051 log_fn(LOG_WARN,"Malformed policy %s.", ent);
2052 r = -1;
2055 SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
2056 smartlist_clear(entries);
2058 smartlist_free(entries);
2059 return r;
2062 /** Release all storage held by <b>p</b> */
2063 void
2064 addr_policy_free(addr_policy_t *p) {
2065 addr_policy_t *e;
2067 while (p) {
2068 e = p;
2069 p = p->next;
2070 tor_free(e->string);
2071 tor_free(e);
2075 /** Parse a single RedirectExit line's contents from <b>line</b>. If
2076 * they are valid, and <b>result</b> is not NULL, add an element to
2077 * <b>result</b> and return 0. Else if they are valid, return 0.
2078 * Else return -1. */
2079 static int
2080 parse_redirect_line(smartlist_t *result, struct config_line_t *line)
2082 smartlist_t *elements = NULL;
2083 exit_redirect_t *r;
2085 tor_assert(line);
2087 r = tor_malloc_zero(sizeof(exit_redirect_t));
2088 elements = smartlist_create();
2089 smartlist_split_string(elements, line->value, NULL,
2090 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2091 if (smartlist_len(elements) != 2) {
2092 log_fn(LOG_WARN, "Wrong number of elements in RedirectExit line");
2093 goto err;
2095 if (parse_addr_and_port_range(smartlist_get(elements,0),&r->addr,&r->mask,
2096 &r->port_min,&r->port_max)) {
2097 log_fn(LOG_WARN, "Error parsing source address in RedirectExit line");
2098 goto err;
2100 if (0==strcasecmp(smartlist_get(elements,1), "pass")) {
2101 r->is_redirect = 0;
2102 } else {
2103 if (parse_addr_port(smartlist_get(elements,1),NULL,&r->addr_dest,
2104 &r->port_dest)) {
2105 log_fn(LOG_WARN, "Error parsing dest address in RedirectExit line");
2106 goto err;
2108 r->is_redirect = 1;
2111 goto done;
2112 err:
2113 tor_free(r);
2114 done:
2115 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2116 smartlist_free(elements);
2117 if (r) {
2118 if (result)
2119 smartlist_add(result, r);
2120 else
2121 tor_free(r);
2122 return 0;
2123 } else {
2124 return -1;
2128 /** Read the contents of a DirServer line from <b>line</b>. Return 0
2129 * if the line is well-formed, and 0 if it isn't. If
2130 * <b>validate_only</b> is 0, and the line is well-formed, then add
2131 * the dirserver described in the line as a valid server. */
2132 static int
2133 parse_dir_server_line(const char *line, int validate_only)
2135 smartlist_t *items = NULL;
2136 int r;
2137 char *addrport, *address=NULL;
2138 uint16_t port;
2139 char digest[DIGEST_LEN];
2141 items = smartlist_create();
2142 smartlist_split_string(items, line, NULL,
2143 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
2144 if (smartlist_len(items) < 2) {
2145 log_fn(LOG_WARN, "Too few arguments to DirServer line.");
2146 goto err;
2148 addrport = smartlist_get(items, 0);
2149 if (parse_addr_port(addrport, &address, NULL, &port)<0) {
2150 log_fn(LOG_WARN, "Error parsing DirServer address '%s'", addrport);
2151 goto err;
2153 if (!port) {
2154 log_fn(LOG_WARN, "Missing port in DirServer address '%s'",addrport);
2155 goto err;
2158 tor_strstrip(smartlist_get(items, 1), " ");
2159 if (strlen(smartlist_get(items, 1)) != HEX_DIGEST_LEN) {
2160 log_fn(LOG_WARN, "Key digest for DirServer is wrong length.");
2161 goto err;
2163 if (base16_decode(digest, DIGEST_LEN,
2164 smartlist_get(items,1), HEX_DIGEST_LEN)<0) {
2165 log_fn(LOG_WARN, "Unable to decode DirServer key digest.");
2166 goto err;
2169 if (!validate_only) {
2170 log_fn(LOG_DEBUG, "Trusted dirserver at %s:%d (%s)", address, (int)port,
2171 (char*)smartlist_get(items,1));
2172 add_trusted_dir_server(address, port, digest);
2175 r = 0;
2176 goto done;
2178 err:
2179 r = -1;
2181 done:
2182 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
2183 smartlist_free(items);
2184 tor_free(address);
2185 return r;
2188 /** Adjust the value of options->DataDirectory, or fill it in if it's
2189 * absent. Return 0 on success, -1 on failure. */
2190 static int
2191 normalize_data_directory(or_options_t *options) {
2192 #ifdef MS_WINDOWS
2193 char *p;
2194 if (options->DataDirectory)
2195 return 0; /* all set */
2196 p = tor_malloc(MAX_PATH);
2197 strlcpy(p,get_windows_conf_root(),MAX_PATH);
2198 options->DataDirectory = p;
2199 return 0;
2200 #else
2201 const char *d = options->DataDirectory;
2202 if (!d)
2203 d = "~/.tor";
2205 if (strncmp(d,"~/",2) == 0) {
2206 char *fn = expand_filename(d);
2207 if (!fn) {
2208 log_fn(LOG_ERR,"Failed to expand filename '%s'.", d);
2209 return -1;
2211 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
2212 /* If our homedir is /, we probably don't want to use it. */
2213 /* XXXX Default to /var/lib/tor? */
2214 log_fn(LOG_WARN, "Defaulting to 'DataDirectory %s', which may not be what you want", fn);
2216 tor_free(options->DataDirectory);
2217 options->DataDirectory = fn;
2219 return 0;
2220 #endif
2223 /** Check and normalize the value of options->DataDirectory; return 0 if it
2224 * sane, -1 otherwise. */
2225 static int
2226 validate_data_directory(or_options_t *options) {
2227 if (normalize_data_directory(options) < 0)
2228 return -1;
2229 tor_assert(options->DataDirectory);
2230 if (strlen(options->DataDirectory) > (512-128)) {
2231 log_fn(LOG_ERR, "DataDirectory is too long.");
2232 return -1;
2234 #if 0
2235 if (check_private_dir(options->DataDirectory, CPD_CHECK != 0)) {
2236 log_fn(LOG_WARN, "Can't create directory %s", options->DataDirectory);
2237 return -1;
2239 #endif
2240 return 0;
2243 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; if you edit it, comments will not be preserved"
2245 /** Save a configuration file for the configuration in <b>options</b>
2246 * into the file <b>fname</b>. If the file already exists, and
2247 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
2248 * replace it. Return 0 on success, -1 on failure. */
2249 static int
2250 write_configuration_file(const char *fname, or_options_t *options)
2252 char fn_tmp[1024];
2253 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
2254 int rename_old = 0, r;
2255 size_t len;
2257 if (fname) {
2258 switch (file_status(fname)) {
2259 case FN_FILE:
2260 old_val = read_file_to_str(fname, 0);
2261 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
2262 rename_old = 1;
2264 tor_free(old_val);
2265 break;
2266 case FN_NOENT:
2267 break;
2268 default:
2269 log_fn(LOG_WARN,"Config file %s is not a file? Failing.", fname);
2270 return -1;
2274 if (!(new_conf = config_dump_options(options, 1))) {
2275 log_fn(LOG_WARN, "Couldn't get configuration string");
2276 goto err;
2279 len = strlen(new_conf)+128;
2280 new_val = tor_malloc(len);
2281 tor_snprintf(new_val, len, "%s\n\n%s", GENERATED_FILE_PREFIX, new_conf);
2283 if (rename_old) {
2284 int i = 1;
2285 while (1) {
2286 if (tor_snprintf(fn_tmp, sizeof(fn_tmp), "%s.orig.%d", fname, i)<0) {
2287 log_fn(LOG_WARN, "Filename too long");
2288 goto err;
2290 if (file_status(fn_tmp) == FN_NOENT)
2291 break;
2292 ++i;
2294 log_fn(LOG_NOTICE, "Renaming old configuration file to %s", fn_tmp);
2295 rename(fname, fn_tmp);
2298 write_str_to_file(fname, new_val, 0);
2300 r = 0;
2301 goto done;
2302 err:
2303 r = -1;
2304 done:
2305 tor_free(new_val);
2306 tor_free(new_conf);
2307 return r;
2311 * Save the current configuration file value to disk. Return 0 on
2312 * success, -1 on failure.
2315 save_current_config(void)
2317 char *fn;
2318 if (config_fname) {
2319 /* XXX This fails if we can't write to our configuration file.
2320 * Arguably, we should try falling back to datadirectory or something.
2321 * But just as arguably, we shouldn't. */
2322 return write_configuration_file(config_fname, get_options());
2324 fn = get_default_conf_file();
2325 return write_configuration_file(fn, get_options());
2328 struct unit_table_t {
2329 const char *unit;
2330 uint64_t multiplier;
2333 static struct unit_table_t memory_units[] = {
2334 { "", 1 },
2335 { "b", 1<< 0 },
2336 { "byte", 1<< 0 },
2337 { "bytes", 1<< 0 },
2338 { "kb", 1<<10 },
2339 { "kilobyte", 1<<10 },
2340 { "kilobytes", 1<<10 },
2341 { "m", 1<<20 },
2342 { "mb", 1<<20 },
2343 { "megabyte", 1<<20 },
2344 { "megabytes", 1<<20 },
2345 { "gb", 1<<30 },
2346 { "gigabyte", 1<<30 },
2347 { "gigabytes", 1<<30 },
2348 { "tb", U64_LITERAL(1)<<40 },
2349 { "terabyte", U64_LITERAL(1)<<40 },
2350 { "terabytes", U64_LITERAL(1)<<40 },
2351 { NULL, 0 },
2354 static struct unit_table_t time_units[] = {
2355 { "", 1 },
2356 { "second", 1 },
2357 { "seconds", 1 },
2358 { "minute", 60 },
2359 { "minutes", 60 },
2360 { "hour", 60*60 },
2361 { "hours", 60*60 },
2362 { "day", 24*60*60 },
2363 { "days", 24*60*60 },
2364 { "week", 7*24*60*60 },
2365 { "weeks", 7*24*60*60 },
2366 { NULL, 0 },
2369 /** Parse a string <b>val</b> containing a number, zero or more
2370 * spaces, and an optional unit string. If the unit appears in the
2371 * table <b>u</b>, then multiply the number by the unit multiplier.
2372 * On success, set *<b>ok</b> to 1 and return this product.
2373 * Otherwise, set *<b>ok</b> to 0.
2375 static uint64_t
2376 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
2378 uint64_t v;
2379 char *cp;
2381 tor_assert(ok);
2383 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
2384 if (!*ok)
2385 return 0;
2386 if (!cp) {
2387 *ok = 1;
2388 return v;
2390 while (TOR_ISSPACE(*cp))
2391 ++cp;
2392 for ( ;u->unit;++u) {
2393 if (!strcasecmp(u->unit, cp)) {
2394 v *= u->multiplier;
2395 *ok = 1;
2396 return v;
2399 log_fn(LOG_WARN, "Unknown unit '%s'.", cp);
2400 *ok = 0;
2401 return 0;
2404 /** Parse a string in the format "number unit", where unit is a unit of
2405 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
2406 * and return the number of bytes specified. Otherwise, set
2407 * *<b>ok</b> to false and return 0. */
2408 static uint64_t
2409 config_parse_memunit(const char *s, int *ok) {
2410 return config_parse_units(s, memory_units, ok);
2413 /** Parse a string in the format "number unit", where unit is a unit of time.
2414 * On success, set *<b>ok</b> to true and return the number of seconds in
2415 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
2417 static int
2418 config_parse_interval(const char *s, int *ok) {
2419 uint64_t r;
2420 r = config_parse_units(s, time_units, ok);
2421 if (!ok)
2422 return -1;
2423 if (r > INT_MAX) {
2424 log_fn(LOG_WARN, "Interval '%s' is too long", s);
2425 *ok = 0;
2426 return -1;
2428 return (int)r;
2431 static void
2432 print_cvs_version(void)
2434 extern const char aes_c_id[];
2435 extern const char compat_c_id[];
2436 extern const char container_c_id[];
2437 extern const char crypto_c_id[];
2438 extern const char fakepoll_c_id[];
2439 extern const char log_c_id[];
2440 extern const char torgzip_c_id[];
2441 extern const char tortls_c_id[];
2442 extern const char util_c_id[];
2444 extern const char buffers_c_id[];
2445 extern const char circuitbuild_c_id[];
2446 extern const char circuitlist_c_id[];
2447 extern const char circuituse_c_id[];
2448 extern const char command_c_id[];
2449 // extern const char config_c_id[];
2450 extern const char connection_c_id[];
2451 extern const char connection_edge_c_id[];
2452 extern const char connection_or_c_id[];
2453 extern const char control_c_id[];
2454 extern const char cpuworker_c_id[];
2455 extern const char directory_c_id[];
2456 extern const char dirserv_c_id[];
2457 extern const char dns_c_id[];
2458 extern const char hibernate_c_id[];
2459 extern const char main_c_id[];
2460 extern const char onion_c_id[];
2461 extern const char relay_c_id[];
2462 extern const char rendclient_c_id[];
2463 extern const char rendcommon_c_id[];
2464 extern const char rendmid_c_id[];
2465 extern const char rendservice_c_id[];
2466 extern const char rephist_c_id[];
2467 extern const char router_c_id[];
2468 extern const char routerlist_c_id[];
2469 extern const char routerparse_c_id[];
2471 puts(AES_H_ID);
2472 puts(COMPAT_H_ID);
2473 puts(CONTAINER_H_ID);
2474 puts(CRYPTO_H_ID);
2475 puts(FAKEPOLL_H_ID);
2476 puts(LOG_H_ID);
2477 puts(TORGZIP_H_ID);
2478 puts(TORINT_H_ID);
2479 puts(TORTLS_H_ID);
2480 puts(UTIL_H_ID);
2481 puts(aes_c_id);
2482 puts(compat_c_id);
2483 puts(container_c_id);
2484 puts(crypto_c_id);
2485 puts(fakepoll_c_id);
2486 puts(log_c_id);
2487 puts(torgzip_c_id);
2488 puts(tortls_c_id);
2489 puts(util_c_id);
2491 puts(OR_H_ID);
2492 puts(buffers_c_id);
2493 puts(circuitbuild_c_id);
2494 puts(circuitlist_c_id);
2495 puts(circuituse_c_id);
2496 puts(command_c_id);
2497 puts(config_c_id);
2498 puts(connection_c_id);
2499 puts(connection_edge_c_id);
2500 puts(connection_or_c_id);
2501 puts(control_c_id);
2502 puts(cpuworker_c_id);
2503 puts(directory_c_id);
2504 puts(dirserv_c_id);
2505 puts(dns_c_id);
2506 puts(hibernate_c_id);
2507 puts(main_c_id);
2508 puts(onion_c_id);
2509 puts(relay_c_id);
2510 puts(rendclient_c_id);
2511 puts(rendcommon_c_id);
2512 puts(rendmid_c_id);
2513 puts(rendservice_c_id);
2514 puts(rephist_c_id);
2515 puts(router_c_id);
2516 puts(routerlist_c_id);
2517 puts(routerparse_c_id);