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$";
11 * \brief Code to parse and interpret configuration files.
18 #include "../common/aes.h"
20 /** Enumeration of types which option values can take */
21 typedef enum config_type_t
{
22 CONFIG_TYPE_STRING
= 0, /**< An arbitrary string. */
23 CONFIG_TYPE_UINT
, /**< A non-negative integer less than MAX_INT */
24 CONFIG_TYPE_INTERVAL
, /**< A number of seconds, with optional units*/
25 CONFIG_TYPE_MEMUNIT
, /**< A number of bytes, with optional units*/
26 CONFIG_TYPE_DOUBLE
, /**< A floating-point value */
27 CONFIG_TYPE_BOOL
, /**< A boolean value, expressed as 0 or 1. */
28 CONFIG_TYPE_CSV
, /**< A list of strings, separated by commas and optional
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 config_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. */
81 /** Return the offset of <b>member</b> within the type <b>tp</b>, in bytes */
82 #define STRUCT_OFFSET(tp, member) ((off_t) (((char*)&((tp*)0)->member)-(char*)0))
83 /** An entry for config_vars: "The option <b>name</b> has type
84 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
85 * or_options_t.<b>member</b>"
87 #define VAR(name,conftype,member,initvalue) \
88 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), initvalue }
89 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
90 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
92 /** Array of configuration options. Until we disallow nonstandard
93 * abbreviations, order is significant, since the first matching option will
96 static config_var_t config_vars
[] = {
97 VAR("Address", STRING
, Address
, NULL
),
98 VAR("AccountingStart", STRING
, AccountingStart
, NULL
),
99 VAR("AllowUnverifiedNodes",CSV
, AllowUnverifiedNodes
, "middle,rendezvous"),
100 VAR("AuthoritativeDirectory",BOOL
, AuthoritativeDir
, "0"),
101 VAR("BandwidthRate", MEMUNIT
, BandwidthRate
, "2 MB"),
102 VAR("BandwidthBurst", MEMUNIT
, BandwidthBurst
, "5 MB"),
103 VAR("MaxAdvertisedBandwidth",MEMUNIT
,MaxAdvertisedBandwidth
,"128 TB"),
104 VAR("ClientOnly", BOOL
, ClientOnly
, "0"),
105 VAR("ContactInfo", STRING
, ContactInfo
, NULL
),
106 VAR("ControlPort", UINT
, ControlPort
, "0"),
107 VAR("CookieAuthentication",BOOL
, CookieAuthentication
, "0"),
108 VAR("DebugLogFile", STRING
, DebugLogFile
, NULL
),
109 VAR("DataDirectory", STRING
, DataDirectory
, NULL
),
110 VAR("DirAllowPrivateAddresses",BOOL
, DirAllowPrivateAddresses
, NULL
),
111 VAR("DirPort", UINT
, DirPort
, "0"),
112 VAR("DirBindAddress", LINELIST
, DirBindAddress
, NULL
),
114 VAR("DirFetchPeriod", INTERVAL
, DirFetchPeriod
, "0 seconds"),
115 VAR("DirPostPeriod", INTERVAL
, DirPostPeriod
, "20 minutes"),
116 VAR("RendPostPeriod", INTERVAL
, RendPostPeriod
, "20 minutes"),
117 VAR("DirPolicy", LINELIST
, DirPolicy
, NULL
),
118 VAR("DirServer", LINELIST
, DirServers
, NULL
),
119 VAR("ExitNodes", STRING
, ExitNodes
, NULL
),
120 VAR("EntryNodes", STRING
, EntryNodes
, NULL
),
121 VAR("StrictExitNodes", BOOL
, StrictExitNodes
, "0"),
122 VAR("StrictEntryNodes", BOOL
, StrictEntryNodes
, "0"),
123 VAR("ExitPolicy", LINELIST
, ExitPolicy
, NULL
),
124 VAR("ExcludeNodes", STRING
, ExcludeNodes
, NULL
),
125 VAR("TrackHostExits", CSV
, TrackHostExits
, NULL
),
126 VAR("TrackHostExitsExpire",INTERVAL
, TrackHostExitsExpire
, "30 minutes"),
127 VAR("MapAddress", LINELIST
, AddressMap
, NULL
),
128 VAR("FascistFirewall", BOOL
, FascistFirewall
, "0"),
129 VAR("FirewallPorts", CSV
, FirewallPorts
, "80,443"),
130 VAR("MyFamily", STRING
, MyFamily
, NULL
),
131 VAR("NodeFamily", LINELIST
, NodeFamilies
, NULL
),
132 VAR("NoPublish", BOOL
, NoPublish
, "0"),
133 VAR("Group", STRING
, Group
, NULL
),
134 VAR("HashedControlPassword",STRING
, HashedControlPassword
, NULL
),
135 VAR("HttpProxy", STRING
, HttpProxy
, NULL
),
136 VAR("HttpsProxy", STRING
, HttpsProxy
, NULL
),
137 VAR("HttpsProxyAuthenticator",STRING
,HttpsProxyAuthenticator
,NULL
),
138 VAR("HiddenServiceOptions",LINELIST_V
, RendConfigLines
, NULL
),
139 VAR("HiddenServiceDir", LINELIST_S
, RendConfigLines
, NULL
),
140 VAR("HiddenServicePort", LINELIST_S
, RendConfigLines
, NULL
),
141 VAR("HiddenServiceNodes", LINELIST_S
, RendConfigLines
, NULL
),
142 VAR("HiddenServiceExcludeNodes", LINELIST_S
, RendConfigLines
, NULL
),
143 VAR("IgnoreVersion", BOOL
, IgnoreVersion
, "0"),
144 VAR("KeepalivePeriod", INTERVAL
, KeepalivePeriod
, "5 minutes"),
145 VAR("Log", LINELIST
, Logs
, NULL
),
146 VAR("LogLevel", LINELIST_S
, OldLogOptions
, NULL
),
147 VAR("LogFile", LINELIST_S
, OldLogOptions
, NULL
),
148 OBSOLETE("LinkPadding"),
149 VAR("ConnLimit", UINT
, ConnLimit
, "1024"),
150 VAR("MaxOnionsPending", UINT
, MaxOnionsPending
, "100"),
151 VAR("MonthlyAccountingStart",UINT
, _MonthlyAccountingStart
,"0"),
152 VAR("AccountingMaxKB", UINT
, _AccountingMaxKB
, "0"),
153 VAR("AccountingMax", MEMUNIT
, AccountingMax
, "0 bytes"),
154 VAR("Nickname", STRING
, Nickname
, NULL
),
155 VAR("NewCircuitPeriod", INTERVAL
, NewCircuitPeriod
, "30 seconds"),
156 VAR("MaxCircuitDirtiness", INTERVAL
, MaxCircuitDirtiness
, "10 minutes"),
157 VAR("NumCpus", UINT
, NumCpus
, "1"),
158 VAR("ORPort", UINT
, ORPort
, "0"),
159 VAR("ORBindAddress", LINELIST
, ORBindAddress
, NULL
),
160 VAR("OutboundBindAddress", STRING
, OutboundBindAddress
, NULL
),
161 VAR("PidFile", STRING
, PidFile
, NULL
),
162 VAR("LongLivedPorts", CSV
, LongLivedPorts
, "21,22,706,1863,5050,5190,5222,5223,6667,8300,8888"),
163 VAR("PathlenCoinWeight", DOUBLE
, PathlenCoinWeight
, "0.3"),
164 VAR("RedirectExit", LINELIST
, RedirectExit
, NULL
),
165 OBSOLETE("RouterFile"),
166 VAR("RunAsDaemon", BOOL
, RunAsDaemon
, "0"),
167 VAR("RunTesting", BOOL
, RunTesting
, "0"),
168 VAR("RecommendedVersions", LINELIST
, RecommendedVersions
, NULL
),
169 VAR("RendNodes", STRING
, RendNodes
, NULL
),
170 VAR("RendExcludeNodes", STRING
, RendExcludeNodes
, NULL
),
171 VAR("ShutdownWaitLength", INTERVAL
, ShutdownWaitLength
, "30 seconds"),
172 VAR("SocksPort", UINT
, SocksPort
, "9050"),
173 VAR("SocksBindAddress", LINELIST
, SocksBindAddress
, NULL
),
174 VAR("SocksPolicy", LINELIST
, SocksPolicy
, NULL
),
176 VAR("StatusFetchPeriod", INTERVAL
, StatusFetchPeriod
, "0 seconds"),
177 VAR("SysLog", LINELIST_S
, OldLogOptions
, NULL
),
178 OBSOLETE("TrafficShaping"),
179 VAR("User", STRING
, User
, NULL
),
180 VAR("__LeaveStreamsUnattached", BOOL
,LeaveStreamsUnattached
, "0"),
181 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
186 /** Largest allowed config line */
187 #define CONFIG_LINE_T_MAXLEN 4096
189 static void config_line_append(struct config_line_t
**lst
,
190 const char *key
, const char *val
);
191 static void option_reset(or_options_t
*options
, config_var_t
*var
);
192 static void options_free(or_options_t
*options
);
193 static int option_is_same(or_options_t
*o1
, or_options_t
*o2
,const char *name
);
194 static or_options_t
*options_dup(or_options_t
*old
);
195 static int options_validate(or_options_t
*options
);
196 static int options_transition_allowed(or_options_t
*old
, or_options_t
*new);
197 static int check_nickname_list(const char *lst
, const char *name
);
198 static void config_register_addressmaps(or_options_t
*options
);
200 static int parse_dir_server_line(const char *line
, int validate_only
);
201 static int parse_redirect_line(smartlist_t
*result
,
202 struct config_line_t
*line
);
203 static int parse_log_severity_range(const char *range
, int *min_out
,
205 static int convert_log_option(or_options_t
*options
,
206 struct config_line_t
*level_opt
,
207 struct config_line_t
*file_opt
, int isDaemon
);
208 static int add_single_log_option(or_options_t
*options
, int minSeverity
,
210 const char *type
, const char *fname
);
211 static int normalize_log_options(or_options_t
*options
);
212 static int validate_data_directory(or_options_t
*options
);
213 static int write_configuration_file(const char *fname
, or_options_t
*options
);
215 static uint64_t config_parse_memunit(const char *s
, int *ok
);
216 static int config_parse_interval(const char *s
, int *ok
);
217 static void print_cvs_version(void);
220 * Functions to read and write the global options pointer.
223 /** Command-line and config-file options. */
224 static or_options_t
*global_options
=NULL
;
225 /** Name of most recently read torrc file. */
226 static char *config_fname
= NULL
;
228 /** Return the currently configured options. */
231 tor_assert(global_options
);
232 return global_options
;
235 /** Change the current global options to contain <b>new_val</b> instead
236 * of their current value; free the old value as necessary.
239 set_options(or_options_t
*new_val
) {
241 options_free(global_options
);
242 global_options
= new_val
;
246 config_free_all(void)
248 options_free(global_options
);
249 tor_free(config_fname
);
252 /** Fetch the active option list, and take actions based on it. All
253 * of the things we do should survive being done repeatedly.
254 * Return 0 if all goes well, return -1 if it's time to die.
256 * Note 1: <b>new_val</b> must have previously been validated with
257 * options_validate(), or Tor may freak out and exit.
259 * Note 2: We haven't moved all the "act on new configuration" logic
260 * here yet. Some is still in do_hup() and other places.
264 struct config_line_t
*cl
;
265 or_options_t
*options
= get_options();
266 static int libevent_initialized
= 0;
268 /* XXXX009 We once had a reason to separate start_daemon and finish_daemon:
269 * It let us have the parent process stick around until we were sure Tor
270 * was started. Should we make start_daemon get called earlier? -NM */
271 if (options
->RunAsDaemon
) {
274 if (!libevent_initialized
) {
275 configure_libevent_logging();
276 suppress_libevent_log_msg("function not implemented");
278 suppress_libevent_log_msg(NULL
);
279 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
280 /* Making this a NOTICE for now so we can link bugs to a libevent versions
281 * or methods better. */
282 log_fn(LOG_NOTICE
, "Initialized libevent version %s using method %s",
283 event_get_version(), event_get_method());
285 log_fn(LOG_NOTICE
, "Initialized old libevent (version 1.0b or earlier)");
287 libevent_initialized
= 1;
290 clear_trusted_dir_servers();
291 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
) {
292 if (parse_dir_server_line(cl
->value
, 0)<0) {
294 "Bug: Previously validated DirServer line could not be added!");
299 if (rend_config_services(options
, 0)<0) {
301 "Bug: Previously validated hidden services line could not be added!");
305 /* Setuid/setgid as appropriate */
306 if (options
->User
|| options
->Group
) {
307 if (switch_id(options
->User
, options
->Group
) != 0) {
312 /* Ensure data directory is private; create if possible. */
313 if (check_private_dir(options
->DataDirectory
, CPD_CREATE
) != 0) {
314 log_fn(LOG_ERR
, "Couldn't access/create private data directory %s",
315 options
->DataDirectory
);
319 /* Bail out at this point if we're not going to be a server: we want
320 * to not fork, and to log stuff to stderr. */
321 if (options
->command
!= CMD_RUN_TOR
)
324 mark_logs_temp(); /* Close current logs once new logs are open. */
325 if (config_init_logs(options
, 0)<0) /* Configure the log(s) */
327 /* Close the temporary log we used while starting up, if it isn't already
330 add_callback_log(LOG_ERR
, LOG_ERR
, control_event_logmsg
);
331 adjust_event_log_severity();
333 options
->_ConnLimit
=
334 set_max_file_descriptors((unsigned)options
->ConnLimit
, MAXCONNECTIONS
);
335 if (options
->_ConnLimit
< 0)
339 smartlist_t
*sl
= smartlist_create();
340 for (cl
= options
->RedirectExit
; cl
; cl
= cl
->next
) {
341 if (parse_redirect_line(sl
, cl
)<0)
344 set_exit_redirects(sl
);
347 /* Finish backgrounding the process */
348 if (options
->RunAsDaemon
) {
349 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
350 finish_daemon(options
->DataDirectory
);
353 /* Write our pid to the pid file. If we do not have write permissions we
354 * will log a warning */
355 if (options
->PidFile
)
356 write_pidfile(options
->PidFile
);
358 /* Register addressmap directives */
359 config_register_addressmaps(options
);
361 /* Update address policies. */
362 parse_socks_policy();
365 init_cookie_authentication(options
->CookieAuthentication
);
367 /* reload keys as needed for rendezvous services. */
368 if (rend_service_load_keys()<0) {
369 log_fn(LOG_ERR
,"Error loading rendezvous service keys");
373 /* Set up accounting */
374 if (accounting_parse_options(options
, 0)<0) {
375 log_fn(LOG_ERR
,"Error in accounting options");
378 if (accounting_is_enabled(options
))
379 configure_accounting(time(NULL
));
381 if (!we_are_hibernating() && retry_all_listeners(1) < 0) {
382 log_fn(LOG_ERR
,"Failed to bind one of the listener ports.");
389 smin
= config_dump_options(options
, 1);
390 smax
= config_dump_options(options
, 0);
391 log_fn(LOG_DEBUG
, "These are our options:\n%s",smax
);
392 log_fn(LOG_DEBUG
, "We changed these options:\n%s",smin
);
398 /* Since our options changed, we might need to regenerate and upload our
399 * server descriptor. (We could probably be more clever about only calling
400 * this when something significant changed.)
402 mark_my_descriptor_dirty();
408 * Functions to parse config options
411 /** If <b>option</b> is an official abbreviation for a longer option,
412 * return the longer option. Otherwise return <b>option</b>.
413 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
414 * apply abbreviations that work for the config file and the command line. */
416 expand_abbrev(const char *option
, int command_line
)
419 for (i
=0; config_abbrevs
[i
].abbreviated
; ++i
) {
420 /* Abbreviations aren't casei. */
421 if (!strcasecmp(option
,config_abbrevs
[i
].abbreviated
) &&
422 (command_line
|| !config_abbrevs
[i
].commandline_only
)) {
423 return config_abbrevs
[i
].full
;
429 /** Helper: Read a list of configuration options from the command line. */
430 static struct config_line_t
*
431 config_get_commandlines(int argc
, char **argv
)
433 struct config_line_t
*new;
434 struct config_line_t
*front
= NULL
;
439 if (!strcmp(argv
[i
],"-f") ||
440 !strcmp(argv
[i
],"--hash-password")) {
441 i
+= 2; /* command-line option with argument. ignore them. */
443 } else if (!strcmp(argv
[i
],"--list-fingerprint")) {
444 i
+= 1; /* command-line option. ignore it. */
446 } else if (!strcmp(argv
[i
],"--nt-service")) {
451 new = tor_malloc(sizeof(struct config_line_t
));
457 new->key
= tor_strdup(expand_abbrev(s
, 1));
458 new->value
= tor_strdup(argv
[i
+1]);
460 log(LOG_DEBUG
,"Commandline: parsed keyword '%s', value '%s'",
461 new->key
, new->value
);
469 /** Helper: allocate a new configuration option mapping 'key' to 'val',
470 * append it to *<b>lst</b>. */
472 config_line_append(struct config_line_t
**lst
,
476 struct config_line_t
*newline
;
478 newline
= tor_malloc(sizeof(struct config_line_t
));
479 newline
->key
= tor_strdup(key
);
480 newline
->value
= tor_strdup(val
);
481 newline
->next
= NULL
;
483 lst
= &((*lst
)->next
);
488 /** Helper: parse the config string and strdup into key/value
489 * strings. Set *result to the list, or NULL if parsing the string
490 * failed. Return 0 on success, -1 on failure. Warn and ignore any
491 * misformatted lines. */
493 config_get_lines(char *string
, struct config_line_t
**result
)
495 struct config_line_t
*list
= NULL
, **next
;
500 string
= parse_line_from_str(string
, &k
, &v
);
502 config_free_lines(list
);
506 /* This list can get long, so we keep a pointer to the end of it
507 * rather than using config_line_append over and over and getting n^2
508 * performance. This is the only really long list. */
509 *next
= tor_malloc(sizeof(struct config_line_t
));
510 (*next
)->key
= tor_strdup(k
);
511 (*next
)->value
= tor_strdup(v
);
512 (*next
)->next
= NULL
;
513 next
= &((*next
)->next
);
522 * Free all the configuration lines on the linked list <b>front</b>.
525 config_free_lines(struct config_line_t
*front
)
527 struct config_line_t
*tmp
;
534 tor_free(tmp
->value
);
539 /** If <b>key</b> is a configuration option, return the corresponding
540 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
541 * warn, and return the corresponding config_var_t. Otherwise return NULL.
543 static config_var_t
*config_find_option(const char *key
)
546 size_t keylen
= strlen(key
);
548 return NULL
; /* if they say "--" on the commandline, it's not an option */
549 /* First, check for an exact (case-insensitive) match */
550 for (i
=0; config_vars
[i
].name
; ++i
) {
551 if (!strcasecmp(key
, config_vars
[i
].name
))
552 return &config_vars
[i
];
554 /* If none, check for an abbreviated match */
555 for (i
=0; config_vars
[i
].name
; ++i
) {
556 if (!strncasecmp(key
, config_vars
[i
].name
, keylen
)) {
557 log_fn(LOG_WARN
, "The abbreviation '%s' is deprecated. "
558 "Tell Nick and Roger to make it official, or just use '%s' instead",
559 key
, config_vars
[i
].name
);
560 return &config_vars
[i
];
563 /* Okay, unrecognized options */
567 /** If <b>c</b> is a syntactically valid configuration line, update
568 * <b>options</b> with its value and return 0. Otherwise return -1 for bad key,
571 * If 'reset' is set, and we get a line containing no value, restore the
572 * option to its default value.
575 config_assign_line(or_options_t
*options
, struct config_line_t
*c
, int reset
)
581 var
= config_find_option(c
->key
);
583 log_fn(LOG_WARN
, "Unknown option '%s'. Failing.", c
->key
);
586 /* Put keyword into canonical case. */
587 if (strcmp(var
->name
, c
->key
)) {
589 c
->key
= tor_strdup(var
->name
);
592 if (reset
&& !strlen(c
->value
)) {
593 option_reset(options
, var
);
597 lvalue
= ((char*)options
) + var
->var_offset
;
600 case CONFIG_TYPE_UINT
:
601 i
= tor_parse_long(c
->value
, 10, 0, INT_MAX
, &ok
, NULL
);
603 log(LOG_WARN
, "Int keyword '%s %s' is malformed or out of bounds.",
610 case CONFIG_TYPE_INTERVAL
: {
611 i
= config_parse_interval(c
->value
, &ok
);
619 case CONFIG_TYPE_MEMUNIT
: {
620 uint64_t u64
= config_parse_memunit(c
->value
, &ok
);
624 *(uint64_t *)lvalue
= u64
;
628 case CONFIG_TYPE_BOOL
:
629 i
= tor_parse_long(c
->value
, 10, 0, 1, &ok
, NULL
);
631 log(LOG_WARN
, "Boolean keyword '%s' expects 0 or 1.", c
->key
);
637 case CONFIG_TYPE_STRING
:
638 tor_free(*(char **)lvalue
);
639 *(char **)lvalue
= tor_strdup(c
->value
);
642 case CONFIG_TYPE_DOUBLE
:
643 *(double *)lvalue
= atof(c
->value
);
646 case CONFIG_TYPE_CSV
:
647 if (*(smartlist_t
**)lvalue
) {
648 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
649 smartlist_clear(*(smartlist_t
**)lvalue
);
651 *(smartlist_t
**)lvalue
= smartlist_create();
654 smartlist_split_string(*(smartlist_t
**)lvalue
, c
->value
, ",",
655 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
658 case CONFIG_TYPE_LINELIST
:
659 case CONFIG_TYPE_LINELIST_S
:
660 config_line_append((struct config_line_t
**)lvalue
, c
->key
, c
->value
);
663 case CONFIG_TYPE_OBSOLETE
:
664 log_fn(LOG_WARN
, "Skipping obsolete configuration option '%s'", c
->key
);
666 case CONFIG_TYPE_LINELIST_V
:
667 log_fn(LOG_WARN
, "Can't provide value for virtual option '%s'", c
->key
);
676 /** restore the option named <b>key</b> in options to its default value. */
678 config_reset_line(or_options_t
*options
, const char *key
)
682 var
= config_find_option(key
);
684 return; /* give error on next pass. */
686 option_reset(options
, var
);
689 /** Return true iff key is a valid configuration option. */
691 config_option_is_recognized(const char *key
)
693 config_var_t
*var
= config_find_option(key
);
694 return (var
!= NULL
);
697 /** Return a canonicalized list of the options assigned for key.
699 struct config_line_t
*
700 config_get_assigned_option(or_options_t
*options
, const char *key
)
705 struct config_line_t
*result
;
706 tor_assert(options
&& key
);
708 var
= config_find_option(key
);
710 log_fn(LOG_WARN
, "Unknown option '%s'. Failing.", key
);
712 } else if (var
->type
== CONFIG_TYPE_LINELIST_S
) {
713 log_fn(LOG_WARN
, "Can't return context-sensitive '%s' on its own", key
);
716 value
= ((char*)options
) + var
->var_offset
;
718 if (var
->type
== CONFIG_TYPE_LINELIST
||
719 var
->type
== CONFIG_TYPE_LINELIST_V
) {
720 /* Linelist requires special handling: we just copy and return it. */
721 const struct config_line_t
*next_in
= *(const struct config_line_t
**)value
;
722 struct config_line_t
**next_out
= &result
;
724 *next_out
= tor_malloc(sizeof(struct config_line_t
));
725 (*next_out
)->key
= tor_strdup(next_in
->key
);
726 (*next_out
)->value
= tor_strdup(next_in
->value
);
727 next_in
= next_in
->next
;
728 next_out
= &((*next_out
)->next
);
734 result
= tor_malloc_zero(sizeof(struct config_line_t
));
735 result
->key
= tor_strdup(var
->name
);
738 case CONFIG_TYPE_STRING
:
739 if (*(char**)value
) {
740 result
->value
= tor_strdup(*(char**)value
);
742 tor_free(result
->key
);
747 case CONFIG_TYPE_INTERVAL
:
748 case CONFIG_TYPE_UINT
:
749 /* This means every or_options_t uint or bool element
750 * needs to be an int. Not, say, a uint16_t or char. */
751 tor_snprintf(buf
, sizeof(buf
), "%d", *(int*)value
);
752 result
->value
= tor_strdup(buf
);
754 case CONFIG_TYPE_MEMUNIT
:
755 tor_snprintf(buf
, sizeof(buf
), U64_FORMAT
,
756 U64_PRINTF_ARG(*(uint64_t*)value
));
757 result
->value
= tor_strdup(buf
);
759 case CONFIG_TYPE_DOUBLE
:
760 tor_snprintf(buf
, sizeof(buf
), "%f", *(double*)value
);
761 result
->value
= tor_strdup(buf
);
763 case CONFIG_TYPE_BOOL
:
764 result
->value
= tor_strdup(*(int*)value
? "1" : "0");
766 case CONFIG_TYPE_CSV
:
767 if (*(smartlist_t
**)value
)
768 result
->value
= smartlist_join_strings(*(smartlist_t
**)value
,",",0,NULL
);
770 result
->value
= tor_strdup("");
772 case CONFIG_TYPE_OBSOLETE
:
773 log_fn(LOG_WARN
,"You asked me for the value of an obsolete config option %s.", key
);
774 tor_free(result
->key
);
778 tor_free(result
->key
);
780 log_fn(LOG_WARN
,"Bug: unknown type %d for known key %s", var
->type
, key
);
787 /** Iterate through the linked list of requested options <b>list</b>.
788 * For each item, convert as appropriate and assign to <b>options</b>.
789 * If an item is unrecognized, return -1 immediately,
790 * else return 0 for success.
792 * If <b>reset</b>, then interpret empty lines as meaning "restore to
793 * default value", and interpret LINELIST* options as replacing (not
794 * extending) their previous values. Return 0 on success, -1 on bad key,
798 config_assign(or_options_t
*options
, struct config_line_t
*list
, int reset
)
800 struct config_line_t
*p
;
803 /* pass 1: normalize keys */
804 for (p
= list
; p
; p
= p
->next
) {
805 const char *full
= expand_abbrev(p
->key
, 0);
806 if (strcmp(full
,p
->key
)) {
808 p
->key
= tor_strdup(full
);
812 /* pass 2: if we're reading from a resetting source, clear all mentioned
815 for (p
= list
; p
; p
= p
->next
)
816 config_reset_line(options
, p
->key
);
819 /* pass 3: assign. */
822 if ((r
=config_assign_line(options
, list
, reset
)))
829 /** Try assigning <b>list</b> to the global options. You do this by duping
830 * options, assigning list to the new one, then validating it. If it's
831 * ok, then throw out the old one and stick with the new one. Else,
832 * revert to old and return failure. Return 0 on success, -1 on bad
833 * keys, -2 on bad values, -3 on bad transition.
836 config_trial_assign(struct config_line_t
*list
, int reset
)
839 or_options_t
*trial_options
= options_dup(get_options());
841 if ((r
=config_assign(trial_options
, list
, reset
)) < 0) {
842 options_free(trial_options
);
846 if (options_validate(trial_options
) < 0) {
847 options_free(trial_options
);
851 if (options_transition_allowed(get_options(), trial_options
) < 0) {
852 options_free(trial_options
);
856 set_options(trial_options
); /* we liked it. put it in place. */
860 /** Replace the option indexed by <b>var</b> in <b>options</b> with its
863 option_reset(or_options_t
*options
, config_var_t
*var
)
865 struct config_line_t
*c
;
868 lvalue
= ((char*)options
) + var
->var_offset
;
870 case CONFIG_TYPE_STRING
:
871 tor_free(*(char**)lvalue
);
873 case CONFIG_TYPE_DOUBLE
:
874 *(double*)lvalue
= 0.0;
876 case CONFIG_TYPE_INTERVAL
:
877 case CONFIG_TYPE_UINT
:
878 case CONFIG_TYPE_BOOL
:
881 case CONFIG_TYPE_MEMUNIT
:
882 *(uint64_t*)lvalue
= 0;
884 case CONFIG_TYPE_CSV
:
885 if (*(smartlist_t
**)lvalue
) {
886 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
887 smartlist_free(*(smartlist_t
**)lvalue
);
888 *(smartlist_t
**)lvalue
= NULL
;
891 case CONFIG_TYPE_LINELIST
:
892 case CONFIG_TYPE_LINELIST_S
:
893 config_free_lines(*(struct config_line_t
**)lvalue
);
894 *(struct config_line_t
**)lvalue
= NULL
;
896 case CONFIG_TYPE_LINELIST_V
:
897 /* handled by linelist_s. */
899 case CONFIG_TYPE_OBSOLETE
:
902 if (var
->initvalue
) {
903 c
= tor_malloc_zero(sizeof(struct config_line_t
));
904 c
->key
= tor_strdup(var
->name
);
905 c
->value
= tor_strdup(var
->initvalue
);
906 config_assign_line(options
,c
,0);
907 config_free_lines(c
);
911 /** Set <b>options</b>->DirServers to contain the default directory
914 add_default_trusted_dirservers(or_options_t
*options
)
917 config_line_append(&options
->DirServers
, "DirServer",
918 "18.244.0.188:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441");
920 config_line_append(&options
->DirServers
, "DirServer",
921 "18.244.0.114:80 719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF");
923 config_line_append(&options
->DirServers
, "DirServer",
924 "62.116.124.106:9030 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D");
925 // "tor.noreply.org:9030 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D");
928 /** Print a usage message for tor. */
933 "Copyright 2001-2004 Roger Dingledine, Nick Mathewson, Matej Pfajfar.\n\n"
934 "tor -f <torrc> [args]\n"
935 "See man page for options, or http://tor.eff.org/ for documentation.\n");
939 * Based on <b>address</b>, guess our public IP address and put it
943 resolve_my_address(const char *address
, uint32_t *addr
)
946 struct hostent
*rent
;
949 char tmpbuf
[INET_NTOA_BUF_LEN
];
950 static uint32_t old_addr
=0;
954 /* workaround: some people were leaving "Address " in their torrc,
955 * and they had a buggy resolver that resolved " " to 0.0.0.0. Oops.
958 while (TOR_ISSPACE(*address
))
961 if (address
&& *address
) {
962 strlcpy(hostname
, address
, sizeof(hostname
));
963 } else { /* then we need to guess our address */
964 explicit_ip
= 0; /* it's implicit */
966 if (gethostname(hostname
, sizeof(hostname
)) < 0) {
967 log_fn(LOG_WARN
,"Error obtaining local hostname");
970 log_fn(LOG_DEBUG
,"Guessed local host name as '%s'",hostname
);
973 /* now we know hostname. resolve it and keep only the IP */
975 if (tor_inet_aton(hostname
, &in
) == 0) {
976 /* then we have to resolve it */
978 rent
= (struct hostent
*)gethostbyname(hostname
);
980 log_fn(LOG_WARN
,"Could not resolve local Address %s. Failing.", hostname
);
983 tor_assert(rent
->h_length
== 4);
984 memcpy(&in
.s_addr
, rent
->h_addr
, rent
->h_length
);
987 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
988 if (!explicit_ip
&& is_internal_IP(htonl(in
.s_addr
))) {
989 log_fn(LOG_WARN
,"Address '%s' resolves to private IP '%s'. "
990 "Please set the Address config option to be the IP you want to use.",
995 log_fn(LOG_DEBUG
, "Resolved Address to %s.", tmpbuf
);
996 *addr
= ntohl(in
.s_addr
);
997 if (old_addr
&& old_addr
!= *addr
) {
998 log_fn(LOG_NOTICE
,"Your IP seems to have changed. Updating.");
999 server_has_changed_ip();
1005 /** Called when we don't have a nickname set. Try to guess a good
1006 * nickname based on the hostname, and return it in a newly allocated string. */
1008 get_default_nickname(void)
1010 char localhostname
[256];
1011 char *cp
, *out
, *outp
;
1013 if (gethostname(localhostname
, sizeof(localhostname
)) < 0) {
1014 log_fn(LOG_WARN
,"Error obtaining local hostname");
1018 /* Put it in lowercase; stop at the first dot. */
1019 for (cp
= localhostname
; *cp
; ++cp
) {
1027 /* Strip invalid characters. */
1029 out
= outp
= tor_malloc(strlen(localhostname
) + 1);
1031 if (strchr(LEGAL_NICKNAME_CHARACTERS
, *cp
))
1038 /* Enforce length. */
1039 if (strlen(out
) > MAX_NICKNAME_LEN
)
1040 out
[MAX_NICKNAME_LEN
]='\0';
1045 /** Release storage held by <b>options</b> */
1047 options_free(or_options_t
*options
)
1052 tor_assert(options
);
1054 for (i
=0; config_vars
[i
].name
; ++i
) {
1055 lvalue
= ((char*)options
) + config_vars
[i
].var_offset
;
1056 switch (config_vars
[i
].type
) {
1057 case CONFIG_TYPE_MEMUNIT
:
1058 case CONFIG_TYPE_INTERVAL
:
1059 case CONFIG_TYPE_UINT
:
1060 case CONFIG_TYPE_BOOL
:
1061 case CONFIG_TYPE_DOUBLE
:
1062 case CONFIG_TYPE_OBSOLETE
:
1063 break; /* nothing to free for these config types */
1064 case CONFIG_TYPE_STRING
:
1065 tor_free(*(char **)lvalue
);
1067 case CONFIG_TYPE_LINELIST
:
1068 case CONFIG_TYPE_LINELIST_V
:
1069 config_free_lines(*(struct config_line_t
**)lvalue
);
1070 *(struct config_line_t
**)lvalue
= NULL
;
1072 case CONFIG_TYPE_CSV
:
1073 if (*(smartlist_t
**)lvalue
) {
1074 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
1075 smartlist_free(*(smartlist_t
**)lvalue
);
1076 *(smartlist_t
**)lvalue
= NULL
;
1079 case CONFIG_TYPE_LINELIST_S
:
1080 /* will be freed by corresponding LINELIST_V. */
1087 /** Return true iff the option <b>var</b> has the same value in <b>o1</b>
1088 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
1091 option_is_same(or_options_t
*o1
, or_options_t
*o2
, const char *name
)
1093 struct config_line_t
*c1
, *c2
;
1095 c1
= config_get_assigned_option(o1
, name
);
1096 c2
= config_get_assigned_option(o2
, name
);
1098 if (strcasecmp(c1
->key
, c2
->key
) ||
1099 strcmp(c1
->value
, c2
->value
)) {
1106 if (r
&& (c1
|| c2
)) {
1109 config_free_lines(c1
);
1110 config_free_lines(c2
);
1114 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
1115 static or_options_t
*
1116 options_dup(or_options_t
*old
)
1118 or_options_t
*newopts
;
1120 struct config_line_t
*line
;
1122 newopts
= tor_malloc_zero(sizeof(or_options_t
));
1123 for (i
=0; config_vars
[i
].name
; ++i
) {
1124 if (config_vars
[i
].type
== CONFIG_TYPE_LINELIST_S
)
1126 if (config_vars
[i
].type
== CONFIG_TYPE_OBSOLETE
)
1128 line
= config_get_assigned_option(old
, config_vars
[i
].name
);
1130 if (config_assign(newopts
, line
, 0) < 0) {
1131 log_fn(LOG_WARN
,"Bug: config_get_assigned_option() generated "
1132 "something we couldn't config_assign().");
1136 config_free_lines(line
);
1141 /** Set <b>options</b> to hold reasonable defaults for most options.
1142 * Each option defaults to zero. */
1144 options_init(or_options_t
*options
)
1149 for (i
=0; config_vars
[i
].name
; ++i
) {
1150 var
= &config_vars
[i
];
1151 if (!var
->initvalue
)
1152 continue; /* defaults to NULL or 0 */
1153 option_reset(options
, var
);
1157 /** Return a string containing a possible configuration file that would give
1158 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
1159 * include options that are the same as Tor's defaults.
1162 config_dump_options(or_options_t
*options
, int minimal
)
1164 smartlist_t
*elements
;
1165 or_options_t
*defaults
;
1166 struct config_line_t
*line
;
1170 defaults
= tor_malloc_zero(sizeof(or_options_t
));
1171 options_init(defaults
);
1172 options_validate(defaults
); /* ??? will this work? */
1174 elements
= smartlist_create();
1175 for (i
=0; config_vars
[i
].name
; ++i
) {
1176 if (config_vars
[i
].type
== CONFIG_TYPE_OBSOLETE
||
1177 config_vars
[i
].type
== CONFIG_TYPE_LINELIST_S
)
1179 /* Don't save 'hidden' control variables. */
1180 if (!strcmpstart(config_vars
[i
].name
, "__"))
1182 if (minimal
&& option_is_same(options
, defaults
, config_vars
[i
].name
))
1184 line
= config_get_assigned_option(options
, config_vars
[i
].name
);
1185 for (; line
; line
= line
->next
) {
1186 size_t len
= strlen(line
->key
) + strlen(line
->value
) + 3;
1188 tmp
= tor_malloc(len
);
1189 if (tor_snprintf(tmp
, len
, "%s %s\n", line
->key
, line
->value
)<0) {
1190 log_fn(LOG_ERR
, "Internal error writing log option");
1193 smartlist_add(elements
, tmp
);
1195 config_free_lines(line
);
1198 result
= smartlist_join_strings(elements
, "", 0, NULL
);
1199 SMARTLIST_FOREACH(elements
, char *, cp
, tor_free(cp
));
1200 smartlist_free(elements
);
1205 validate_ports_csv(smartlist_t
*sl
, const char *name
) {
1213 SMARTLIST_FOREACH(sl
, const char *, cp
,
1216 if (i
< 1 || i
> 65535) {
1217 log(LOG_WARN
, "Port '%s' out of range in %s", cp
, name
);
1224 /** Return 0 if every setting in <b>options</b> is reasonable. Else
1225 * warn and return -1. Should have no side effects, except for
1226 * normalizing the contents of <b>options</b>. */
1228 options_validate(or_options_t
*options
)
1231 struct config_line_t
*cl
;
1232 addr_policy_t
*addr_policy
=NULL
;
1234 if (options
->ORPort
< 0 || options
->ORPort
> 65535) {
1235 log(LOG_WARN
, "ORPort option out of bounds.");
1239 /* XXX might similarly want to check the other *BindAddress options */
1240 if (options
->ORPort
== 0 && options
->ORBindAddress
!= NULL
) {
1241 log(LOG_WARN
, "ORPort must be defined if ORBindAddress is defined.");
1245 if (validate_data_directory(options
)<0) {
1246 log(LOG_WARN
, "Invalid DataDirectory");
1250 if (options
->Nickname
== NULL
) {
1251 if (server_mode(options
)) {
1252 if (!(options
->Nickname
= get_default_nickname()))
1254 log_fn(LOG_NOTICE
, "Choosing default nickname %s", options
->Nickname
);
1257 if (strspn(options
->Nickname
, LEGAL_NICKNAME_CHARACTERS
) !=
1258 strlen(options
->Nickname
)) {
1259 log_fn(LOG_WARN
, "Nickname '%s' contains illegal characters.", options
->Nickname
);
1262 if (strlen(options
->Nickname
) == 0) {
1263 log_fn(LOG_WARN
, "Nickname must have at least one character");
1266 if (strlen(options
->Nickname
) > MAX_NICKNAME_LEN
) {
1267 log_fn(LOG_WARN
, "Nickname '%s' has more than %d characters.",
1268 options
->Nickname
, MAX_NICKNAME_LEN
);
1273 if (normalize_log_options(options
))
1276 /* Special case if no options are given. */
1277 if (!options
->Logs
) {
1278 config_line_append(&options
->Logs
, "Log", "notice stdout");
1281 if (config_init_logs(options
, 1)<0) /* Validate the log(s) */
1284 if (server_mode(options
)) {
1285 /* confirm that our address isn't broken, so we can complain now */
1287 if (resolve_my_address(options
->Address
, &tmp
) < 0)
1291 if (options
->SocksPort
< 0 || options
->SocksPort
> 65535) {
1292 log(LOG_WARN
, "SocksPort option out of bounds.");
1296 if (options
->SocksPort
== 0 && options
->ORPort
== 0) {
1297 log(LOG_WARN
, "SocksPort and ORPort are both undefined? Quitting.");
1301 if (options
->ControlPort
< 0 || options
->ControlPort
> 65535) {
1302 log(LOG_WARN
, "ControlPort option out of bounds.");
1306 if (options
->DirPort
< 0 || options
->DirPort
> 65535) {
1307 log(LOG_WARN
, "DirPort option out of bounds.");
1311 if (options
->StrictExitNodes
&&
1312 (!options
->ExitNodes
|| !strlen(options
->ExitNodes
))) {
1313 log(LOG_WARN
, "StrictExitNodes set, but no ExitNodes listed.");
1316 if (options
->StrictEntryNodes
&&
1317 (!options
->EntryNodes
|| !strlen(options
->EntryNodes
))) {
1318 log(LOG_WARN
, "StrictEntryNodes set, but no EntryNodes listed.");
1321 if (options
->AuthoritativeDir
&& options
->RecommendedVersions
== NULL
) {
1322 log(LOG_WARN
, "Directory servers must configure RecommendedVersions.");
1326 if (options
->AuthoritativeDir
&& !options
->DirPort
) {
1327 log(LOG_WARN
, "Running as authoritative directory, but no DirPort set.");
1331 if (options
->AuthoritativeDir
&& !options
->ORPort
) {
1332 log(LOG_WARN
, "Running as authoritative directory, but no ORPort set.");
1336 if (options
->AuthoritativeDir
&& options
->ClientOnly
) {
1337 log(LOG_WARN
, "Running as authoritative directory, but ClientOnly also set.");
1341 if (options
->AuthoritativeDir
&& options
->NoPublish
) {
1342 log(LOG_WARN
, "You cannot set both AuthoritativeDir and NoPublish.");
1346 if (options
->ConnLimit
<= 0) {
1347 log(LOG_WARN
, "ConnLimit must be greater than 0, but was set to %d",
1348 options
->ConnLimit
);
1352 if (options
->_AccountingMaxKB
) {
1353 log(LOG_WARN
, "AccountingMaxKB is deprecated. Say 'AccountingMax %d KB' instead.", options
->_AccountingMaxKB
);
1354 options
->AccountingMax
= U64_LITERAL(1024)*options
->_AccountingMaxKB
;
1355 options
->_AccountingMaxKB
= 0;
1358 if (validate_ports_csv(options
->FirewallPorts
,
1359 "FirewallPorts") < 0)
1362 if (validate_ports_csv(options
->LongLivedPorts
,
1363 "LongLivedPorts") < 0)
1366 options
->_AllowUnverified
= 0;
1367 if (options
->AllowUnverifiedNodes
) {
1368 SMARTLIST_FOREACH(options
->AllowUnverifiedNodes
, const char *, cp
, {
1369 if (!strcasecmp(cp
, "entry"))
1370 options
->_AllowUnverified
|= ALLOW_UNVERIFIED_ENTRY
;
1371 else if (!strcasecmp(cp
, "exit"))
1372 options
->_AllowUnverified
|= ALLOW_UNVERIFIED_EXIT
;
1373 else if (!strcasecmp(cp
, "middle"))
1374 options
->_AllowUnverified
|= ALLOW_UNVERIFIED_MIDDLE
;
1375 else if (!strcasecmp(cp
, "introduction"))
1376 options
->_AllowUnverified
|= ALLOW_UNVERIFIED_INTRODUCTION
;
1377 else if (!strcasecmp(cp
, "rendezvous"))
1378 options
->_AllowUnverified
|= ALLOW_UNVERIFIED_RENDEZVOUS
;
1380 log(LOG_WARN
, "Unrecognized value '%s' in AllowUnverifiedNodes",
1387 if (options
->SocksPort
>= 1 &&
1388 (options
->PathlenCoinWeight
< 0.0 || options
->PathlenCoinWeight
>= 1.0)) {
1389 log(LOG_WARN
, "PathlenCoinWeight option must be >=0.0 and <1.0.");
1393 #define MIN_DIR_FETCH_PERIOD 600
1394 #define MIN_DIR_POST_PERIOD 300
1395 #define MIN_REND_POST_PERIOD 300
1396 #define MIN_STATUS_FETCH_PERIOD 60
1398 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
1399 #define MAX_CACHE_DIR_FETCH_PERIOD 3600
1400 #define MAX_CACHE_STATUS_FETCH_PERIOD 900
1402 if (options
->DirFetchPeriod
&&
1403 options
->DirFetchPeriod
< MIN_DIR_FETCH_PERIOD
) {
1404 log(LOG_WARN
, "DirFetchPeriod option must be at least %d seconds. Clipping.", MIN_DIR_FETCH_PERIOD
);
1405 options
->DirFetchPeriod
= MIN_DIR_FETCH_PERIOD
;
1407 if (options
->StatusFetchPeriod
&&
1408 options
->StatusFetchPeriod
< MIN_STATUS_FETCH_PERIOD
) {
1409 log(LOG_WARN
, "StatusFetchPeriod option must be at least %d seconds. Clipping.", MIN_STATUS_FETCH_PERIOD
);
1410 options
->StatusFetchPeriod
= MIN_STATUS_FETCH_PERIOD
;
1412 if (options
->DirPostPeriod
< MIN_DIR_POST_PERIOD
) {
1413 log(LOG_WARN
, "DirPostPeriod option must be at least %d seconds. Clipping.",
1414 MIN_DIR_POST_PERIOD
);
1415 options
->DirPostPeriod
= MIN_DIR_POST_PERIOD
;
1417 if (options
->RendPostPeriod
< MIN_REND_POST_PERIOD
) {
1418 log(LOG_WARN
,"RendPostPeriod option must be at least %d seconds. Clipping.",
1419 MIN_REND_POST_PERIOD
);
1420 options
->RendPostPeriod
= MIN_REND_POST_PERIOD
;
1423 if (options
->DirPort
&& ! options
->AuthoritativeDir
) {
1424 if (options
->DirFetchPeriod
> MAX_CACHE_DIR_FETCH_PERIOD
) {
1425 log(LOG_WARN
, "Caching directory servers must have DirFetchPeriod less than %d seconds. Clipping.", MAX_CACHE_DIR_FETCH_PERIOD
);
1426 options
->DirFetchPeriod
= MAX_CACHE_DIR_FETCH_PERIOD
;
1428 if (options
->StatusFetchPeriod
> MAX_CACHE_STATUS_FETCH_PERIOD
) {
1429 log(LOG_WARN
, "Caching directory servers must have StatusFetchPeriod less than %d seconds. Clipping.", MAX_CACHE_STATUS_FETCH_PERIOD
);
1430 options
->StatusFetchPeriod
= MAX_CACHE_STATUS_FETCH_PERIOD
;
1434 if (options
->DirFetchPeriod
> MAX_DIR_PERIOD
) {
1435 log(LOG_WARN
, "DirFetchPeriod is too large; clipping.");
1436 options
->DirFetchPeriod
= MAX_DIR_PERIOD
;
1438 if (options
->DirPostPeriod
> MAX_DIR_PERIOD
) {
1439 log(LOG_WARN
, "DirPostPeriod is too large; clipping.");
1440 options
->DirPostPeriod
= MAX_DIR_PERIOD
;
1442 if (options
->StatusFetchPeriod
> MAX_DIR_PERIOD
) {
1443 log(LOG_WARN
, "StatusFetchPeriod is too large; clipping.");
1444 options
->StatusFetchPeriod
= MAX_DIR_PERIOD
;
1446 if (options
->RendPostPeriod
> MAX_DIR_PERIOD
) {
1447 log(LOG_WARN
, "RendPostPeriod is too large; clipping.");
1448 options
->RendPostPeriod
= MAX_DIR_PERIOD
;
1451 if (options
->KeepalivePeriod
< 1) {
1452 log(LOG_WARN
,"KeepalivePeriod option must be positive.");
1456 if (options
->BandwidthRate
> INT_MAX
) {
1457 log(LOG_WARN
,"BandwidthRate must be less than %d",INT_MAX
);
1460 if (options
->BandwidthBurst
> INT_MAX
) {
1461 log(LOG_WARN
,"BandwidthBurst must be less than %d",INT_MAX
);
1464 if (server_mode(options
) &&
1465 options
->BandwidthRate
< ROUTER_REQUIRED_MIN_BANDWIDTH
*2) {
1466 log(LOG_WARN
,"BandwidthRate is set to %d bytes/second. For servers, it must be at least %d.", (int)options
->BandwidthRate
, ROUTER_REQUIRED_MIN_BANDWIDTH
*2);
1469 if (options
->BandwidthRate
> options
->BandwidthBurst
) {
1470 log(LOG_WARN
,"BandwidthBurst must be at least equal to BandwidthRate.");
1474 if (2*options
->BandwidthRate
> options
->BandwidthBurst
) {
1475 log(LOG_NOTICE
,"You have chosen a BandwidthBurst less than twice BandwidthRate. Please consider setting your BandwidthBurst higher (at least %d), to provide better service to the Tor network.", (int)(2*options
->BandwidthRate
));
1479 if (options
->_MonthlyAccountingStart
) {
1480 if (options
->AccountingStart
) {
1481 log(LOG_WARN
,"Can't specify AccountingStart and MonthlyAccountingStart");
1484 options
->AccountingStart
= tor_malloc(32);
1485 if (tor_snprintf(options
->AccountingStart
, 32, "month %d 0:00",
1486 options
->_MonthlyAccountingStart
)<0) {
1487 log_fn(LOG_WARN
,"Error translating MonthlyAccountingStart");
1490 log_fn(LOG_WARN
,"MonthlyAccountingStart is deprecated. Use 'AccountingStart %s' instead.", options
->AccountingStart
);
1495 if (accounting_parse_options(options
, 1)<0) {
1499 if (options
->HttpProxy
) { /* parse it now */
1500 if (parse_addr_port(options
->HttpProxy
, NULL
,
1501 &options
->HttpProxyAddr
, &options
->HttpProxyPort
) < 0) {
1502 log(LOG_WARN
,"HttpProxy failed to parse or resolve. Please fix.");
1505 if (options
->HttpProxyPort
== 0) { /* give it a default */
1506 options
->HttpProxyPort
= 80;
1510 if (options
->HttpsProxy
) { /* parse it now */
1511 if (parse_addr_port(options
->HttpsProxy
, NULL
,
1512 &options
->HttpsProxyAddr
, &options
->HttpsProxyPort
) < 0) {
1513 log(LOG_WARN
,"HttpsProxy failed to parse or resolve. Please fix.");
1516 if (options
->HttpsProxyPort
== 0) { /* give it a default */
1517 options
->HttpsProxyPort
= 443;
1521 if (options
->HttpsProxyAuthenticator
) {
1522 if (strlen(options
->HttpsProxyAuthenticator
) >= 48) {
1523 log(LOG_WARN
, "HttpsProxyAuthenticator is too long (>= 48 chars).");
1528 if (options
->HashedControlPassword
) {
1529 if (decode_hashed_password(NULL
, options
->HashedControlPassword
)<0) {
1530 log_fn(LOG_WARN
,"Bad HashedControlPassword: wrong length or bad base64");
1534 if (options
->HashedControlPassword
&& options
->CookieAuthentication
) {
1535 log_fn(LOG_WARN
,"Cannot enable both HashedControlPassword and CookieAuthentication");
1539 if (check_nickname_list(options
->ExitNodes
, "ExitNodes"))
1541 if (check_nickname_list(options
->EntryNodes
, "EntryNodes"))
1543 if (check_nickname_list(options
->ExcludeNodes
, "ExcludeNodes"))
1545 if (check_nickname_list(options
->RendNodes
, "RendNodes"))
1547 if (check_nickname_list(options
->RendNodes
, "RendExcludeNodes"))
1549 if (check_nickname_list(options
->MyFamily
, "MyFamily"))
1551 for (cl
= options
->NodeFamilies
; cl
; cl
= cl
->next
) {
1552 if (check_nickname_list(cl
->value
, "NodeFamily"))
1556 if (config_parse_addr_policy(options
->ExitPolicy
, &addr_policy
)) {
1557 log_fn(LOG_WARN
, "Error in Exit Policy entry.");
1560 if (server_mode(options
)) {
1561 exit_policy_implicitly_allows_local_networks(addr_policy
, 1);
1563 /* The rest of these calls *append* to addr_policy. So don't actually
1564 * use the results for anything other than checking if they parse! */
1565 if (config_parse_addr_policy(options
->DirPolicy
, &addr_policy
)) {
1566 log_fn(LOG_WARN
, "Error in DirPolicy entry.");
1569 if (config_parse_addr_policy(options
->SocksPolicy
, &addr_policy
)) {
1570 log_fn(LOG_WARN
, "Error in SocksPolicy entry.");
1573 addr_policy_free(addr_policy
);
1575 for (cl
= options
->RedirectExit
; cl
; cl
= cl
->next
) {
1576 if (parse_redirect_line(NULL
, cl
)<0)
1580 if (!options
->DirServers
) {
1581 add_default_trusted_dirservers(options
);
1583 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
) {
1584 if (parse_dir_server_line(cl
->value
, 1)<0)
1589 if (rend_config_services(options
, 1) < 0)
1595 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
1598 opt_streq(const char *s1
, const char *s2
)
1602 else if (s1
&& s2
&& !strcmp(s1
,s2
))
1608 /** Check if any of the previous options have changed but aren't allowed to. */
1610 options_transition_allowed(or_options_t
*old
, or_options_t
*new_val
) {
1615 if (!opt_streq(old
->PidFile
, new_val
->PidFile
)) {
1616 log_fn(LOG_WARN
,"PidFile is not allowed to change. Failing.");
1620 if (old
->RunAsDaemon
&& !new_val
->RunAsDaemon
) {
1621 log_fn(LOG_WARN
,"During reload, change from RunAsDaemon=1 to =0 not allowed. Failing.");
1625 if (old
->ORPort
!= new_val
->ORPort
) {
1626 log_fn(LOG_WARN
,"During reload, changing ORPort is not allowed. Failing.");
1630 if (strcmp(old
->DataDirectory
,new_val
->DataDirectory
)!=0) {
1631 log_fn(LOG_WARN
,"During reload, changing DataDirectory (%s->%s) is not allowed. Failing.", old
->DataDirectory
, new_val
->DataDirectory
);
1635 if (!opt_streq(old
->User
, new_val
->User
)) {
1636 log_fn(LOG_WARN
,"During reload, changing User is not allowed. Failing.");
1640 if (!opt_streq(old
->Group
, new_val
->Group
)) {
1641 log_fn(LOG_WARN
,"During reload, changing User is not allowed. Failing.");
1649 /** Return the directory on windows where we expect to find our application
1651 static char *get_windows_conf_root(void)
1653 static int is_set
= 0;
1654 static char path
[MAX_PATH
+1];
1663 /* Find X:\documents and settings\username\application data\ .
1664 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
1666 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL
, CSIDL_APPDATA
,
1668 GetCurrentDirectory(MAX_PATH
, path
);
1670 log_fn(LOG_WARN
, "I couldn't find your application data folder: are you running an ancient version of Windows 95? Defaulting to '%s'", path
);
1673 /* Convert the path from an "ID List" (whatever that is!) to a path. */
1674 result
= SHGetPathFromIDList(idl
, path
);
1675 /* Now we need to free the */
1678 m
->lpVtbl
->Free(m
, idl
);
1679 m
->lpVtbl
->Release(m
);
1681 if (!SUCCEEDED(result
)) {
1684 strlcat(path
,"\\tor",MAX_PATH
);
1690 /** Return the default location for our torrc file. */
1692 get_default_conf_file(void)
1695 char *path
= tor_malloc(MAX_PATH
);
1696 strlcpy(path
, get_windows_conf_root(), MAX_PATH
);
1697 strlcat(path
,"\\torrc",MAX_PATH
);
1700 return tor_strdup(CONFDIR
"/torrc");
1704 /** Verify whether lst is a string containing valid-looking space-separated
1705 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
1707 static int check_nickname_list(const char *lst
, const char *name
)
1714 sl
= smartlist_create();
1715 smartlist_split_string(sl
, lst
, ",", SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1716 SMARTLIST_FOREACH(sl
, const char *, s
,
1718 if (!is_legal_nickname_or_hexdigest(s
)) {
1719 log_fn(LOG_WARN
, "Invalid nickname '%s' in %s line", s
, name
);
1723 SMARTLIST_FOREACH(sl
, char *, s
, tor_free(s
));
1728 /** Read a configuration file into <b>options</b>, finding the configuration
1729 * file location based on the command line. After loading the options,
1730 * validate them for consistency, then take actions based on them.
1731 * Return 0 if success, -1 if failure. */
1733 init_from_config(int argc
, char **argv
)
1735 or_options_t
*oldoptions
, *newoptions
;
1736 struct config_line_t
*cl
;
1737 char *cf
=NULL
, *fname
=NULL
;
1739 int using_default_torrc
;
1740 static char **backup_argv
;
1741 static int backup_argc
;
1743 if (argv
) { /* first time we're called. save commandline args */
1747 } else { /* we're reloading. need to clean up old options first. */
1750 oldoptions
= get_options();
1752 if (argc
> 1 && (!strcmp(argv
[1], "-h") || !strcmp(argv
[1],"--help"))) {
1757 if (argc
> 1 && (!strcmp(argv
[1],"--version"))) {
1758 printf("Tor version %s.\n",VERSION
);
1759 if (argc
> 2 && (!strcmp(argv
[2],"--version"))) {
1760 print_cvs_version();
1765 newoptions
= tor_malloc_zero(sizeof(or_options_t
));
1766 options_init(newoptions
);
1768 /* learn config file name, get config lines, assign them */
1770 using_default_torrc
= 1;
1771 newoptions
->command
= CMD_RUN_TOR
;
1772 for (i
= 1; i
< argc
; ++i
) {
1773 if (i
< argc
-1 && !strcmp(argv
[i
],"-f")) {
1775 log(LOG_WARN
, "Duplicate -f options on command line.");
1778 fname
= tor_strdup(argv
[i
+1]);
1779 using_default_torrc
= 0;
1781 } else if (!strcmp(argv
[i
],"--list-fingerprint")) {
1782 newoptions
->command
= CMD_LIST_FINGERPRINT
;
1783 } else if (!strcmp(argv
[i
],"--hash-password")) {
1784 newoptions
->command
= CMD_HASH_PASSWORD
;
1785 newoptions
->command_arg
= tor_strdup( (i
< argc
-1) ? argv
[i
+1] : "");
1790 if (using_default_torrc
) {
1791 /* didn't find one, try CONFDIR */
1793 fn
= get_default_conf_file();
1794 if (fn
&& file_status(fn
) == FN_FILE
) {
1799 fn
= expand_filename("~/.torrc");
1800 if (fn
&& file_status(fn
) == FN_FILE
) {
1804 fname
= get_default_conf_file();
1807 fname
= get_default_conf_file();
1812 log(LOG_DEBUG
, "Opening config file '%s'", fname
);
1814 if (file_status(fname
) != FN_FILE
||
1815 !(cf
= read_file_to_str(fname
,0))) {
1816 if (using_default_torrc
== 1) {
1817 log(LOG_NOTICE
, "Configuration file '%s' not present, "
1818 "using reasonable defaults.", fname
);
1819 tor_free(fname
); /* sets fname to NULL */
1821 log(LOG_WARN
, "Unable to open configuration file '%s'.", fname
);
1825 } else { /* it opened successfully. use it. */
1826 retval
= config_get_lines(cf
, &cl
);
1830 retval
= config_assign(newoptions
, cl
, 0);
1831 config_free_lines(cl
);
1836 /* Go through command-line variables too */
1837 cl
= config_get_commandlines(argc
,argv
);
1838 retval
= config_assign(newoptions
,cl
,0);
1839 config_free_lines(cl
);
1843 /* Validate newoptions */
1844 if (options_validate(newoptions
) < 0)
1847 if (options_transition_allowed(oldoptions
, newoptions
) < 0)
1850 set_options(newoptions
); /* frees and replaces old options */
1851 if (options_act() < 0) { /* acting on them failed. die. */
1852 log_fn(LOG_ERR
,"Acting on config options left us in a broken state. Dying.");
1855 tor_free(config_fname
);
1856 config_fname
= fname
;
1860 options_free(newoptions
);
1865 config_register_addressmaps(or_options_t
*options
) {
1867 struct config_line_t
*opt
;
1870 addressmap_clear_configured();
1871 elts
= smartlist_create();
1872 for (opt
= options
->AddressMap
; opt
; opt
= opt
->next
) {
1873 smartlist_split_string(elts
, opt
->value
, NULL
,
1874 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
1875 if (smartlist_len(elts
) >= 2) {
1876 from
= smartlist_get(elts
,0);
1877 to
= smartlist_get(elts
,1);
1878 if (!is_plausible_address(from
)) {
1879 log_fn(LOG_WARN
,"Skipping invalid argument '%s' to MapAddress",from
);
1880 } else if (!is_plausible_address(to
)) {
1881 log_fn(LOG_WARN
,"Skipping invalid argument '%s' to MapAddress",to
);
1883 addressmap_register(from
, tor_strdup(to
), 0);
1884 if (smartlist_len(elts
)>2) {
1885 log_fn(LOG_WARN
,"Ignoring extra arguments to MapAddress.");
1889 log_fn(LOG_WARN
,"MapAddress '%s' has too few arguments. Ignoring.", opt
->value
);
1891 SMARTLIST_FOREACH(elts
, char*, cp
, tor_free(cp
));
1892 smartlist_clear(elts
);
1894 smartlist_free(elts
);
1897 /** If <b>range</b> is of the form MIN-MAX, for MIN and MAX both
1898 * recognized log severity levels, set *<b>min_out</b> to MIN and
1899 * *<b>max_out</b> to MAX and return 0. Else, if <b>range<b> is of
1900 * the form MIN, act as if MIN-err had been specified. Else, warn and
1904 parse_log_severity_range(const char *range
, int *min_out
, int *max_out
)
1906 int levelMin
, levelMax
;
1908 cp
= strchr(range
, '-');
1911 levelMin
= LOG_DEBUG
;
1913 char *tmp_sev
= tor_strndup(range
, cp
- range
);
1914 levelMin
= parse_log_level(tmp_sev
);
1916 log_fn(LOG_WARN
, "Unrecognized log severity '%s': must be one of "
1917 "err|warn|notice|info|debug", tmp_sev
);
1926 levelMax
= parse_log_level(cp
+1);
1928 log_fn(LOG_WARN
, "Unrecognized log severity '%s': must be one of "
1929 "err|warn|notice|info|debug", cp
+1);
1934 levelMin
= parse_log_level(range
);
1936 log_fn(LOG_WARN
, "Unrecognized log severity '%s': must be one of "
1937 "err|warn|notice|info|debug", range
);
1943 *min_out
= levelMin
;
1944 *max_out
= levelMax
;
1949 /** Try to convert a pair of old-style logging options [LogLevel, and
1950 * (LogFile/Syslog)] to a new-style option, and add the new option to
1953 convert_log_option(or_options_t
*options
, struct config_line_t
*level_opt
,
1954 struct config_line_t
*file_opt
, int isDaemon
)
1956 int levelMin
= -1, levelMax
= -1;
1959 if (parse_log_severity_range(level_opt
->value
, &levelMin
, &levelMax
))
1962 if (levelMin
< 0 && levelMax
< 0) {
1963 levelMin
= LOG_NOTICE
;
1965 } else if (levelMin
< 0) {
1966 levelMin
= levelMax
;
1971 if (file_opt
&& !strcasecmp(file_opt
->key
, "LogFile")) {
1972 if (add_single_log_option(options
, levelMin
, levelMax
, "file", file_opt
->value
) < 0) {
1973 log_fn(LOG_WARN
, "Cannot write to LogFile '%s': %s.", file_opt
->value
,
1977 } else if (file_opt
&& !strcasecmp(file_opt
->key
, "SysLog")) {
1978 if (add_single_log_option(options
, levelMin
, levelMax
, "syslog", NULL
) < 0)
1980 } else if (!isDaemon
) {
1981 add_single_log_option(options
, levelMin
, levelMax
, "stdout", NULL
);
1987 * Initialize the logs based on the configuration file.
1990 config_init_logs(or_options_t
*options
, int validate_only
)
1992 struct config_line_t
*opt
;
1997 elts
= smartlist_create();
1998 for (opt
= options
->Logs
; opt
; opt
= opt
->next
) {
1999 int levelMin
=LOG_DEBUG
, levelMax
=LOG_ERR
;
2000 smartlist_split_string(elts
, opt
->value
, NULL
,
2001 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 3);
2002 if (smartlist_len(elts
) == 0) {
2003 log_fn(LOG_WARN
, "Bad syntax on Log option 'Log %s'", opt
->value
);
2004 ok
= 0; goto cleanup
;
2006 if (parse_log_severity_range(smartlist_get(elts
,0), &levelMin
, &levelMax
)) {
2007 ok
= 0; goto cleanup
;
2009 if (smartlist_len(elts
) < 2) { /* only loglevels were provided */
2011 add_stream_log(levelMin
, levelMax
, "<stdout>", stdout
);
2014 if (!strcasecmp(smartlist_get(elts
,1), "file")) {
2015 if (smartlist_len(elts
) != 3) {
2016 log_fn(LOG_WARN
, "Bad syntax on Log option 'Log %s'", opt
->value
);
2017 ok
= 0; goto cleanup
;
2020 add_file_log(levelMin
, levelMax
, smartlist_get(elts
, 2));
2023 if (smartlist_len(elts
) != 2) {
2024 log_fn(LOG_WARN
, "Bad syntax on Log option 'Log %s'", opt
->value
);
2025 ok
= 0; goto cleanup
;
2027 if (!strcasecmp(smartlist_get(elts
,1), "stdout")) {
2028 if (!validate_only
) {
2029 add_stream_log(levelMin
, levelMax
, "<stdout>", stdout
);
2032 } else if (!strcasecmp(smartlist_get(elts
,1), "stderr")) {
2033 if (!validate_only
) {
2034 add_stream_log(levelMin
, levelMax
, "<stderr>", stderr
);
2037 } else if (!strcasecmp(smartlist_get(elts
,1), "syslog")) {
2038 #ifdef HAVE_SYSLOG_H
2040 add_syslog_log(levelMin
, levelMax
);
2042 log_fn(LOG_WARN
, "Syslog is not supported in this compilation.");
2045 log_fn(LOG_WARN
, "Unrecognized log type %s",
2046 (const char*)smartlist_get(elts
,1));
2047 if (strchr(smartlist_get(elts
,1), '/')) {
2048 log_fn(LOG_WARN
, "Did you mean to say 'Log file %s' ?",
2049 (const char *)smartlist_get(elts
,1));
2051 ok
= 0; goto cleanup
;
2054 SMARTLIST_FOREACH(elts
, char*, cp
, tor_free(cp
));
2055 smartlist_clear(elts
);
2057 smartlist_free(elts
);
2064 /** Add a single option of the form Log min-max <type> [fname] to options. */
2066 add_single_log_option(or_options_t
*options
, int minSeverity
, int maxSeverity
,
2067 const char *type
, const char *fname
)
2072 n
= tor_snprintf(buf
, sizeof(buf
), "%s%s%s %s%s%s",
2073 log_level_to_string(minSeverity
),
2074 maxSeverity
== LOG_ERR
? "" : "-",
2075 maxSeverity
== LOG_ERR
? "" : log_level_to_string(maxSeverity
),
2076 type
, fname
?" ":"", fname
?fname
:"");
2078 log_fn(LOG_WARN
, "Normalized log option too long.");
2082 log(LOG_WARN
, "The old LogLevel/LogFile/DebugLogFile/SysLog options are deprecated, and will go away soon. Your new torrc line should be: 'Log %s'", buf
);
2083 config_line_append(&options
->Logs
, "Log", buf
);
2087 /** Convert all old-style logging options to new-style Log options. Return 0
2088 * on success, -1 on failure. */
2090 normalize_log_options(or_options_t
*options
)
2092 /* The order of options is: Level? (File Level?)+
2094 struct config_line_t
*opt
= options
->OldLogOptions
;
2096 /* Special case for if first option is LogLevel. */
2097 if (opt
&& !strcasecmp(opt
->key
, "LogLevel")) {
2098 if (opt
->next
&& (!strcasecmp(opt
->next
->key
, "LogFile") ||
2099 !strcasecmp(opt
->next
->key
, "SysLog"))) {
2100 if (convert_log_option(options
, opt
, opt
->next
, options
->RunAsDaemon
) < 0)
2102 opt
= opt
->next
->next
;
2103 } else if (!opt
->next
) {
2104 if (convert_log_option(options
, opt
, NULL
, options
->RunAsDaemon
) < 0)
2108 ; /* give warning below */
2113 if (!strcasecmp(opt
->key
, "LogLevel")) {
2114 log_fn(LOG_WARN
, "Two LogLevel options in a row without intervening LogFile or SysLog");
2117 tor_assert(!strcasecmp(opt
->key
, "LogFile") ||
2118 !strcasecmp(opt
->key
, "SysLog"));
2119 if (opt
->next
&& !strcasecmp(opt
->next
->key
, "LogLevel")) {
2120 /* LogFile/SysLog followed by LogLevel */
2121 if (convert_log_option(options
,opt
->next
,opt
, options
->RunAsDaemon
) < 0)
2123 opt
= opt
->next
->next
;
2125 /* LogFile/SysLog followed by LogFile/SysLog or end of list. */
2126 if (convert_log_option(options
,NULL
, opt
, options
->RunAsDaemon
) < 0)
2133 if (options
->DebugLogFile
) {
2134 if (add_single_log_option(options
, LOG_DEBUG
, LOG_ERR
, "file", options
->DebugLogFile
) < 0)
2138 tor_free(options
->DebugLogFile
);
2139 config_free_lines(options
->OldLogOptions
);
2140 options
->OldLogOptions
= NULL
;
2146 * Given a linked list of config lines containing "allow" and "deny" tokens,
2147 * parse them and append the result to <b>dest</b>. Return -1 if any tokens
2148 * are malformed, else return 0.
2151 config_parse_addr_policy(struct config_line_t
*cfg
,
2152 addr_policy_t
**dest
)
2154 addr_policy_t
**nextp
;
2155 smartlist_t
*entries
;
2164 nextp
= &((*nextp
)->next
);
2166 entries
= smartlist_create();
2167 for (; cfg
; cfg
= cfg
->next
) {
2168 smartlist_split_string(entries
, cfg
->value
, ",", SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2169 SMARTLIST_FOREACH(entries
, const char *, ent
,
2171 log_fn(LOG_DEBUG
,"Adding new entry '%s'",ent
);
2172 *nextp
= router_parse_addr_policy_from_string(ent
);
2174 nextp
= &((*nextp
)->next
);
2176 log_fn(LOG_WARN
,"Malformed policy %s.", ent
);
2180 SMARTLIST_FOREACH(entries
, char *, ent
, tor_free(ent
));
2181 smartlist_clear(entries
);
2183 smartlist_free(entries
);
2187 /** Release all storage held by <b>p</b> */
2189 addr_policy_free(addr_policy_t
*p
) {
2195 tor_free(e
->string
);
2200 /** Parse a single RedirectExit line's contents from <b>line</b>. If
2201 * they are valid, and <b>result</b> is not NULL, add an element to
2202 * <b>result</b> and return 0. Else if they are valid, return 0.
2203 * Else return -1. */
2205 parse_redirect_line(smartlist_t
*result
, struct config_line_t
*line
)
2207 smartlist_t
*elements
= NULL
;
2212 r
= tor_malloc_zero(sizeof(exit_redirect_t
));
2213 elements
= smartlist_create();
2214 smartlist_split_string(elements
, line
->value
, NULL
,
2215 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2216 if (smartlist_len(elements
) != 2) {
2217 log_fn(LOG_WARN
, "Wrong number of elements in RedirectExit line");
2220 if (parse_addr_and_port_range(smartlist_get(elements
,0),&r
->addr
,&r
->mask
,
2221 &r
->port_min
,&r
->port_max
)) {
2222 log_fn(LOG_WARN
, "Error parsing source address in RedirectExit line");
2225 if (0==strcasecmp(smartlist_get(elements
,1), "pass")) {
2228 if (parse_addr_port(smartlist_get(elements
,1),NULL
,&r
->addr_dest
,
2230 log_fn(LOG_WARN
, "Error parsing dest address in RedirectExit line");
2240 SMARTLIST_FOREACH(elements
, char *, cp
, tor_free(cp
));
2241 smartlist_free(elements
);
2244 smartlist_add(result
, r
);
2253 /** Read the contents of a DirServer line from <b>line</b>. Return 0
2254 * if the line is well-formed, and 0 if it isn't. If
2255 * <b>validate_only</b> is 0, and the line is well-formed, then add
2256 * the dirserver described in the line as a valid server. */
2258 parse_dir_server_line(const char *line
, int validate_only
)
2260 smartlist_t
*items
= NULL
;
2262 char *addrport
, *address
=NULL
;
2264 char digest
[DIGEST_LEN
];
2266 items
= smartlist_create();
2267 smartlist_split_string(items
, line
, NULL
,
2268 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
2269 if (smartlist_len(items
) < 2) {
2270 log_fn(LOG_WARN
, "Too few arguments to DirServer line.");
2273 addrport
= smartlist_get(items
, 0);
2274 if (parse_addr_port(addrport
, &address
, NULL
, &port
)<0) {
2275 log_fn(LOG_WARN
, "Error parsing DirServer address '%s'", addrport
);
2279 log_fn(LOG_WARN
, "Missing port in DirServer address '%s'",addrport
);
2283 tor_strstrip(smartlist_get(items
, 1), " ");
2284 if (strlen(smartlist_get(items
, 1)) != HEX_DIGEST_LEN
) {
2285 log_fn(LOG_WARN
, "Key digest for DirServer is wrong length.");
2288 if (base16_decode(digest
, DIGEST_LEN
,
2289 smartlist_get(items
,1), HEX_DIGEST_LEN
)<0) {
2290 log_fn(LOG_WARN
, "Unable to decode DirServer key digest.");
2294 if (!validate_only
) {
2295 log_fn(LOG_DEBUG
, "Trusted dirserver at %s:%d (%s)", address
, (int)port
,
2296 (char*)smartlist_get(items
,1));
2297 add_trusted_dir_server(address
, port
, digest
);
2307 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
2308 smartlist_free(items
);
2313 /** Adjust the value of options->DataDirectory, or fill it in if it's
2314 * absent. Return 0 on success, -1 on failure. */
2316 normalize_data_directory(or_options_t
*options
) {
2319 if (options
->DataDirectory
)
2320 return 0; /* all set */
2321 p
= tor_malloc(MAX_PATH
);
2322 strlcpy(p
,get_windows_conf_root(),MAX_PATH
);
2323 options
->DataDirectory
= p
;
2326 const char *d
= options
->DataDirectory
;
2330 if (strncmp(d
,"~/",2) == 0) {
2331 char *fn
= expand_filename(d
);
2333 log_fn(LOG_ERR
,"Failed to expand filename '%s'.", d
);
2336 if (!options
->DataDirectory
&& !strcmp(fn
,"/.tor")) {
2337 /* If our homedir is /, we probably don't want to use it. */
2338 /* XXXX Default to /var/lib/tor? */
2339 log_fn(LOG_WARN
, "Defaulting to 'DataDirectory %s', which may not be what you want", fn
);
2341 tor_free(options
->DataDirectory
);
2342 options
->DataDirectory
= fn
;
2348 /** Check and normalize the value of options->DataDirectory; return 0 if it
2349 * sane, -1 otherwise. */
2351 validate_data_directory(or_options_t
*options
) {
2352 if (normalize_data_directory(options
) < 0)
2354 tor_assert(options
->DataDirectory
);
2355 if (strlen(options
->DataDirectory
) > (512-128)) {
2356 log_fn(LOG_ERR
, "DataDirectory is too long.");
2360 if (check_private_dir(options
->DataDirectory
, CPD_CHECK
!= 0)) {
2361 log_fn(LOG_WARN
, "Can't create directory %s", options
->DataDirectory
);
2368 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; if you edit it, comments will not be preserved"
2370 /** Save a configuration file for the configuration in <b>options</b>
2371 * into the file <b>fname</b>. If the file already exists, and
2372 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
2373 * replace it. Return 0 on success, -1 on failure. */
2375 write_configuration_file(const char *fname
, or_options_t
*options
)
2377 char *old_val
=NULL
, *new_val
=NULL
, *new_conf
=NULL
;
2378 int rename_old
= 0, r
;
2382 switch (file_status(fname
)) {
2384 old_val
= read_file_to_str(fname
, 0);
2385 if (strcmpstart(old_val
, GENERATED_FILE_PREFIX
)) {
2393 log_fn(LOG_WARN
,"Config file %s is not a file? Failing.", fname
);
2398 if (!(new_conf
= config_dump_options(options
, 1))) {
2399 log_fn(LOG_WARN
, "Couldn't get configuration string");
2403 len
= strlen(new_conf
)+128;
2404 new_val
= tor_malloc(len
);
2405 tor_snprintf(new_val
, len
, "%s\n\n%s", GENERATED_FILE_PREFIX
, new_conf
);
2409 size_t fn_tmp_len
= strlen(fname
)+32;
2411 tor_assert(fn_tmp_len
> strlen(fname
)); /*check for overflow*/
2412 fn_tmp
= tor_malloc(fn_tmp_len
);
2414 if (tor_snprintf(fn_tmp
, fn_tmp_len
, "%s.orig.%d", fname
, i
)<0) {
2415 log_fn(LOG_WARN
, "tor_snprintf failed inexplicably");
2419 if (file_status(fn_tmp
) == FN_NOENT
)
2423 log_fn(LOG_NOTICE
, "Renaming old configuration file to %s", fn_tmp
);
2424 rename(fname
, fn_tmp
);
2428 write_str_to_file(fname
, new_val
, 0);
2441 * Save the current configuration file value to disk. Return 0 on
2442 * success, -1 on failure.
2445 save_current_config(void)
2449 /* XXX This fails if we can't write to our configuration file.
2450 * Arguably, we should try falling back to datadirectory or something.
2451 * But just as arguably, we shouldn't. */
2452 return write_configuration_file(config_fname
, get_options());
2454 fn
= get_default_conf_file();
2455 return write_configuration_file(fn
, get_options());
2458 struct unit_table_t
{
2460 uint64_t multiplier
;
2463 static struct unit_table_t memory_units
[] = {
2469 { "kilobyte", 1<<10 },
2470 { "kilobytes", 1<<10 },
2473 { "megabyte", 1<<20 },
2474 { "megabytes", 1<<20 },
2476 { "gigabyte", 1<<30 },
2477 { "gigabytes", 1<<30 },
2478 { "tb", U64_LITERAL(1)<<40 },
2479 { "terabyte", U64_LITERAL(1)<<40 },
2480 { "terabytes", U64_LITERAL(1)<<40 },
2484 static struct unit_table_t time_units
[] = {
2492 { "day", 24*60*60 },
2493 { "days", 24*60*60 },
2494 { "week", 7*24*60*60 },
2495 { "weeks", 7*24*60*60 },
2499 /** Parse a string <b>val</b> containing a number, zero or more
2500 * spaces, and an optional unit string. If the unit appears in the
2501 * table <b>u</b>, then multiply the number by the unit multiplier.
2502 * On success, set *<b>ok</b> to 1 and return this product.
2503 * Otherwise, set *<b>ok</b> to 0.
2506 config_parse_units(const char *val
, struct unit_table_t
*u
, int *ok
)
2513 v
= tor_parse_uint64(val
, 10, 0, UINT64_MAX
, ok
, &cp
);
2520 while (TOR_ISSPACE(*cp
))
2522 for ( ;u
->unit
;++u
) {
2523 if (!strcasecmp(u
->unit
, cp
)) {
2529 log_fn(LOG_WARN
, "Unknown unit '%s'.", cp
);
2534 /** Parse a string in the format "number unit", where unit is a unit of
2535 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
2536 * and return the number of bytes specified. Otherwise, set
2537 * *<b>ok</b> to false and return 0. */
2539 config_parse_memunit(const char *s
, int *ok
) {
2540 return config_parse_units(s
, memory_units
, ok
);
2543 /** Parse a string in the format "number unit", where unit is a unit of time.
2544 * On success, set *<b>ok</b> to true and return the number of seconds in
2545 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
2548 config_parse_interval(const char *s
, int *ok
) {
2550 r
= config_parse_units(s
, time_units
, ok
);
2554 log_fn(LOG_WARN
, "Interval '%s' is too long", s
);
2562 print_cvs_version(void)
2564 extern const char aes_c_id
[];
2565 extern const char compat_c_id
[];
2566 extern const char container_c_id
[];
2567 extern const char crypto_c_id
[];
2568 extern const char log_c_id
[];
2569 extern const char torgzip_c_id
[];
2570 extern const char tortls_c_id
[];
2571 extern const char util_c_id
[];
2573 extern const char buffers_c_id
[];
2574 extern const char circuitbuild_c_id
[];
2575 extern const char circuitlist_c_id
[];
2576 extern const char circuituse_c_id
[];
2577 extern const char command_c_id
[];
2578 // extern const char config_c_id[];
2579 extern const char connection_c_id
[];
2580 extern const char connection_edge_c_id
[];
2581 extern const char connection_or_c_id
[];
2582 extern const char control_c_id
[];
2583 extern const char cpuworker_c_id
[];
2584 extern const char directory_c_id
[];
2585 extern const char dirserv_c_id
[];
2586 extern const char dns_c_id
[];
2587 extern const char hibernate_c_id
[];
2588 extern const char main_c_id
[];
2589 extern const char onion_c_id
[];
2590 extern const char relay_c_id
[];
2591 extern const char rendclient_c_id
[];
2592 extern const char rendcommon_c_id
[];
2593 extern const char rendmid_c_id
[];
2594 extern const char rendservice_c_id
[];
2595 extern const char rephist_c_id
[];
2596 extern const char router_c_id
[];
2597 extern const char routerlist_c_id
[];
2598 extern const char routerparse_c_id
[];
2602 puts(CONTAINER_H_ID
);
2611 puts(container_c_id
);
2620 puts(circuitbuild_c_id
);
2621 puts(circuitlist_c_id
);
2622 puts(circuituse_c_id
);
2625 puts(connection_c_id
);
2626 puts(connection_edge_c_id
);
2627 puts(connection_or_c_id
);
2629 puts(cpuworker_c_id
);
2630 puts(directory_c_id
);
2633 puts(hibernate_c_id
);
2637 puts(rendclient_c_id
);
2638 puts(rendcommon_c_id
);
2640 puts(rendservice_c_id
);
2643 puts(routerlist_c_id
);
2644 puts(routerparse_c_id
);