and take the bang out
[tor.git] / src / or / config.c
blob7e6aaf8cbeaa986c8e79ffe8b1074663acbba1ce
1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char config_c_id[] = "$Id$";
8 /**
9 * \file config.c
10 * \brief Code to parse and interpret configuration files.
11 **/
13 #include "or.h"
14 #ifdef MS_WINDOWS
15 #include <shlobj.h>
16 #endif
17 #include "../common/aes.h"
19 /** Enumeration of types which option values can take */
20 typedef enum config_type_t {
21 CONFIG_TYPE_STRING = 0, /**< An arbitrary string. */
22 CONFIG_TYPE_UINT, /**< A non-negative integer less than MAX_INT */
23 CONFIG_TYPE_INTERVAL, /**< A number of seconds, with optional units*/
24 CONFIG_TYPE_MEMUNIT, /**< A number of bytes, with optional units*/
25 CONFIG_TYPE_DOUBLE, /**< A floating-point value */
26 CONFIG_TYPE_BOOL, /**< A boolean value, expressed as 0 or 1. */
27 CONFIG_TYPE_ISOTIME, /**< An ISO-formated time relative to GMT. */
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 _option_abbrevs[] = {
52 PLURAL(ExitNode),
53 PLURAL(EntryNode),
54 PLURAL(ExcludeNode),
55 PLURAL(FirewallPort),
56 PLURAL(LongLivedPort),
57 PLURAL(HiddenServiceNode),
58 PLURAL(HiddenServiceExcludeNode),
59 PLURAL(NumCpu),
60 PLURAL(RendNode),
61 PLURAL(RendExcludeNode),
62 PLURAL(StrictEntryNode),
63 PLURAL(StrictExitNode),
64 { "l", "Log", 1},
65 { "BandwidthRateBytes", "BandwidthRate", 0},
66 { "BandwidthBurstBytes", "BandwidthBurst", 0},
67 { "DirFetchPostPeriod", "StatusFetchPeriod", 0},
68 { "MaxConn", "ConnLimit", 0},
69 { NULL, NULL , 0},
71 #undef PLURAL
73 /** A variable allowed in the configuration file or on the command line. */
74 typedef struct config_var_t {
75 const char *name; /**< The full keyword (case insensitive). */
76 config_type_t type; /**< How to interpret the type and turn it into a value. */
77 off_t var_offset; /**< Offset of the corresponding member of or_options_t. */
78 const char *initvalue; /**< String (or null) describing initial value. */
79 const char *description;
80 } config_var_t;
82 /** Return the offset of <b>member</b> within the type <b>tp</b>, in bytes */
83 #define STRUCT_OFFSET(tp, member) ((off_t) (((char*)&((tp*)0)->member)-(char*)0))
84 /** An entry for config_vars: "The option <b>name</b> has type
85 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
86 * or_options_t.<b>member</b>"
88 #define VAR(name,conftype,member,initvalue) \
89 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), initvalue, NULL }
90 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
91 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL, NULL }
93 /** Array of configuration options. Until we disallow nonstandard
94 * abbreviations, order is significant, since the first matching option will
95 * be chosen first.
97 static config_var_t _option_vars[] = {
98 VAR("AccountingMax", MEMUNIT, AccountingMax, "0 bytes"),
99 VAR("AccountingMaxKB", UINT, _AccountingMaxKB, "0"),
100 VAR("AccountingStart", STRING, AccountingStart, NULL),
101 VAR("Address", STRING, Address, NULL),
102 VAR("AllowUnverifiedNodes",CSV, AllowUnverifiedNodes, "middle,rendezvous"),
103 VAR("AssumeReachable", BOOL, AssumeReachable, "0"),
104 VAR("AuthoritativeDirectory",BOOL, AuthoritativeDir, "0"),
105 /* XXXX 011 change this default on 0.1.1.x */
106 VAR("V1AuthoritativeDirectory",BOOL, V1AuthoritativeDir, "1"),
107 VAR("BandwidthBurst", MEMUNIT, BandwidthBurst, "5 MB"),
108 VAR("BandwidthRate", MEMUNIT, BandwidthRate, "2 MB"),
109 VAR("ClientOnly", BOOL, ClientOnly, "0"),
110 VAR("ConnLimit", UINT, ConnLimit, "1024"),
111 VAR("ContactInfo", STRING, ContactInfo, NULL),
112 VAR("ControlPort", UINT, ControlPort, "0"),
113 VAR("CookieAuthentication",BOOL, CookieAuthentication, "0"),
114 VAR("DataDirectory", STRING, DataDirectory, NULL),
115 VAR("DebugLogFile", STRING, DebugLogFile, NULL),
116 VAR("DirAllowPrivateAddresses",BOOL, DirAllowPrivateAddresses, NULL),
117 VAR("DirBindAddress", LINELIST, DirBindAddress, NULL),
118 VAR("DirFetchPeriod", INTERVAL, DirFetchPeriod, "0 seconds"), /** DOCDOC **/
119 VAR("DirPolicy", LINELIST, DirPolicy, NULL),
120 VAR("DirPort", UINT, DirPort, "0"),
121 OBSOLETE("DirPostPeriod"),
122 VAR("DirServer", LINELIST, DirServers, NULL),
123 VAR("EntryNodes", STRING, EntryNodes, NULL),
124 VAR("ExcludeNodes", STRING, ExcludeNodes, NULL),
125 VAR("ExitNodes", STRING, ExitNodes, NULL),
126 VAR("ExitPolicy", LINELIST, ExitPolicy, NULL),
127 VAR("FascistFirewall", BOOL, FascistFirewall, "0"),
128 VAR("FirewallPorts", CSV, FirewallPorts, ""),
129 VAR("Group", STRING, Group, NULL),
130 VAR("HardwareAccel", BOOL, HardwareAccel, "1"),
131 VAR("HashedControlPassword",STRING, HashedControlPassword, NULL),
132 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
133 VAR("HiddenServiceExcludeNodes", LINELIST_S, RendConfigLines, NULL),
134 VAR("HiddenServiceNodes", LINELIST_S, RendConfigLines, NULL),
135 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
136 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
137 VAR("HttpProxy", STRING, HttpProxy, NULL),
138 VAR("HttpProxyAuthenticator",STRING, HttpProxyAuthenticator,NULL),
139 VAR("HttpsProxy", STRING, HttpsProxy, NULL),
140 VAR("HttpsProxyAuthenticator",STRING,HttpsProxyAuthenticator,NULL),
141 OBSOLETE("IgnoreVersion"),
142 VAR("KeepalivePeriod", INTERVAL, KeepalivePeriod, "5 minutes"),
143 VAR("Log", LINELIST, Logs, NULL),
144 OBSOLETE("LinkPadding"),
145 VAR("LogFile", LINELIST_S, OldLogOptions, NULL),
146 VAR("LogLevel", LINELIST_S, OldLogOptions, NULL),
147 VAR("LongLivedPorts", CSV, LongLivedPorts, "21,22,706,1863,5050,5190,5222,5223,6667,8300,8888"),
148 VAR("MapAddress", LINELIST, AddressMap, NULL),
149 VAR("MaxAdvertisedBandwidth",MEMUNIT,MaxAdvertisedBandwidth,"128 TB"),
150 VAR("MaxCircuitDirtiness", INTERVAL, MaxCircuitDirtiness, "10 minutes"),
151 VAR("MaxOnionsPending", UINT, MaxOnionsPending, "100"),
152 OBSOLETE("MonthlyAccountingStart"),
153 VAR("MyFamily", STRING, MyFamily, NULL),
154 VAR("NewCircuitPeriod", INTERVAL, NewCircuitPeriod, "30 seconds"),
155 VAR("Nickname", STRING, Nickname, NULL),
156 VAR("NoPublish", BOOL, NoPublish, "0"),
157 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
158 VAR("NumCpus", UINT, NumCpus, "1"),
159 VAR("NumHelperNodes", UINT, NumHelperNodes, "3"),
160 VAR("ORBindAddress", LINELIST, ORBindAddress, NULL),
161 VAR("ORPort", UINT, ORPort, "0"),
162 VAR("OutboundBindAddress", STRING, OutboundBindAddress, NULL),
163 VAR("PathlenCoinWeight", DOUBLE, PathlenCoinWeight, "0.3"),
164 VAR("PidFile", STRING, PidFile, NULL),
165 VAR("ReachableAddresses", LINELIST, ReachableAddresses, NULL),
166 VAR("RecommendedVersions", LINELIST, RecommendedVersions, NULL),
167 VAR("RecommendedClientVersions", LINELIST, RecommendedClientVersions, NULL),
168 VAR("RecommendedServerVersions", LINELIST, RecommendedServerVersions, NULL),
169 VAR("RedirectExit", LINELIST, RedirectExit, NULL),
170 VAR("RendExcludeNodes", STRING, RendExcludeNodes, NULL),
171 VAR("RendNodes", STRING, RendNodes, NULL),
172 VAR("RendPostPeriod", INTERVAL, RendPostPeriod, "20 minutes"),
173 VAR("RephistTrackTime", INTERVAL, RephistTrackTime, "24 hours"),
174 OBSOLETE("RouterFile"),
175 VAR("RunAsDaemon", BOOL, RunAsDaemon, "0"),
176 VAR("RunTesting", BOOL, RunTesting, "0"),
177 VAR("SafeLogging", BOOL, SafeLogging, "1"),
178 VAR("ShutdownWaitLength", INTERVAL, ShutdownWaitLength, "30 seconds"),
179 VAR("SocksBindAddress", LINELIST, SocksBindAddress, NULL),
180 VAR("SocksPolicy", LINELIST, SocksPolicy, NULL),
181 VAR("SocksPort", UINT, SocksPort, "9050"),
182 VAR("StatusFetchPeriod", INTERVAL, StatusFetchPeriod, "0 seconds"), /** DOCDOC */
183 VAR("StrictEntryNodes", BOOL, StrictEntryNodes, "0"),
184 VAR("StrictExitNodes", BOOL, StrictExitNodes, "0"),
185 VAR("SysLog", LINELIST_S, OldLogOptions, NULL),
186 VAR("TrackHostExits", CSV, TrackHostExits, NULL),
187 VAR("TrackHostExitsExpire",INTERVAL, TrackHostExitsExpire, "30 minutes"),
188 OBSOLETE("TrafficShaping"),
189 VAR("UseHelperNodes", BOOL, UseHelperNodes, "0"),
190 VAR("User", STRING, User, NULL),
191 VAR("__LeaveStreamsUnattached", BOOL,LeaveStreamsUnattached, "0"),
192 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL, NULL }
194 #undef VAR
196 #define VAR(name,conftype,member,initvalue) \
197 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), initvalue, NULL }
198 static config_var_t _state_vars[] = {
199 VAR("AccountingBytesReadInterval", MEMUNIT, AccountingBytesReadInInterval,NULL),
200 VAR("AccountingBytesWrittenInInterval", MEMUNIT,
201 AccountingBytesWrittenInInterval, NULL),
202 VAR("AccountingExpectedUsage", MEMUNIT, AccountingExpectedUsage, NULL),
203 VAR("AccountingIntervalStart", ISOTIME, AccountingIntervalStart, NULL),
204 VAR("AccountingSecondsActive", INTERVAL, AccountingSecondsActive, NULL),
205 VAR("HelperNode", LINELIST_S, HelperNodes, NULL),
206 VAR("HelperNodeDownSince", LINELIST_S, HelperNodes, NULL),
207 VAR("HelperNodeUnlistedSince", LINELIST_S, HelperNodes, NULL),
208 VAR("HelperNodes", LINELIST_V, HelperNodes, NULL),
209 VAR("LastWritten", ISOTIME, LastWritten, NULL),
211 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL, NULL }
214 #undef VAR
215 #undef OBSOLETE
217 /** DOCDOC*/
218 typedef struct config_var_description_t {
219 const char *name;
220 const char *description;
221 } config_var_description_t;
223 static config_var_description_t options_description[] = {
224 { "Address", "The advertised (external) address we should use." },
225 // { "AccountingStart", ""},
226 { NULL, NULL },
229 static config_var_description_t state_description[] = {
230 { "HelperNode", "One of the nodes we have chosen as a fixed entry" },
231 { "HelperNodeDownSince",
232 "The last helper node has been down since this time." },
233 { "HelperNodeUnlistedSince",
234 "The last helper node has been unlisted since this time." },
235 { NULL, NULL },
238 typedef int (*validate_fn_t)(void*);
240 typedef struct {
241 size_t size;
242 uint32_t magic;
243 off_t magic_offset;
244 config_abbrev_t *abbrevs;
245 config_var_t *vars;
246 validate_fn_t validate_fn;
247 config_var_description_t *descriptions;
248 } config_format_t;
250 #define CHECK(fmt, cfg) do { \
251 tor_assert(fmt && cfg); \
252 tor_assert((fmt)->magic == *(uint32_t*)(((char*)(cfg))+fmt->magic_offset)); \
253 } while (0)
255 /** Largest allowed config line */
256 #define CONFIG_LINE_T_MAXLEN 4096
258 static void config_line_append(config_line_t **lst,
259 const char *key, const char *val);
260 static void option_clear(config_format_t *fmt, or_options_t *options,
261 config_var_t *var);
262 static void option_reset(config_format_t *fmt, or_options_t *options,
263 config_var_t *var, int use_defaults);
264 static void config_free(config_format_t *fmt, void *options);
265 static int option_is_same(config_format_t *fmt,
266 or_options_t *o1, or_options_t *o2, const char *name);
267 static or_options_t *options_dup(config_format_t *fmt, or_options_t *old);
268 static int options_validate(or_options_t *options);
269 static int options_act(or_options_t *old_options);
270 static int options_transition_allowed(or_options_t *old, or_options_t *new);
271 static int options_transition_affects_workers(or_options_t *old_options,
272 or_options_t *new_options);
273 static int options_transition_affects_descriptor(or_options_t *old_options,
274 or_options_t *new_options);
275 static int check_nickname_list(const char *lst, const char *name);
276 static void config_register_addressmaps(or_options_t *options);
278 static int parse_dir_server_line(const char *line, int validate_only);
279 static int parse_redirect_line(smartlist_t *result,
280 config_line_t *line);
281 static int parse_log_severity_range(const char *range, int *min_out,
282 int *max_out);
283 static int convert_log_option(or_options_t *options,
284 config_line_t *level_opt,
285 config_line_t *file_opt, int isDaemon);
286 static int add_single_log_option(or_options_t *options, int minSeverity,
287 int maxSeverity,
288 const char *type, const char *fname);
289 static int normalize_log_options(or_options_t *options);
290 static int validate_data_directory(or_options_t *options);
291 static int write_configuration_file(const char *fname, or_options_t *options);
292 static config_line_t *get_assigned_option(config_format_t *fmt,
293 or_options_t *options, const char *key);
294 static void config_init(config_format_t *fmt, void *options);
295 static int or_state_validate(or_state_t *options);
297 static uint64_t config_parse_memunit(const char *s, int *ok);
298 static int config_parse_interval(const char *s, int *ok);
299 static void print_cvs_version(void);
300 static void parse_reachable_addresses(void);
301 static int init_libevent(void);
302 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
303 static void check_libevent_version(const char *m, const char *v, int server);
304 #endif
306 /*static*/ or_options_t *options_new(void);
308 #define OR_OPTIONS_MAGIC 9090909
310 static config_format_t options_format = {
311 sizeof(or_options_t),
312 OR_OPTIONS_MAGIC,
313 STRUCT_OFFSET(or_options_t, _magic),
314 _option_abbrevs,
315 _option_vars,
316 (validate_fn_t)options_validate,
317 options_description
320 #define OR_STATE_MAGIC 0x57A73f57
322 static config_format_t state_format = {
323 sizeof(or_state_t),
324 OR_STATE_MAGIC,
325 STRUCT_OFFSET(or_state_t, _magic),
326 NULL,
327 _state_vars,
328 (validate_fn_t)or_state_validate,
329 state_description
333 * Functions to read and write the global options pointer.
336 /** Command-line and config-file options. */
337 static or_options_t *global_options = NULL;
338 /** Name of most recently read torrc file. */
339 static char *torrc_fname = NULL;
340 /** Persistant serialized state. */
341 static or_state_t *global_state = NULL;
342 /** DOCDOC */
343 static addr_policy_t *reachable_addr_policy = NULL;
345 static void *
346 config_alloc(config_format_t *fmt)
348 void *opts = opts = tor_malloc_zero(fmt->size);
349 *(uint32_t*)(((char*)opts)+fmt->magic_offset) = fmt->magic;
350 CHECK(fmt, opts);
351 return opts;
354 /** Return the currently configured options. */
355 or_options_t *
356 get_options(void)
358 tor_assert(global_options);
359 return global_options;
362 /** Change the current global options to contain <b>new_val</b> instead of
363 * their current value; take action based on the new value; free the old value
364 * as necessary.
366 void
367 set_options(or_options_t *new_val)
369 or_options_t *old_options = global_options;
370 global_options = new_val;
371 /* Note that we pass the *old* options below, for comparison. It
372 * pulls the new options directly out of global_options. */
373 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
374 log_fn(LOG_ERR,"Acting on config options left us in a broken state. Dying.");
375 exit(1);
377 if (old_options)
378 config_free(&options_format, old_options);
381 void
382 config_free_all(void)
384 config_free(&options_format, global_options);
385 tor_free(torrc_fname);
386 addr_policy_free(reachable_addr_policy);
387 reachable_addr_policy = NULL;
390 /** If options->SafeLogging is on, return a not very useful string,
391 * else return address.
393 const char *
394 safe_str(const char *address)
396 if (get_options()->SafeLogging)
397 return "[scrubbed]";
398 else
399 return address;
402 /** Fetch the active option list, and take actions based on it. All of the
403 * things we do should survive being done repeatedly. If present,
404 * <b>old_options</b> contains the previous value of the options.
406 * Return 0 if all goes well, return -1 if it's time to die.
408 * Note 2: We haven't moved all the "act on new configuration" logic
409 * here yet. Some is still in do_hup() and other places.
411 static int
412 options_act(or_options_t *old_options)
414 config_line_t *cl;
415 char *fn;
416 size_t len;
417 or_options_t *options = get_options();
418 int running_tor = options->command == CMD_RUN_TOR;
419 static int libevent_initialized = 0;
421 if (running_tor && options->RunAsDaemon) {
422 start_daemon();
425 clear_trusted_dir_servers();
426 for (cl = options->DirServers; cl; cl = cl->next) {
427 if (parse_dir_server_line(cl->value, 0)<0) {
428 log_fn(LOG_ERR,
429 "Bug: Previously validated DirServer line could not be added!");
430 return -1;
434 if (running_tor && rend_config_services(options, 0)<0) {
435 log_fn(LOG_ERR,
436 "Bug: Previously validated hidden services line could not be added!");
437 return -1;
440 if (options->EntryNodes && strlen(options->EntryNodes))
441 options->UseHelperNodes = 0;
443 /* Setuid/setgid as appropriate */
444 if (options->User || options->Group) {
445 if (switch_id(options->User, options->Group) != 0) {
446 return -1;
450 /* Ensure data directory is private; create if possible. */
451 if (check_private_dir(options->DataDirectory, CPD_CREATE) != 0) {
452 log_fn(LOG_ERR, "Couldn't access/create private data directory \"%s\"",
453 options->DataDirectory);
454 return -1;
456 if (running_tor) {
457 len = strlen(options->DataDirectory)+32;
458 fn = tor_malloc(len);
459 tor_snprintf(fn, len, "%s/cached-status", options->DataDirectory);
460 if (check_private_dir(fn, CPD_CREATE) != 0) {
461 log_fn(LOG_ERR, "Couldn't access/create private data directory \"%s\"",
462 fn);
463 tor_free(fn);
464 return -1;
466 tor_free(fn);
469 /* Bail out at this point if we're not going to be a client or server:
470 * we want to not fork, and to log stuff to stderr. */
471 if (options->command != CMD_RUN_TOR)
472 return 0;
474 mark_logs_temp(); /* Close current logs once new logs are open. */
475 if (options_init_logs(options, 0)<0) /* Configure the log(s) */
476 return -1;
478 /* Close the temporary log we used while starting up, if it isn't already
479 * gone. */
480 close_temp_logs();
481 add_callback_log(LOG_ERR, LOG_ERR, control_event_logmsg);
482 control_adjust_event_log_severity();
484 /* Set up libevent. */
485 if (running_tor && !libevent_initialized) {
486 if (init_libevent())
487 return -1;
488 libevent_initialized = 1;
491 /* Load state */
492 if (! global_state)
493 if (or_state_load())
494 return -1;
496 options->_ConnLimit =
497 set_max_file_descriptors((unsigned)options->ConnLimit, MAXCONNECTIONS);
498 if (options->_ConnLimit < 0)
499 return -1;
502 smartlist_t *sl = smartlist_create();
503 for (cl = options->RedirectExit; cl; cl = cl->next) {
504 if (parse_redirect_line(sl, cl)<0)
505 return -1;
507 set_exit_redirects(sl);
510 /* Finish backgrounding the process */
511 if (running_tor && options->RunAsDaemon) {
512 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
513 finish_daemon(options->DataDirectory);
516 /* Write our pid to the pid file. If we do not have write permissions we
517 * will log a warning */
518 if (running_tor && options->PidFile)
519 write_pidfile(options->PidFile);
521 /* Register addressmap directives */
522 config_register_addressmaps(options);
524 /* Update address policies. */
525 parse_socks_policy();
526 parse_dir_policy();
527 parse_reachable_addresses();
529 init_cookie_authentication(options->CookieAuthentication);
531 /* reload keys as needed for rendezvous services. */
532 if (rend_service_load_keys()<0) {
533 log_fn(LOG_ERR,"Error loading rendezvous service keys");
534 return -1;
537 /* Set up accounting */
538 if (accounting_parse_options(options, 0)<0) {
539 log_fn(LOG_ERR,"Error in accounting options");
540 return -1;
542 if (accounting_is_enabled(options))
543 configure_accounting(time(NULL));
545 if (!running_tor)
546 return 0;
548 if (!we_are_hibernating() && retry_all_listeners(0) < 0) {
549 log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
550 return -1;
553 /* Check for transitions that need action. */
554 if (old_options) {
555 if (options_transition_affects_workers(old_options, options)) {
556 log_fn(LOG_INFO,"Worker-related options changed. Rotating workers.");
557 cpuworkers_rotate();
558 dnsworkers_rotate();
562 /* Since our options changed, we might need to regenerate and upload our
563 * server descriptor.
565 if (!old_options || options_transition_affects_descriptor(old_options, options))
566 mark_my_descriptor_dirty();
568 return 0;
572 * Functions to parse config options
575 /** If <b>option</b> is an official abbreviation for a longer option,
576 * return the longer option. Otherwise return <b>option</b>.
577 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
578 * apply abbreviations that work for the config file and the command line. */
579 static const char *
580 expand_abbrev(config_format_t *fmt, const char *option, int command_line)
582 int i;
583 if (! fmt->abbrevs)
584 return option;
585 for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
586 /* Abbreviations aren't casei. */
587 if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
588 (command_line || !fmt->abbrevs[i].commandline_only)) {
589 return fmt->abbrevs[i].full;
592 return option;
595 /** Helper: Read a list of configuration options from the command line.
596 * If successful, put them in *<b>result</b> and return 0, and return
597 * -1 and leave *<b>result</b> alone. */
598 static int
599 config_get_commandlines(int argc, char **argv, config_line_t **result)
601 config_line_t *front = NULL;
602 config_line_t **new = &front;
603 char *s;
604 int i = 1;
606 while (i < argc) {
607 if (!strcmp(argv[i],"-f") ||
608 !strcmp(argv[i],"--hash-password")) {
609 i += 2; /* command-line option with argument. ignore them. */
610 continue;
611 } else if (!strcmp(argv[i],"--list-fingerprint")) {
612 i += 1; /* command-line option. ignore it. */
613 continue;
614 } else if (!strcmp(argv[i],"--nt-service")) {
615 i += 1;
616 continue;
618 if (i == argc-1) {
619 log_fn(LOG_WARN,"Command-line option '%s' with no value. Failing.",
620 argv[i]);
621 config_free_lines(front);
622 return -1;
625 *new = tor_malloc_zero(sizeof(config_line_t));
626 s = argv[i];
628 while (*s == '-')
629 s++;
631 (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1));
632 (*new)->value = tor_strdup(argv[i+1]);
633 (*new)->next = NULL;
634 log(LOG_DEBUG,"Commandline: parsed keyword '%s', value '%s'",
635 (*new)->key, (*new)->value);
637 new = &((*new)->next);
638 i += 2;
640 *result = front;
641 return 0;
644 /** Helper: allocate a new configuration option mapping 'key' to 'val',
645 * append it to *<b>lst</b>. */
646 static void
647 config_line_append(config_line_t **lst,
648 const char *key,
649 const char *val)
651 config_line_t *newline;
653 newline = tor_malloc(sizeof(config_line_t));
654 newline->key = tor_strdup(key);
655 newline->value = tor_strdup(val);
656 newline->next = NULL;
657 while (*lst)
658 lst = &((*lst)->next);
660 (*lst) = newline;
663 /** Helper: parse the config string and strdup into key/value
664 * strings. Set *result to the list, or NULL if parsing the string
665 * failed. Return 0 on success, -1 on failure. Warn and ignore any
666 * misformatted lines. */
668 config_get_lines(char *string, config_line_t **result)
670 config_line_t *list = NULL, **next;
671 char *k, *v;
673 next = &list;
674 do {
675 string = parse_line_from_str(string, &k, &v);
676 if (!string) {
677 config_free_lines(list);
678 return -1;
680 if (k && v) {
681 /* This list can get long, so we keep a pointer to the end of it
682 * rather than using config_line_append over and over and getting n^2
683 * performance. This is the only really long list. */
684 *next = tor_malloc(sizeof(config_line_t));
685 (*next)->key = tor_strdup(k);
686 (*next)->value = tor_strdup(v);
687 (*next)->next = NULL;
688 next = &((*next)->next);
690 } while (*string);
692 *result = list;
693 return 0;
697 * Free all the configuration lines on the linked list <b>front</b>.
699 void
700 config_free_lines(config_line_t *front)
702 config_line_t *tmp;
704 while (front) {
705 tmp = front;
706 front = tmp->next;
708 tor_free(tmp->key);
709 tor_free(tmp->value);
710 tor_free(tmp);
714 /** DOCDOC */
715 static const char *
716 config_find_description(config_format_t *fmt, const char *name)
718 int i;
719 for (i=0; fmt->descriptions[i].name; ++i) {
720 if (!strcasecmp(name, fmt->descriptions[i].name))
721 return fmt->descriptions[i].description;
723 return NULL;
726 /** If <b>key</b> is a configuration option, return the corresponding
727 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
728 * warn, and return the corresponding config_var_t. Otherwise return NULL.
730 static config_var_t *
731 config_find_option(config_format_t *fmt, const char *key)
733 int i;
734 size_t keylen = strlen(key);
735 if (!keylen)
736 return NULL; /* if they say "--" on the commandline, it's not an option */
737 /* First, check for an exact (case-insensitive) match */
738 for (i=0; fmt->vars[i].name; ++i) {
739 if (!strcasecmp(key, fmt->vars[i].name)) {
740 return &fmt->vars[i];
743 /* If none, check for an abbreviated match */
744 for (i=0; fmt->vars[i].name; ++i) {
745 if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
746 log_fn(LOG_WARN, "The abbreviation '%s' is deprecated. "
747 "Please use '%s' instead",
748 key, fmt->vars[i].name);
749 return &fmt->vars[i];
752 /* Okay, unrecognized options */
753 return NULL;
757 * Functions to assign config options.
760 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
761 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
763 * Called from config_assign_line() and option_reset().
765 static int
766 config_assign_value(config_format_t *fmt, or_options_t *options,
767 config_line_t *c)
769 int i, ok;
770 config_var_t *var;
771 void *lvalue;
773 CHECK(fmt, options);
775 var = config_find_option(fmt, c->key);
776 tor_assert(var);
778 lvalue = ((char*)options) + var->var_offset;
780 switch (var->type) {
782 case CONFIG_TYPE_UINT:
783 i = tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
784 if (!ok) {
785 log(LOG_WARN, "Int keyword '%s %s' is malformed or out of bounds.",
786 c->key,c->value);
787 return -1;
789 *(int *)lvalue = i;
790 break;
792 case CONFIG_TYPE_INTERVAL: {
793 i = config_parse_interval(c->value, &ok);
794 if (!ok) {
795 return -1;
797 *(int *)lvalue = i;
798 break;
801 case CONFIG_TYPE_MEMUNIT: {
802 uint64_t u64 = config_parse_memunit(c->value, &ok);
803 if (!ok) {
804 return -1;
806 *(uint64_t *)lvalue = u64;
807 break;
810 case CONFIG_TYPE_BOOL:
811 i = tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
812 if (!ok) {
813 log(LOG_WARN, "Boolean keyword '%s' expects 0 or 1.", c->key);
814 return -1;
816 *(int *)lvalue = i;
817 break;
819 case CONFIG_TYPE_STRING:
820 tor_free(*(char **)lvalue);
821 *(char **)lvalue = tor_strdup(c->value);
822 break;
824 case CONFIG_TYPE_DOUBLE:
825 *(double *)lvalue = atof(c->value);
826 break;
828 case CONFIG_TYPE_ISOTIME:
829 if (parse_iso_time(c->value, (time_t *)lvalue)) {
830 log(LOG_WARN, "Invalid time '%s' for keyword '%s'", c->value, c->key);
831 return -1;
833 break;
835 case CONFIG_TYPE_CSV:
836 if (*(smartlist_t**)lvalue) {
837 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
838 smartlist_clear(*(smartlist_t**)lvalue);
839 } else {
840 *(smartlist_t**)lvalue = smartlist_create();
843 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
844 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
845 break;
847 case CONFIG_TYPE_LINELIST:
848 case CONFIG_TYPE_LINELIST_S:
849 config_line_append((config_line_t**)lvalue, c->key, c->value);
850 break;
852 case CONFIG_TYPE_OBSOLETE:
853 log_fn(LOG_WARN, "Skipping obsolete configuration option '%s'", c->key);
854 break;
855 case CONFIG_TYPE_LINELIST_V:
856 log_fn(LOG_WARN, "Can't provide value for virtual option '%s'", c->key);
857 return -1;
858 default:
859 tor_assert(0);
860 break;
862 return 0;
865 /** If <b>c</b> is a syntactically valid configuration line, update
866 * <b>options</b> with its value and return 0. Otherwise return -1 for bad key,
867 * -2 for bad value.
869 * If <b>clear_first</b> is set, clear the value first. Then if
870 * <b>use_defaults</b> is set, set the value to the default.
872 * Called from config_assign().
874 static int
875 config_assign_line(config_format_t *fmt, or_options_t *options,
876 config_line_t *c, int use_defaults, int clear_first)
878 config_var_t *var;
880 CHECK(fmt, options);
882 var = config_find_option(fmt, c->key);
883 if (!var) {
884 log_fn(LOG_WARN, "Unknown option '%s'. Failing.", c->key);
885 return -1;
887 /* Put keyword into canonical case. */
888 if (strcmp(var->name, c->key)) {
889 tor_free(c->key);
890 c->key = tor_strdup(var->name);
893 if (!strlen(c->value)) { /* reset or clear it, then return */
894 option_reset(fmt, options, var, use_defaults);
895 return 0;
898 if (config_assign_value(fmt, options, c) < 0)
899 return -2;
900 return 0;
903 /** Restore the option named <b>key</b> in options to its default value.
904 * Called from config_assign(). */
905 static void
906 config_reset_line(config_format_t *fmt, or_options_t *options,
907 const char *key, int use_defaults)
909 config_var_t *var;
911 CHECK(fmt, options);
913 var = config_find_option(fmt, key);
914 if (!var)
915 return; /* give error on next pass. */
917 option_reset(fmt, options, var, use_defaults);
920 /** Return true iff key is a valid configuration option. */
922 option_is_recognized(const char *key)
924 config_var_t *var = config_find_option(&options_format, key);
925 return (var != NULL);
928 /** Return the canonical name of a configuration option. */
929 const char *
930 option_get_canonical_name(const char *key)
932 config_var_t *var = config_find_option(&options_format, key);
933 return var->name;
936 /** Return a canonicalized list of the options assigned for key.
938 config_line_t *
939 option_get_assignment(or_options_t *options, const char *key)
941 return get_assigned_option(&options_format, options, key);
944 static config_line_t *
945 config_lines_dup(const config_line_t *inp)
947 config_line_t *result = NULL;
948 config_line_t **next_out = &result;
949 while (inp) {
950 *next_out = tor_malloc(sizeof(config_line_t));
951 (*next_out)->key = tor_strdup(inp->key);
952 (*next_out)->value = tor_strdup(inp->value);
953 inp = inp->next;
954 next_out = &((*next_out)->next);
956 (*next_out) = NULL;
957 return result;
960 static config_line_t *
961 get_assigned_option(config_format_t *fmt, or_options_t *options, const char *key)
963 config_var_t *var;
964 const void *value;
965 char buf[32];
966 config_line_t *result;
967 tor_assert(options && key);
969 CHECK(fmt, options);
971 var = config_find_option(fmt, key);
972 if (!var) {
973 log_fn(LOG_WARN, "Unknown option '%s'. Failing.", key);
974 return NULL;
975 } else if (var->type == CONFIG_TYPE_LINELIST_S) {
976 log_fn(LOG_WARN, "Can't return context-sensitive '%s' on its own", key);
977 return NULL;
979 value = ((char*)options) + var->var_offset;
981 if (var->type == CONFIG_TYPE_LINELIST ||
982 var->type == CONFIG_TYPE_LINELIST_V) {
983 /* Linelist requires special handling: we just copy and return it. */
984 return config_lines_dup(*(const config_line_t**)value);
987 result = tor_malloc_zero(sizeof(config_line_t));
988 result->key = tor_strdup(var->name);
989 switch (var->type)
991 case CONFIG_TYPE_STRING:
992 if (*(char**)value) {
993 result->value = tor_strdup(*(char**)value);
994 } else {
995 tor_free(result->key);
996 tor_free(result);
997 return NULL;
999 break;
1000 case CONFIG_TYPE_ISOTIME:
1001 if (*(time_t*)value) {
1002 result->value = tor_malloc(ISO_TIME_LEN+1);
1003 format_iso_time(result->value, *(time_t*)value);
1004 } else {
1005 tor_free(result->key);
1006 tor_free(result);
1008 break;
1009 case CONFIG_TYPE_INTERVAL:
1010 case CONFIG_TYPE_UINT:
1011 /* This means every or_options_t uint or bool element
1012 * needs to be an int. Not, say, a uint16_t or char. */
1013 tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
1014 result->value = tor_strdup(buf);
1015 break;
1016 case CONFIG_TYPE_MEMUNIT:
1017 tor_snprintf(buf, sizeof(buf), U64_FORMAT,
1018 U64_PRINTF_ARG(*(uint64_t*)value));
1019 result->value = tor_strdup(buf);
1020 break;
1021 case CONFIG_TYPE_DOUBLE:
1022 tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
1023 result->value = tor_strdup(buf);
1024 break;
1025 case CONFIG_TYPE_BOOL:
1026 result->value = tor_strdup(*(int*)value ? "1" : "0");
1027 break;
1028 case CONFIG_TYPE_CSV:
1029 if (*(smartlist_t**)value)
1030 result->value = smartlist_join_strings(*(smartlist_t**)value,",",0,NULL);
1031 else
1032 result->value = tor_strdup("");
1033 break;
1034 case CONFIG_TYPE_OBSOLETE:
1035 log_fn(LOG_WARN,"You asked me for the value of an obsolete config option '%s'.", key);
1036 tor_free(result->key);
1037 tor_free(result);
1038 return NULL;
1039 default:
1040 tor_free(result->key);
1041 tor_free(result);
1042 log_fn(LOG_WARN,"Bug: unknown type %d for known key '%s'", var->type, key);
1043 return NULL;
1046 return result;
1049 /** Iterate through the linked list of requested options <b>list</b>.
1050 * For each item, convert as appropriate and assign to <b>options</b>.
1051 * If an item is unrecognized, return -1 immediately,
1052 * else return 0 for success.
1054 * If <b>clear_first</b>, interpret config options as replacing (not
1055 * extending) their previous values. If <b>clear_first</b> is set,
1056 * then <b>use_defaults</b> to decide if you set to defaults after
1057 * clearing, or make the value 0 or NULL.
1059 * Here are the use cases:
1060 * 1. A non-empty AllowUnverified line in your torrc. Appends to current
1061 * if linelist, replaces current if csv.
1062 * 2. An empty AllowUnverified line in your torrc. Should clear it.
1063 * 3. "RESETCONF AllowUnverified" sets it to default.
1064 * 4. "SETCONF AllowUnverified" makes it NULL.
1065 * 5. "SETCONF AllowUnverified=foo" clears it and sets it to "foo".
1067 * Use_defaults Clear_first
1068 * 0 0 "append"
1069 * 1 0 undefined, don't use
1070 * 0 1 "set to null first"
1071 * 1 1 "set to defaults first"
1072 * Return 0 on success, -1 on bad key, -2 on bad value.
1076 There are three call cases for config_assign() currently.
1078 Case one: Torrc entry
1079 options_init_from_torrc() calls config_assign(0, 0)
1080 calls config_assign_line(0, 0).
1081 if value is empty, calls option_reset(0) and returns.
1082 calls config_assign_value(), appends.
1084 Case two: setconf
1085 options_trial_assign() calls config_assign(0, 1)
1086 calls config_reset_line(0)
1087 calls option_reset(0)
1088 calls option_clear().
1089 calls config_assign_line(0, 1).
1090 if value is empty, calls option_reset(0) and returns.
1091 calls config_assign_value(), appends.
1093 Case three: resetconf
1094 options_trial_assign() calls config_assign(1, 1)
1095 calls config_reset_line(1)
1096 calls option_reset(1)
1097 calls option_clear().
1098 calls config_assign_value(default)
1099 calls config_assign_line(1, 1).
1100 calls option_reset(1) and returns.
1102 static int
1103 config_assign(config_format_t *fmt, void *options,
1104 config_line_t *list, int use_defaults, int clear_first)
1106 config_line_t *p;
1108 CHECK(fmt, options);
1110 /* pass 1: normalize keys */
1111 for (p = list; p; p = p->next) {
1112 const char *full = expand_abbrev(fmt, p->key, 0);
1113 if (strcmp(full,p->key)) {
1114 tor_free(p->key);
1115 p->key = tor_strdup(full);
1119 /* pass 2: if we're reading from a resetting source, clear all
1120 * mentioned config options, and maybe set to their defaults. */
1121 if (clear_first) {
1122 for (p = list; p; p = p->next)
1123 config_reset_line(fmt, options, p->key, use_defaults);
1126 /* pass 3: assign. */
1127 while (list) {
1128 int r;
1129 if ((r=config_assign_line(fmt, options, list, use_defaults, clear_first)))
1130 return r;
1131 list = list->next;
1133 return 0;
1136 /** Try assigning <b>list</b> to the global options. You do this by duping
1137 * options, assigning list to the new one, then validating it. If it's
1138 * ok, then throw out the old one and stick with the new one. Else,
1139 * revert to old and return failure. Return 0 on success, -1 on bad
1140 * keys, -2 on bad values, -3 on bad transition.
1143 options_trial_assign(config_line_t *list, int use_defaults, int clear_first)
1145 int r;
1146 or_options_t *trial_options = options_dup(&options_format, get_options());
1148 if ((r=config_assign(&options_format, trial_options,
1149 list, use_defaults, clear_first)) < 0) {
1150 config_free(&options_format, trial_options);
1151 return r;
1154 if (options_validate(trial_options) < 0) {
1155 config_free(&options_format, trial_options);
1156 return -2;
1159 if (options_transition_allowed(get_options(), trial_options) < 0) {
1160 config_free(&options_format, trial_options);
1161 return -3;
1164 set_options(trial_options); /* we liked it. put it in place. */
1165 return 0;
1168 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
1169 * Called from option_reset() and config_free(). */
1170 static void
1171 option_clear(config_format_t *fmt, or_options_t *options, config_var_t *var)
1173 void *lvalue = ((char*)options) + var->var_offset;
1174 switch (var->type) {
1175 case CONFIG_TYPE_STRING:
1176 tor_free(*(char**)lvalue);
1177 break;
1178 case CONFIG_TYPE_DOUBLE:
1179 *(double*)lvalue = 0.0;
1180 break;
1181 case CONFIG_TYPE_ISOTIME:
1182 *(time_t*)lvalue = 0;
1183 case CONFIG_TYPE_INTERVAL:
1184 case CONFIG_TYPE_UINT:
1185 case CONFIG_TYPE_BOOL:
1186 *(int*)lvalue = 0;
1187 break;
1188 case CONFIG_TYPE_MEMUNIT:
1189 *(uint64_t*)lvalue = 0;
1190 break;
1191 case CONFIG_TYPE_CSV:
1192 if (*(smartlist_t**)lvalue) {
1193 SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
1194 smartlist_free(*(smartlist_t **)lvalue);
1195 *(smartlist_t **)lvalue = NULL;
1197 break;
1198 case CONFIG_TYPE_LINELIST:
1199 case CONFIG_TYPE_LINELIST_S:
1200 config_free_lines(*(config_line_t **)lvalue);
1201 *(config_line_t **)lvalue = NULL;
1202 break;
1203 case CONFIG_TYPE_LINELIST_V:
1204 /* handled by linelist_s. */
1205 break;
1206 case CONFIG_TYPE_OBSOLETE:
1207 break;
1211 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
1212 * <b>use_defaults</b>, set it to its default value.
1213 * Called by config_init() and option_reset_line() and option_assign_line(). */
1214 static void
1215 option_reset(config_format_t *fmt, or_options_t *options,
1216 config_var_t *var, int use_defaults)
1218 config_line_t *c;
1219 void *lvalue;
1220 CHECK(fmt, options);
1221 option_clear(fmt, options, var); /* clear it first */
1222 if (!use_defaults)
1223 return; /* all done */
1224 lvalue = ((char*)options) + var->var_offset;
1225 if (var->initvalue) {
1226 c = tor_malloc_zero(sizeof(config_line_t));
1227 c->key = tor_strdup(var->name);
1228 c->value = tor_strdup(var->initvalue);
1229 config_assign_value(fmt, options, c);
1230 config_free_lines(c);
1234 /** Set <b>options</b>-&gt;DirServers to contain the default directory
1235 * servers. */
1236 static void
1237 add_default_trusted_dirservers(or_options_t *options)
1239 /* moria1 */
1240 config_line_append(&options->DirServers, "DirServer",
1241 "v1 18.244.0.188:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441");
1242 /* moria2 */
1243 config_line_append(&options->DirServers, "DirServer",
1244 "v1 18.244.0.114:80 719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF");
1245 /* tor26 */
1246 config_line_append(&options->DirServers, "DirServer",
1247 "v1 86.59.5.130:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D");
1248 // "tor.noreply.org:9030 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D");
1251 /** Print a usage message for tor. */
1252 static void
1253 print_usage(void)
1255 printf(
1256 "Copyright 2001-2005 Roger Dingledine, Nick Mathewson.\n\n"
1257 "tor -f <torrc> [args]\n"
1258 "See man page for options, or http://tor.eff.org/ for documentation.\n");
1262 * Based on <b>options-\>Address</b>, guess our public IP address and put it
1263 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided, set
1264 * *<b>hostname_out</b> to a new string holding the hostname we used to get
1265 * the address. Return 0 if all is well, or -1 if we can't find a suitable
1266 * public IP address.
1269 resolve_my_address(or_options_t *options, uint32_t *addr_out, char **hostname_out)
1271 struct in_addr in;
1272 struct hostent *rent;
1273 char hostname[256];
1274 int explicit_ip=1;
1275 char tmpbuf[INET_NTOA_BUF_LEN];
1276 static uint32_t old_addr=0;
1277 const char *address = options->Address;
1279 tor_assert(addr_out);
1281 if (address && *address) {
1282 strlcpy(hostname, address, sizeof(hostname));
1283 } else { /* then we need to guess our address */
1284 explicit_ip = 0; /* it's implicit */
1286 if (gethostname(hostname, sizeof(hostname)) < 0) {
1287 log_fn(LOG_WARN,"Error obtaining local hostname");
1288 return -1;
1290 log_fn(LOG_DEBUG,"Guessed local host name as '%s'",hostname);
1293 /* now we know hostname. resolve it and keep only the IP */
1295 if (tor_inet_aton(hostname, &in) == 0) {
1296 /* then we have to resolve it */
1297 explicit_ip = 0;
1298 rent = (struct hostent *)gethostbyname(hostname);
1299 if (!rent) {
1300 log_fn(LOG_WARN,"Could not resolve local Address '%s'. Failing.", hostname);
1301 return -1;
1303 tor_assert(rent->h_length == 4);
1304 memcpy(&in.s_addr, rent->h_addr, rent->h_length);
1307 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
1308 if (is_internal_IP(htonl(in.s_addr)) && !options->NoPublish) {
1309 /* make sure we're ok with publishing an internal IP */
1310 if (!options->DirServers) {
1311 /* if they are using the default dirservers, disallow internal IPs always. */
1312 log_fn(LOG_WARN,"Address '%s' resolves to private IP '%s'. "
1313 "Tor servers that use the default DirServers must have public IP addresses.",
1314 hostname, tmpbuf);
1315 return -1;
1317 if (!explicit_ip) {
1318 /* even if they've set their own dirservers, require an explicit IP if
1319 * they're using an internal address. */
1320 log_fn(LOG_WARN,"Address '%s' resolves to private IP '%s'. "
1321 "Please set the Address config option to be the IP you want to use.",
1322 hostname, tmpbuf);
1323 return -1;
1327 log_fn(LOG_DEBUG, "Resolved Address to '%s'.", tmpbuf);
1328 *addr_out = ntohl(in.s_addr);
1329 if (old_addr && old_addr != *addr_out) {
1330 log_fn(LOG_NOTICE,"Your IP seems to have changed. Updating.");
1331 server_has_changed_ip();
1333 old_addr = *addr_out;
1334 if (hostname_out)
1335 *hostname_out = tor_strdup(hostname);
1336 return 0;
1339 /** Called when we don't have a nickname set. Try to guess a good
1340 * nickname based on the hostname, and return it in a newly allocated string. */
1341 static char *
1342 get_default_nickname(void)
1344 char localhostname[256];
1345 char *cp, *out, *outp;
1347 if (gethostname(localhostname, sizeof(localhostname)) < 0) {
1348 log_fn(LOG_WARN,"Error obtaining local hostname");
1349 return NULL;
1352 /* Put it in lowercase; stop at the first dot. */
1353 for (cp = localhostname; *cp; ++cp) {
1354 if (*cp == '.') {
1355 *cp = '\0';
1356 break;
1358 *cp = tolower(*cp);
1361 /* Strip invalid characters. */
1362 cp = localhostname;
1363 out = outp = tor_malloc(strlen(localhostname) + 1);
1364 while (*cp) {
1365 if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
1366 *outp++ = *cp++;
1367 else
1368 cp++;
1370 *outp = '\0';
1372 /* Enforce length. */
1373 if (strlen(out) > MAX_NICKNAME_LEN)
1374 out[MAX_NICKNAME_LEN]='\0';
1376 return out;
1379 /** Release storage held by <b>options</b> */
1380 static void
1381 config_free(config_format_t *fmt, void *options)
1383 int i;
1385 tor_assert(options);
1387 for (i=0; fmt->vars[i].name; ++i)
1388 option_clear(fmt, options, &(fmt->vars[i]));
1389 tor_free(options);
1392 /** Return true iff a and b contain identical keys and values in identical
1393 * order. */
1394 static int
1395 config_lines_eq(config_line_t *a, config_line_t *b)
1397 while (a && b) {
1398 if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
1399 return 0;
1400 a = a->next;
1401 b = b->next;
1403 if (a || b)
1404 return 0;
1405 return 1;
1408 /** Return true iff the option <b>var</b> has the same value in <b>o1</b>
1409 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
1411 static int
1412 option_is_same(config_format_t *fmt,
1413 or_options_t *o1, or_options_t *o2, const char *name)
1415 config_line_t *c1, *c2;
1416 int r = 1;
1417 CHECK(fmt, o1);
1418 CHECK(fmt, o2);
1420 c1 = get_assigned_option(fmt, o1, name);
1421 c2 = get_assigned_option(fmt, o2, name);
1422 r = config_lines_eq(c1, c2);
1423 config_free_lines(c1);
1424 config_free_lines(c2);
1425 return r;
1428 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
1429 static or_options_t *
1430 options_dup(config_format_t *fmt, or_options_t *old)
1432 or_options_t *newopts;
1433 int i;
1434 config_line_t *line;
1436 newopts = config_alloc(fmt);
1437 for (i=0; fmt->vars[i].name; ++i) {
1438 if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
1439 continue;
1440 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
1441 continue;
1442 line = get_assigned_option(fmt, old, fmt->vars[i].name);
1443 if (line) {
1444 if (config_assign(fmt, newopts, line, 0, 0) < 0) {
1445 log_fn(LOG_WARN,"Bug: config_get_assigned_option() generated "
1446 "something we couldn't config_assign().");
1447 tor_assert(0);
1450 config_free_lines(line);
1452 return newopts;
1455 /** Return a new empty or_options_t. Used for testing. */
1456 or_options_t *
1457 options_new(void)
1459 return config_alloc(&options_format);
1462 /** Set <b>options</b> to hold reasonable defaults for most options.
1463 * Each option defaults to zero. */
1464 void
1465 options_init(or_options_t *options)
1467 config_init(&options_format, options);
1470 /* DOCDOC */
1471 static void
1472 config_init(config_format_t *fmt, void *options)
1474 int i;
1475 config_var_t *var;
1476 CHECK(fmt, options);
1478 for (i=0; fmt->vars[i].name; ++i) {
1479 var = &fmt->vars[i];
1480 if (!var->initvalue)
1481 continue; /* defaults to NULL or 0 */
1482 option_reset(fmt, options, var, 1);
1486 /* DOCDOC */
1487 static char *
1488 config_dump(config_format_t *fmt, void *options, int minimal)
1490 smartlist_t *elements;
1491 or_options_t *defaults;
1492 config_line_t *line;
1493 char *result;
1494 int i;
1495 const char *desc;
1497 defaults = config_alloc(fmt);
1498 config_init(fmt, defaults);
1499 fmt->validate_fn(defaults);
1501 elements = smartlist_create();
1502 for (i=0; fmt->vars[i].name; ++i) {
1503 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
1504 fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
1505 continue;
1506 /* Don't save 'hidden' control variables. */
1507 if (!strcmpstart(fmt->vars[i].name, "__"))
1508 continue;
1509 if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
1510 continue;
1512 desc = config_find_description(fmt, fmt->vars[i].name);
1513 if (desc) {
1514 size_t len = strlen(desc)+8;
1515 char *tmp = tor_malloc(len);
1516 tor_snprintf(tmp, len, "# %s\n",desc);
1517 smartlist_add(elements, tmp);
1520 line = get_assigned_option(fmt, options, fmt->vars[i].name);
1521 for (; line; line = line->next) {
1522 size_t len = strlen(line->key) + strlen(line->value) + 3;
1523 char *tmp;
1524 tmp = tor_malloc(len);
1525 if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
1526 log_fn(LOG_ERR, "Internal error writing log option");
1527 tor_assert(0);
1529 smartlist_add(elements, tmp);
1531 config_free_lines(line);
1534 result = smartlist_join_strings(elements, "", 0, NULL);
1535 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
1536 smartlist_free(elements);
1537 return result;
1540 /** Return a string containing a possible configuration file that would give
1541 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
1542 * include options that are the same as Tor's defaults.
1544 char *
1545 options_dump(or_options_t *options, int minimal)
1547 return config_dump(&options_format, options, minimal);
1550 /* Return 0 if every element of sl is a string holding a decimal
1551 * representation of a port number, or if sl is NULL.
1552 * Otherwise return -1. */
1553 static int
1554 validate_ports_csv(smartlist_t *sl, const char *name)
1556 int i;
1557 int result = 0;
1558 tor_assert(name);
1560 if (!sl)
1561 return 0;
1563 SMARTLIST_FOREACH(sl, const char *, cp,
1565 i = atoi(cp);
1566 if (i < 1 || i > 65535) {
1567 log(LOG_WARN, "Port '%s' out of range in %s", cp, name);
1568 result=-1;
1571 return result;
1574 /** DOCDOC */
1575 static void
1576 parse_reachable_addresses(void)
1578 or_options_t *options = get_options();
1580 addr_policy_free(reachable_addr_policy);
1581 reachable_addr_policy = NULL;
1583 if (config_parse_addr_policy(options->ReachableAddresses,
1584 &reachable_addr_policy,
1585 ADDR_POLICY_ACCEPT)) {
1586 log_fn(LOG_WARN, "Error in ReachableAddresses entry; ignoring.");
1587 return;
1591 /** Return true iff the firewall options might block any address:port
1592 * combination
1595 firewall_is_fascist(void)
1597 return reachable_addr_policy ? 1 : 0;
1600 /** Return true iff we are configured to think that the local fascist
1601 * firewall (if any) will allow a connection to <b>addr</b>:<b>port</b> */
1603 fascist_firewall_allows_address(uint32_t addr, uint16_t port)
1605 addr_policy_result_t p = router_compare_addr_to_addr_policy(
1606 addr, port, reachable_addr_policy);
1608 switch (p) {
1609 case ADDR_POLICY_PROBABLY_ACCEPTED:
1610 case ADDR_POLICY_ACCEPTED:
1611 return 1;
1612 case ADDR_POLICY_PROBABLY_REJECTED:
1613 case ADDR_POLICY_REJECTED:
1614 return 0;
1615 default:
1616 log_fn(LOG_WARN, "Unexpected result: %d", (int)p);
1617 return 0;
1621 /** Return 0 if every setting in <b>options</b> is reasonable. Else
1622 * warn and return -1. Should have no side effects, except for
1623 * normalizing the contents of <b>options</b>. */
1624 static int
1625 options_validate(or_options_t *options)
1627 int result = 0;
1628 config_line_t *cl;
1629 addr_policy_t *addr_policy=NULL;
1631 if (options->ORPort < 0 || options->ORPort > 65535) {
1632 log(LOG_WARN, "ORPort option out of bounds.");
1633 result = -1;
1636 if (options->ORPort == 0 && options->ORBindAddress != NULL) {
1637 log(LOG_WARN, "ORPort must be defined if ORBindAddress is defined.");
1638 result = -1;
1640 if (options->DirPort == 0 && options->DirBindAddress != NULL) {
1641 log(LOG_WARN, "DirPort must be defined if DirBindAddress is defined.");
1642 result = -1;
1644 if (options->SocksPort == 0 && options->SocksBindAddress != NULL) {
1645 log(LOG_WARN, "SocksPort must be defined if SocksBindAddress is defined.");
1646 result = -1;
1649 if (validate_data_directory(options)<0) {
1650 log(LOG_WARN, "Invalid DataDirectory");
1651 result = -1;
1654 if (options->Nickname == NULL) {
1655 if (server_mode(options)) {
1656 if (!(options->Nickname = get_default_nickname()))
1657 return -1;
1658 log_fn(LOG_NOTICE, "Choosing default nickname '%s'", options->Nickname);
1660 } else {
1661 if (!is_legal_nickname(options->Nickname)) {
1662 log_fn(LOG_WARN, "Nickname '%s' is wrong length or contains illegal characters.", options->Nickname);
1663 result = -1;
1667 if (server_mode(options) && !options->ContactInfo)
1668 log_fn(LOG_NOTICE,"Your ContactInfo config option is not set. Please consider setting it, so we can contact you if your server is misconfigured or something else goes wrong.");
1670 if (normalize_log_options(options))
1671 return -1;
1673 /* Special case if no options are given. */
1674 if (!options->Logs) {
1675 config_line_append(&options->Logs, "Log", "notice stdout");
1678 if (options_init_logs(options, 1)<0) /* Validate the log(s) */
1679 return -1;
1681 if (server_mode(options)) {
1682 /* confirm that our address isn't broken, so we can complain now */
1683 uint32_t tmp;
1684 if (resolve_my_address(options, &tmp, NULL) < 0)
1685 result = -1;
1688 if (options->SocksPort < 0 || options->SocksPort > 65535) {
1689 log(LOG_WARN, "SocksPort option out of bounds.");
1690 result = -1;
1693 if (options->SocksPort == 0 && options->ORPort == 0) {
1694 log(LOG_WARN, "SocksPort and ORPort are both undefined? Quitting.");
1695 result = -1;
1698 if (options->ControlPort < 0 || options->ControlPort > 65535) {
1699 log(LOG_WARN, "ControlPort option out of bounds.");
1700 result = -1;
1703 if (options->DirPort < 0 || options->DirPort > 65535) {
1704 log(LOG_WARN, "DirPort option out of bounds.");
1705 result = -1;
1708 if (options->StrictExitNodes &&
1709 (!options->ExitNodes || !strlen(options->ExitNodes))) {
1710 log(LOG_WARN, "StrictExitNodes set, but no ExitNodes listed.");
1713 if (options->StrictEntryNodes &&
1714 (!options->EntryNodes || !strlen(options->EntryNodes))) {
1715 log(LOG_WARN, "StrictEntryNodes set, but no EntryNodes listed.");
1718 if (options->AuthoritativeDir) {
1719 if (!options->ContactInfo) {
1720 log(LOG_WARN, "Authoritative directory servers must set ContactInfo");
1721 result = -1;
1723 if (!options->RecommendedVersions) {
1724 log(LOG_WARN, "Authoritative directory servers must configure RecommendedVersions.");
1725 result = -1;
1727 if (!options->RecommendedClientVersions)
1728 options->RecommendedClientVersions =
1729 config_lines_dup(options->RecommendedVersions);
1730 if (!options->RecommendedServerVersions)
1731 options->RecommendedServerVersions =
1732 config_lines_dup(options->RecommendedVersions);
1735 if (options->AuthoritativeDir && !options->DirPort) {
1736 log(LOG_WARN, "Running as authoritative directory, but no DirPort set.");
1737 result = -1;
1740 if (options->AuthoritativeDir && !options->ORPort) {
1741 log(LOG_WARN, "Running as authoritative directory, but no ORPort set.");
1742 result = -1;
1745 if (options->AuthoritativeDir && options->ClientOnly) {
1746 log(LOG_WARN, "Running as authoritative directory, but ClientOnly also set.");
1747 result = -1;
1750 if (options->AuthoritativeDir && options->NoPublish) {
1751 log(LOG_WARN, "You cannot set both AuthoritativeDir and NoPublish.");
1752 result = -1;
1755 if (options->ConnLimit <= 0) {
1756 log(LOG_WARN, "ConnLimit must be greater than 0, but was set to %d",
1757 options->ConnLimit);
1758 result = -1;
1761 if (options->_AccountingMaxKB) {
1762 log(LOG_WARN, "AccountingMaxKB is deprecated. Say 'AccountingMax %d KB' instead.", options->_AccountingMaxKB);
1763 options->AccountingMax = U64_LITERAL(1024)*options->_AccountingMaxKB;
1764 options->_AccountingMaxKB = 0;
1767 if (validate_ports_csv(options->FirewallPorts,
1768 "FirewallPorts") < 0)
1769 result = -1;
1771 if (validate_ports_csv(options->LongLivedPorts,
1772 "LongLivedPorts") < 0)
1773 result = -1;
1775 if (options->FascistFirewall) {
1776 smartlist_t *instead = smartlist_create();
1777 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
1778 new_line->key = tor_strdup("ReachableAddresses");
1779 /* If we're configured with the old format, we need to prepend some
1780 * open ports. */
1781 if (!smartlist_len(options->FirewallPorts)) {
1782 smartlist_add(options->FirewallPorts, tor_strdup("80"));
1783 smartlist_add(options->FirewallPorts, tor_strdup("443"));
1785 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
1787 int p = atoi(portno);
1788 char *s;
1789 if (p<0) continue;
1790 s = tor_malloc(16);
1791 tor_snprintf(s, 16, "*:%d", p);
1792 smartlist_add(instead, s);
1794 new_line->value = smartlist_join_strings(instead,",",0,NULL);
1795 /* These have been deprecated since 0.1.1.5-alpha-cvs */
1796 log_fn(LOG_WARN, "FascistFirewall and FirewallPorts are deprecated. Instead, use \"ReachableAddresses %s\"", new_line->value);
1797 new_line->next = options->ReachableAddresses;
1798 options->ReachableAddresses = new_line;
1799 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
1800 smartlist_free(instead);
1803 if (options->FascistFirewall || options->ReachableAddresses) {
1804 /* We need to end with a reject *:*, not an implicit accept *:* */
1805 config_line_t **linep = &options->ReachableAddresses;
1806 while (*linep) {
1807 linep = &((*linep)->next);
1809 *linep = tor_malloc_zero(sizeof(config_line_t));
1810 (*linep)->key = tor_strdup("ReachableAddresses");
1811 (*linep)->value = tor_strdup("reject *:*");
1814 options->_AllowUnverified = 0;
1815 if (options->AllowUnverifiedNodes) {
1816 SMARTLIST_FOREACH(options->AllowUnverifiedNodes, const char *, cp, {
1817 if (!strcasecmp(cp, "entry"))
1818 options->_AllowUnverified |= ALLOW_UNVERIFIED_ENTRY;
1819 else if (!strcasecmp(cp, "exit"))
1820 options->_AllowUnverified |= ALLOW_UNVERIFIED_EXIT;
1821 else if (!strcasecmp(cp, "middle"))
1822 options->_AllowUnverified |= ALLOW_UNVERIFIED_MIDDLE;
1823 else if (!strcasecmp(cp, "introduction"))
1824 options->_AllowUnverified |= ALLOW_UNVERIFIED_INTRODUCTION;
1825 else if (!strcasecmp(cp, "rendezvous"))
1826 options->_AllowUnverified |= ALLOW_UNVERIFIED_RENDEZVOUS;
1827 else {
1828 log(LOG_WARN, "Unrecognized value '%s' in AllowUnverifiedNodes",
1829 cp);
1830 result = -1;
1835 if (options->SocksPort >= 1 &&
1836 (options->PathlenCoinWeight < 0.0 || options->PathlenCoinWeight >= 1.0)) {
1837 log(LOG_WARN, "PathlenCoinWeight option must be >=0.0 and <1.0.");
1838 result = -1;
1841 #define MIN_DIR_FETCH_PERIOD 600
1842 #define MIN_REND_POST_PERIOD 300
1843 #define MIN_STATUS_FETCH_PERIOD 60
1845 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
1846 #define MAX_CACHE_DIR_FETCH_PERIOD 3600
1847 #define MAX_CACHE_STATUS_FETCH_PERIOD 900
1849 if (options->DirFetchPeriod &&
1850 options->DirFetchPeriod < MIN_DIR_FETCH_PERIOD) {
1851 log(LOG_WARN, "DirFetchPeriod option must be at least %d seconds. Clipping.", MIN_DIR_FETCH_PERIOD);
1852 options->DirFetchPeriod = MIN_DIR_FETCH_PERIOD;
1854 if (options->StatusFetchPeriod &&
1855 options->StatusFetchPeriod < MIN_STATUS_FETCH_PERIOD) {
1856 log(LOG_WARN, "StatusFetchPeriod option must be at least %d seconds. Clipping.", MIN_STATUS_FETCH_PERIOD);
1857 options->StatusFetchPeriod = MIN_STATUS_FETCH_PERIOD;
1859 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
1860 log(LOG_WARN,"RendPostPeriod option must be at least %d seconds. Clipping.",
1861 MIN_REND_POST_PERIOD);
1862 options->RendPostPeriod = MIN_REND_POST_PERIOD;
1865 if (options->DirPort && ! options->AuthoritativeDir) {
1866 if (options->DirFetchPeriod > MAX_CACHE_DIR_FETCH_PERIOD) {
1867 log(LOG_WARN, "Caching directory servers must have DirFetchPeriod less than %d seconds. Clipping.", MAX_CACHE_DIR_FETCH_PERIOD);
1868 options->DirFetchPeriod = MAX_CACHE_DIR_FETCH_PERIOD;
1870 if (options->StatusFetchPeriod > MAX_CACHE_STATUS_FETCH_PERIOD) {
1871 log(LOG_WARN, "Caching directory servers must have StatusFetchPeriod less than %d seconds. Clipping.", MAX_CACHE_STATUS_FETCH_PERIOD);
1872 options->StatusFetchPeriod = MAX_CACHE_STATUS_FETCH_PERIOD;
1876 if (options->DirFetchPeriod > MAX_DIR_PERIOD) {
1877 log(LOG_WARN, "DirFetchPeriod is too large; clipping to %ds.", MAX_DIR_PERIOD);
1878 options->DirFetchPeriod = MAX_DIR_PERIOD;
1880 if (options->StatusFetchPeriod > MAX_DIR_PERIOD) {
1881 log(LOG_WARN, "StatusFetchPeriod is too large; clipping to %ds.", MAX_DIR_PERIOD);
1882 options->StatusFetchPeriod = MAX_DIR_PERIOD;
1884 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
1885 log(LOG_WARN, "RendPostPeriod is too large; clipping to %ds.", MAX_DIR_PERIOD);
1886 options->RendPostPeriod = MAX_DIR_PERIOD;
1889 if (options->KeepalivePeriod < 1) {
1890 log(LOG_WARN,"KeepalivePeriod option must be positive.");
1891 result = -1;
1894 if (options->BandwidthRate > INT_MAX) {
1895 log(LOG_WARN,"BandwidthRate must be less than %d",INT_MAX);
1896 result = -1;
1898 if (options->BandwidthBurst > INT_MAX) {
1899 log(LOG_WARN,"BandwidthBurst must be less than %d",INT_MAX);
1900 result = -1;
1902 if (server_mode(options) &&
1903 options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH*2) {
1904 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);
1905 result = -1;
1907 if (options->BandwidthRate > options->BandwidthBurst) {
1908 log(LOG_WARN,"BandwidthBurst must be at least equal to BandwidthRate.");
1909 result = -1;
1912 if (accounting_parse_options(options, 1)<0) {
1913 result = -1;
1916 if (options->HttpProxy) { /* parse it now */
1917 if (parse_addr_port(options->HttpProxy, NULL,
1918 &options->HttpProxyAddr, &options->HttpProxyPort) < 0) {
1919 log(LOG_WARN,"HttpProxy failed to parse or resolve. Please fix.");
1920 result = -1;
1922 if (options->HttpProxyPort == 0) { /* give it a default */
1923 options->HttpProxyPort = 80;
1927 if (options->HttpProxyAuthenticator) {
1928 if (strlen(options->HttpProxyAuthenticator) >= 48) {
1929 log(LOG_WARN, "HttpProxyAuthenticator is too long (>= 48 chars).");
1930 result = -1;
1934 if (options->HttpsProxy) { /* parse it now */
1935 if (parse_addr_port(options->HttpsProxy, NULL,
1936 &options->HttpsProxyAddr, &options->HttpsProxyPort) < 0) {
1937 log(LOG_WARN,"HttpsProxy failed to parse or resolve. Please fix.");
1938 result = -1;
1940 if (options->HttpsProxyPort == 0) { /* give it a default */
1941 options->HttpsProxyPort = 443;
1945 if (options->HttpsProxyAuthenticator) {
1946 if (strlen(options->HttpsProxyAuthenticator) >= 48) {
1947 log(LOG_WARN, "HttpsProxyAuthenticator is too long (>= 48 chars).");
1948 result = -1;
1952 if (options->HashedControlPassword) {
1953 if (decode_hashed_password(NULL, options->HashedControlPassword)<0) {
1954 log_fn(LOG_WARN,"Bad HashedControlPassword: wrong length or bad encoding");
1955 result = -1;
1958 if (options->HashedControlPassword && options->CookieAuthentication) {
1959 log_fn(LOG_WARN,"Cannot enable both HashedControlPassword and CookieAuthentication");
1960 result = -1;
1963 if (options->UseHelperNodes && ! options->NumHelperNodes) {
1964 log_fn(LOG_WARN, "Cannot enable UseHelperNodes with NumHelperNodes set to 0");
1965 result = -1;
1968 if (check_nickname_list(options->ExitNodes, "ExitNodes"))
1969 result = -1;
1970 if (check_nickname_list(options->EntryNodes, "EntryNodes"))
1971 result = -1;
1972 if (check_nickname_list(options->ExcludeNodes, "ExcludeNodes"))
1973 result = -1;
1974 if (check_nickname_list(options->RendNodes, "RendNodes"))
1975 result = -1;
1976 if (check_nickname_list(options->RendNodes, "RendExcludeNodes"))
1977 result = -1;
1978 if (check_nickname_list(options->MyFamily, "MyFamily"))
1979 result = -1;
1980 for (cl = options->NodeFamilies; cl; cl = cl->next) {
1981 if (check_nickname_list(cl->value, "NodeFamily"))
1982 result = -1;
1985 if (config_parse_addr_policy(options->ExitPolicy, &addr_policy, -1)) {
1986 log_fn(LOG_WARN, "Error in Exit Policy entry.");
1987 result = -1;
1989 options_append_default_exit_policy(&addr_policy);
1990 if (server_mode(options)) {
1991 exit_policy_implicitly_allows_local_networks(addr_policy, 1);
1993 /* The rest of these calls *append* to addr_policy. So don't actually
1994 * use the results for anything other than checking if they parse! */
1995 if (config_parse_addr_policy(options->DirPolicy, &addr_policy, -1)) {
1996 log_fn(LOG_WARN, "Error in DirPolicy entry.");
1997 result = -1;
1999 if (config_parse_addr_policy(options->SocksPolicy, &addr_policy, -1)) {
2000 log_fn(LOG_WARN, "Error in SocksPolicy entry.");
2001 result = -1;
2003 if (config_parse_addr_policy(options->ReachableAddresses, &addr_policy,
2004 ADDR_POLICY_ACCEPT)) {
2005 log_fn(LOG_WARN, "Error in ReachableAddresses entry.");
2006 result = -1;
2008 addr_policy_free(addr_policy);
2010 for (cl = options->RedirectExit; cl; cl = cl->next) {
2011 if (parse_redirect_line(NULL, cl)<0)
2012 result = -1;
2015 if (!options->DirServers) {
2016 add_default_trusted_dirservers(options);
2017 } else {
2018 for (cl = options->DirServers; cl; cl = cl->next) {
2019 if (parse_dir_server_line(cl->value, 1)<0)
2020 result = -1;
2024 if (rend_config_services(options, 1) < 0)
2025 result = -1;
2027 return result;
2030 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
2031 * equal strings. */
2032 static int
2033 opt_streq(const char *s1, const char *s2)
2035 if (!s1 && !s2)
2036 return 1;
2037 else if (s1 && s2 && !strcmp(s1,s2))
2038 return 1;
2039 else
2040 return 0;
2043 /** Check if any of the previous options have changed but aren't allowed to. */
2044 static int
2045 options_transition_allowed(or_options_t *old, or_options_t *new_val)
2047 if (!old)
2048 return 0;
2050 if (!opt_streq(old->PidFile, new_val->PidFile)) {
2051 log_fn(LOG_WARN,"PidFile is not allowed to change. Failing.");
2052 return -1;
2055 if (old->RunAsDaemon != new_val->RunAsDaemon) {
2056 log_fn(LOG_WARN,"While Tor is running, changing RunAsDaemon is not allowed. Failing.");
2057 return -1;
2060 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
2061 log_fn(LOG_WARN,"While Tor is running, changing DataDirectory (\"%s\"->\"%s\") is not allowed. Failing.", old->DataDirectory, new_val->DataDirectory);
2062 return -1;
2065 if (!opt_streq(old->User, new_val->User)) {
2066 log_fn(LOG_WARN,"While Tor is running, changing User is not allowed. Failing.");
2067 return -1;
2070 if (!opt_streq(old->Group, new_val->Group)) {
2071 log_fn(LOG_WARN,"While Tor is running, changing Group is not allowed. Failing.");
2072 return -1;
2075 if (old->HardwareAccel != new_val->HardwareAccel) {
2076 log_fn(LOG_WARN,"While Tor is running, changing HardwareAccel is not allowed. Failing.");
2077 return -1;
2080 return 0;
2083 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
2084 * will require us to rotate the cpu and dns workers; else return 0. */
2085 static int
2086 options_transition_affects_workers(or_options_t *old_options,
2087 or_options_t *new_options)
2089 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
2090 old_options->NumCpus != new_options->NumCpus ||
2091 old_options->ORPort != new_options->ORPort ||
2092 old_options->SafeLogging != new_options->SafeLogging ||
2093 !config_lines_eq(old_options->Logs, new_options->Logs))
2094 return 1;
2096 /* Check whether log options match. */
2098 /* Nothing that changed matters. */
2099 return 0;
2102 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
2103 * will require us to generate a new descriptor; else return 0. */
2104 static int
2105 options_transition_affects_descriptor(or_options_t *old_options,
2106 or_options_t *new_options)
2108 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
2109 !opt_streq(old_options->Nickname,new_options->Nickname) ||
2110 !opt_streq(old_options->Address,new_options->Address) ||
2111 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
2112 old_options->ORPort != new_options->ORPort ||
2113 old_options->DirPort != new_options->DirPort ||
2114 old_options->ClientOnly != new_options->ClientOnly ||
2115 old_options->NoPublish != new_options->NoPublish ||
2116 old_options->BandwidthRate != new_options->BandwidthRate ||
2117 old_options->BandwidthBurst != new_options->BandwidthBurst ||
2118 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
2119 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
2120 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
2121 old_options->AccountingMax != new_options->AccountingMax)
2122 return 1;
2124 return 0;
2127 #ifdef MS_WINDOWS
2128 /** Return the directory on windows where we expect to find our application
2129 * data. */
2130 static char *
2131 get_windows_conf_root(void)
2133 static int is_set = 0;
2134 static char path[MAX_PATH+1];
2136 LPITEMIDLIST idl;
2137 IMalloc *m;
2138 HRESULT result;
2140 if (is_set)
2141 return path;
2143 /* Find X:\documents and settings\username\application data\ .
2144 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
2146 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA,
2147 &idl))) {
2148 GetCurrentDirectory(MAX_PATH, path);
2149 is_set = 1;
2150 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);
2151 return path;
2153 /* Convert the path from an "ID List" (whatever that is!) to a path. */
2154 result = SHGetPathFromIDList(idl, path);
2155 /* Now we need to free the */
2156 SHGetMalloc(&m);
2157 if (m) {
2158 m->lpVtbl->Free(m, idl);
2159 m->lpVtbl->Release(m);
2161 if (!SUCCEEDED(result)) {
2162 return NULL;
2164 strlcat(path,"\\tor",MAX_PATH);
2165 is_set = 1;
2166 return path;
2168 #endif
2170 /** Return the default location for our torrc file. */
2171 static const char *
2172 get_default_conf_file(void)
2174 #ifdef MS_WINDOWS
2175 static char path[MAX_PATH+1];
2176 strlcpy(path, get_windows_conf_root(), MAX_PATH);
2177 strlcat(path,"\\torrc",MAX_PATH);
2178 return path;
2179 #else
2180 return (CONFDIR "/torrc");
2181 #endif
2184 /** Verify whether lst is a string containing valid-looking space-separated
2185 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
2187 static int
2188 check_nickname_list(const char *lst, const char *name)
2190 int r = 0;
2191 smartlist_t *sl;
2193 if (!lst)
2194 return 0;
2195 sl = smartlist_create();
2196 smartlist_split_string(sl, lst, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2197 SMARTLIST_FOREACH(sl, const char *, s,
2199 if (!is_legal_nickname_or_hexdigest(s)) {
2200 log_fn(LOG_WARN, "Invalid nickname '%s' in %s line", s, name);
2201 r = -1;
2204 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
2205 smartlist_free(sl);
2206 return r;
2209 /** Read a configuration file into <b>options</b>, finding the configuration
2210 * file location based on the command line. After loading the options,
2211 * validate them for consistency, then take actions based on them.
2212 * Return 0 if success, -1 if failure. */
2214 options_init_from_torrc(int argc, char **argv)
2216 or_options_t *oldoptions, *newoptions;
2217 config_line_t *cl;
2218 char *cf=NULL, *fname=NULL;
2219 int i, retval;
2220 int using_default_torrc;
2221 static char **backup_argv;
2222 static int backup_argc;
2224 if (argv) { /* first time we're called. save commandline args */
2225 backup_argv = argv;
2226 backup_argc = argc;
2227 oldoptions = NULL;
2228 } else { /* we're reloading. need to clean up old options first. */
2229 argv = backup_argv;
2230 argc = backup_argc;
2231 oldoptions = get_options();
2233 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
2234 print_usage();
2235 exit(0);
2238 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
2239 printf("Tor version %s.\n",VERSION);
2240 if (argc > 2 && (!strcmp(argv[2],"--version"))) {
2241 print_cvs_version();
2243 exit(0);
2246 newoptions = tor_malloc_zero(sizeof(or_options_t));
2247 newoptions->_magic = OR_OPTIONS_MAGIC;
2248 options_init(newoptions);
2250 /* learn config file name */
2251 fname = NULL;
2252 using_default_torrc = 1;
2253 newoptions->command = CMD_RUN_TOR;
2254 for (i = 1; i < argc; ++i) {
2255 if (i < argc-1 && !strcmp(argv[i],"-f")) {
2256 if (fname) {
2257 log(LOG_WARN, "Duplicate -f options on command line.");
2258 tor_free(fname);
2260 fname = tor_strdup(argv[i+1]);
2261 using_default_torrc = 0;
2262 ++i;
2263 } else if (!strcmp(argv[i],"--list-fingerprint")) {
2264 newoptions->command = CMD_LIST_FINGERPRINT;
2265 } else if (!strcmp(argv[i],"--hash-password")) {
2266 newoptions->command = CMD_HASH_PASSWORD;
2267 newoptions->command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
2268 ++i;
2269 } else if (!strcmp(argv[i],"--verify-config")) {
2270 newoptions->command = CMD_VERIFY_CONFIG;
2273 if (using_default_torrc) {
2274 /* didn't find one, try CONFDIR */
2275 const char *dflt = get_default_conf_file();
2276 char *fn = NULL;
2277 if (dflt && file_status(dflt) == FN_FILE) {
2278 fname = tor_strdup(dflt);
2279 } else {
2280 #ifndef MS_WINDOWS
2281 fn = expand_filename("~/.torrc");
2282 if (fn && file_status(fn) == FN_FILE) {
2283 fname = fn;
2284 } else {
2285 tor_free(fn);
2286 fname = tor_strdup(dflt);
2288 #else
2289 fname = tor_strdup(dflt);
2290 #endif
2293 tor_assert(fname);
2294 log(LOG_DEBUG, "Opening config file \"%s\"", fname);
2296 /* get config lines, assign them */
2297 if (file_status(fname) != FN_FILE ||
2298 !(cf = read_file_to_str(fname,0))) {
2299 if (using_default_torrc == 1) {
2300 log(LOG_NOTICE, "Configuration file \"%s\" not present, "
2301 "using reasonable defaults.", fname);
2302 tor_free(fname); /* sets fname to NULL */
2303 } else {
2304 log(LOG_WARN, "Unable to open configuration file \"%s\".", fname);
2305 tor_free(fname);
2306 goto err;
2308 } else { /* it opened successfully. use it. */
2309 retval = config_get_lines(cf, &cl);
2310 tor_free(cf);
2311 if (retval < 0)
2312 goto err;
2313 retval = config_assign(&options_format, newoptions, cl, 0, 0);
2314 config_free_lines(cl);
2315 if (retval < 0)
2316 goto err;
2319 /* Go through command-line variables too */
2320 if (config_get_commandlines(argc, argv, &cl) < 0)
2321 goto err;
2322 retval = config_assign(&options_format, newoptions, cl, 0, 0);
2323 config_free_lines(cl);
2324 if (retval < 0)
2325 goto err;
2327 /* Validate newoptions */
2328 if (options_validate(newoptions) < 0)
2329 goto err;
2331 if (options_transition_allowed(oldoptions, newoptions) < 0)
2332 goto err;
2334 set_options(newoptions); /* frees and replaces old options */
2335 tor_free(torrc_fname);
2336 torrc_fname = fname;
2337 return 0;
2338 err:
2339 tor_free(fname);
2340 config_free(&options_format, newoptions);
2341 return -1;
2344 /** Return the location for our configuration file.
2346 const char *
2347 get_torrc_fname(void)
2349 if (torrc_fname)
2350 return torrc_fname;
2351 else
2352 return get_default_conf_file();
2355 /** Adjust the address map mased on the MapAddress elements in the
2356 * configuration <b>options</b>
2358 static void
2359 config_register_addressmaps(or_options_t *options)
2361 smartlist_t *elts;
2362 config_line_t *opt;
2363 char *from, *to;
2365 addressmap_clear_configured();
2366 elts = smartlist_create();
2367 for (opt = options->AddressMap; opt; opt = opt->next) {
2368 smartlist_split_string(elts, opt->value, NULL,
2369 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
2370 if (smartlist_len(elts) >= 2) {
2371 from = smartlist_get(elts,0);
2372 to = smartlist_get(elts,1);
2373 if (!is_plausible_address(from)) {
2374 log_fn(LOG_WARN,"Skipping invalid argument '%s' to MapAddress",from);
2375 } else if (!is_plausible_address(to)) {
2376 log_fn(LOG_WARN,"Skipping invalid argument '%s' to MapAddress",to);
2377 } else {
2378 addressmap_register(from, tor_strdup(to), 0);
2379 if (smartlist_len(elts)>2) {
2380 log_fn(LOG_WARN,"Ignoring extra arguments to MapAddress.");
2383 } else {
2384 log_fn(LOG_WARN,"MapAddress '%s' has too few arguments. Ignoring.", opt->value);
2386 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
2387 smartlist_clear(elts);
2389 smartlist_free(elts);
2392 /** If <b>range</b> is of the form MIN-MAX, for MIN and MAX both
2393 * recognized log severity levels, set *<b>min_out</b> to MIN and
2394 * *<b>max_out</b> to MAX and return 0. Else, if <b>range</b> is of
2395 * the form MIN, act as if MIN-err had been specified. Else, warn and
2396 * return -1.
2398 static int
2399 parse_log_severity_range(const char *range, int *min_out, int *max_out)
2401 int levelMin, levelMax;
2402 const char *cp;
2403 cp = strchr(range, '-');
2404 if (cp) {
2405 if (cp == range) {
2406 levelMin = LOG_DEBUG;
2407 } else {
2408 char *tmp_sev = tor_strndup(range, cp - range);
2409 levelMin = parse_log_level(tmp_sev);
2410 if (levelMin < 0) {
2411 log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
2412 "err|warn|notice|info|debug", tmp_sev);
2413 tor_free(tmp_sev);
2414 return -1;
2416 tor_free(tmp_sev);
2418 if (!*(cp+1)) {
2419 levelMax = LOG_ERR;
2420 } else {
2421 levelMax = parse_log_level(cp+1);
2422 if (levelMax < 0) {
2423 log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
2424 "err|warn|notice|info|debug", cp+1);
2425 return -1;
2428 } else {
2429 levelMin = parse_log_level(range);
2430 if (levelMin < 0) {
2431 log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
2432 "err|warn|notice|info|debug", range);
2433 return -1;
2435 levelMax = LOG_ERR;
2438 *min_out = levelMin;
2439 *max_out = levelMax;
2441 return 0;
2444 /** Try to convert a pair of old-style logging options [LogLevel, and
2445 * (LogFile/Syslog)] to a new-style option, and add the new option to
2446 * options->Logs. */
2447 static int
2448 convert_log_option(or_options_t *options, config_line_t *level_opt,
2449 config_line_t *file_opt, int isDaemon)
2451 int levelMin = -1, levelMax = -1;
2453 if (level_opt) {
2454 if (parse_log_severity_range(level_opt->value, &levelMin, &levelMax))
2455 return -1;
2457 if (levelMin < 0 && levelMax < 0) {
2458 levelMin = LOG_NOTICE;
2459 levelMax = LOG_ERR;
2460 } else if (levelMin < 0) {
2461 levelMin = levelMax;
2462 } else {
2463 levelMax = LOG_ERR;
2466 if (file_opt && !strcasecmp(file_opt->key, "LogFile")) {
2467 if (add_single_log_option(options, levelMin, levelMax, "file", file_opt->value) < 0) {
2468 log_fn(LOG_WARN, "Cannot write to LogFile \"%s\": %s.", file_opt->value,
2469 strerror(errno));
2470 return -1;
2472 } else if (file_opt && !strcasecmp(file_opt->key, "SysLog")) {
2473 if (add_single_log_option(options, levelMin, levelMax, "syslog", NULL) < 0)
2474 return -1;
2475 } else if (!isDaemon) {
2476 add_single_log_option(options, levelMin, levelMax, "stdout", NULL);
2478 return 0;
2482 * Initialize the logs based on the configuration file.
2485 options_init_logs(or_options_t *options, int validate_only)
2487 config_line_t *opt;
2488 int ok;
2489 smartlist_t *elts;
2491 ok = 1;
2492 elts = smartlist_create();
2493 for (opt = options->Logs; opt; opt = opt->next) {
2494 int levelMin=LOG_DEBUG, levelMax=LOG_ERR;
2495 smartlist_split_string(elts, opt->value, NULL,
2496 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
2497 if (smartlist_len(elts) == 0) {
2498 log_fn(LOG_WARN, "Bad syntax on Log option 'Log %s'", opt->value);
2499 ok = 0; goto cleanup;
2501 if (parse_log_severity_range(smartlist_get(elts,0), &levelMin, &levelMax)) {
2502 ok = 0; goto cleanup;
2504 if (smartlist_len(elts) < 2) { /* only loglevels were provided */
2505 if (!validate_only)
2506 add_stream_log(levelMin, levelMax, "<stdout>", stdout);
2507 goto cleanup;
2509 if (!strcasecmp(smartlist_get(elts,1), "file")) {
2510 if (smartlist_len(elts) != 3) {
2511 log_fn(LOG_WARN, "Bad syntax on Log option 'Log %s'", opt->value);
2512 ok = 0; goto cleanup;
2514 if (!validate_only)
2515 add_file_log(levelMin, levelMax, smartlist_get(elts, 2));
2516 goto cleanup;
2518 if (smartlist_len(elts) != 2) {
2519 log_fn(LOG_WARN, "Bad syntax on Log option 'Log %s'", opt->value);
2520 ok = 0; goto cleanup;
2522 if (!strcasecmp(smartlist_get(elts,1), "stdout")) {
2523 if (!validate_only) {
2524 add_stream_log(levelMin, levelMax, "<stdout>", stdout);
2525 close_temp_logs();
2527 } else if (!strcasecmp(smartlist_get(elts,1), "stderr")) {
2528 if (!validate_only) {
2529 add_stream_log(levelMin, levelMax, "<stderr>", stderr);
2530 close_temp_logs();
2532 } else if (!strcasecmp(smartlist_get(elts,1), "syslog")) {
2533 #ifdef HAVE_SYSLOG_H
2534 if (!validate_only)
2535 add_syslog_log(levelMin, levelMax);
2536 #else
2537 log_fn(LOG_WARN, "Syslog is not supported in this compilation.");
2538 #endif
2539 } else {
2540 log_fn(LOG_WARN, "Unrecognized log type %s",
2541 (const char*)smartlist_get(elts,1));
2542 if (strchr(smartlist_get(elts,1), '/')) {
2543 log_fn(LOG_WARN, "Did you mean to say 'Log file %s' ?",
2544 (const char *)smartlist_get(elts,1));
2546 ok = 0; goto cleanup;
2548 cleanup:
2549 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
2550 smartlist_clear(elts);
2552 smartlist_free(elts);
2553 if (!validate_only)
2554 close_temp_logs();
2556 return ok?0:-1;
2559 /** Add a single option of the form Log min-max \<type\> [fname] to options. */
2560 static int
2561 add_single_log_option(or_options_t *options, int minSeverity, int maxSeverity,
2562 const char *type, const char *fname)
2564 char buf[512];
2565 int n;
2567 n = tor_snprintf(buf, sizeof(buf), "%s%s%s %s%s%s",
2568 log_level_to_string(minSeverity),
2569 maxSeverity == LOG_ERR ? "" : "-",
2570 maxSeverity == LOG_ERR ? "" : log_level_to_string(maxSeverity),
2571 type, fname?" ":"", fname?fname:"");
2572 if (n<0) {
2573 log_fn(LOG_WARN, "Normalized log option too long.");
2574 return -1;
2577 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);
2578 config_line_append(&options->Logs, "Log", buf);
2579 return 0;
2582 /** Convert all old-style logging options to new-style Log options. Return 0
2583 * on success, -1 on failure. */
2584 static int
2585 normalize_log_options(or_options_t *options)
2587 /* The order of options is: Level? (File Level?)+
2589 config_line_t *opt = options->OldLogOptions;
2591 /* Special case for if first option is LogLevel. */
2592 if (opt && !strcasecmp(opt->key, "LogLevel")) {
2593 if (opt->next && (!strcasecmp(opt->next->key, "LogFile") ||
2594 !strcasecmp(opt->next->key, "SysLog"))) {
2595 if (convert_log_option(options, opt, opt->next, options->RunAsDaemon) < 0)
2596 return -1;
2597 opt = opt->next->next;
2598 } else if (!opt->next) {
2599 if (convert_log_option(options, opt, NULL, options->RunAsDaemon) < 0)
2600 return -1;
2601 opt = opt->next;
2602 } else {
2603 ; /* give warning below */
2607 while (opt) {
2608 if (!strcasecmp(opt->key, "LogLevel")) {
2609 log_fn(LOG_WARN, "Two LogLevel options in a row without intervening LogFile or SysLog");
2610 opt = opt->next;
2611 } else {
2612 tor_assert(!strcasecmp(opt->key, "LogFile") ||
2613 !strcasecmp(opt->key, "SysLog"));
2614 if (opt->next && !strcasecmp(opt->next->key, "LogLevel")) {
2615 /* LogFile/SysLog followed by LogLevel */
2616 if (convert_log_option(options,opt->next,opt, options->RunAsDaemon) < 0)
2617 return -1;
2618 opt = opt->next->next;
2619 } else {
2620 /* LogFile/SysLog followed by LogFile/SysLog or end of list. */
2621 if (convert_log_option(options,NULL, opt, options->RunAsDaemon) < 0)
2622 return -1;
2623 opt = opt->next;
2628 if (options->DebugLogFile) {
2629 if (add_single_log_option(options, LOG_DEBUG, LOG_ERR, "file", options->DebugLogFile) < 0)
2630 return -1;
2633 tor_free(options->DebugLogFile);
2634 config_free_lines(options->OldLogOptions);
2635 options->OldLogOptions = NULL;
2637 return 0;
2640 #define DEFAULT_EXIT_POLICY "reject 0.0.0.0/8,reject 169.254.0.0/16,reject 127.0.0.0/8,reject 192.168.0.0/16,reject 10.0.0.0/8,reject 172.16.0.0/12,reject *:25,reject *:119,reject *:135-139,reject *:445,reject *:465,reject *:587,reject *:1214,reject *:4661-4666,reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*"
2642 /** Add the default exit policy entries to <b>policy</b>
2644 void
2645 options_append_default_exit_policy(addr_policy_t **policy)
2647 config_line_t tmp;
2648 addr_policy_t *ap;
2650 tmp.key = NULL;
2651 tmp.value = (char*)DEFAULT_EXIT_POLICY;
2652 tmp.next = NULL;
2653 config_parse_addr_policy(&tmp, policy, -1);
2655 /* Remove redundant parts, if any. */
2656 for (ap=*policy; ap; ap=ap->next) {
2657 if (ap->msk == 0 && ap->prt_min <= 1 && ap->prt_max >= 65535) {
2658 if (ap->next) {
2659 addr_policy_free(ap->next);
2660 ap->next = NULL;
2662 return;
2668 * Given a linked list of config lines containing "allow" and "deny" tokens,
2669 * parse them and append the result to <b>dest</b>. Return -1 if any tokens
2670 * are malformed, else return 0.
2673 config_parse_addr_policy(config_line_t *cfg,
2674 addr_policy_t **dest,
2675 int assume_action)
2677 addr_policy_t **nextp;
2678 smartlist_t *entries;
2679 int r = 0;
2681 if (!cfg)
2682 return 0;
2684 nextp = dest;
2686 while (*nextp)
2687 nextp = &((*nextp)->next);
2689 entries = smartlist_create();
2690 for (; cfg; cfg = cfg->next) {
2691 smartlist_split_string(entries, cfg->value, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2692 SMARTLIST_FOREACH(entries, const char *, ent,
2694 log_fn(LOG_DEBUG,"Adding new entry '%s'",ent);
2695 *nextp = router_parse_addr_policy_from_string(ent, assume_action);
2696 if (*nextp) {
2697 nextp = &((*nextp)->next);
2698 } else {
2699 log_fn(LOG_WARN,"Malformed policy '%s'.", ent);
2700 r = -1;
2703 SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
2704 smartlist_clear(entries);
2706 smartlist_free(entries);
2707 return r;
2710 /** Release all storage held by <b>p</b> */
2711 void
2712 addr_policy_free(addr_policy_t *p)
2714 addr_policy_t *e;
2716 while (p) {
2717 e = p;
2718 p = p->next;
2719 tor_free(e->string);
2720 tor_free(e);
2724 /** Parse a single RedirectExit line's contents from <b>line</b>. If
2725 * they are valid, and <b>result</b> is not NULL, add an element to
2726 * <b>result</b> and return 0. Else if they are valid, return 0.
2727 * Else return -1. */
2728 static int
2729 parse_redirect_line(smartlist_t *result, config_line_t *line)
2731 smartlist_t *elements = NULL;
2732 exit_redirect_t *r;
2734 tor_assert(line);
2736 r = tor_malloc_zero(sizeof(exit_redirect_t));
2737 elements = smartlist_create();
2738 smartlist_split_string(elements, line->value, NULL,
2739 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2740 if (smartlist_len(elements) != 2) {
2741 log_fn(LOG_WARN, "Wrong number of elements in RedirectExit line");
2742 goto err;
2744 if (parse_addr_and_port_range(smartlist_get(elements,0),&r->addr,&r->mask,
2745 &r->port_min,&r->port_max)) {
2746 log_fn(LOG_WARN, "Error parsing source address in RedirectExit line");
2747 goto err;
2749 if (0==strcasecmp(smartlist_get(elements,1), "pass")) {
2750 r->is_redirect = 0;
2751 } else {
2752 if (parse_addr_port(smartlist_get(elements,1),NULL,&r->addr_dest,
2753 &r->port_dest)) {
2754 log_fn(LOG_WARN, "Error parsing dest address in RedirectExit line");
2755 goto err;
2757 r->is_redirect = 1;
2760 goto done;
2761 err:
2762 tor_free(r);
2763 done:
2764 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2765 smartlist_free(elements);
2766 if (r) {
2767 if (result)
2768 smartlist_add(result, r);
2769 else
2770 tor_free(r);
2771 return 0;
2772 } else {
2773 return -1;
2777 /** Read the contents of a DirServer line from <b>line</b>. Return 0
2778 * if the line is well-formed, and -1 if it isn't. If
2779 * <b>validate_only</b> is 0, and the line is well-formed, then add
2780 * the dirserver described in the line as a valid server. */
2781 static int
2782 parse_dir_server_line(const char *line, int validate_only)
2784 smartlist_t *items = NULL;
2785 int r;
2786 char *addrport, *address=NULL;
2787 uint16_t port;
2788 char digest[DIGEST_LEN];
2789 int supports_v1 = 1; /*XXXX011 change default when clients support v2. */
2791 while (TOR_ISSPACE(*line))
2792 ++line;
2794 if (!strcmpstart(line, "v1 ")) {
2795 line += 3;
2796 supports_v1 = 1;
2799 items = smartlist_create();
2800 smartlist_split_string(items, line, NULL,
2801 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
2802 if (smartlist_len(items) < 2) {
2803 log_fn(LOG_WARN, "Too few arguments to DirServer line.");
2804 goto err;
2806 addrport = smartlist_get(items, 0);
2807 if (parse_addr_port(addrport, &address, NULL, &port)<0) {
2808 log_fn(LOG_WARN, "Error parsing DirServer address '%s'", addrport);
2809 goto err;
2811 if (!port) {
2812 log_fn(LOG_WARN, "Missing port in DirServer address '%s'",addrport);
2813 goto err;
2816 tor_strstrip(smartlist_get(items, 1), " ");
2817 if (strlen(smartlist_get(items, 1)) != HEX_DIGEST_LEN) {
2818 log_fn(LOG_WARN, "Key digest for DirServer is wrong length.");
2819 goto err;
2821 if (base16_decode(digest, DIGEST_LEN,
2822 smartlist_get(items,1), HEX_DIGEST_LEN)<0) {
2823 log_fn(LOG_WARN, "Unable to decode DirServer key digest.");
2824 goto err;
2827 if (!validate_only) {
2828 log_fn(LOG_DEBUG, "Trusted dirserver at %s:%d (%s)", address, (int)port,
2829 (char*)smartlist_get(items,1));
2830 add_trusted_dir_server(address, port, digest, supports_v1);
2833 r = 0;
2834 goto done;
2836 err:
2837 r = -1;
2839 done:
2840 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
2841 smartlist_free(items);
2842 tor_free(address);
2843 return r;
2846 /** Adjust the value of options->DataDirectory, or fill it in if it's
2847 * absent. Return 0 on success, -1 on failure. */
2848 static int
2849 normalize_data_directory(or_options_t *options)
2851 #ifdef MS_WINDOWS
2852 char *p;
2853 if (options->DataDirectory)
2854 return 0; /* all set */
2855 p = tor_malloc(MAX_PATH);
2856 strlcpy(p,get_windows_conf_root(),MAX_PATH);
2857 options->DataDirectory = p;
2858 return 0;
2859 #else
2860 const char *d = options->DataDirectory;
2861 if (!d)
2862 d = "~/.tor";
2864 if (strncmp(d,"~/",2) == 0) {
2865 char *fn = expand_filename(d);
2866 if (!fn) {
2867 log_fn(LOG_ERR,"Failed to expand filename \"%s\".", d);
2868 return -1;
2870 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
2871 /* If our homedir is /, we probably don't want to use it. */
2872 /* XXXX Default to /var/lib/tor? */
2873 log_fn(LOG_WARN, "Default DataDirectory is \"~/.tor\". This expands to \"%s\", which is probably not what you want. Using \"%s/tor\" instead", fn, LOCALSTATEDIR);
2874 tor_free(fn);
2875 fn = tor_strdup(LOCALSTATEDIR"/tor");
2878 tor_free(options->DataDirectory);
2879 options->DataDirectory = fn;
2881 return 0;
2882 #endif
2885 /** Check and normalize the value of options->DataDirectory; return 0 if it
2886 * sane, -1 otherwise. */
2887 static int
2888 validate_data_directory(or_options_t *options)
2890 if (normalize_data_directory(options) < 0)
2891 return -1;
2892 tor_assert(options->DataDirectory);
2893 if (strlen(options->DataDirectory) > (512-128)) {
2894 log_fn(LOG_ERR, "DataDirectory is too long.");
2895 return -1;
2897 return 0;
2900 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; if you edit it, comments will not be preserved"
2902 /** Save a configuration file for the configuration in <b>options</b>
2903 * into the file <b>fname</b>. If the file already exists, and
2904 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
2905 * replace it. Return 0 on success, -1 on failure. */
2906 static int
2907 write_configuration_file(const char *fname, or_options_t *options)
2909 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
2910 int rename_old = 0, r;
2911 size_t len;
2913 if (fname) {
2914 switch (file_status(fname)) {
2915 case FN_FILE:
2916 old_val = read_file_to_str(fname, 0);
2917 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
2918 rename_old = 1;
2920 tor_free(old_val);
2921 break;
2922 case FN_NOENT:
2923 break;
2924 default:
2925 log_fn(LOG_WARN,"Config file \"%s\" is not a file? Failing.", fname);
2926 return -1;
2930 if (!(new_conf = options_dump(options, 1))) {
2931 log_fn(LOG_WARN, "Couldn't get configuration string");
2932 goto err;
2935 len = strlen(new_conf)+128;
2936 new_val = tor_malloc(len);
2937 tor_snprintf(new_val, len, "%s\n\n%s", GENERATED_FILE_PREFIX, new_conf);
2939 if (rename_old) {
2940 int i = 1;
2941 size_t fn_tmp_len = strlen(fname)+32;
2942 char *fn_tmp;
2943 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
2944 fn_tmp = tor_malloc(fn_tmp_len);
2945 while (1) {
2946 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
2947 log_fn(LOG_WARN, "tor_snprintf failed inexplicably");
2948 tor_free(fn_tmp);
2949 goto err;
2951 if (file_status(fn_tmp) == FN_NOENT)
2952 break;
2953 ++i;
2955 log_fn(LOG_NOTICE, "Renaming old configuration file to \"%s\"", fn_tmp);
2956 rename(fname, fn_tmp);
2957 tor_free(fn_tmp);
2960 write_str_to_file(fname, new_val, 0);
2962 r = 0;
2963 goto done;
2964 err:
2965 r = -1;
2966 done:
2967 tor_free(new_val);
2968 tor_free(new_conf);
2969 return r;
2973 * Save the current configuration file value to disk. Return 0 on
2974 * success, -1 on failure.
2977 options_save_current(void)
2979 if (torrc_fname) {
2980 /* XXX This fails if we can't write to our configuration file.
2981 * Arguably, we should try falling back to datadirectory or something.
2982 * But just as arguably, we shouldn't. */
2983 return write_configuration_file(torrc_fname, get_options());
2985 return write_configuration_file(get_default_conf_file(), get_options());
2988 struct unit_table_t {
2989 const char *unit;
2990 uint64_t multiplier;
2993 static struct unit_table_t memory_units[] = {
2994 { "", 1 },
2995 { "b", 1<< 0 },
2996 { "byte", 1<< 0 },
2997 { "bytes", 1<< 0 },
2998 { "kb", 1<<10 },
2999 { "kilobyte", 1<<10 },
3000 { "kilobytes", 1<<10 },
3001 { "m", 1<<20 },
3002 { "mb", 1<<20 },
3003 { "megabyte", 1<<20 },
3004 { "megabytes", 1<<20 },
3005 { "gb", 1<<30 },
3006 { "gigabyte", 1<<30 },
3007 { "gigabytes", 1<<30 },
3008 { "tb", U64_LITERAL(1)<<40 },
3009 { "terabyte", U64_LITERAL(1)<<40 },
3010 { "terabytes", U64_LITERAL(1)<<40 },
3011 { NULL, 0 },
3014 static struct unit_table_t time_units[] = {
3015 { "", 1 },
3016 { "second", 1 },
3017 { "seconds", 1 },
3018 { "minute", 60 },
3019 { "minutes", 60 },
3020 { "hour", 60*60 },
3021 { "hours", 60*60 },
3022 { "day", 24*60*60 },
3023 { "days", 24*60*60 },
3024 { "week", 7*24*60*60 },
3025 { "weeks", 7*24*60*60 },
3026 { NULL, 0 },
3029 /** Parse a string <b>val</b> containing a number, zero or more
3030 * spaces, and an optional unit string. If the unit appears in the
3031 * table <b>u</b>, then multiply the number by the unit multiplier.
3032 * On success, set *<b>ok</b> to 1 and return this product.
3033 * Otherwise, set *<b>ok</b> to 0.
3035 static uint64_t
3036 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
3038 uint64_t v;
3039 char *cp;
3041 tor_assert(ok);
3043 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
3044 if (!*ok)
3045 return 0;
3046 if (!cp) {
3047 *ok = 1;
3048 return v;
3050 while (TOR_ISSPACE(*cp))
3051 ++cp;
3052 for ( ;u->unit;++u) {
3053 if (!strcasecmp(u->unit, cp)) {
3054 v *= u->multiplier;
3055 *ok = 1;
3056 return v;
3059 log_fn(LOG_WARN, "Unknown unit '%s'.", cp);
3060 *ok = 0;
3061 return 0;
3064 /** Parse a string in the format "number unit", where unit is a unit of
3065 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
3066 * and return the number of bytes specified. Otherwise, set
3067 * *<b>ok</b> to false and return 0. */
3068 static uint64_t
3069 config_parse_memunit(const char *s, int *ok) {
3070 return config_parse_units(s, memory_units, ok);
3073 /** Parse a string in the format "number unit", where unit is a unit of time.
3074 * On success, set *<b>ok</b> to true and return the number of seconds in
3075 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
3077 static int
3078 config_parse_interval(const char *s, int *ok) {
3079 uint64_t r;
3080 r = config_parse_units(s, time_units, ok);
3081 if (!ok)
3082 return -1;
3083 if (r > INT_MAX) {
3084 log_fn(LOG_WARN, "Interval '%s' is too long", s);
3085 *ok = 0;
3086 return -1;
3088 return (int)r;
3092 * Initialize the libevent library.
3094 static int
3095 init_libevent(void)
3097 configure_libevent_logging();
3098 /* If the kernel complains that some method (say, epoll) doesn't
3099 * exist, we don't care about it, since libevent will cope.
3101 suppress_libevent_log_msg("Function not implemented");
3102 #ifdef __APPLE__
3103 putenv("EVENT_NOKQUEUE=1");
3104 #endif
3105 event_init();
3106 suppress_libevent_log_msg(NULL);
3107 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
3108 /* Making this a NOTICE for now so we can link bugs to a libevent versions
3109 * or methods better. */
3110 log(LOG_NOTICE, "Initialized libevent version %s using method %s. Good.",
3111 event_get_version(), event_get_method());
3112 check_libevent_version(event_get_method(), event_get_version(),
3113 get_options()->ORPort != 0);
3114 #else
3115 log(LOG_NOTICE, "Initialized old libevent (version 1.0b or earlier).");
3116 log(LOG_WARN, "You have a very old version of libevent. It is likely to be buggy; please consider building Tor with a more recent version.");
3117 #endif
3119 return 0;
3122 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
3124 * Compare the given libevent method and version to a list of versions
3125 * which are known not to work. Warn the user as appropriate.
3128 static void
3129 check_libevent_version(const char *m, const char *v, int server)
3131 int buggy = 0, iffy = 0, slow = 0;
3133 tor_assert(m && v);
3135 if (!strcmp(m, "kqueue")) {
3136 if (!strcmp(v, "1.0c") || !strcmp(v, "1.0d") || !strcmp(v, "1.0e") ||
3137 !strcmp(v, "1.1")) {
3138 buggy = 1;
3140 } else if (!strcmp(m, "epoll")) {
3141 if (!strcmp(v, "1.0c") || !strcmp(v, "1.0d") || !strcmp(v, "1.0e"))
3142 iffy = 1;
3143 } else if (!strcmp(m, "poll")) {
3144 if (!strcmp(v, "1.0c") || !strcmp(v, "1.0d"))
3145 buggy = 1;
3146 else if (!strcmp(v, "1.0e"))
3147 slow = 1;
3148 } else if (!strcmp(m, "poll")) {
3149 if (!strcmp(v, "1.0c") || !strcmp(v, "1.0d") || !strcmp(v, "1.0e"))
3150 slow = 1;
3153 if (buggy) {
3154 log(LOG_WARN,
3155 "There are known bugs in using %s with libevent %s. "
3156 "Please use the latest version of libevent.", m, v);
3157 } else if (iffy) {
3158 log(LOG_WARN,
3159 "There are minor bugs in using %s with libevent %s. "
3160 "You may want to use the latest version of libevent.", m, v);
3161 } else if (slow && server) {
3162 log(LOG_WARN,
3163 "libevent %s can be very slow with %s. "
3164 "When running a server, please use the latest version of libevent.",v,m);
3168 #endif
3170 /* Versioning issues and state: we want to be able to understand old state
3171 * files, and not choke on new ones.
3173 * We could preserve all unrecognized variables across invocations, but we could
3174 * screw up order, if their order is significant with respect to existing
3175 * options.
3177 * We could just dump unrecognized variables if you downgrade.
3179 * This needs thought. XXXX NM
3182 /** DOCDOC */
3183 or_state_t *
3184 get_or_state(void)
3186 return global_state;
3189 /** DOCDOC */
3190 static char *
3191 get_or_state_fname(void)
3193 char *fname = NULL;
3194 or_options_t *options = get_options();
3195 size_t len = strlen(options->DataDirectory) + 16;
3196 fname = tor_malloc(len);
3197 tor_snprintf(fname, len, "%s/state", options->DataDirectory);
3198 return fname;
3201 /** DOCDOC */
3202 static int
3203 or_state_validate(or_state_t *state)
3205 const char *err;
3206 if (helper_nodes_parse_state(state, 0, &err)<0) {
3207 log_fn(LOG_WARN, "Unable to parse helper nodes: %s", err);
3208 return -1;
3210 return 0;
3213 /** DOCDOC */
3214 static void
3215 or_state_set(or_state_t *new_state)
3217 const char *err;
3218 tor_assert(new_state);
3219 if (global_state)
3220 config_free(&state_format, global_state);
3221 global_state = new_state;
3222 if (helper_nodes_parse_state(global_state, 1, &err)<0)
3223 log_fn(LOG_WARN,"Unparseable helper nodes state: %s",err);
3227 /* DOCDOC */
3229 or_state_load(void)
3231 or_state_t *new_state = NULL;
3232 char *contents = NULL, *fname;
3233 int r = -1;
3235 fname = get_or_state_fname();
3236 switch (file_status(fname)) {
3237 case FN_FILE:
3238 if (!(contents = read_file_to_str(fname, 0))) {
3239 log_fn(LOG_WARN, "Unable to read state file \"%s\"", fname);
3240 goto done;
3242 break;
3243 case FN_NOENT:
3244 break;
3245 default:
3246 log_fn(LOG_WARN,"State file \"%s\" is not a file? Failing.", fname);
3247 goto done;
3249 new_state = tor_malloc_zero(sizeof(or_state_t));
3250 new_state->_magic = OR_STATE_MAGIC;
3251 config_init(&state_format, new_state);
3252 if (contents) {
3253 config_line_t *lines=NULL;
3254 int assign_retval;
3255 if (config_get_lines(contents, &lines)<0)
3256 goto done;
3257 assign_retval = config_assign(&state_format, new_state, lines, 0, 0);
3258 config_free_lines(lines);
3259 if (assign_retval<0)
3260 goto done;
3263 if (or_state_validate(new_state) < 0)
3264 goto done;
3266 if (contents)
3267 log_fn(LOG_INFO, "Loaded state from \"%s\"", fname);
3268 else
3269 log_fn(LOG_INFO, "Initialized state");
3270 or_state_set(new_state);
3271 new_state = NULL;
3272 if (!contents) {
3273 global_state->dirty = 1;
3274 or_state_save();
3277 r = 0;
3278 done:
3279 tor_free(fname);
3280 tor_free(contents);
3281 if (new_state)
3282 config_free(&state_format, new_state);
3284 return r;
3287 /** DOCDOC */
3289 or_state_save(void)
3291 char *state, *contents;
3292 char tbuf[ISO_TIME_LEN+1];
3293 size_t len;
3294 char *fname;
3296 helper_nodes_update_state(global_state);
3298 if (!global_state->dirty)
3299 return 0;
3301 global_state->LastWritten = time(NULL);
3302 state = config_dump(&state_format, global_state, 0);
3303 len = strlen(state)+128;
3304 contents = tor_malloc(len);
3305 format_local_iso_time(tbuf, time(NULL));
3306 tor_snprintf(contents, len,
3307 "# Tor state file last generated on %s\n"
3308 "# You *do not* need to edit this file.\n\n%s",
3309 tbuf, state);
3310 tor_free(state);
3311 fname = get_or_state_fname();
3312 if (write_str_to_file(fname, contents, 0)<0) {
3313 log_fn(LOG_WARN, "Unable to write state to file \"%s\"", fname);
3314 tor_free(fname);
3315 tor_free(contents);
3316 return -1;
3318 log_fn(LOG_INFO, "Saved state to \"%s\"", fname);
3319 tor_free(fname);
3320 tor_free(contents);
3322 global_state->dirty = 0;
3323 return 0;
3326 /** DOCDOC */
3328 config_getinfo_helper(const char *question, char **answer)
3330 if (!strcmp(question, "config/names")) {
3331 smartlist_t *sl = smartlist_create();
3332 int i;
3333 for (i = 0; _option_vars[i].name; ++i) {
3334 config_var_t *var = &_option_vars[i];
3335 const char *type, *desc;
3336 char *line;
3337 size_t len;
3338 desc = config_find_description(&options_format, var->name);
3339 switch (var->type) {
3340 case CONFIG_TYPE_STRING: type = "String"; break;
3341 case CONFIG_TYPE_UINT: type = "Integer"; break;
3342 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
3343 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
3344 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
3345 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
3346 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
3347 case CONFIG_TYPE_CSV: type = "CommaList"; break;
3348 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
3349 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
3350 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
3351 default:
3352 case CONFIG_TYPE_OBSOLETE:
3353 type = NULL; break;
3355 if (!type)
3356 continue;
3357 len = strlen(var->name)+strlen(type)+16;
3358 if (desc)
3359 len += strlen(desc);
3360 line = tor_malloc(len);
3361 if (desc)
3362 tor_snprintf(line, len, "%s %s %s\n",var->name,type,desc);
3363 else
3364 tor_snprintf(line, len, "%s %s\n",var->name,type);
3365 smartlist_add(sl, line);
3367 *answer = smartlist_join_strings(sl, "", 0, NULL);
3368 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
3369 smartlist_free(sl);
3371 return 0;
3374 /** Dump the version of every file to the log. */
3375 static void
3376 print_cvs_version(void)
3378 extern const char aes_c_id[];
3379 extern const char compat_c_id[];
3380 extern const char container_c_id[];
3381 extern const char crypto_c_id[];
3382 extern const char log_c_id[];
3383 extern const char torgzip_c_id[];
3384 extern const char tortls_c_id[];
3385 extern const char util_c_id[];
3387 extern const char buffers_c_id[];
3388 extern const char circuitbuild_c_id[];
3389 extern const char circuitlist_c_id[];
3390 extern const char circuituse_c_id[];
3391 extern const char command_c_id[];
3392 // extern const char config_c_id[];
3393 extern const char connection_c_id[];
3394 extern const char connection_edge_c_id[];
3395 extern const char connection_or_c_id[];
3396 extern const char control_c_id[];
3397 extern const char cpuworker_c_id[];
3398 extern const char directory_c_id[];
3399 extern const char dirserv_c_id[];
3400 extern const char dns_c_id[];
3401 extern const char hibernate_c_id[];
3402 extern const char main_c_id[];
3403 extern const char onion_c_id[];
3404 extern const char relay_c_id[];
3405 extern const char rendclient_c_id[];
3406 extern const char rendcommon_c_id[];
3407 extern const char rendmid_c_id[];
3408 extern const char rendservice_c_id[];
3409 extern const char rephist_c_id[];
3410 extern const char router_c_id[];
3411 extern const char routerlist_c_id[];
3412 extern const char routerparse_c_id[];
3414 puts(AES_H_ID);
3415 puts(COMPAT_H_ID);
3416 puts(CONTAINER_H_ID);
3417 puts(CRYPTO_H_ID);
3418 puts(LOG_H_ID);
3419 puts(TORGZIP_H_ID);
3420 puts(TORINT_H_ID);
3421 puts(TORTLS_H_ID);
3422 puts(UTIL_H_ID);
3423 puts(aes_c_id);
3424 puts(compat_c_id);
3425 puts(container_c_id);
3426 puts(crypto_c_id);
3427 puts(log_c_id);
3428 puts(torgzip_c_id);
3429 puts(tortls_c_id);
3430 puts(util_c_id);
3432 puts(OR_H_ID);
3433 puts(buffers_c_id);
3434 puts(circuitbuild_c_id);
3435 puts(circuitlist_c_id);
3436 puts(circuituse_c_id);
3437 puts(command_c_id);
3438 puts(config_c_id);
3439 puts(connection_c_id);
3440 puts(connection_edge_c_id);
3441 puts(connection_or_c_id);
3442 puts(control_c_id);
3443 puts(cpuworker_c_id);
3444 puts(directory_c_id);
3445 puts(dirserv_c_id);
3446 puts(dns_c_id);
3447 puts(hibernate_c_id);
3448 puts(main_c_id);
3449 puts(onion_c_id);
3450 puts(relay_c_id);
3451 puts(rendclient_c_id);
3452 puts(rendcommon_c_id);
3453 puts(rendmid_c_id);
3454 puts(rendservice_c_id);
3455 puts(rephist_c_id);
3456 puts(router_c_id);
3457 puts(routerlist_c_id);
3458 puts(routerparse_c_id);