If anybody set DirFetchPostPeriod, give them StatuFetchPeriod instead. Impose minima...
[tor.git] / src / or / config.c
blob8397a0dbdaceb660d52ffb000f8f95aa9852cfeb
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.
13 **/
15 #include "or.h"
16 #ifdef MS_WINDOWS
17 #include <shlobj.h>
18 #endif
19 #include "../common/aes.h"
21 /** Enumeration of types which option values can take */
22 typedef enum config_type_t {
23 CONFIG_TYPE_STRING = 0, /**< An arbitrary string. */
24 CONFIG_TYPE_UINT, /**< A non-negative integer less than MAX_INT */
25 CONFIG_TYPE_INTERVAL, /**< A number of seconds, with optional units*/
26 CONFIG_TYPE_MEMUNIT, /**< A number of bytes, with optional units*/
27 CONFIG_TYPE_DOUBLE, /**< A floating-point value */
28 CONFIG_TYPE_BOOL, /**< A boolean value, expressed as 0 or 1. */
29 CONFIG_TYPE_CSV, /**< A list of strings, separated by commas and optional
30 * whitespace. */
31 CONFIG_TYPE_LINELIST, /**< Uninterpreted config lines */
32 CONFIG_TYPE_LINELIST_S, /**< Uninterpreted, context-sensitive config lines,
33 * mixed with other keywords. */
34 CONFIG_TYPE_LINELIST_V, /**< Catch-all "virtual" option to summarize
35 * context-sensitive config lines when fetching.
37 CONFIG_TYPE_OBSOLETE, /**< Obsolete (ignored) option. */
38 } config_type_t;
40 /* An abbreviation for a configuration option allowed on the command line */
41 typedef struct config_abbrev_t {
42 const char *abbreviated;
43 const char *full;
44 int commandline_only;
45 } config_abbrev_t;
47 /* Handy macro for declaring "In the config file or on the command line,
48 * you can abbreviate <b>tok</b>s as <b>tok</b>". */
49 #define PLURAL(tok) { #tok, #tok "s", 0 }
51 /* A list of command-line abbreviations. */
52 static config_abbrev_t config_abbrevs[] = {
53 PLURAL(ExitNode),
54 PLURAL(EntryNode),
55 PLURAL(ExcludeNode),
56 PLURAL(FirewallPort),
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("DirPort", UINT, DirPort, "0"),
108 VAR("DirBindAddress", LINELIST, DirBindAddress, NULL),
109 VAR("DirFetchPeriod", INTERVAL, DirFetchPeriod, "1 hours"),
110 VAR("DirPostPeriod", INTERVAL, DirPostPeriod, "20 minutes"),
111 VAR("RendPostPeriod", INTERVAL, RendPostPeriod, "20 minutes"),
112 VAR("DirPolicy", LINELIST, DirPolicy, NULL),
113 VAR("DirServer", LINELIST, DirServers, NULL),
114 VAR("ExitNodes", STRING, ExitNodes, NULL),
115 VAR("EntryNodes", STRING, EntryNodes, NULL),
116 VAR("StrictExitNodes", BOOL, StrictExitNodes, "0"),
117 VAR("StrictEntryNodes", BOOL, StrictEntryNodes, "0"),
118 VAR("ExitPolicy", LINELIST, ExitPolicy, NULL),
119 VAR("ExcludeNodes", STRING, ExcludeNodes, NULL),
120 VAR("FascistFirewall", BOOL, FascistFirewall, "0"),
121 VAR("FirewallPorts", CSV, FirewallPorts, "80,443"),
122 VAR("MyFamily", STRING, MyFamily, NULL),
123 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
124 VAR("Group", STRING, Group, NULL),
125 VAR("HashedControlPassword",STRING, HashedControlPassword, NULL),
126 VAR("HttpProxy", STRING, HttpProxy, NULL),
127 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
128 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
129 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
130 VAR("HiddenServiceNodes", LINELIST_S, RendConfigLines, NULL),
131 VAR("HiddenServiceExcludeNodes", LINELIST_S, RendConfigLines, NULL),
132 VAR("IgnoreVersion", BOOL, IgnoreVersion, "0"),
133 VAR("KeepalivePeriod", INTERVAL, KeepalivePeriod, "5 minutes"),
134 VAR("Log", LINELIST, Logs, NULL),
135 VAR("LogLevel", LINELIST_S, OldLogOptions, NULL),
136 VAR("LogFile", LINELIST_S, OldLogOptions, NULL),
137 OBSOLETE("LinkPadding"),
138 VAR("MaxConn", UINT, MaxConn, "1024"),
139 VAR("MaxOnionsPending", UINT, MaxOnionsPending, "100"),
140 VAR("MonthlyAccountingStart",UINT, _MonthlyAccountingStart,"0"),
141 VAR("AccountingMaxKB", UINT, _AccountingMaxKB, "0"),
142 VAR("AccountingMax", MEMUNIT, AccountingMax, "0 bytes"),
143 VAR("Nickname", STRING, Nickname, NULL),
144 VAR("NewCircuitPeriod", INTERVAL, NewCircuitPeriod, "30 seconds"),
145 VAR("NumCpus", UINT, NumCpus, "1"),
146 VAR("ORPort", UINT, ORPort, "0"),
147 VAR("ORBindAddress", LINELIST, ORBindAddress, NULL),
148 VAR("OutboundBindAddress", STRING, OutboundBindAddress, NULL),
149 VAR("PidFile", STRING, PidFile, NULL),
150 VAR("PathlenCoinWeight", DOUBLE, PathlenCoinWeight, "0.3"),
151 VAR("RedirectExit", LINELIST, RedirectExit, NULL),
152 OBSOLETE("RouterFile"),
153 VAR("RunAsDaemon", BOOL, RunAsDaemon, "0"),
154 VAR("RunTesting", BOOL, RunTesting, "0"),
155 VAR("RecommendedVersions", LINELIST, RecommendedVersions, NULL),
156 VAR("RendNodes", STRING, RendNodes, NULL),
157 VAR("RendExcludeNodes", STRING, RendExcludeNodes, NULL),
158 VAR("SocksPort", UINT, SocksPort, "9050"),
159 VAR("SocksBindAddress", LINELIST, SocksBindAddress, NULL),
160 VAR("SocksPolicy", LINELIST, SocksPolicy, NULL),
161 VAR("StatusFetchPeriod", INTERVAL, StatusFetchPeriod, "20 minutes"),
162 VAR("SysLog", LINELIST_S, OldLogOptions, NULL),
163 OBSOLETE("TrafficShaping"),
164 VAR("User", STRING, User, NULL),
165 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
167 #undef VAR
168 #undef OBSOLETE
170 /** Largest allowed config line */
171 #define CONFIG_LINE_T_MAXLEN 4096
173 static void option_reset(or_options_t *options, config_var_t *var);
174 static void options_free(or_options_t *options);
175 static int option_is_same(or_options_t *o1, or_options_t *o2,const char *name);
176 static or_options_t *options_dup(or_options_t *old);
177 static int options_validate(or_options_t *options);
178 static int options_transition_allowed(or_options_t *old, or_options_t *new);
179 static int check_nickname_list(const char *lst, const char *name);
181 static int parse_dir_server_line(const char *line, int validate_only);
182 static int parse_redirect_line(smartlist_t *result,
183 struct config_line_t *line);
184 static int parse_log_severity_range(const char *range, int *min_out,
185 int *max_out);
186 static int convert_log_option(or_options_t *options,
187 struct config_line_t *level_opt,
188 struct config_line_t *file_opt, int isDaemon);
189 static int add_single_log_option(or_options_t *options, int minSeverity,
190 int maxSeverity,
191 const char *type, const char *fname);
192 static int normalize_log_options(or_options_t *options);
193 static int validate_data_directory(or_options_t *options);
194 static int write_configuration_file(const char *fname, or_options_t *options);
196 static uint64_t config_parse_memunit(const char *s, int *ok);
197 static int config_parse_interval(const char *s, int *ok);
198 static void print_cvs_version(void);
201 * Functions to read and write the global options pointer.
204 /** Command-line and config-file options. */
205 static or_options_t *global_options=NULL;
206 /** Name of most recently read torrc file. */
207 static char *config_fname = NULL;
209 /** Return the currently configured options. */
210 or_options_t *
211 get_options(void) {
212 tor_assert(global_options);
213 return global_options;
216 /** Change the current global options to contain <b>new_val</b> instead
217 * of their current value; free the old value as necessary. Where
218 * <b>new_val</b> is different from the old value, update the process to
219 * use the new value instead.
221 * Note 1: <b>new_val</b> must have previously been validated with
222 * options_validate(), or Tor may freak out and exit.
224 * Note 2: We haven't moved all the "act on new configuration" logic
225 * here yet. Some is still in do_hup() and other places.
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.
239 options_act(void) {
240 struct config_line_t *cl;
241 or_options_t *options = get_options();
243 clear_trusted_dir_servers();
244 for (cl = options->DirServers; cl; cl = cl->next) {
245 if (parse_dir_server_line(cl->value, 0)<0) {
246 log_fn(LOG_ERR,
247 "Previously validated DirServer line could not be added!");
248 return -1;
252 if (rend_config_services(options, 0)<0) {
253 log_fn(LOG_ERR,
254 "Previously validated hidden services line could not be added!");
255 return -1;
258 /* Setuid/setgid as appropriate */
259 if (options->User || options->Group) {
260 if (switch_id(options->User, options->Group) != 0) {
261 return -1;
265 /* Ensure data directory is private; create if possible. */
266 if (check_private_dir(options->DataDirectory, CPD_CREATE) != 0) {
267 log_fn(LOG_ERR, "Couldn't access/create private data directory %s",
268 options->DataDirectory);
269 return -1;
272 /* Bail out at this point if we're not going to be a server: we want
273 * to not fork, and to log stuff to stderr. */
274 if (options->command != CMD_RUN_TOR)
275 return 0;
277 mark_logs_temp(); /* Close current logs once new logs are open. */
278 if (config_init_logs(options, 0)<0) /* Configure the log(s) */
279 return -1;
280 /* Close the temporary log we used while starting up, if it isn't already
281 * gone. */
282 close_temp_logs();
283 add_callback_log(LOG_NOTICE, LOG_ERR, control_event_logmsg);
285 if (set_max_file_descriptors(options->MaxConn) < 0)
286 return -1;
289 smartlist_t *sl = smartlist_create();
290 for (cl = options->RedirectExit; cl; cl = cl->next) {
291 if (parse_redirect_line(sl, cl)<0)
292 return -1;
294 set_exit_redirects(sl);
297 /* Start backgrounding the process, if requested. */
299 /* XXXX009 We once had a reason to separate start_daemon and finish_daemon:
300 * It let us have the parent process stick around until we were sure Tor
301 * was started. Should we make start_daemon get called earlier? -NM */
302 if (options->RunAsDaemon) {
303 start_daemon(options->DataDirectory);
306 /* Finish backgrounding the process */
307 if (options->RunAsDaemon) {
308 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
309 finish_daemon();
312 /* Write our pid to the pid file. If we do not have write permissions we
313 * will log a warning */
314 if (options->PidFile)
315 write_pidfile(options->PidFile);
317 /* Update address policies. */
318 parse_socks_policy();
319 parse_dir_policy();
321 init_cookie_authentication(options->CookieAuthentication);
323 /* reload keys as needed for rendezvous services. */
324 if (rend_service_load_keys()<0) {
325 log_fn(LOG_ERR,"Error reloading rendezvous service keys");
326 return -1;
329 /* Set up accounting */
330 if (accounting_parse_options(options, 0)<0) {
331 log_fn(LOG_ERR,"Error in accouting options");
332 return -1;
334 if (accounting_is_enabled(options))
335 configure_accounting(time(NULL));
337 if (retry_all_listeners(1) < 0) {
338 log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
339 return -1;
342 #if 0
344 char *smin, *smax;
345 smin = config_dump_options(options, 1);
346 smax = config_dump_options(options, 0);
347 log_fn(LOG_DEBUG, "These are our options:\n%s",smax);
348 log_fn(LOG_DEBUG, "We changed these options:\n%s",smin);
349 tor_free(smin);
350 tor_free(smax);
352 #endif
354 /* Since our options changed, we might need to regenerate and upload our
355 * server descriptor. (We could probably be more clever about only calling
356 * this when something significant changed.)
358 mark_my_descriptor_dirty();
360 return 0;
364 * Functions to parse config options
367 /** If <b>option</b> is an official abbreviation for a longer option,
368 * return the longer option. Otherwise return <b>option</b>.
369 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
370 * apply abbreviations that work for the config file and the command line. */
371 static const char *
372 expand_abbrev(const char *option, int command_line)
374 int i;
375 for (i=0; config_abbrevs[i].abbreviated; ++i) {
376 /* Abbreviations aren't casei. */
377 if (!strcasecmp(option,config_abbrevs[i].abbreviated) &&
378 (command_line || !config_abbrevs[i].commandline_only)) {
379 return config_abbrevs[i].full;
382 return option;
385 /** Helper: Read a list of configuration options from the command line. */
386 static struct config_line_t *
387 config_get_commandlines(int argc, char **argv)
389 struct config_line_t *new;
390 struct config_line_t *front = NULL;
391 char *s;
392 int i = 1;
394 while (i < argc-1) {
395 if (!strcmp(argv[i],"-f") ||
396 !strcmp(argv[i],"--hash-password")) {
397 i += 2; /* command-line option with argument. ignore them. */
398 continue;
399 } else if (!strcmp(argv[i],"--list-fingerprint")) {
400 i += 1; /* command-line option. ignore it. */
401 continue;
404 new = tor_malloc(sizeof(struct config_line_t));
405 s = argv[i];
407 while (*s == '-')
408 s++;
410 new->key = tor_strdup(expand_abbrev(s, 1));
411 new->value = tor_strdup(argv[i+1]);
413 log(LOG_DEBUG,"Commandline: parsed keyword '%s', value '%s'",
414 new->key, new->value);
415 new->next = front;
416 front = new;
417 i += 2;
419 return front;
422 /** Helper: allocate a new configuration option mapping 'key' to 'val',
423 * prepend it to 'front', and return the newly allocated config_line_t */
424 struct config_line_t *
425 config_line_prepend(struct config_line_t *front,
426 const char *key,
427 const char *val)
429 struct config_line_t *newline;
431 newline = tor_malloc(sizeof(struct config_line_t));
432 newline->key = tor_strdup(key);
433 newline->value = tor_strdup(val);
434 newline->next = front;
435 return newline;
438 /** Helper: parse the config string and strdup into key/value
439 * strings. Set *result to the list, or NULL if parsing the string
440 * failed. Return 0 on success, -1 on failure. Warn and ignore any
441 * misformatted lines. */
443 config_get_lines(char *string, struct config_line_t **result)
445 struct config_line_t *list = NULL;
446 char *k, *v;
448 do {
449 string = parse_line_from_str(string, &k, &v);
450 if (!string) {
451 config_free_lines(list);
452 return -1;
454 if (k && v)
455 list = config_line_prepend(list, k, v);
456 } while (*string);
458 *result = list;
459 return 0;
463 * Free all the configuration lines on the linked list <b>front</b>.
465 void
466 config_free_lines(struct config_line_t *front)
468 struct config_line_t *tmp;
470 while (front) {
471 tmp = front;
472 front = tmp->next;
474 tor_free(tmp->key);
475 tor_free(tmp->value);
476 tor_free(tmp);
480 /** If <b>key</b> is a configuration option, return the corresponding
481 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
482 * warn, and return the corresponding config_var_t. Otherwise return NULL.
484 static config_var_t *config_find_option(const char *key)
486 int i;
487 /* First, check for an exact (case-insensitive) match */
488 for (i=0; config_vars[i].name; ++i) {
489 if (!strcasecmp(key, config_vars[i].name))
490 return &config_vars[i];
492 /* If none, check for an abbreviated match */
493 for (i=0; config_vars[i].name; ++i) {
494 if (!strncasecmp(key, config_vars[i].name, strlen(key))) {
495 log_fn(LOG_WARN, "The abbreviation '%s' is deprecated. "
496 "Tell Nick and Roger to make it official, or just use '%s' instead",
497 key, config_vars[i].name);
498 return &config_vars[i];
501 /* Okay, unrecogized options */
502 return NULL;
505 /** If <b>c</b> is a syntactically valid configuration line, update
506 * <b>options</b> with its value and return 0. Otherwise return -1 for bad key,
507 * -2 for bad value.
509 * If 'reset' is set, and we get a line containing no value, restore the
510 * option to its default value.
512 static int
513 config_assign_line(or_options_t *options, struct config_line_t *c, int reset)
515 int i, ok;
516 config_var_t *var;
517 void *lvalue;
519 var = config_find_option(c->key);
520 if (!var) {
521 log_fn(LOG_WARN, "Unknown option '%s'. Failing.", c->key);
522 return -1;
524 /* Put keyword into canonical case. */
525 if (strcmp(var->name, c->key)) {
526 tor_free(c->key);
527 c->key = tor_strdup(var->name);
530 if (reset && !strlen(c->value)) {
531 option_reset(options, var);
532 return 0;
535 lvalue = ((char*)options) + var->var_offset;
536 switch (var->type) {
538 case CONFIG_TYPE_UINT:
539 i = tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
540 if (!ok) {
541 log(LOG_WARN, "Int keyword '%s %s' is malformed or out of bounds.",
542 c->key,c->value);
543 return -2;
545 *(int *)lvalue = i;
546 break;
548 case CONFIG_TYPE_INTERVAL: {
549 i = config_parse_interval(c->value, &ok);
550 if (!ok) {
551 return -2;
553 *(int *)lvalue = i;
554 break;
557 case CONFIG_TYPE_MEMUNIT: {
558 uint64_t u64 = config_parse_memunit(c->value, &ok);
559 if (!ok) {
560 return -2;
562 *(uint64_t *)lvalue = u64;
563 break;
566 case CONFIG_TYPE_BOOL:
567 i = tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
568 if (!ok) {
569 log(LOG_WARN, "Boolean keyword '%s' expects 0 or 1.", c->key);
570 return -2;
572 *(int *)lvalue = i;
573 break;
575 case CONFIG_TYPE_STRING:
576 tor_free(*(char **)lvalue);
577 *(char **)lvalue = tor_strdup(c->value);
578 break;
580 case CONFIG_TYPE_DOUBLE:
581 *(double *)lvalue = atof(c->value);
582 break;
584 case CONFIG_TYPE_CSV:
585 if (*(smartlist_t**)lvalue == NULL)
586 *(smartlist_t**)lvalue = smartlist_create();
588 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
589 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
590 break;
592 case CONFIG_TYPE_LINELIST:
593 case CONFIG_TYPE_LINELIST_S:
594 /* Note: this reverses the order that the lines appear in. That's
595 * just fine, since we build up the list of lines reversed in the
596 * first place. */
597 *(struct config_line_t**)lvalue =
598 config_line_prepend(*(struct config_line_t**)lvalue, c->key, c->value);
599 break;
601 case CONFIG_TYPE_OBSOLETE:
602 log_fn(LOG_WARN, "Skipping obsolete configuration option '%s'", c->key);
603 break;
604 case CONFIG_TYPE_LINELIST_V:
605 log_fn(LOG_WARN, "Can't provide value for virtual option '%s'", c->key);
606 return -2;
607 default:
608 tor_assert(0);
609 break;
611 return 0;
614 /** restore the option named <b>key</b> in options to its default value. */
615 static void
616 config_reset_line(or_options_t *options, const char *key)
618 config_var_t *var;
620 var = config_find_option(key);
621 if (!var)
622 return; /* give error on next pass. */
624 option_reset(options, var);
627 /** Return true iff key is a valid configuration option. */
629 config_option_is_recognized(const char *key)
631 config_var_t *var = config_find_option(key);
632 return (var != NULL);
635 /** Return a canonicalized list of the options assigned for key.
637 struct config_line_t *
638 config_get_assigned_option(or_options_t *options, const char *key)
640 config_var_t *var;
641 const void *value;
642 char buf[32];
643 struct config_line_t *result;
644 tor_assert(options && key);
646 var = config_find_option(key);
647 if (!var) {
648 log_fn(LOG_WARN, "Unknown option '%s'. Failing.", key);
649 return NULL;
650 } else if (var->type == CONFIG_TYPE_LINELIST_S) {
651 log_fn(LOG_WARN, "Can't return context-sensitive '%s' on its own", key);
652 return NULL;
654 value = ((char*)options) + var->var_offset;
656 if (var->type == CONFIG_TYPE_LINELIST ||
657 var->type == CONFIG_TYPE_LINELIST_V) {
658 /* Linelist requires special handling: we just copy and return it. */
659 const struct config_line_t *next_in = *(const struct config_line_t**)value;
660 struct config_line_t **next_out = &result;
661 while (next_in) {
662 *next_out = tor_malloc(sizeof(struct config_line_t));
663 (*next_out)->key = tor_strdup(next_in->key);
664 (*next_out)->value = tor_strdup(next_in->value);
665 next_in = next_in->next;
666 next_out = &((*next_out)->next);
668 (*next_out) = NULL;
669 return result;
672 result = tor_malloc_zero(sizeof(struct config_line_t));
673 result->key = tor_strdup(var->name);
674 switch (var->type)
676 case CONFIG_TYPE_STRING:
677 if (*(char**)value) {
678 result->value = tor_strdup(*(char**)value);
679 } else {
680 tor_free(result->key);
681 tor_free(result);
682 return NULL;
684 break;
685 case CONFIG_TYPE_INTERVAL:
686 case CONFIG_TYPE_UINT:
687 /* This means every or_options_t uint or bool element
688 * needs to be an int. Not, say, a uint16_t or char. */
689 tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
690 result->value = tor_strdup(buf);
691 break;
692 case CONFIG_TYPE_MEMUNIT:
693 tor_snprintf(buf, sizeof(buf), U64_FORMAT,
694 U64_PRINTF_ARG(*(uint64_t*)value));
695 result->value = tor_strdup(buf);
696 break;
697 case CONFIG_TYPE_DOUBLE:
698 tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
699 result->value = tor_strdup(buf);
700 break;
701 case CONFIG_TYPE_BOOL:
702 result->value = tor_strdup(*(int*)value ? "1" : "0");
703 break;
704 case CONFIG_TYPE_CSV:
705 if (*(smartlist_t**)value)
706 result->value = smartlist_join_strings(*(smartlist_t**)value,",",0,NULL);
707 else
708 result->value = tor_strdup("");
709 break;
710 case CONFIG_TYPE_OBSOLETE:
711 log_fn(LOG_WARN,"You asked me for the value of an obsolete config option %s.", key);
712 tor_free(result->key);
713 tor_free(result);
714 return NULL;
715 default:
716 tor_free(result->key);
717 tor_free(result);
718 log_fn(LOG_WARN,"Bug: unknown type %d for known key %s", var->type, key);
719 return NULL;
722 return result;
725 /** Iterate through the linked list of requested options <b>list</b>.
726 * For each item, convert as appropriate and assign to <b>options</b>.
727 * If an item is unrecognized, return -1 immediately,
728 * else return 0 for success.
730 * If <b>reset</b>, then interpret empty lines as meaning "restore to
731 * default value", and interpret LINELIST* options as replacing (not
732 * extending) their previous values. Return 0 on success, -1 on bad key,
733 * -2 on bad value.
735 static int
736 config_assign(or_options_t *options, struct config_line_t *list, int reset)
738 struct config_line_t *p;
739 tor_assert(options);
741 /* pass 1: normalize keys */
742 for (p = list; p; p = p->next) {
743 const char *full = expand_abbrev(p->key, 0);
744 if (strcmp(full,p->key)) {
745 tor_free(p->key);
746 p->key = tor_strdup(full);
750 /* pass 2: if we're reading from a resetting source, clear all mentioned
751 * linelists. */
752 if (reset) {
753 for (p = list; p; p = p->next)
754 config_reset_line(options, p->key);
757 /* pass 3: assign. */
758 while (list) {
759 int r;
760 if ((r=config_assign_line(options, list, reset)))
761 return r;
762 list = list->next;
764 return 0;
767 /** Try assigning <b>list</b> to the global options. You do this by duping
768 * options, assigning list to the new one, then validating it. If it's
769 * ok, then throw out the old one and stick with the new one. Else,
770 * revert to old and return failure. Return 0 on success, -1 on bad
771 * keys, -2 on bad values, -3 on bad transition.
774 config_trial_assign(struct config_line_t *list, int reset)
776 int r;
777 or_options_t *trial_options = options_dup(get_options());
779 if ((r=config_assign(trial_options, list, reset)) < 0) {
780 options_free(trial_options);
781 return r;
784 if (options_validate(trial_options) < 0) {
785 options_free(trial_options);
786 return -2;
789 if (options_transition_allowed(get_options(), trial_options) < 0) {
790 options_free(trial_options);
791 return -3;
794 set_options(trial_options); /* we liked it. put it in place. */
795 return 0;
798 /** Replace the option indexed by <b>var</b> in <b>options</b> with its
799 * default value. */
800 static void
801 option_reset(or_options_t *options, config_var_t *var)
803 struct config_line_t *c;
804 void *lvalue;
806 lvalue = ((char*)options) + var->var_offset;
807 switch (var->type) {
808 case CONFIG_TYPE_STRING:
809 tor_free(*(char**)lvalue);
810 break;
811 case CONFIG_TYPE_DOUBLE:
812 *(double*)lvalue = 0.0;
813 break;
814 case CONFIG_TYPE_INTERVAL:
815 case CONFIG_TYPE_UINT:
816 case CONFIG_TYPE_BOOL:
817 *(int*)lvalue = 0;
818 break;
819 case CONFIG_TYPE_MEMUNIT:
820 *(uint64_t*)lvalue = 0;
821 break;
822 case CONFIG_TYPE_CSV:
823 if (*(smartlist_t**)lvalue) {
824 SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
825 smartlist_free(*(smartlist_t **)lvalue);
826 *(smartlist_t **)lvalue = NULL;
828 break;
829 case CONFIG_TYPE_LINELIST:
830 case CONFIG_TYPE_LINELIST_S:
831 config_free_lines(*(struct config_line_t **)lvalue);
832 *(struct config_line_t **)lvalue = NULL;
833 break;
834 case CONFIG_TYPE_LINELIST_V:
835 /* handled by linelist_s. */
836 break;
837 case CONFIG_TYPE_OBSOLETE:
838 break;
840 if (var->initvalue) {
841 c = tor_malloc_zero(sizeof(struct config_line_t));
842 c->key = tor_strdup(var->name);
843 c->value = tor_strdup(var->initvalue);
844 config_assign_line(options,c,0);
845 config_free_lines(c);
849 /** Set <b>options</b>-&gt;DirServers to contain the default directory
850 * servers. */
851 static void
852 add_default_trusted_dirservers(or_options_t *options)
854 /* moria1 */
855 options->DirServers = config_line_prepend(options->DirServers, "DirServer",
856 "18.244.0.188:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441");
857 /* moria2 */
858 options->DirServers = config_line_prepend(options->DirServers, "DirServer",
859 "18.244.0.114:80 719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF");
860 /* tor26 */
861 options->DirServers = config_line_prepend(options->DirServers, "DirServer",
862 "62.116.124.106:9030 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D");
865 /** Print a usage message for tor. */
866 static void
867 print_usage(void)
869 printf(
870 "Copyright 2001-2004 Roger Dingledine, Nick Mathewson, Matej Pfajfar.\n\n"
871 "tor -f <torrc> [args]\n"
872 "See man page for options, or http://freehaven.net/tor/ for documentation.\n");
876 * Based on <b>address</b>, guess our public IP address and put it
877 * in <b>addr</b>.
880 resolve_my_address(const char *address, uint32_t *addr)
882 struct in_addr in;
883 struct hostent *rent;
884 char hostname[256];
885 int explicit_ip=1;
887 tor_assert(addr);
889 if (address) {
890 strlcpy(hostname, address, sizeof(hostname));
891 } else { /* then we need to guess our address */
892 explicit_ip = 0; /* it's implicit */
894 if (gethostname(hostname, sizeof(hostname)) < 0) {
895 log_fn(LOG_WARN,"Error obtaining local hostname");
896 return -1;
898 log_fn(LOG_DEBUG,"Guessed local host name as '%s'",hostname);
901 /* now we know hostname. resolve it and keep only the IP */
903 if (tor_inet_aton(hostname, &in) == 0) {
904 /* then we have to resolve it */
905 explicit_ip = 0;
906 rent = (struct hostent *)gethostbyname(hostname);
907 if (!rent) {
908 log_fn(LOG_WARN,"Could not resolve local Address %s. Failing.", hostname);
909 return -1;
911 tor_assert(rent->h_length == 4);
912 memcpy(&in.s_addr, rent->h_addr, rent->h_length);
915 if (!explicit_ip && is_internal_IP(htonl(in.s_addr))) {
916 log_fn(LOG_WARN,"Address '%s' resolves to private IP '%s'. "
917 "Please set the Address config option to be the IP you want to use.",
918 hostname, inet_ntoa(in));
919 return -1;
922 log_fn(LOG_DEBUG, "Resolved Address to %s.", inet_ntoa(in));
923 *addr = ntohl(in.s_addr);
924 return 0;
927 /** Called when we don't have a nickname set. Try to guess a good
928 * nickname based on the hostname, and return it. */
929 static char *
930 get_default_nickname(void)
932 char localhostname[256];
933 char *cp, *out, *outp;
935 if (gethostname(localhostname, sizeof(localhostname)) < 0) {
936 log_fn(LOG_WARN,"Error obtaining local hostname");
937 return NULL;
940 /* Put it in lowercase; stop at the first dot. */
941 for (cp = localhostname; *cp; ++cp) {
942 if (*cp == '.') {
943 *cp = '\0';
944 break;
946 *cp = tolower(*cp);
949 /* Strip invalid characters. */
950 cp = localhostname;
951 out = outp = tor_malloc(strlen(localhostname) + 1);
952 while (*cp) {
953 if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
954 *outp++ = *cp++;
955 else
956 cp++;
958 *outp = '\0';
960 /* Enforce length. */
961 if (strlen(out) > MAX_NICKNAME_LEN)
962 out[MAX_NICKNAME_LEN]='\0';
964 return out;
967 /** Release storage held by <b>options</b> */
968 static void
969 options_free(or_options_t *options)
971 int i;
972 void *lvalue;
974 for (i=0; config_vars[i].name; ++i) {
975 lvalue = ((char*)options) + config_vars[i].var_offset;
976 switch (config_vars[i].type) {
977 case CONFIG_TYPE_MEMUNIT:
978 case CONFIG_TYPE_INTERVAL:
979 case CONFIG_TYPE_UINT:
980 case CONFIG_TYPE_BOOL:
981 case CONFIG_TYPE_DOUBLE:
982 case CONFIG_TYPE_OBSOLETE:
983 break; /* nothing to free for these config types */
984 case CONFIG_TYPE_STRING:
985 tor_free(*(char **)lvalue);
986 break;
987 case CONFIG_TYPE_LINELIST:
988 case CONFIG_TYPE_LINELIST_V:
989 config_free_lines(*(struct config_line_t**)lvalue);
990 *(struct config_line_t**)lvalue = NULL;
991 break;
992 case CONFIG_TYPE_CSV:
993 if (*(smartlist_t**)lvalue) {
994 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
995 smartlist_free(*(smartlist_t**)lvalue);
996 *(smartlist_t**)lvalue = NULL;
998 break;
999 case CONFIG_TYPE_LINELIST_S:
1000 /* will be freed by corresponding LINELIST_V. */
1001 break;
1006 /** Return true iff the option <b>var</b> has the same value in <b>o1</b>
1007 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
1009 static int
1010 option_is_same(or_options_t *o1, or_options_t *o2, const char *name)
1012 struct config_line_t *c1, *c2;
1013 int r = 1;
1014 c1 = config_get_assigned_option(o1, name);
1015 c2 = config_get_assigned_option(o2, name);
1016 while (c1 && c2) {
1017 if (strcasecmp(c1->key, c2->key) ||
1018 strcmp(c1->value, c2->value)) {
1019 r = 0;
1020 break;
1022 c1 = c1->next;
1023 c2 = c2->next;
1025 if (r && (c1 || c2)) {
1026 r = 0;
1028 config_free_lines(c1);
1029 config_free_lines(c2);
1030 return r;
1033 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
1034 static or_options_t *
1035 options_dup(or_options_t *old)
1037 or_options_t *newopts;
1038 int i;
1039 struct config_line_t *line;
1041 newopts = tor_malloc_zero(sizeof(or_options_t));
1042 for (i=0; config_vars[i].name; ++i) {
1043 if (config_vars[i].type == CONFIG_TYPE_LINELIST_S)
1044 continue;
1045 if (config_vars[i].type == CONFIG_TYPE_OBSOLETE)
1046 continue;
1047 line = config_get_assigned_option(old, config_vars[i].name);
1048 if (line) {
1049 if (config_assign(newopts, line, 0) < 0) {
1050 log_fn(LOG_WARN,"Bug: config_get_assigned_option() generated "
1051 "something we couldn't config_assign().");
1052 tor_assert(0);
1055 config_free_lines(line);
1057 return newopts;
1060 /** Set <b>options</b> to hold reasonable defaults for most options.
1061 * Each option defaults to zero. */
1062 void
1063 options_init(or_options_t *options)
1065 int i;
1066 config_var_t *var;
1068 for (i=0; config_vars[i].name; ++i) {
1069 var = &config_vars[i];
1070 if (!var->initvalue)
1071 continue; /* defaults to NULL or 0 */
1072 option_reset(options, var);
1076 /** Return a string containing a possible configuration file that would give
1077 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
1078 * include options that are the same as Tor's defaults.
1080 char *
1081 config_dump_options(or_options_t *options, int minimal)
1083 smartlist_t *elements;
1084 or_options_t *defaults;
1085 struct config_line_t *line;
1086 char *result;
1087 int i;
1089 defaults = tor_malloc_zero(sizeof(or_options_t));
1090 options_init(defaults);
1091 options_validate(defaults); /* ??? will this work? */
1093 elements = smartlist_create();
1094 for (i=0; config_vars[i].name; ++i) {
1095 if (config_vars[i].type == CONFIG_TYPE_OBSOLETE ||
1096 config_vars[i].type == CONFIG_TYPE_LINELIST_S)
1097 continue;
1098 if (minimal && option_is_same(options, defaults, config_vars[i].name))
1099 continue;
1100 line = config_get_assigned_option(options, config_vars[i].name);
1101 for (; line; line = line->next) {
1102 size_t len = strlen(line->key) + strlen(line->value) + 3;
1103 char *tmp;
1104 tmp = tor_malloc(len);
1105 if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
1106 log_fn(LOG_ERR, "Internal error writing log option");
1107 tor_assert(0);
1109 smartlist_add(elements, tmp);
1111 config_free_lines(line);
1114 result = smartlist_join_strings(elements, "", 0, NULL);
1115 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
1116 smartlist_free(elements);
1117 return result;
1120 /** Return 0 if every setting in <b>options</b> is reasonable. Else
1121 * warn and return -1. Should have no side effects, except for
1122 * normalizing the contents of <b>options</b>. */
1123 static int
1124 options_validate(or_options_t *options)
1126 int i;
1127 int result = 0;
1128 struct config_line_t *cl;
1129 struct addr_policy_t *addr_policy=NULL;
1131 if (options->ORPort < 0 || options->ORPort > 65535) {
1132 log(LOG_WARN, "ORPort option out of bounds.");
1133 result = -1;
1136 if (validate_data_directory(options)<0) {
1137 log(LOG_WARN, "Invalid DataDirectory");
1138 result = -1;
1141 if (options->Nickname == NULL) {
1142 if (server_mode(options)) {
1143 if (!(options->Nickname = get_default_nickname()))
1144 return -1;
1145 log_fn(LOG_NOTICE, "Choosing default nickname %s", options->Nickname);
1147 } else {
1148 if (strspn(options->Nickname, LEGAL_NICKNAME_CHARACTERS) !=
1149 strlen(options->Nickname)) {
1150 log_fn(LOG_WARN, "Nickname '%s' contains illegal characters.", options->Nickname);
1151 result = -1;
1153 if (strlen(options->Nickname) == 0) {
1154 log_fn(LOG_WARN, "Nickname must have at least one character");
1155 result = -1;
1157 if (strlen(options->Nickname) > MAX_NICKNAME_LEN) {
1158 log_fn(LOG_WARN, "Nickname '%s' has more than %d characters.",
1159 options->Nickname, MAX_NICKNAME_LEN);
1160 result = -1;
1164 if (normalize_log_options(options))
1165 return -1;
1167 /* Special case if no options are given. */
1168 if (!options->Logs) {
1169 options->Logs = config_line_prepend(NULL, "Log", "notice-err stdout");
1172 if (config_init_logs(options, 1)<0) /* Validate the log(s) */
1173 return -1;
1175 if (server_mode(options)) {
1176 /* confirm that our address isn't broken, so we can complain now */
1177 uint32_t tmp;
1178 if (resolve_my_address(options->Address, &tmp) < 0)
1179 result = -1;
1182 if (options->SocksPort < 0 || options->SocksPort > 65535) {
1183 log(LOG_WARN, "SocksPort option out of bounds.");
1184 result = -1;
1187 if (options->SocksPort == 0 && options->ORPort == 0) {
1188 log(LOG_WARN, "SocksPort and ORPort are both undefined? Quitting.");
1189 result = -1;
1192 if (options->ControlPort < 0 || options->ControlPort > 65535) {
1193 log(LOG_WARN, "ControlPort option out of bounds.");
1194 result = -1;
1197 if (options->DirPort < 0 || options->DirPort > 65535) {
1198 log(LOG_WARN, "DirPort option out of bounds.");
1199 result = -1;
1202 if (options->StrictExitNodes &&
1203 (!options->ExitNodes || !strlen(options->ExitNodes))) {
1204 log(LOG_WARN, "StrictExitNodes set, but no ExitNodes listed.");
1207 if (options->StrictEntryNodes &&
1208 (!options->EntryNodes || !strlen(options->EntryNodes))) {
1209 log(LOG_WARN, "StrictEntryNodes set, but no EntryNodes listed.");
1212 if (options->AuthoritativeDir && options->RecommendedVersions == NULL) {
1213 log(LOG_WARN, "Directory servers must configure RecommendedVersions.");
1214 result = -1;
1217 if (options->AuthoritativeDir && !options->DirPort) {
1218 log(LOG_WARN, "Running as authoritative directory, but no DirPort set.");
1219 result = -1;
1222 if (options->AuthoritativeDir && !options->ORPort) {
1223 log(LOG_WARN, "Running as authoritative directory, but no ORPort set.");
1224 result = -1;
1227 if (options->AuthoritativeDir && options->ClientOnly) {
1228 log(LOG_WARN, "Running as authoritative directory, but ClientOnly also set.");
1229 result = -1;
1232 if (options->_AccountingMaxKB) {
1233 log(LOG_WARN, "AccountingMaxKB is deprecated. Say 'AccountingMax %d KB' instead.", options->_AccountingMaxKB);
1234 options->AccountingMax = U64_LITERAL(1024)*options->_AccountingMaxKB;
1235 options->_AccountingMaxKB = 0;
1238 if (options->FirewallPorts) {
1239 SMARTLIST_FOREACH(options->FirewallPorts, const char *, cp,
1241 i = atoi(cp);
1242 if (i < 1 || i > 65535) {
1243 log(LOG_WARN, "Port '%s' out of range in FirewallPorts", cp);
1244 result=-1;
1248 options->_AllowUnverified = 0;
1249 if (options->AllowUnverifiedNodes) {
1250 SMARTLIST_FOREACH(options->AllowUnverifiedNodes, const char *, cp, {
1251 if (!strcasecmp(cp, "entry"))
1252 options->_AllowUnverified |= ALLOW_UNVERIFIED_ENTRY;
1253 else if (!strcasecmp(cp, "exit"))
1254 options->_AllowUnverified |= ALLOW_UNVERIFIED_EXIT;
1255 else if (!strcasecmp(cp, "middle"))
1256 options->_AllowUnverified |= ALLOW_UNVERIFIED_MIDDLE;
1257 else if (!strcasecmp(cp, "introduction"))
1258 options->_AllowUnverified |= ALLOW_UNVERIFIED_INTRODUCTION;
1259 else if (!strcasecmp(cp, "rendezvous"))
1260 options->_AllowUnverified |= ALLOW_UNVERIFIED_RENDEZVOUS;
1261 else {
1262 log(LOG_WARN, "Unrecognized value '%s' in AllowUnverifiedNodes",
1263 cp);
1264 result=-1;
1269 if (options->SocksPort >= 1 &&
1270 (options->PathlenCoinWeight < 0.0 || options->PathlenCoinWeight >= 1.0)) {
1271 log(LOG_WARN, "PathlenCoinWeight option must be >=0.0 and <1.0.");
1272 result = -1;
1275 if (options->MaxConn < 1) {
1276 log(LOG_WARN, "MaxConn option must be a non-zero positive integer.");
1277 result = -1;
1280 if (options->MaxConn >= MAXCONNECTIONS) {
1281 log(LOG_WARN, "MaxConn option must be less than %d.", MAXCONNECTIONS);
1282 result = -1;
1285 #define MIN_DIR_FETCH_PERIOD 600
1286 #define MIN_DIR_POST_PERIOD 300
1287 #define MIN_REND_POST_PERIOD 300
1288 #define MIN_STATUS_FETCH_PERIOD 60
1290 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
1291 #define MAX_CACHE_DIR_FETCH_PERIOD 3600
1292 #define MAX_CACHE_STATUS_FETCH_PERIOD 900
1294 if (options->DirFetchPeriod < MIN_DIR_FETCH_PERIOD) {
1295 log(LOG_WARN, "DirFetchPeriod option must be at least %d seconds. Clipping.", MIN_DIR_FETCH_PERIOD);
1296 options->DirFetchPeriod = MIN_DIR_FETCH_PERIOD;
1298 if (options->StatusFetchPeriod < MIN_STATUS_FETCH_PERIOD) {
1299 log(LOG_WARN, "StatusFetchPeriod option must be at least %d seconds. Clipping.", MIN_STATUS_FETCH_PERIOD);
1300 options->StatusFetchPeriod = MIN_STATUS_FETCH_PERIOD;
1302 if (options->DirPostPeriod < MIN_DIR_POST_PERIOD) {
1303 log(LOG_WARN, "DirPostPeriod option must be at least %d seconds. Clipping.",
1304 MIN_DIR_POST_PERIOD);
1305 options->DirPostPeriod = MIN_DIR_POST_PERIOD;
1307 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
1308 log(LOG_WARN,"RendPostPeriod option must be at least %d seconds. Clipping.",
1309 MIN_REND_POST_PERIOD);
1310 options->RendPostPeriod = MIN_REND_POST_PERIOD;
1313 if (options->DirPort && ! options->AuthoritativeDir) {
1314 if (options->DirFetchPeriod > MAX_CACHE_DIR_FETCH_PERIOD) {
1315 log(LOG_WARN, "Caching directory servers must have DirFetchPeriod less than %d seconds. Clipping.", MAX_CACHE_DIR_FETCH_PERIOD);
1316 options->DirFetchPeriod = MAX_CACHE_DIR_FETCH_PERIOD;
1318 if (options->StatusFetchPeriod > MAX_CACHE_STATUS_FETCH_PERIOD) {
1319 log(LOG_WARN, "Caching directory servers must have StatusFetchPeriod less than %d seconds. Clipping.", MAX_CACHE_STATUS_FETCH_PERIOD);
1320 options->StatusFetchPeriod = MAX_CACHE_STATUS_FETCH_PERIOD;
1324 if (options->DirFetchPeriod > MAX_DIR_PERIOD) {
1325 log(LOG_WARN, "DirFetchPeriod is too large; clipping.");
1326 options->DirFetchPeriod = MAX_DIR_PERIOD;
1328 if (options->DirPostPeriod > MAX_DIR_PERIOD) {
1329 log(LOG_WARN, "DirPostPeriod is too large; clipping.");
1330 options->DirPostPeriod = MAX_DIR_PERIOD;
1332 if (options->StatusFetchPeriod > MAX_DIR_PERIOD) {
1333 log(LOG_WARN, "StatusFetchPeriod is too large; clipping.");
1334 options->StatusFetchPeriod = MAX_DIR_PERIOD;
1336 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
1337 log(LOG_WARN, "RendPostPeriod is too large; clipping.");
1338 options->RendPostPeriod = MAX_DIR_PERIOD;
1341 if (options->KeepalivePeriod < 1) {
1342 log(LOG_WARN,"KeepalivePeriod option must be positive.");
1343 result = -1;
1346 if (2*options->BandwidthRate >= options->BandwidthBurst) {
1347 log(LOG_WARN,"BandwidthBurst must be more than twice BandwidthRate.");
1348 result = -1;
1350 if (options->BandwidthRate > INT_MAX) {
1351 log(LOG_WARN,"BandwidthRate must be less than %d",INT_MAX);
1352 result = -1;
1354 if (options->BandwidthBurst > INT_MAX) {
1355 log(LOG_WARN,"BandwidthBurst must be less than %d",INT_MAX);
1356 result = -1;
1359 if (options->_MonthlyAccountingStart) {
1360 if (options->AccountingStart) {
1361 log(LOG_WARN,"Can't specify AccountingStart and MonthlyAccountingStart");
1362 result = -1;
1363 } else {
1364 options->AccountingStart = tor_malloc(32);
1365 if (tor_snprintf(options->AccountingStart, 32, "month %d 0:00",
1366 options->_MonthlyAccountingStart)<0) {
1367 log_fn(LOG_WARN,"Error translating MonthlyAccountingStart");
1368 result = -1;
1369 } else {
1370 log_fn(LOG_WARN,"MonthlyAccountingStart is deprecated. Use 'AccountingStart %s' instead.", options->AccountingStart);
1375 if (accounting_parse_options(options, 1)<0) {
1376 result = -1;
1379 if (options->HttpProxy) { /* parse it now */
1380 if (parse_addr_port(options->HttpProxy, NULL,
1381 &options->HttpProxyAddr, &options->HttpProxyPort) < 0) {
1382 log(LOG_WARN,"HttpProxy failed to parse or resolve. Please fix.");
1383 result = -1;
1385 if (options->HttpProxyPort == 0) { /* give it a default */
1386 options->HttpProxyPort = 80;
1390 if (options->HashedControlPassword) {
1391 char buf[S2K_SPECIFIER_LEN+DIGEST_LEN];
1392 if (base64_decode(buf,sizeof(buf),options->HashedControlPassword,
1393 strlen(options->HashedControlPassword)!=sizeof(buf))) {
1394 log_fn(LOG_WARN,"Bad HashedControlPassword: wrong length or bad base64");
1395 result = -1;
1398 if (options->HashedControlPassword && options->CookieAuthentication) {
1399 log_fn(LOG_WARN,"Cannot enable both HashedControlPassword and CookieAuthentication");
1400 result = -1;
1403 if (check_nickname_list(options->ExitNodes, "ExitNodes"))
1404 result = -1;
1405 if (check_nickname_list(options->EntryNodes, "EntryNodes"))
1406 result = -1;
1407 if (check_nickname_list(options->ExcludeNodes, "ExcludeNodes"))
1408 result = -1;
1409 if (check_nickname_list(options->RendNodes, "RendNodes"))
1410 result = -1;
1411 if (check_nickname_list(options->RendNodes, "RendExcludeNodes"))
1412 result = -1;
1413 if (check_nickname_list(options->MyFamily, "MyFamily"))
1414 result = -1;
1415 for (cl = options->NodeFamilies; cl; cl = cl->next) {
1416 if (check_nickname_list(cl->value, "NodeFamily"))
1417 result = -1;
1420 if (config_parse_addr_policy(options->ExitPolicy, &addr_policy)) {
1421 log_fn(LOG_WARN, "Error in Exit Policy entry.");
1422 result = -1;
1424 if (config_parse_addr_policy(options->DirPolicy, &addr_policy)) {
1425 log_fn(LOG_WARN, "Error in DirPolicy entry.");
1426 result = -1;
1428 if (config_parse_addr_policy(options->SocksPolicy, &addr_policy)) {
1429 log_fn(LOG_WARN, "Error in SocksPolicy entry.");
1430 result = -1;
1432 addr_policy_free(addr_policy);
1434 for (cl = options->RedirectExit; cl; cl = cl->next) {
1435 if (parse_redirect_line(NULL, cl)<0)
1436 result = -1;
1439 if (!options->DirServers) {
1440 add_default_trusted_dirservers(options);
1441 } else {
1442 for (cl = options->DirServers; cl; cl = cl->next) {
1443 if (parse_dir_server_line(cl->value, 1)<0)
1444 result = -1;
1448 if (rend_config_services(options, 1) < 0)
1449 result = -1;
1451 return result;
1454 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
1455 * equal strings. */
1456 static int
1457 opt_streq(const char *s1, const char *s2)
1459 if (!s1 && !s2)
1460 return 1;
1461 else if (s1 && s2 && !strcmp(s1,s2))
1462 return 1;
1463 else
1464 return 0;
1467 /** Check if any of the previous options have changed but aren't allowed to. */
1468 static int
1469 options_transition_allowed(or_options_t *old, or_options_t *new_val) {
1471 if (!old)
1472 return 0;
1474 if (!opt_streq(old->PidFile, new_val->PidFile)) {
1475 log_fn(LOG_WARN,"PidFile is not allowed to change. Failing.");
1476 return -1;
1479 if (old->RunAsDaemon && !new_val->RunAsDaemon) {
1480 log_fn(LOG_WARN,"During reload, change from RunAsDaemon=1 to =0 not allowed. Failing.");
1481 return -1;
1484 if (old->ORPort != new_val->ORPort) {
1485 log_fn(LOG_WARN,"During reload, changing ORPort is not allowed. Failing.");
1486 return -1;
1489 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
1490 log_fn(LOG_WARN,"During reload, changing DataDirectory (%s->%s) is not allowed. Failing.", old->DataDirectory, new_val->DataDirectory);
1491 return -1;
1494 if (!opt_streq(old->User, new_val->User)) {
1495 log_fn(LOG_WARN,"During reload, changing User is not allowed. Failing.");
1496 return -1;
1499 if (!opt_streq(old->Group, new_val->Group)) {
1500 log_fn(LOG_WARN,"During reload, changing User is not allowed. Failing.");
1501 return -1;
1504 return 0;
1507 #ifdef MS_WINDOWS
1508 /** Return the directory on windows where we expect to find our application
1509 * data. */
1510 static char *get_windows_conf_root(void)
1512 static int is_set = 0;
1513 static char path[MAX_PATH+1];
1515 LPITEMIDLIST idl;
1516 IMalloc *m;
1517 HRESULT result;
1519 if (is_set)
1520 return path;
1522 /* Find X:\documents and settings\username\applicatation data\ .
1523 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
1525 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA,
1526 &idl))) {
1527 GetCurrentDirectory(MAX_PATH, path);
1528 is_set = 1;
1529 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);
1530 return path;
1532 /* Convert the path from an "ID List" (whatever that is!) to a path. */
1533 result = SHGetPathFromIDList(idl, path);
1534 /* Now we need to free the */
1535 SHGetMalloc(&m);
1536 if (m) {
1537 m->lpVtbl->Free(m, idl);
1538 m->lpVtbl->Release(m);
1540 if (!SUCCEEDED(result)) {
1541 return NULL;
1543 strlcat(path,"\\tor",MAX_PATH);
1544 is_set = 1;
1545 return path;
1547 #endif
1549 /** Return the default location for our torrc file. */
1550 static char *
1551 get_default_conf_file(void)
1553 #ifdef MS_WINDOWS
1554 char *path = tor_malloc(MAX_PATH);
1555 strlcpy(path, get_windows_conf_root(), MAX_PATH);
1556 strlcat(path,"\\torrc",MAX_PATH);
1557 return path;
1558 #else
1559 return tor_strdup(CONFDIR "/torrc");
1560 #endif
1563 /** Verify whether lst is a string containing valid-looking space-separated
1564 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
1566 static int check_nickname_list(const char *lst, const char *name)
1568 int r = 0;
1569 smartlist_t *sl;
1571 if (!lst)
1572 return 0;
1573 sl = smartlist_create();
1574 smartlist_split_string(sl, lst, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1575 SMARTLIST_FOREACH(sl, const char *, s,
1577 if (!is_legal_nickname_or_hexdigest(s)) {
1578 log_fn(LOG_WARN, "Invalid nickname '%s' in %s line", s, name);
1579 r = -1;
1582 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
1583 smartlist_free(sl);
1584 return r;
1587 /** Read a configuration file into <b>options</b>, finding the configuration
1588 * file location based on the command line. After loading the options,
1589 * validate them for consistency, then take actions based on them.
1590 * Return 0 if success, -1 if failure. */
1592 init_from_config(int argc, char **argv)
1594 or_options_t *oldoptions, *newoptions;
1595 struct config_line_t *cl;
1596 char *cf=NULL, *fname=NULL;
1597 int i, retval;
1598 int using_default_torrc;
1599 static char **backup_argv;
1600 static int backup_argc;
1602 if (argv) { /* first time we're called. save commandline args */
1603 backup_argv = argv;
1604 backup_argc = argc;
1605 oldoptions = NULL;
1606 } else { /* we're reloading. need to clean up old options first. */
1607 argv = backup_argv;
1608 argc = backup_argc;
1609 oldoptions = get_options();
1611 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
1612 print_usage();
1613 exit(0);
1616 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
1617 printf("Tor version %s.\n",VERSION);
1618 if (argc > 2 && (!strcmp(argv[2],"--version"))) {
1619 print_cvs_version();
1621 exit(0);
1624 newoptions = tor_malloc_zero(sizeof(or_options_t));
1625 options_init(newoptions);
1627 /* learn config file name, get config lines, assign them */
1628 fname = NULL;
1629 using_default_torrc = 1;
1630 newoptions->command = CMD_RUN_TOR;
1631 for (i = 1; i < argc; ++i) {
1632 if (i < argc-1 && !strcmp(argv[i],"-f")) {
1633 if (fname) {
1634 log(LOG_WARN, "Duplicate -f options on command line.");
1635 tor_free(fname);
1637 fname = tor_strdup(argv[i+1]);
1638 using_default_torrc = 0;
1639 ++i;
1640 } else if (!strcmp(argv[i],"--list-fingerprint")) {
1641 newoptions->command = CMD_LIST_FINGERPRINT;
1642 } else if (!strcmp(argv[i],"--hash-password")) {
1643 newoptions->command = CMD_HASH_PASSWORD;
1644 newoptions->command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
1645 ++i;
1649 if (using_default_torrc) {
1650 /* didn't find one, try CONFDIR */
1651 char *fn;
1652 fn = get_default_conf_file();
1653 if (fn && file_status(fn) == FN_FILE) {
1654 fname = fn;
1655 } else {
1656 tor_free(fn);
1657 fn = expand_filename("~/.torrc");
1658 if (fn && file_status(fn) == FN_FILE) {
1659 fname = fn;
1660 } else {
1661 tor_free(fn);
1662 fname = get_default_conf_file();
1666 tor_assert(fname);
1667 log(LOG_DEBUG, "Opening config file '%s'", fname);
1669 cf = read_file_to_str(fname, 0);
1670 if (!cf) {
1671 if (using_default_torrc == 1) {
1672 log(LOG_NOTICE, "Configuration file '%s' not present, "
1673 "using reasonable defaults.", fname);
1674 tor_free(fname); /* sets fname to NULL */
1675 } else {
1676 log(LOG_WARN, "Unable to open configuration file '%s'.", fname);
1677 tor_free(fname);
1678 goto err;
1680 } else { /* it opened successfully. use it. */
1681 retval = config_get_lines(cf, &cl);
1682 tor_free(cf);
1683 if (retval < 0)
1684 goto err;
1685 retval = config_assign(newoptions, cl, 0);
1686 config_free_lines(cl);
1687 if (retval < 0)
1688 goto err;
1691 /* Go through command-line variables too */
1692 cl = config_get_commandlines(argc,argv);
1693 retval = config_assign(newoptions,cl,0);
1694 config_free_lines(cl);
1695 if (retval < 0)
1696 goto err;
1698 /* Validate newoptions */
1699 if (options_validate(newoptions) < 0)
1700 goto err;
1702 if (options_transition_allowed(oldoptions, newoptions) < 0)
1703 goto err;
1705 set_options(newoptions); /* frees and replaces old options */
1706 if (options_act() < 0) { /* acting on them failed. die. */
1707 log_fn(LOG_ERR,"Acting on config options left us in a broken state. Dying.");
1708 exit(1);
1710 tor_free(config_fname);
1711 config_fname = fname;
1712 return 0;
1713 err:
1714 tor_free(fname);
1715 options_free(newoptions);
1716 return -1;
1719 /** If <b>range</b> is of the form MIN-MAX, for MIN and MAX both
1720 * recognized log severity levels, set *<b>min_out</b> to MIN and
1721 * *<b>max_out</b> to MAX and return 0. Else, if <b>range<b> is of
1722 * the form MIN, act as if MIN-err had been specified. Else, warn and
1723 * return -1.
1725 static int
1726 parse_log_severity_range(const char *range, int *min_out, int *max_out)
1728 int levelMin, levelMax;
1729 const char *cp;
1730 cp = strchr(range, '-');
1731 if (cp) {
1732 if (cp == range) {
1733 levelMin = LOG_DEBUG;
1734 } else {
1735 char *tmp_sev = tor_strndup(range, cp - range);
1736 levelMin = parse_log_level(tmp_sev);
1737 if (levelMin < 0) {
1738 log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
1739 "err|warn|notice|info|debug", tmp_sev);
1740 tor_free(tmp_sev);
1741 return -1;
1743 tor_free(tmp_sev);
1745 if (!*(cp+1)) {
1746 levelMax = LOG_ERR;
1747 } else {
1748 levelMax = parse_log_level(cp+1);
1749 if (levelMax < 0) {
1750 log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
1751 "err|warn|notice|info|debug", cp+1);
1752 return -1;
1755 } else {
1756 levelMin = parse_log_level(range);
1757 if (levelMin < 0) {
1758 log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
1759 "err|warn|notice|info|debug", range);
1760 return -1;
1762 levelMax = LOG_ERR;
1765 *min_out = levelMin;
1766 *max_out = levelMax;
1768 return 0;
1771 /** Try to convert a pair of old-style logging options [LogLevel, and
1772 * (LogFile/Syslog)] to a new-style option, and add the new option to
1773 * options->Logs. */
1774 static int
1775 convert_log_option(or_options_t *options, struct config_line_t *level_opt,
1776 struct config_line_t *file_opt, int isDaemon)
1778 int levelMin = -1, levelMax = -1;
1780 if (level_opt) {
1781 if (parse_log_severity_range(level_opt->value, &levelMin, &levelMax))
1782 return -1;
1784 if (levelMin < 0 && levelMax < 0) {
1785 levelMin = LOG_NOTICE;
1786 levelMax = LOG_ERR;
1787 } else if (levelMin < 0) {
1788 levelMin = levelMax;
1789 } else {
1790 levelMax = LOG_ERR;
1793 if (file_opt && !strcasecmp(file_opt->key, "LogFile")) {
1794 if (add_single_log_option(options, levelMin, levelMax, "file", file_opt->value) < 0) {
1795 log_fn(LOG_WARN, "Cannot write to LogFile '%s': %s.", file_opt->value,
1796 strerror(errno));
1797 return -1;
1799 } else if (file_opt && !strcasecmp(file_opt->key, "SysLog")) {
1800 if (add_single_log_option(options, levelMin, levelMax, "syslog", NULL) < 0)
1801 return -1;
1802 } else if (!isDaemon) {
1803 add_single_log_option(options, levelMin, levelMax, "stdout", NULL);
1805 return 0;
1809 * Initialize the logs based on the configuration file.
1812 config_init_logs(or_options_t *options, int validate_only)
1814 struct config_line_t *opt;
1815 int ok;
1816 smartlist_t *elts;
1818 ok = 1;
1819 elts = smartlist_create();
1820 for (opt = options->Logs; opt; opt = opt->next) {
1821 int levelMin=LOG_DEBUG, levelMax=LOG_ERR;
1822 smartlist_split_string(elts, opt->value, " ",
1823 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
1824 if (smartlist_len(elts) == 0) {
1825 log_fn(LOG_WARN, "Bad syntax on Log option 'Log %s'", opt->value);
1826 ok = 0; goto cleanup;
1828 if (parse_log_severity_range(smartlist_get(elts,0), &levelMin, &levelMax)) {
1829 ok = 0; goto cleanup;
1831 if (smartlist_len(elts) < 2) { /* only loglevels were provided */
1832 if (!validate_only)
1833 add_stream_log(levelMin, levelMax, "<stdout>", stdout);
1834 goto cleanup;
1836 if (!strcasecmp(smartlist_get(elts,1), "file")) {
1837 if (smartlist_len(elts) != 3) {
1838 log_fn(LOG_WARN, "Bad syntax on Log option 'Log %s'", opt->value);
1839 ok = 0; goto cleanup;
1841 if (!validate_only)
1842 add_file_log(levelMin, levelMax, smartlist_get(elts, 2));
1843 goto cleanup;
1845 if (smartlist_len(elts) != 2) {
1846 log_fn(LOG_WARN, "Bad syntax on Log option 'Log %s'", opt->value);
1847 ok = 0; goto cleanup;
1849 if (!strcasecmp(smartlist_get(elts,1), "stdout")) {
1850 if (!validate_only) {
1851 add_stream_log(levelMin, levelMax, "<stdout>", stdout);
1852 close_temp_logs();
1854 } else if (!strcasecmp(smartlist_get(elts,1), "stderr")) {
1855 if (!validate_only) {
1856 add_stream_log(levelMin, levelMax, "<stderr>", stderr);
1857 close_temp_logs();
1859 } else if (!strcasecmp(smartlist_get(elts,1), "syslog")) {
1860 #ifdef HAVE_SYSLOG_H
1861 if (!validate_only)
1862 add_syslog_log(levelMin, levelMax);
1863 #else
1864 log_fn(LOG_WARN, "Syslog is not supported in this compilation.");
1865 #endif
1866 } else {
1867 log_fn(LOG_WARN, "Unrecognized log type %s",
1868 (const char*)smartlist_get(elts,1));
1869 if (strchr(smartlist_get(elts,1), '/')) {
1870 log_fn(LOG_WARN, "Did you mean to say 'Log file %s' ?",
1871 (const char *)smartlist_get(elts,1));
1873 ok = 0; goto cleanup;
1875 cleanup:
1876 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
1877 smartlist_clear(elts);
1879 smartlist_free(elts);
1880 if (!validate_only)
1881 close_temp_logs();
1883 return ok?0:-1;
1886 /** Add a single option of the form Log min-max <type> [fname] to options. */
1887 static int
1888 add_single_log_option(or_options_t *options, int minSeverity, int maxSeverity,
1889 const char *type, const char *fname)
1891 char buf[512];
1892 int n;
1894 n = tor_snprintf(buf, sizeof(buf), "%s-%s %s%s%s",
1895 log_level_to_string(minSeverity),
1896 log_level_to_string(maxSeverity),
1897 type, fname?" ":"", fname?fname:"");
1898 if (n<0) {
1899 log_fn(LOG_WARN, "Normalized log option too long.");
1900 return -1;
1903 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);
1904 options->Logs = config_line_prepend(options->Logs, "Log", buf);
1905 return 0;
1908 /** Convert all old-style logging options to new-style Log options. Return 0
1909 * on success, -1 on faulure. */
1910 static int
1911 normalize_log_options(or_options_t *options)
1913 /* The order of options is: Level? (File Level?)+
1915 struct config_line_t *opt = options->OldLogOptions;
1917 /* Special case for if first option is LogLevel. */
1918 if (opt && !strcasecmp(opt->key, "LogLevel")) {
1919 if (opt->next && (!strcasecmp(opt->next->key, "LogFile") ||
1920 !strcasecmp(opt->next->key, "SysLog"))) {
1921 if (convert_log_option(options, opt, opt->next, options->RunAsDaemon) < 0)
1922 return -1;
1923 opt = opt->next->next;
1924 } else if (!opt->next) {
1925 if (convert_log_option(options, opt, NULL, options->RunAsDaemon) < 0)
1926 return -1;
1927 opt = opt->next;
1928 } else {
1929 ; /* give warning below */
1933 while (opt) {
1934 if (!strcasecmp(opt->key, "LogLevel")) {
1935 log_fn(LOG_WARN, "Two LogLevel options in a row without intervening LogFile or SysLog");
1936 opt = opt->next;
1937 } else {
1938 tor_assert(!strcasecmp(opt->key, "LogFile") ||
1939 !strcasecmp(opt->key, "SysLog"));
1940 if (opt->next && !strcasecmp(opt->next->key, "LogLevel")) {
1941 /* LogFile/SysLog followed by LogLevel */
1942 if (convert_log_option(options,opt->next,opt, options->RunAsDaemon) < 0)
1943 return -1;
1944 opt = opt->next->next;
1945 } else {
1946 /* LogFile/SysLog followed by LogFile/SysLog or end of list. */
1947 if (convert_log_option(options,NULL, opt, options->RunAsDaemon) < 0)
1948 return -1;
1949 opt = opt->next;
1954 if (options->DebugLogFile) {
1955 if (add_single_log_option(options, LOG_DEBUG, LOG_ERR, "file", options->DebugLogFile) < 0)
1956 return -1;
1959 tor_free(options->DebugLogFile);
1960 config_free_lines(options->OldLogOptions);
1961 options->OldLogOptions = NULL;
1963 return 0;
1967 * Given a linked list of config lines containing "allow" and "deny" tokens,
1968 * parse them and append the result to <b>dest</b>. Return -1 if any tokens
1969 * are malformed, else return 0.
1972 config_parse_addr_policy(struct config_line_t *cfg,
1973 struct addr_policy_t **dest)
1975 struct addr_policy_t **nextp;
1976 smartlist_t *entries;
1977 int r = 0;
1979 if (!cfg)
1980 return 0;
1982 nextp = dest;
1984 while (*nextp)
1985 nextp = &((*nextp)->next);
1987 entries = smartlist_create();
1988 for (; cfg; cfg = cfg->next) {
1989 smartlist_split_string(entries, cfg->value, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1990 SMARTLIST_FOREACH(entries, const char *, ent,
1992 log_fn(LOG_DEBUG,"Adding new entry '%s'",ent);
1993 *nextp = router_parse_addr_policy_from_string(ent);
1994 if (*nextp) {
1995 nextp = &((*nextp)->next);
1996 } else {
1997 log_fn(LOG_WARN,"Malformed policy %s.", ent);
1998 r = -1;
2001 SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
2002 smartlist_clear(entries);
2004 smartlist_free(entries);
2005 return r;
2008 /** Release all storage held by <b>p</b> */
2009 void
2010 addr_policy_free(struct addr_policy_t *p) {
2011 struct addr_policy_t *e;
2013 while (p) {
2014 e = p;
2015 p = p->next;
2016 tor_free(e->string);
2017 tor_free(e);
2021 /** Parse a single RedirectExit line's contents from <b>line</b>. If
2022 * they are valid, and <b>result</b> is not NULL, add an element to
2023 * <b>result</b> and return 0. Else if they are valid, return 0.
2024 * Else return -1. */
2025 static int
2026 parse_redirect_line(smartlist_t *result, struct config_line_t *line)
2028 smartlist_t *elements = NULL;
2029 exit_redirect_t *r;
2031 tor_assert(line);
2033 r = tor_malloc_zero(sizeof(exit_redirect_t));
2034 elements = smartlist_create();
2035 smartlist_split_string(elements, line->value, " ",
2036 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2037 if (smartlist_len(elements) != 2) {
2038 log_fn(LOG_WARN, "Wrong number of elements in RedirectExit line");
2039 goto err;
2041 if (parse_addr_and_port_range(smartlist_get(elements,0),&r->addr,&r->mask,
2042 &r->port_min,&r->port_max)) {
2043 log_fn(LOG_WARN, "Error parsing source address in RedirectExit line");
2044 goto err;
2046 if (0==strcasecmp(smartlist_get(elements,1), "pass")) {
2047 r->is_redirect = 0;
2048 } else {
2049 if (parse_addr_port(smartlist_get(elements,1),NULL,&r->addr_dest,
2050 &r->port_dest)) {
2051 log_fn(LOG_WARN, "Error parsing dest address in RedirectExit line");
2052 goto err;
2054 r->is_redirect = 1;
2057 goto done;
2058 err:
2059 tor_free(r);
2060 done:
2061 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2062 smartlist_free(elements);
2063 if (r) {
2064 if (result)
2065 smartlist_add(result, r);
2066 else
2067 tor_free(r);
2068 return 0;
2069 } else {
2070 return -1;
2074 /** Read the contents of a DirServer line from <b>line</b>. Return 0
2075 * if the line is well-formed, and 0 if it isn't. If
2076 * <b>validate_only</b> is 0, and the line is well-formed, then add
2077 * the dirserver desribed in the line as a valid server. */
2078 static int
2079 parse_dir_server_line(const char *line, int validate_only)
2081 smartlist_t *items = NULL;
2082 int r;
2083 char *addrport, *address=NULL;
2084 uint16_t port;
2085 char digest[DIGEST_LEN];
2087 items = smartlist_create();
2088 smartlist_split_string(items, line, " ",
2089 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
2090 if (smartlist_len(items) < 2) {
2091 log_fn(LOG_WARN, "Too few arguments to DirServer line.");
2092 goto err;
2094 addrport = smartlist_get(items, 0);
2095 if (parse_addr_port(addrport, &address, NULL, &port)<0) {
2096 log_fn(LOG_WARN, "Error parsing DirServer address '%s'", addrport);
2097 goto err;
2099 if (!port) {
2100 log_fn(LOG_WARN, "Missing port in DirServe address '%s'",addrport);
2101 goto err;
2104 tor_strstrip(smartlist_get(items, 1), " ");
2105 if (strlen(smartlist_get(items, 1)) != HEX_DIGEST_LEN) {
2106 log_fn(LOG_WARN, "Key digest for DirServer is wrong length.");
2107 goto err;
2109 if (base16_decode(digest, DIGEST_LEN,
2110 smartlist_get(items,1), HEX_DIGEST_LEN)<0) {
2111 log_fn(LOG_WARN, "Unable to decode DirServer key digest.");
2112 goto err;
2115 if (!validate_only) {
2116 log_fn(LOG_DEBUG, "Trusted dirserver at %s:%d (%s)", address, (int)port,
2117 (char*)smartlist_get(items,1));
2118 add_trusted_dir_server(address, port, digest);
2121 r = 0;
2122 goto done;
2124 err:
2125 r = -1;
2127 done:
2128 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
2129 smartlist_free(items);
2130 tor_free(address);
2131 return r;
2134 /** Adjust the value of options->DataDirectory, or fill it in if it's
2135 * absent. Return 0 on success, -1 on failure. */
2136 static int
2137 normalize_data_directory(or_options_t *options) {
2138 #ifdef MS_WINDOWS
2139 char *p;
2140 if (options->DataDirectory)
2141 return 0; /* all set */
2142 p = tor_malloc(MAX_PATH);
2143 strlcpy(p,get_windows_conf_root(),MAX_PATH);
2144 options->DataDirectory = p;
2145 return 0;
2146 #else
2147 const char *d = options->DataDirectory;
2148 if (!d)
2149 d = "~/.tor";
2151 if (strncmp(d,"~/",2) == 0) {
2152 char *fn = expand_filename(d);
2153 if (!fn) {
2154 log_fn(LOG_ERR,"Failed to expand filename '%s'.", d);
2155 return -1;
2157 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
2158 /* If our homedir is /, we probably don't want to use it. */
2159 /* XXXX Default to /var/lib/tor? */
2160 log_fn(LOG_WARN, "Defaulting to 'DataDirectory %s', which may not be what you want", fn);
2162 tor_free(options->DataDirectory);
2163 options->DataDirectory = fn;
2165 return 0;
2166 #endif
2169 /** Check and normalize the value of options->DataDirectory; return 0 if it
2170 * sane, -1 otherwise. */
2171 static int
2172 validate_data_directory(or_options_t *options) {
2173 if (normalize_data_directory(options) < 0)
2174 return -1;
2175 tor_assert(options->DataDirectory);
2176 if (strlen(options->DataDirectory) > (512-128)) {
2177 log_fn(LOG_ERR, "DataDirectory is too long.");
2178 return -1;
2180 #if 0
2181 if (check_private_dir(options->DataDirectory, CPD_CHECK != 0)) {
2182 log_fn(LOG_WARN, "Can't create directory %s", options->DataDirectory);
2183 return -1;
2185 #endif
2186 return 0;
2189 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; if you edit it, comments will not be preserved"
2191 /** Save a configuration file for the configuration in <b>options</b>
2192 * into the file <b>fname</b>. If the file already exists, and
2193 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
2194 * replace it. Return 0 on success, -1 on failure. */
2195 static int
2196 write_configuration_file(const char *fname, or_options_t *options)
2198 char fn_tmp[1024];
2199 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
2200 int rename_old = 0, r;
2201 size_t len;
2203 if (fname) {
2204 switch (file_status(fname)) {
2205 case FN_FILE:
2206 old_val = read_file_to_str(fname, 0);
2207 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
2208 rename_old = 1;
2210 tor_free(old_val);
2211 break;
2212 case FN_NOENT:
2213 break;
2214 default:
2215 log_fn(LOG_WARN,"Config file %s is not a file? Failing.", fname);
2216 return -1;
2220 if (!(new_conf = config_dump_options(options, 1))) {
2221 log_fn(LOG_WARN, "Couldn't get configuration string");
2222 goto err;
2225 len = strlen(new_conf)+128;
2226 new_val = tor_malloc(len);
2227 tor_snprintf(new_val, len, "%s\n\n%s", GENERATED_FILE_PREFIX, new_conf);
2229 if (rename_old) {
2230 int i = 1;
2231 while (1) {
2232 if (tor_snprintf(fn_tmp, sizeof(fn_tmp), "%s.orig.%d", fname, i)<0) {
2233 log_fn(LOG_WARN, "Filename too long");
2234 goto err;
2236 if (file_status(fn_tmp) == FN_NOENT)
2237 break;
2238 ++i;
2240 log_fn(LOG_NOTICE, "Renaming old configuration file to %s", fn_tmp);
2241 rename(fname, fn_tmp);
2244 write_str_to_file(fname, new_val, 0);
2246 r = 0;
2247 goto done;
2248 err:
2249 r = -1;
2250 done:
2251 tor_free(new_val);
2252 tor_free(new_conf);
2253 return r;
2257 * Save the current configuration file value to disk. Return 0 on
2258 * success, -1 on failure.
2261 save_current_config(void)
2263 char *fn;
2264 if (config_fname) {
2265 /* XXX This fails if we can't write to our configuration file.
2266 * Arguably, we should try falling back to datadirectory or something.
2267 * But just as arguably, we shouldn't. */
2268 return write_configuration_file(config_fname, get_options());
2270 fn = get_default_conf_file();
2271 return write_configuration_file(fn, get_options());
2274 struct unit_table_t {
2275 const char *unit;
2276 uint64_t multiplier;
2279 static struct unit_table_t memory_units[] = {
2280 { "", 1 },
2281 { "b", 1<< 0 },
2282 { "byte", 1<< 0 },
2283 { "bytes", 1<< 0 },
2284 { "kb", 1<<10 },
2285 { "kilobyte", 1<<10 },
2286 { "kilobytes", 1<<10 },
2287 { "m", 1<<20 },
2288 { "mb", 1<<20 },
2289 { "megabyte", 1<<20 },
2290 { "megabytes", 1<<20 },
2291 { "gb", 1<<30 },
2292 { "gigabyte", 1<<30 },
2293 { "gigabytes", 1<<30 },
2294 { "tb", U64_LITERAL(1)<<40 },
2295 { "terabyte", U64_LITERAL(1)<<40 },
2296 { "terabytes", U64_LITERAL(1)<<40 },
2297 { NULL, 0 },
2300 static struct unit_table_t time_units[] = {
2301 { "", 1 },
2302 { "second", 1 },
2303 { "seconds", 1 },
2304 { "minute", 60 },
2305 { "minutes", 60 },
2306 { "hour", 60*60 },
2307 { "hours", 60*60 },
2308 { "day", 24*60*60 },
2309 { "days", 24*60*60 },
2310 { "week", 7*24*60*60 },
2311 { "weeks", 7*24*60*60 },
2312 { NULL, 0 },
2315 /** Parse a string <b>val</b> containing a number, zero or more
2316 * spaces, and an optional unit string. If the unit appears in the
2317 * table <b>u</b>, then multiply the number by the unit multiplier.
2318 * On success, set *<b>ok</b> to 1 and return this product.
2319 * Otherwise, set *<b>ok</b> to 0.
2321 static uint64_t
2322 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
2324 uint64_t v;
2325 char *cp;
2327 tor_assert(ok);
2329 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
2330 if (!*ok)
2331 return 0;
2332 if (!cp) {
2333 *ok = 1;
2334 return v;
2336 while (isspace(*cp))
2337 ++cp;
2338 for ( ;u->unit;++u) {
2339 if (!strcasecmp(u->unit, cp)) {
2340 v *= u->multiplier;
2341 *ok = 1;
2342 return v;
2345 log_fn(LOG_WARN, "Unknown unit '%s'.", cp);
2346 *ok = 0;
2347 return 0;
2350 /** Parse a string in the format "number unit", where unit is a unit of
2351 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
2352 * and return the number of bytes specified. Otherwise, set
2353 * *<b>ok</b> to false and return 0. */
2354 static uint64_t
2355 config_parse_memunit(const char *s, int *ok) {
2356 return config_parse_units(s, memory_units, ok);
2359 /** Parse a string in the format "number unit", where unit is a unit of time.
2360 * On success, set *<b>ok</b> to true and return the number of seconds in
2361 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
2363 static int
2364 config_parse_interval(const char *s, int *ok) {
2365 uint64_t r;
2366 r = config_parse_units(s, time_units, ok);
2367 if (!ok)
2368 return -1;
2369 if (r > INT_MAX) {
2370 log_fn(LOG_WARN, "Interval '%s' is too long", s);
2371 *ok = 0;
2372 return -1;
2374 return (int)r;
2377 static void
2378 print_cvs_version(void)
2380 extern const char aes_c_id[];
2381 extern const char compat_c_id[];
2382 extern const char container_c_id[];
2383 extern const char crypto_c_id[];
2384 extern const char fakepoll_c_id[];
2385 extern const char log_c_id[];
2386 extern const char torgzip_c_id[];
2387 extern const char tortls_c_id[];
2388 extern const char util_c_id[];
2390 extern const char buffers_c_id[];
2391 extern const char circuitbuild_c_id[];
2392 extern const char circuitlist_c_id[];
2393 extern const char circuituse_c_id[];
2394 extern const char command_c_id[];
2395 extern const char config_c_id[];
2396 extern const char connection_c_id[];
2397 extern const char connection_edge_c_id[];
2398 extern const char connection_or_c_id[];
2399 extern const char control_c_id[];
2400 extern const char cpuworker_c_id[];
2401 extern const char directory_c_id[];
2402 extern const char dirserv_c_id[];
2403 extern const char dns_c_id[];
2404 extern const char hibernate_c_id[];
2405 extern const char main_c_id[];
2406 extern const char onion_c_id[];
2407 extern const char relay_c_id[];
2408 extern const char rendclient_c_id[];
2409 extern const char rendcommon_c_id[];
2410 extern const char rendmid_c_id[];
2411 extern const char rendservice_c_id[];
2412 extern const char rephist_c_id[];
2413 extern const char router_c_id[];
2414 extern const char routerlist_c_id[];
2415 extern const char routerparse_c_id[];
2417 puts(AES_H_ID);
2418 puts(COMPAT_H_ID);
2419 puts(CONTAINER_H_ID);
2420 puts(CRYPTO_H_ID);
2421 puts(FAKEPOLL_H_ID);
2422 puts(LOG_H_ID);
2423 puts(TORGZIP_H_ID);
2424 puts(TORINT_H_ID);
2425 puts(TORTLS_H_ID);
2426 puts(UTIL_H_ID);
2427 puts(aes_c_id);
2428 puts(compat_c_id);
2429 puts(container_c_id);
2430 puts(crypto_c_id);
2431 puts(fakepoll_c_id);
2432 puts(log_c_id);
2433 puts(torgzip_c_id);
2434 puts(tortls_c_id);
2435 puts(util_c_id);
2437 puts(OR_H_ID);
2438 puts(buffers_c_id);
2439 puts(circuitbuild_c_id);
2440 puts(circuitlist_c_id);
2441 puts(circuituse_c_id);
2442 puts(command_c_id);
2443 puts(config_c_id);
2444 puts(connection_c_id);
2445 puts(connection_edge_c_id);
2446 puts(connection_or_c_id);
2447 puts(control_c_id);
2448 puts(cpuworker_c_id);
2449 puts(directory_c_id);
2450 puts(dirserv_c_id);
2451 puts(dns_c_id);
2452 puts(hibernate_c_id);
2453 puts(main_c_id);
2454 puts(onion_c_id);
2455 puts(relay_c_id);
2456 puts(rendclient_c_id);
2457 puts(rendcommon_c_id);
2458 puts(rendmid_c_id);
2459 puts(rendservice_c_id);
2460 puts(rephist_c_id);
2461 puts(router_c_id);
2462 puts(routerlist_c_id);
2463 puts(routerparse_c_id);