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 */
6 const char config_c_id
[] = "$Id$";
10 * \brief Code to parse and interpret configuration files.
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
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. */
39 /* An abbreviation for a configuration option allowed on the command line */
40 typedef struct config_abbrev_t
{
41 const char *abbreviated
;
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
[] = {
56 PLURAL(LongLivedPort
),
57 PLURAL(HiddenServiceNode
),
58 PLURAL(HiddenServiceExcludeNode
),
61 PLURAL(RendExcludeNode
),
62 PLURAL(StrictEntryNode
),
63 PLURAL(StrictExitNode
),
65 { "BandwidthRateBytes", "BandwidthRate", 0},
66 { "BandwidthBurstBytes", "BandwidthBurst", 0},
67 { "DirFetchPostPeriod", "StatusFetchPeriod", 0},
68 { "MaxConn", "ConnLimit", 0},
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
;
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
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
}
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
}
218 typedef struct config_var_description_t
{
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", ""},
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." },
238 typedef int (*validate_fn_t
)(void*);
244 config_abbrev_t
*abbrevs
;
246 validate_fn_t validate_fn
;
247 config_var_description_t
*descriptions
;
250 #define CHECK(fmt, cfg) do { \
251 tor_assert(fmt && cfg); \
252 tor_assert((fmt)->magic == *(uint32_t*)(((char*)(cfg))+fmt->magic_offset)); \
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
,
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
,
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
,
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
);
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
),
313 STRUCT_OFFSET(or_options_t
, _magic
),
316 (validate_fn_t
)options_validate
,
320 #define OR_STATE_MAGIC 0x57A73f57
322 static config_format_t state_format
= {
325 STRUCT_OFFSET(or_state_t
, _magic
),
328 (validate_fn_t
)or_state_validate
,
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
;
343 static addr_policy_t
*reachable_addr_policy
= NULL
;
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
;
354 /** Return the currently configured options. */
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
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.");
378 config_free(&options_format
, old_options
);
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.
394 safe_str(const char *address
)
396 if (get_options()->SafeLogging
)
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.
412 options_act(or_options_t
*old_options
)
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
) {
425 clear_trusted_dir_servers();
426 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
) {
427 if (parse_dir_server_line(cl
->value
, 0)<0) {
429 "Bug: Previously validated DirServer line could not be added!");
434 if (running_tor
&& rend_config_services(options
, 0)<0) {
436 "Bug: Previously validated hidden services line could not be added!");
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) {
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
);
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\"",
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
)
474 mark_logs_temp(); /* Close current logs once new logs are open. */
475 if (options_init_logs(options
, 0)<0) /* Configure the log(s) */
478 /* Close the temporary log we used while starting up, if it isn't already
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
) {
488 libevent_initialized
= 1;
496 options
->_ConnLimit
=
497 set_max_file_descriptors((unsigned)options
->ConnLimit
, MAXCONNECTIONS
);
498 if (options
->_ConnLimit
< 0)
502 smartlist_t
*sl
= smartlist_create();
503 for (cl
= options
->RedirectExit
; cl
; cl
= cl
->next
) {
504 if (parse_redirect_line(sl
, cl
)<0)
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();
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");
537 /* Set up accounting */
538 if (accounting_parse_options(options
, 0)<0) {
539 log_fn(LOG_ERR
,"Error in accounting options");
542 if (accounting_is_enabled(options
))
543 configure_accounting(time(NULL
));
548 if (!we_are_hibernating() && retry_all_listeners(0) < 0) {
549 log_fn(LOG_ERR
,"Failed to bind one of the listener ports.");
553 /* Check for transitions that need action. */
555 if (options_transition_affects_workers(old_options
, options
)) {
556 log_fn(LOG_INFO
,"Worker-related options changed. Rotating workers.");
562 /* Since our options changed, we might need to regenerate and upload our
565 if (!old_options
|| options_transition_affects_descriptor(old_options
, options
))
566 mark_my_descriptor_dirty();
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. */
580 expand_abbrev(config_format_t
*fmt
, const char *option
, int command_line
)
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
;
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. */
599 config_get_commandlines(int argc
, char **argv
, config_line_t
**result
)
601 config_line_t
*front
= NULL
;
602 config_line_t
**new = &front
;
607 if (!strcmp(argv
[i
],"-f") ||
608 !strcmp(argv
[i
],"--hash-password")) {
609 i
+= 2; /* command-line option with argument. ignore them. */
611 } else if (!strcmp(argv
[i
],"--list-fingerprint")) {
612 i
+= 1; /* command-line option. ignore it. */
614 } else if (!strcmp(argv
[i
],"--nt-service")) {
619 log_fn(LOG_WARN
,"Command-line option '%s' with no value. Failing.",
621 config_free_lines(front
);
625 *new = tor_malloc_zero(sizeof(config_line_t
));
631 (*new)->key
= tor_strdup(expand_abbrev(&options_format
, s
, 1));
632 (*new)->value
= tor_strdup(argv
[i
+1]);
634 log(LOG_DEBUG
,"Commandline: parsed keyword '%s', value '%s'",
635 (*new)->key
, (*new)->value
);
637 new = &((*new)->next
);
644 /** Helper: allocate a new configuration option mapping 'key' to 'val',
645 * append it to *<b>lst</b>. */
647 config_line_append(config_line_t
**lst
,
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
;
658 lst
= &((*lst
)->next
);
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
;
675 string
= parse_line_from_str(string
, &k
, &v
);
677 config_free_lines(list
);
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
);
697 * Free all the configuration lines on the linked list <b>front</b>.
700 config_free_lines(config_line_t
*front
)
709 tor_free(tmp
->value
);
716 config_find_description(config_format_t
*fmt
, const char *name
)
719 for (i
=0; fmt
->descriptions
[i
].name
; ++i
) {
720 if (!strcasecmp(name
, fmt
->descriptions
[i
].name
))
721 return fmt
->descriptions
[i
].description
;
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
)
734 size_t keylen
= strlen(key
);
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 */
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().
766 config_assign_value(config_format_t
*fmt
, or_options_t
*options
,
775 var
= config_find_option(fmt
, c
->key
);
778 lvalue
= ((char*)options
) + var
->var_offset
;
782 case CONFIG_TYPE_UINT
:
783 i
= tor_parse_long(c
->value
, 10, 0, INT_MAX
, &ok
, NULL
);
785 log(LOG_WARN
, "Int keyword '%s %s' is malformed or out of bounds.",
792 case CONFIG_TYPE_INTERVAL
: {
793 i
= config_parse_interval(c
->value
, &ok
);
801 case CONFIG_TYPE_MEMUNIT
: {
802 uint64_t u64
= config_parse_memunit(c
->value
, &ok
);
806 *(uint64_t *)lvalue
= u64
;
810 case CONFIG_TYPE_BOOL
:
811 i
= tor_parse_long(c
->value
, 10, 0, 1, &ok
, NULL
);
813 log(LOG_WARN
, "Boolean keyword '%s' expects 0 or 1.", c
->key
);
819 case CONFIG_TYPE_STRING
:
820 tor_free(*(char **)lvalue
);
821 *(char **)lvalue
= tor_strdup(c
->value
);
824 case CONFIG_TYPE_DOUBLE
:
825 *(double *)lvalue
= atof(c
->value
);
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
);
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
);
840 *(smartlist_t
**)lvalue
= smartlist_create();
843 smartlist_split_string(*(smartlist_t
**)lvalue
, c
->value
, ",",
844 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
847 case CONFIG_TYPE_LINELIST
:
848 case CONFIG_TYPE_LINELIST_S
:
849 config_line_append((config_line_t
**)lvalue
, c
->key
, c
->value
);
852 case CONFIG_TYPE_OBSOLETE
:
853 log_fn(LOG_WARN
, "Skipping obsolete configuration option '%s'", c
->key
);
855 case CONFIG_TYPE_LINELIST_V
:
856 log_fn(LOG_WARN
, "Can't provide value for virtual option '%s'", c
->key
);
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,
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().
875 config_assign_line(config_format_t
*fmt
, or_options_t
*options
,
876 config_line_t
*c
, int use_defaults
, int clear_first
)
882 var
= config_find_option(fmt
, c
->key
);
884 log_fn(LOG_WARN
, "Unknown option '%s'. Failing.", c
->key
);
887 /* Put keyword into canonical case. */
888 if (strcmp(var
->name
, 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
);
898 if (config_assign_value(fmt
, options
, c
) < 0)
903 /** Restore the option named <b>key</b> in options to its default value.
904 * Called from config_assign(). */
906 config_reset_line(config_format_t
*fmt
, or_options_t
*options
,
907 const char *key
, int use_defaults
)
913 var
= config_find_option(fmt
, key
);
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. */
930 option_get_canonical_name(const char *key
)
932 config_var_t
*var
= config_find_option(&options_format
, key
);
936 /** Return a canonicalized list of the options assigned for key.
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
;
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
);
954 next_out
= &((*next_out
)->next
);
960 static config_line_t
*
961 get_assigned_option(config_format_t
*fmt
, or_options_t
*options
, const char *key
)
966 config_line_t
*result
;
967 tor_assert(options
&& key
);
971 var
= config_find_option(fmt
, key
);
973 log_fn(LOG_WARN
, "Unknown option '%s'. Failing.", key
);
975 } else if (var
->type
== CONFIG_TYPE_LINELIST_S
) {
976 log_fn(LOG_WARN
, "Can't return context-sensitive '%s' on its own", key
);
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
);
991 case CONFIG_TYPE_STRING
:
992 if (*(char**)value
) {
993 result
->value
= tor_strdup(*(char**)value
);
995 tor_free(result
->key
);
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
);
1005 tor_free(result
->key
);
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
);
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
);
1021 case CONFIG_TYPE_DOUBLE
:
1022 tor_snprintf(buf
, sizeof(buf
), "%f", *(double*)value
);
1023 result
->value
= tor_strdup(buf
);
1025 case CONFIG_TYPE_BOOL
:
1026 result
->value
= tor_strdup(*(int*)value
? "1" : "0");
1028 case CONFIG_TYPE_CSV
:
1029 if (*(smartlist_t
**)value
)
1030 result
->value
= smartlist_join_strings(*(smartlist_t
**)value
,",",0,NULL
);
1032 result
->value
= tor_strdup("");
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
);
1040 tor_free(result
->key
);
1042 log_fn(LOG_WARN
,"Bug: unknown type %d for known key '%s'", var
->type
, key
);
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
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.
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.
1103 config_assign(config_format_t
*fmt
, void *options
,
1104 config_line_t
*list
, int use_defaults
, int clear_first
)
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
)) {
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. */
1122 for (p
= list
; p
; p
= p
->next
)
1123 config_reset_line(fmt
, options
, p
->key
, use_defaults
);
1126 /* pass 3: assign. */
1129 if ((r
=config_assign_line(fmt
, options
, list
, use_defaults
, clear_first
)))
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
)
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
);
1154 if (options_validate(trial_options
) < 0) {
1155 config_free(&options_format
, trial_options
);
1159 if (options_transition_allowed(get_options(), trial_options
) < 0) {
1160 config_free(&options_format
, trial_options
);
1164 set_options(trial_options
); /* we liked it. put it in place. */
1168 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
1169 * Called from option_reset() and config_free(). */
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
);
1178 case CONFIG_TYPE_DOUBLE
:
1179 *(double*)lvalue
= 0.0;
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
:
1188 case CONFIG_TYPE_MEMUNIT
:
1189 *(uint64_t*)lvalue
= 0;
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
;
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
;
1203 case CONFIG_TYPE_LINELIST_V
:
1204 /* handled by linelist_s. */
1206 case CONFIG_TYPE_OBSOLETE
:
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(). */
1215 option_reset(config_format_t
*fmt
, or_options_t
*options
,
1216 config_var_t
*var
, int use_defaults
)
1220 CHECK(fmt
, options
);
1221 option_clear(fmt
, options
, var
); /* clear it first */
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>->DirServers to contain the default directory
1237 add_default_trusted_dirservers(or_options_t
*options
)
1240 config_line_append(&options
->DirServers
, "DirServer",
1241 "v1 18.244.0.188:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441");
1243 config_line_append(&options
->DirServers
, "DirServer",
1244 "v1 18.244.0.114:80 719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF");
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. */
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
)
1272 struct hostent
*rent
;
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");
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 */
1298 rent
= (struct hostent
*)gethostbyname(hostname
);
1300 log_fn(LOG_WARN
,"Could not resolve local Address '%s'. Failing.", hostname
);
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.",
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.",
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
;
1335 *hostname_out
= tor_strdup(hostname
);
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. */
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");
1352 /* Put it in lowercase; stop at the first dot. */
1353 for (cp
= localhostname
; *cp
; ++cp
) {
1361 /* Strip invalid characters. */
1363 out
= outp
= tor_malloc(strlen(localhostname
) + 1);
1365 if (strchr(LEGAL_NICKNAME_CHARACTERS
, *cp
))
1372 /* Enforce length. */
1373 if (strlen(out
) > MAX_NICKNAME_LEN
)
1374 out
[MAX_NICKNAME_LEN
]='\0';
1379 /** Release storage held by <b>options</b> */
1381 config_free(config_format_t
*fmt
, void *options
)
1385 tor_assert(options
);
1387 for (i
=0; fmt
->vars
[i
].name
; ++i
)
1388 option_clear(fmt
, options
, &(fmt
->vars
[i
]));
1392 /** Return true iff a and b contain identical keys and values in identical
1395 config_lines_eq(config_line_t
*a
, config_line_t
*b
)
1398 if (strcasecmp(a
->key
, b
->key
) || strcmp(a
->value
, b
->value
))
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.
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
;
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
);
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
;
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
)
1440 if (fmt
->vars
[i
].type
== CONFIG_TYPE_OBSOLETE
)
1442 line
= get_assigned_option(fmt
, old
, fmt
->vars
[i
].name
);
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().");
1450 config_free_lines(line
);
1455 /** Return a new empty or_options_t. Used for testing. */
1459 return config_alloc(&options_format
);
1462 /** Set <b>options</b> to hold reasonable defaults for most options.
1463 * Each option defaults to zero. */
1465 options_init(or_options_t
*options
)
1467 config_init(&options_format
, options
);
1472 config_init(config_format_t
*fmt
, void *options
)
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);
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
;
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
)
1506 /* Don't save 'hidden' control variables. */
1507 if (!strcmpstart(fmt
->vars
[i
].name
, "__"))
1509 if (minimal
&& option_is_same(fmt
, options
, defaults
, fmt
->vars
[i
].name
))
1512 desc
= config_find_description(fmt
, fmt
->vars
[i
].name
);
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;
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");
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
);
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.
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. */
1554 validate_ports_csv(smartlist_t
*sl
, const char *name
)
1563 SMARTLIST_FOREACH(sl
, const char *, cp
,
1566 if (i
< 1 || i
> 65535) {
1567 log(LOG_WARN
, "Port '%s' out of range in %s", cp
, name
);
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.");
1591 /** Return true iff the firewall options might block any address:port
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
);
1609 case ADDR_POLICY_PROBABLY_ACCEPTED
:
1610 case ADDR_POLICY_ACCEPTED
:
1612 case ADDR_POLICY_PROBABLY_REJECTED
:
1613 case ADDR_POLICY_REJECTED
:
1616 log_fn(LOG_WARN
, "Unexpected result: %d", (int)p
);
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>. */
1625 options_validate(or_options_t
*options
)
1629 addr_policy_t
*addr_policy
=NULL
;
1631 if (options
->ORPort
< 0 || options
->ORPort
> 65535) {
1632 log(LOG_WARN
, "ORPort option out of bounds.");
1636 if (options
->ORPort
== 0 && options
->ORBindAddress
!= NULL
) {
1637 log(LOG_WARN
, "ORPort must be defined if ORBindAddress is defined.");
1640 if (options
->DirPort
== 0 && options
->DirBindAddress
!= NULL
) {
1641 log(LOG_WARN
, "DirPort must be defined if DirBindAddress is defined.");
1644 if (options
->SocksPort
== 0 && options
->SocksBindAddress
!= NULL
) {
1645 log(LOG_WARN
, "SocksPort must be defined if SocksBindAddress is defined.");
1649 if (validate_data_directory(options
)<0) {
1650 log(LOG_WARN
, "Invalid DataDirectory");
1654 if (options
->Nickname
== NULL
) {
1655 if (server_mode(options
)) {
1656 if (!(options
->Nickname
= get_default_nickname()))
1658 log_fn(LOG_NOTICE
, "Choosing default nickname '%s'", options
->Nickname
);
1661 if (!is_legal_nickname(options
->Nickname
)) {
1662 log_fn(LOG_WARN
, "Nickname '%s' is wrong length or contains illegal characters.", options
->Nickname
);
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
))
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) */
1681 if (server_mode(options
)) {
1682 /* confirm that our address isn't broken, so we can complain now */
1684 if (resolve_my_address(options
, &tmp
, NULL
) < 0)
1688 if (options
->SocksPort
< 0 || options
->SocksPort
> 65535) {
1689 log(LOG_WARN
, "SocksPort option out of bounds.");
1693 if (options
->SocksPort
== 0 && options
->ORPort
== 0) {
1694 log(LOG_WARN
, "SocksPort and ORPort are both undefined? Quitting.");
1698 if (options
->ControlPort
< 0 || options
->ControlPort
> 65535) {
1699 log(LOG_WARN
, "ControlPort option out of bounds.");
1703 if (options
->DirPort
< 0 || options
->DirPort
> 65535) {
1704 log(LOG_WARN
, "DirPort option out of bounds.");
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");
1723 if (!options
->RecommendedVersions
) {
1724 log(LOG_WARN
, "Authoritative directory servers must configure RecommendedVersions.");
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.");
1740 if (options
->AuthoritativeDir
&& !options
->ORPort
) {
1741 log(LOG_WARN
, "Running as authoritative directory, but no ORPort set.");
1745 if (options
->AuthoritativeDir
&& options
->ClientOnly
) {
1746 log(LOG_WARN
, "Running as authoritative directory, but ClientOnly also set.");
1750 if (options
->AuthoritativeDir
&& options
->NoPublish
) {
1751 log(LOG_WARN
, "You cannot set both AuthoritativeDir and NoPublish.");
1755 if (options
->ConnLimit
<= 0) {
1756 log(LOG_WARN
, "ConnLimit must be greater than 0, but was set to %d",
1757 options
->ConnLimit
);
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)
1771 if (validate_ports_csv(options
->LongLivedPorts
,
1772 "LongLivedPorts") < 0)
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
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
);
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
;
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
;
1828 log(LOG_WARN
, "Unrecognized value '%s' in AllowUnverifiedNodes",
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.");
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.");
1894 if (options
->BandwidthRate
> INT_MAX
) {
1895 log(LOG_WARN
,"BandwidthRate must be less than %d",INT_MAX
);
1898 if (options
->BandwidthBurst
> INT_MAX
) {
1899 log(LOG_WARN
,"BandwidthBurst must be less than %d",INT_MAX
);
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);
1907 if (options
->BandwidthRate
> options
->BandwidthBurst
) {
1908 log(LOG_WARN
,"BandwidthBurst must be at least equal to BandwidthRate.");
1912 if (accounting_parse_options(options
, 1)<0) {
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.");
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).");
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.");
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).");
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");
1958 if (options
->HashedControlPassword
&& options
->CookieAuthentication
) {
1959 log_fn(LOG_WARN
,"Cannot enable both HashedControlPassword and CookieAuthentication");
1963 if (options
->UseHelperNodes
&& ! options
->NumHelperNodes
) {
1964 log_fn(LOG_WARN
, "Cannot enable UseHelperNodes with NumHelperNodes set to 0");
1968 if (check_nickname_list(options
->ExitNodes
, "ExitNodes"))
1970 if (check_nickname_list(options
->EntryNodes
, "EntryNodes"))
1972 if (check_nickname_list(options
->ExcludeNodes
, "ExcludeNodes"))
1974 if (check_nickname_list(options
->RendNodes
, "RendNodes"))
1976 if (check_nickname_list(options
->RendNodes
, "RendExcludeNodes"))
1978 if (check_nickname_list(options
->MyFamily
, "MyFamily"))
1980 for (cl
= options
->NodeFamilies
; cl
; cl
= cl
->next
) {
1981 if (check_nickname_list(cl
->value
, "NodeFamily"))
1985 if (config_parse_addr_policy(options
->ExitPolicy
, &addr_policy
, -1)) {
1986 log_fn(LOG_WARN
, "Error in Exit Policy entry.");
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.");
1999 if (config_parse_addr_policy(options
->SocksPolicy
, &addr_policy
, -1)) {
2000 log_fn(LOG_WARN
, "Error in SocksPolicy entry.");
2003 if (config_parse_addr_policy(options
->ReachableAddresses
, &addr_policy
,
2004 ADDR_POLICY_ACCEPT
)) {
2005 log_fn(LOG_WARN
, "Error in ReachableAddresses entry.");
2008 addr_policy_free(addr_policy
);
2010 for (cl
= options
->RedirectExit
; cl
; cl
= cl
->next
) {
2011 if (parse_redirect_line(NULL
, cl
)<0)
2015 if (!options
->DirServers
) {
2016 add_default_trusted_dirservers(options
);
2018 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
) {
2019 if (parse_dir_server_line(cl
->value
, 1)<0)
2024 if (rend_config_services(options
, 1) < 0)
2030 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
2033 opt_streq(const char *s1
, const char *s2
)
2037 else if (s1
&& s2
&& !strcmp(s1
,s2
))
2043 /** Check if any of the previous options have changed but aren't allowed to. */
2045 options_transition_allowed(or_options_t
*old
, or_options_t
*new_val
)
2050 if (!opt_streq(old
->PidFile
, new_val
->PidFile
)) {
2051 log_fn(LOG_WARN
,"PidFile is not allowed to change. Failing.");
2055 if (old
->RunAsDaemon
!= new_val
->RunAsDaemon
) {
2056 log_fn(LOG_WARN
,"While Tor is running, changing RunAsDaemon is not allowed. Failing.");
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
);
2065 if (!opt_streq(old
->User
, new_val
->User
)) {
2066 log_fn(LOG_WARN
,"While Tor is running, changing User is not allowed. Failing.");
2070 if (!opt_streq(old
->Group
, new_val
->Group
)) {
2071 log_fn(LOG_WARN
,"While Tor is running, changing Group is not allowed. Failing.");
2075 if (old
->HardwareAccel
!= new_val
->HardwareAccel
) {
2076 log_fn(LOG_WARN
,"While Tor is running, changing HardwareAccel is not allowed. Failing.");
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. */
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
))
2096 /* Check whether log options match. */
2098 /* Nothing that changed matters. */
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. */
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
)
2128 /** Return the directory on windows where we expect to find our application
2131 get_windows_conf_root(void)
2133 static int is_set
= 0;
2134 static char path
[MAX_PATH
+1];
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
,
2148 GetCurrentDirectory(MAX_PATH
, path
);
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
);
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 */
2158 m
->lpVtbl
->Free(m
, idl
);
2159 m
->lpVtbl
->Release(m
);
2161 if (!SUCCEEDED(result
)) {
2164 strlcat(path
,"\\tor",MAX_PATH
);
2170 /** Return the default location for our torrc file. */
2172 get_default_conf_file(void)
2175 static char path
[MAX_PATH
+1];
2176 strlcpy(path
, get_windows_conf_root(), MAX_PATH
);
2177 strlcat(path
,"\\torrc",MAX_PATH
);
2180 return (CONFDIR
"/torrc");
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.
2188 check_nickname_list(const char *lst
, const char *name
)
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
);
2204 SMARTLIST_FOREACH(sl
, char *, s
, tor_free(s
));
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
;
2218 char *cf
=NULL
, *fname
=NULL
;
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 */
2228 } else { /* we're reloading. need to clean up old options first. */
2231 oldoptions
= get_options();
2233 if (argc
> 1 && (!strcmp(argv
[1], "-h") || !strcmp(argv
[1],"--help"))) {
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();
2246 newoptions
= tor_malloc_zero(sizeof(or_options_t
));
2247 newoptions
->_magic
= OR_OPTIONS_MAGIC
;
2248 options_init(newoptions
);
2250 /* learn config file name */
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")) {
2257 log(LOG_WARN
, "Duplicate -f options on command line.");
2260 fname
= tor_strdup(argv
[i
+1]);
2261 using_default_torrc
= 0;
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] : "");
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();
2277 if (dflt
&& file_status(dflt
) == FN_FILE
) {
2278 fname
= tor_strdup(dflt
);
2281 fn
= expand_filename("~/.torrc");
2282 if (fn
&& file_status(fn
) == FN_FILE
) {
2286 fname
= tor_strdup(dflt
);
2289 fname
= tor_strdup(dflt
);
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 */
2304 log(LOG_WARN
, "Unable to open configuration file \"%s\".", fname
);
2308 } else { /* it opened successfully. use it. */
2309 retval
= config_get_lines(cf
, &cl
);
2313 retval
= config_assign(&options_format
, newoptions
, cl
, 0, 0);
2314 config_free_lines(cl
);
2319 /* Go through command-line variables too */
2320 if (config_get_commandlines(argc
, argv
, &cl
) < 0)
2322 retval
= config_assign(&options_format
, newoptions
, cl
, 0, 0);
2323 config_free_lines(cl
);
2327 /* Validate newoptions */
2328 if (options_validate(newoptions
) < 0)
2331 if (options_transition_allowed(oldoptions
, newoptions
) < 0)
2334 set_options(newoptions
); /* frees and replaces old options */
2335 tor_free(torrc_fname
);
2336 torrc_fname
= fname
;
2340 config_free(&options_format
, newoptions
);
2344 /** Return the location for our configuration file.
2347 get_torrc_fname(void)
2352 return get_default_conf_file();
2355 /** Adjust the address map mased on the MapAddress elements in the
2356 * configuration <b>options</b>
2359 config_register_addressmaps(or_options_t
*options
)
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
);
2378 addressmap_register(from
, tor_strdup(to
), 0);
2379 if (smartlist_len(elts
)>2) {
2380 log_fn(LOG_WARN
,"Ignoring extra arguments to MapAddress.");
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
2399 parse_log_severity_range(const char *range
, int *min_out
, int *max_out
)
2401 int levelMin
, levelMax
;
2403 cp
= strchr(range
, '-');
2406 levelMin
= LOG_DEBUG
;
2408 char *tmp_sev
= tor_strndup(range
, cp
- range
);
2409 levelMin
= parse_log_level(tmp_sev
);
2411 log_fn(LOG_WARN
, "Unrecognized log severity '%s': must be one of "
2412 "err|warn|notice|info|debug", tmp_sev
);
2421 levelMax
= parse_log_level(cp
+1);
2423 log_fn(LOG_WARN
, "Unrecognized log severity '%s': must be one of "
2424 "err|warn|notice|info|debug", cp
+1);
2429 levelMin
= parse_log_level(range
);
2431 log_fn(LOG_WARN
, "Unrecognized log severity '%s': must be one of "
2432 "err|warn|notice|info|debug", range
);
2438 *min_out
= levelMin
;
2439 *max_out
= levelMax
;
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
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;
2454 if (parse_log_severity_range(level_opt
->value
, &levelMin
, &levelMax
))
2457 if (levelMin
< 0 && levelMax
< 0) {
2458 levelMin
= LOG_NOTICE
;
2460 } else if (levelMin
< 0) {
2461 levelMin
= levelMax
;
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
,
2472 } else if (file_opt
&& !strcasecmp(file_opt
->key
, "SysLog")) {
2473 if (add_single_log_option(options
, levelMin
, levelMax
, "syslog", NULL
) < 0)
2475 } else if (!isDaemon
) {
2476 add_single_log_option(options
, levelMin
, levelMax
, "stdout", NULL
);
2482 * Initialize the logs based on the configuration file.
2485 options_init_logs(or_options_t
*options
, int validate_only
)
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 */
2506 add_stream_log(levelMin
, levelMax
, "<stdout>", stdout
);
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
;
2515 add_file_log(levelMin
, levelMax
, smartlist_get(elts
, 2));
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
);
2527 } else if (!strcasecmp(smartlist_get(elts
,1), "stderr")) {
2528 if (!validate_only
) {
2529 add_stream_log(levelMin
, levelMax
, "<stderr>", stderr
);
2532 } else if (!strcasecmp(smartlist_get(elts
,1), "syslog")) {
2533 #ifdef HAVE_SYSLOG_H
2535 add_syslog_log(levelMin
, levelMax
);
2537 log_fn(LOG_WARN
, "Syslog is not supported in this compilation.");
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
;
2549 SMARTLIST_FOREACH(elts
, char*, cp
, tor_free(cp
));
2550 smartlist_clear(elts
);
2552 smartlist_free(elts
);
2559 /** Add a single option of the form Log min-max \<type\> [fname] to options. */
2561 add_single_log_option(or_options_t
*options
, int minSeverity
, int maxSeverity
,
2562 const char *type
, const char *fname
)
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
:"");
2573 log_fn(LOG_WARN
, "Normalized log option too long.");
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
);
2582 /** Convert all old-style logging options to new-style Log options. Return 0
2583 * on success, -1 on failure. */
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)
2597 opt
= opt
->next
->next
;
2598 } else if (!opt
->next
) {
2599 if (convert_log_option(options
, opt
, NULL
, options
->RunAsDaemon
) < 0)
2603 ; /* give warning below */
2608 if (!strcasecmp(opt
->key
, "LogLevel")) {
2609 log_fn(LOG_WARN
, "Two LogLevel options in a row without intervening LogFile or SysLog");
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)
2618 opt
= opt
->next
->next
;
2620 /* LogFile/SysLog followed by LogFile/SysLog or end of list. */
2621 if (convert_log_option(options
,NULL
, opt
, options
->RunAsDaemon
) < 0)
2628 if (options
->DebugLogFile
) {
2629 if (add_single_log_option(options
, LOG_DEBUG
, LOG_ERR
, "file", options
->DebugLogFile
) < 0)
2633 tor_free(options
->DebugLogFile
);
2634 config_free_lines(options
->OldLogOptions
);
2635 options
->OldLogOptions
= NULL
;
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>
2645 options_append_default_exit_policy(addr_policy_t
**policy
)
2651 tmp
.value
= (char*)DEFAULT_EXIT_POLICY
;
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) {
2659 addr_policy_free(ap
->next
);
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
,
2677 addr_policy_t
**nextp
;
2678 smartlist_t
*entries
;
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
);
2697 nextp
= &((*nextp
)->next
);
2699 log_fn(LOG_WARN
,"Malformed policy '%s'.", ent
);
2703 SMARTLIST_FOREACH(entries
, char *, ent
, tor_free(ent
));
2704 smartlist_clear(entries
);
2706 smartlist_free(entries
);
2710 /** Release all storage held by <b>p</b> */
2712 addr_policy_free(addr_policy_t
*p
)
2719 tor_free(e
->string
);
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. */
2729 parse_redirect_line(smartlist_t
*result
, config_line_t
*line
)
2731 smartlist_t
*elements
= NULL
;
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");
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");
2749 if (0==strcasecmp(smartlist_get(elements
,1), "pass")) {
2752 if (parse_addr_port(smartlist_get(elements
,1),NULL
,&r
->addr_dest
,
2754 log_fn(LOG_WARN
, "Error parsing dest address in RedirectExit line");
2764 SMARTLIST_FOREACH(elements
, char *, cp
, tor_free(cp
));
2765 smartlist_free(elements
);
2768 smartlist_add(result
, r
);
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. */
2782 parse_dir_server_line(const char *line
, int validate_only
)
2784 smartlist_t
*items
= NULL
;
2786 char *addrport
, *address
=NULL
;
2788 char digest
[DIGEST_LEN
];
2789 int supports_v1
= 1; /*XXXX011 change default when clients support v2. */
2791 while (TOR_ISSPACE(*line
))
2794 if (!strcmpstart(line
, "v1 ")) {
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.");
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
);
2812 log_fn(LOG_WARN
, "Missing port in DirServer address '%s'",addrport
);
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.");
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.");
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
);
2840 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
2841 smartlist_free(items
);
2846 /** Adjust the value of options->DataDirectory, or fill it in if it's
2847 * absent. Return 0 on success, -1 on failure. */
2849 normalize_data_directory(or_options_t
*options
)
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
;
2860 const char *d
= options
->DataDirectory
;
2864 if (strncmp(d
,"~/",2) == 0) {
2865 char *fn
= expand_filename(d
);
2867 log_fn(LOG_ERR
,"Failed to expand filename \"%s\".", d
);
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
);
2875 fn
= tor_strdup(LOCALSTATEDIR
"/tor");
2878 tor_free(options
->DataDirectory
);
2879 options
->DataDirectory
= fn
;
2885 /** Check and normalize the value of options->DataDirectory; return 0 if it
2886 * sane, -1 otherwise. */
2888 validate_data_directory(or_options_t
*options
)
2890 if (normalize_data_directory(options
) < 0)
2892 tor_assert(options
->DataDirectory
);
2893 if (strlen(options
->DataDirectory
) > (512-128)) {
2894 log_fn(LOG_ERR
, "DataDirectory is too long.");
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. */
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
;
2914 switch (file_status(fname
)) {
2916 old_val
= read_file_to_str(fname
, 0);
2917 if (strcmpstart(old_val
, GENERATED_FILE_PREFIX
)) {
2925 log_fn(LOG_WARN
,"Config file \"%s\" is not a file? Failing.", fname
);
2930 if (!(new_conf
= options_dump(options
, 1))) {
2931 log_fn(LOG_WARN
, "Couldn't get configuration string");
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
);
2941 size_t fn_tmp_len
= strlen(fname
)+32;
2943 tor_assert(fn_tmp_len
> strlen(fname
)); /*check for overflow*/
2944 fn_tmp
= tor_malloc(fn_tmp_len
);
2946 if (tor_snprintf(fn_tmp
, fn_tmp_len
, "%s.orig.%d", fname
, i
)<0) {
2947 log_fn(LOG_WARN
, "tor_snprintf failed inexplicably");
2951 if (file_status(fn_tmp
) == FN_NOENT
)
2955 log_fn(LOG_NOTICE
, "Renaming old configuration file to \"%s\"", fn_tmp
);
2956 rename(fname
, fn_tmp
);
2960 write_str_to_file(fname
, new_val
, 0);
2973 * Save the current configuration file value to disk. Return 0 on
2974 * success, -1 on failure.
2977 options_save_current(void)
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
{
2990 uint64_t multiplier
;
2993 static struct unit_table_t memory_units
[] = {
2999 { "kilobyte", 1<<10 },
3000 { "kilobytes", 1<<10 },
3003 { "megabyte", 1<<20 },
3004 { "megabytes", 1<<20 },
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 },
3014 static struct unit_table_t time_units
[] = {
3022 { "day", 24*60*60 },
3023 { "days", 24*60*60 },
3024 { "week", 7*24*60*60 },
3025 { "weeks", 7*24*60*60 },
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.
3036 config_parse_units(const char *val
, struct unit_table_t
*u
, int *ok
)
3043 v
= tor_parse_uint64(val
, 10, 0, UINT64_MAX
, ok
, &cp
);
3050 while (TOR_ISSPACE(*cp
))
3052 for ( ;u
->unit
;++u
) {
3053 if (!strcasecmp(u
->unit
, cp
)) {
3059 log_fn(LOG_WARN
, "Unknown unit '%s'.", cp
);
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. */
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.
3078 config_parse_interval(const char *s
, int *ok
) {
3080 r
= config_parse_units(s
, time_units
, ok
);
3084 log_fn(LOG_WARN
, "Interval '%s' is too long", s
);
3092 * Initialize the libevent library.
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");
3103 putenv("EVENT_NOKQUEUE=1");
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);
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.");
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.
3129 check_libevent_version(const char *m
, const char *v
, int server
)
3131 int buggy
= 0, iffy
= 0, slow
= 0;
3135 if (!strcmp(m
, "kqueue")) {
3136 if (!strcmp(v
, "1.0c") || !strcmp(v
, "1.0d") || !strcmp(v
, "1.0e") ||
3137 !strcmp(v
, "1.1")) {
3140 } else if (!strcmp(m
, "epoll")) {
3141 if (!strcmp(v
, "1.0c") || !strcmp(v
, "1.0d") || !strcmp(v
, "1.0e"))
3143 } else if (!strcmp(m
, "poll")) {
3144 if (!strcmp(v
, "1.0c") || !strcmp(v
, "1.0d"))
3146 else if (!strcmp(v
, "1.0e"))
3148 } else if (!strcmp(m
, "poll")) {
3149 if (!strcmp(v
, "1.0c") || !strcmp(v
, "1.0d") || !strcmp(v
, "1.0e"))
3155 "There are known bugs in using %s with libevent %s. "
3156 "Please use the latest version of libevent.", m
, v
);
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
) {
3163 "libevent %s can be very slow with %s. "
3164 "When running a server, please use the latest version of libevent.",v
,m
);
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
3177 * We could just dump unrecognized variables if you downgrade.
3179 * This needs thought. XXXX NM
3186 return global_state
;
3191 get_or_state_fname(void)
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
);
3203 or_state_validate(or_state_t
*state
)
3206 if (helper_nodes_parse_state(state
, 0, &err
)<0) {
3207 log_fn(LOG_WARN
, "Unable to parse helper nodes: %s", err
);
3215 or_state_set(or_state_t
*new_state
)
3218 tor_assert(new_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
);
3231 or_state_t
*new_state
= NULL
;
3232 char *contents
= NULL
, *fname
;
3235 fname
= get_or_state_fname();
3236 switch (file_status(fname
)) {
3238 if (!(contents
= read_file_to_str(fname
, 0))) {
3239 log_fn(LOG_WARN
, "Unable to read state file \"%s\"", fname
);
3246 log_fn(LOG_WARN
,"State file \"%s\" is not a file? Failing.", fname
);
3249 new_state
= tor_malloc_zero(sizeof(or_state_t
));
3250 new_state
->_magic
= OR_STATE_MAGIC
;
3251 config_init(&state_format
, new_state
);
3253 config_line_t
*lines
=NULL
;
3255 if (config_get_lines(contents
, &lines
)<0)
3257 assign_retval
= config_assign(&state_format
, new_state
, lines
, 0, 0);
3258 config_free_lines(lines
);
3259 if (assign_retval
<0)
3263 if (or_state_validate(new_state
) < 0)
3267 log_fn(LOG_INFO
, "Loaded state from \"%s\"", fname
);
3269 log_fn(LOG_INFO
, "Initialized state");
3270 or_state_set(new_state
);
3273 global_state
->dirty
= 1;
3282 config_free(&state_format
, new_state
);
3291 char *state
, *contents
;
3292 char tbuf
[ISO_TIME_LEN
+1];
3296 helper_nodes_update_state(global_state
);
3298 if (!global_state
->dirty
)
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",
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
);
3318 log_fn(LOG_INFO
, "Saved state to \"%s\"", fname
);
3322 global_state
->dirty
= 0;
3328 config_getinfo_helper(const char *question
, char **answer
)
3330 if (!strcmp(question
, "config/names")) {
3331 smartlist_t
*sl
= smartlist_create();
3333 for (i
= 0; _option_vars
[i
].name
; ++i
) {
3334 config_var_t
*var
= &_option_vars
[i
];
3335 const char *type
, *desc
;
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;
3352 case CONFIG_TYPE_OBSOLETE
:
3357 len
= strlen(var
->name
)+strlen(type
)+16;
3359 len
+= strlen(desc
);
3360 line
= tor_malloc(len
);
3362 tor_snprintf(line
, len
, "%s %s %s\n",var
->name
,type
,desc
);
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
));
3374 /** Dump the version of every file to the log. */
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
[];
3416 puts(CONTAINER_H_ID
);
3425 puts(container_c_id
);
3434 puts(circuitbuild_c_id
);
3435 puts(circuitlist_c_id
);
3436 puts(circuituse_c_id
);
3439 puts(connection_c_id
);
3440 puts(connection_edge_c_id
);
3441 puts(connection_or_c_id
);
3443 puts(cpuworker_c_id
);
3444 puts(directory_c_id
);
3447 puts(hibernate_c_id
);
3451 puts(rendclient_c_id
);
3452 puts(rendcommon_c_id
);
3454 puts(rendservice_c_id
);
3457 puts(routerlist_c_id
);
3458 puts(routerparse_c_id
);