1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004 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
),
60 PLURAL(RendExcludeNode
),
61 PLURAL(StrictEntryNode
),
62 PLURAL(StrictExitNode
),
64 { "BandwidthRateBytes", "BandwidthRate", 0},
65 { "BandwidthBurstBytes", "BandwidthBurst", 0},
66 { "DirFetchPostPeriod", "StatusFetchPeriod", 0},
71 /** A variable allowed in the configuration file or on the command line. */
72 typedef struct config_var_t
{
73 const char *name
; /**< The full keyword (case insensitive). */
74 config_type_t type
; /**< How to interpret the type and turn it into a value. */
75 off_t var_offset
; /**< Offset of the corresponding member of or_options_t. */
76 const char *initvalue
; /**< String (or null) describing initial value. */
79 /** Return the offset of <b>member</b> within the type <b>tp</b>, in bytes */
80 #define STRUCT_OFFSET(tp, member) ((off_t) (((char*)&((tp*)0)->member)-(char*)0))
81 /** An entry for config_vars: "The option <b>name</b> has type
82 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
83 * or_options_t.<b>member</b>"
85 #define VAR(name,conftype,member,initvalue) \
86 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), initvalue }
87 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
88 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
90 /** Array of configuration options. Until we disallow nonstandard
91 * abbreviations, order is significant, since the first matching option will
94 static config_var_t config_vars
[] = {
95 VAR("Address", STRING
, Address
, NULL
),
96 VAR("AccountingStart", STRING
, AccountingStart
, NULL
),
97 VAR("AllowUnverifiedNodes",CSV
, AllowUnverifiedNodes
, "middle,rendezvous"),
98 VAR("AuthoritativeDirectory",BOOL
, AuthoritativeDir
, "0"),
99 VAR("BandwidthRate", MEMUNIT
, BandwidthRate
, "780 KB"),
100 VAR("BandwidthBurst", MEMUNIT
, BandwidthBurst
, "48 MB"),
101 VAR("ClientOnly", BOOL
, ClientOnly
, "0"),
102 VAR("ContactInfo", STRING
, ContactInfo
, NULL
),
103 VAR("ControlPort", UINT
, ControlPort
, "0"),
104 VAR("CookieAuthentication",BOOL
, CookieAuthentication
, "0"),
105 VAR("DebugLogFile", STRING
, DebugLogFile
, NULL
),
106 VAR("DataDirectory", STRING
, DataDirectory
, NULL
),
107 VAR("DirAllowPrivateAddresses",BOOL
, DirAllowPrivateAddresses
, NULL
),
108 VAR("DirPort", UINT
, DirPort
, "0"),
109 VAR("DirBindAddress", LINELIST
, DirBindAddress
, NULL
),
110 /* XXX we'd like dirfetchperiod to be higher for people with dirport not
111 * set, but low for people with dirport set. how to have two defaults? */
112 VAR("DirFetchPeriod", INTERVAL
, DirFetchPeriod
, "1 hour"),
113 VAR("DirPostPeriod", INTERVAL
, DirPostPeriod
, "20 minutes"),
114 VAR("RendPostPeriod", INTERVAL
, RendPostPeriod
, "20 minutes"),
115 VAR("DirPolicy", LINELIST
, DirPolicy
, NULL
),
116 VAR("DirServer", LINELIST
, DirServers
, NULL
),
117 VAR("ExitNodes", STRING
, ExitNodes
, NULL
),
118 VAR("EntryNodes", STRING
, EntryNodes
, NULL
),
119 VAR("StrictExitNodes", BOOL
, StrictExitNodes
, "0"),
120 VAR("StrictEntryNodes", BOOL
, StrictEntryNodes
, "0"),
121 VAR("ExitPolicy", LINELIST
, ExitPolicy
, NULL
),
122 VAR("ExcludeNodes", STRING
, ExcludeNodes
, NULL
),
123 VAR("FascistFirewall", BOOL
, FascistFirewall
, "0"),
124 VAR("FirewallPorts", CSV
, FirewallPorts
, "80,443"),
125 VAR("MyFamily", STRING
, MyFamily
, NULL
),
126 VAR("NodeFamily", LINELIST
, NodeFamilies
, NULL
),
127 VAR("Group", STRING
, Group
, NULL
),
128 VAR("HashedControlPassword",STRING
, HashedControlPassword
, NULL
),
129 VAR("HttpProxy", STRING
, HttpProxy
, NULL
),
130 VAR("HiddenServiceOptions",LINELIST_V
, RendConfigLines
, NULL
),
131 VAR("HiddenServiceDir", LINELIST_S
, RendConfigLines
, NULL
),
132 VAR("HiddenServicePort", LINELIST_S
, RendConfigLines
, NULL
),
133 VAR("HiddenServiceNodes", LINELIST_S
, RendConfigLines
, NULL
),
134 VAR("HiddenServiceExcludeNodes", LINELIST_S
, RendConfigLines
, NULL
),
135 VAR("IgnoreVersion", BOOL
, IgnoreVersion
, "0"),
136 VAR("KeepalivePeriod", INTERVAL
, KeepalivePeriod
, "5 minutes"),
137 VAR("Log", LINELIST
, Logs
, NULL
),
138 VAR("LogLevel", LINELIST_S
, OldLogOptions
, NULL
),
139 VAR("LogFile", LINELIST_S
, OldLogOptions
, NULL
),
140 OBSOLETE("LinkPadding"),
141 VAR("MaxConn", UINT
, MaxConn
, "1024"),
142 VAR("MaxOnionsPending", UINT
, MaxOnionsPending
, "100"),
143 VAR("MonthlyAccountingStart",UINT
, _MonthlyAccountingStart
,"0"),
144 VAR("AccountingMaxKB", UINT
, _AccountingMaxKB
, "0"),
145 VAR("AccountingMax", MEMUNIT
, AccountingMax
, "0 bytes"),
146 VAR("Nickname", STRING
, Nickname
, NULL
),
147 VAR("NewCircuitPeriod", INTERVAL
, NewCircuitPeriod
, "30 seconds"),
148 VAR("NumCpus", UINT
, NumCpus
, "1"),
149 VAR("ORPort", UINT
, ORPort
, "0"),
150 VAR("ORBindAddress", LINELIST
, ORBindAddress
, NULL
),
151 VAR("OutboundBindAddress", STRING
, OutboundBindAddress
, NULL
),
152 VAR("PidFile", STRING
, PidFile
, NULL
),
153 VAR("LongLivedPorts", CSV
, LongLivedPorts
, "21,22,706,1863,5050,5190,5222,5223,6667,8300,8888"),
154 VAR("PathlenCoinWeight", DOUBLE
, PathlenCoinWeight
, "0.3"),
155 VAR("RedirectExit", LINELIST
, RedirectExit
, NULL
),
156 OBSOLETE("RouterFile"),
157 VAR("RunAsDaemon", BOOL
, RunAsDaemon
, "0"),
158 VAR("RunTesting", BOOL
, RunTesting
, "0"),
159 VAR("RecommendedVersions", LINELIST
, RecommendedVersions
, NULL
),
160 VAR("RendNodes", STRING
, RendNodes
, NULL
),
161 VAR("RendExcludeNodes", STRING
, RendExcludeNodes
, NULL
),
162 VAR("SocksPort", UINT
, SocksPort
, "9050"),
163 VAR("SocksBindAddress", LINELIST
, SocksBindAddress
, NULL
),
164 VAR("SocksPolicy", LINELIST
, SocksPolicy
, NULL
),
165 /* XXX as with dirfetchperiod, we want this to be 15 minutes for people
166 * with a dirport open, but higher for people without a dirport open. */
167 VAR("StatusFetchPeriod", INTERVAL
, StatusFetchPeriod
, "15 minutes"),
168 VAR("SysLog", LINELIST_S
, OldLogOptions
, NULL
),
169 OBSOLETE("TrafficShaping"),
170 VAR("User", STRING
, User
, NULL
),
171 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
176 /** Largest allowed config line */
177 #define CONFIG_LINE_T_MAXLEN 4096
179 static void config_line_append(struct config_line_t
**lst
,
180 const char *key
, const char *val
);
181 static void option_reset(or_options_t
*options
, config_var_t
*var
);
182 static void options_free(or_options_t
*options
);
183 static int option_is_same(or_options_t
*o1
, or_options_t
*o2
,const char *name
);
184 static or_options_t
*options_dup(or_options_t
*old
);
185 static int options_validate(or_options_t
*options
);
186 static int options_transition_allowed(or_options_t
*old
, or_options_t
*new);
187 static int check_nickname_list(const char *lst
, const char *name
);
189 static int parse_dir_server_line(const char *line
, int validate_only
);
190 static int parse_redirect_line(smartlist_t
*result
,
191 struct config_line_t
*line
);
192 static int parse_log_severity_range(const char *range
, int *min_out
,
194 static int convert_log_option(or_options_t
*options
,
195 struct config_line_t
*level_opt
,
196 struct config_line_t
*file_opt
, int isDaemon
);
197 static int add_single_log_option(or_options_t
*options
, int minSeverity
,
199 const char *type
, const char *fname
);
200 static int normalize_log_options(or_options_t
*options
);
201 static int validate_data_directory(or_options_t
*options
);
202 static int write_configuration_file(const char *fname
, or_options_t
*options
);
204 static uint64_t config_parse_memunit(const char *s
, int *ok
);
205 static int config_parse_interval(const char *s
, int *ok
);
206 static void print_cvs_version(void);
209 * Functions to read and write the global options pointer.
212 /** Command-line and config-file options. */
213 static or_options_t
*global_options
=NULL
;
214 /** Name of most recently read torrc file. */
215 static char *config_fname
= NULL
;
217 /** Return the currently configured options. */
220 tor_assert(global_options
);
221 return global_options
;
224 /** Change the current global options to contain <b>new_val</b> instead
225 * of their current value; free the old value as necessary.
228 set_options(or_options_t
*new_val
) {
230 options_free(global_options
);
231 global_options
= new_val
;
234 /** Fetch the active option list, and take actions based on it. All
235 * of the things we do should survive being done repeatedly.
236 * Return 0 if all goes well, return -1 if it's time to die.
238 * Note 1: <b>new_val</b> must have previously been validated with
239 * options_validate(), or Tor may freak out and exit.
241 * Note 2: We haven't moved all the "act on new configuration" logic
242 * here yet. Some is still in do_hup() and other places.
246 struct config_line_t
*cl
;
247 or_options_t
*options
= get_options();
249 clear_trusted_dir_servers();
250 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
) {
251 if (parse_dir_server_line(cl
->value
, 0)<0) {
253 "Bug: Previously validated DirServer line could not be added!");
258 if (rend_config_services(options
, 0)<0) {
260 "Bug: Previously validated hidden services line could not be added!");
264 /* Setuid/setgid as appropriate */
265 if (options
->User
|| options
->Group
) {
266 if (switch_id(options
->User
, options
->Group
) != 0) {
271 /* Ensure data directory is private; create if possible. */
272 if (check_private_dir(options
->DataDirectory
, CPD_CREATE
) != 0) {
273 log_fn(LOG_ERR
, "Couldn't access/create private data directory %s",
274 options
->DataDirectory
);
278 /* Bail out at this point if we're not going to be a server: we want
279 * to not fork, and to log stuff to stderr. */
280 if (options
->command
!= CMD_RUN_TOR
)
283 mark_logs_temp(); /* Close current logs once new logs are open. */
284 if (config_init_logs(options
, 0)<0) /* Configure the log(s) */
286 /* Close the temporary log we used while starting up, if it isn't already
289 add_callback_log(LOG_NOTICE
, LOG_ERR
, control_event_logmsg
);
291 if (set_max_file_descriptors(options
->MaxConn
) < 0)
295 smartlist_t
*sl
= smartlist_create();
296 for (cl
= options
->RedirectExit
; cl
; cl
= cl
->next
) {
297 if (parse_redirect_line(sl
, cl
)<0)
300 set_exit_redirects(sl
);
303 /* Start backgrounding the process, if requested. */
305 /* XXXX009 We once had a reason to separate start_daemon and finish_daemon:
306 * It let us have the parent process stick around until we were sure Tor
307 * was started. Should we make start_daemon get called earlier? -NM */
308 if (options
->RunAsDaemon
) {
309 start_daemon(options
->DataDirectory
);
312 /* Finish backgrounding the process */
313 if (options
->RunAsDaemon
) {
314 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
318 /* Write our pid to the pid file. If we do not have write permissions we
319 * will log a warning */
320 if (options
->PidFile
)
321 write_pidfile(options
->PidFile
);
323 /* Update address policies. */
324 parse_socks_policy();
327 init_cookie_authentication(options
->CookieAuthentication
);
329 /* reload keys as needed for rendezvous services. */
330 if (rend_service_load_keys()<0) {
331 log_fn(LOG_ERR
,"Error loading rendezvous service keys");
335 /* Set up accounting */
336 if (accounting_parse_options(options
, 0)<0) {
337 log_fn(LOG_ERR
,"Error in accounting options");
340 if (accounting_is_enabled(options
))
341 configure_accounting(time(NULL
));
343 if (!we_are_hibernating() && retry_all_listeners(1) < 0) {
344 log_fn(LOG_ERR
,"Failed to bind one of the listener ports.");
351 smin
= config_dump_options(options
, 1);
352 smax
= config_dump_options(options
, 0);
353 log_fn(LOG_DEBUG
, "These are our options:\n%s",smax
);
354 log_fn(LOG_DEBUG
, "We changed these options:\n%s",smin
);
360 /* Since our options changed, we might need to regenerate and upload our
361 * server descriptor. (We could probably be more clever about only calling
362 * this when something significant changed.)
364 mark_my_descriptor_dirty();
370 * Functions to parse config options
373 /** If <b>option</b> is an official abbreviation for a longer option,
374 * return the longer option. Otherwise return <b>option</b>.
375 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
376 * apply abbreviations that work for the config file and the command line. */
378 expand_abbrev(const char *option
, int command_line
)
381 for (i
=0; config_abbrevs
[i
].abbreviated
; ++i
) {
382 /* Abbreviations aren't casei. */
383 if (!strcasecmp(option
,config_abbrevs
[i
].abbreviated
) &&
384 (command_line
|| !config_abbrevs
[i
].commandline_only
)) {
385 return config_abbrevs
[i
].full
;
391 /** Helper: Read a list of configuration options from the command line. */
392 static struct config_line_t
*
393 config_get_commandlines(int argc
, char **argv
)
395 struct config_line_t
*new;
396 struct config_line_t
*front
= NULL
;
401 if (!strcmp(argv
[i
],"-f") ||
402 !strcmp(argv
[i
],"--hash-password")) {
403 i
+= 2; /* command-line option with argument. ignore them. */
405 } else if (!strcmp(argv
[i
],"--list-fingerprint")) {
406 i
+= 1; /* command-line option. ignore it. */
410 new = tor_malloc(sizeof(struct config_line_t
));
416 new->key
= tor_strdup(expand_abbrev(s
, 1));
417 new->value
= tor_strdup(argv
[i
+1]);
419 log(LOG_DEBUG
,"Commandline: parsed keyword '%s', value '%s'",
420 new->key
, new->value
);
428 /** Helper: allocate a new configuration option mapping 'key' to 'val',
429 * append it to *<b>lst</b>. */
431 config_line_append(struct config_line_t
**lst
,
435 struct config_line_t
*newline
;
437 newline
= tor_malloc(sizeof(struct config_line_t
));
438 newline
->key
= tor_strdup(key
);
439 newline
->value
= tor_strdup(val
);
440 newline
->next
= NULL
;
442 lst
= &((*lst
)->next
);
447 /** Helper: parse the config string and strdup into key/value
448 * strings. Set *result to the list, or NULL if parsing the string
449 * failed. Return 0 on success, -1 on failure. Warn and ignore any
450 * misformatted lines. */
452 config_get_lines(char *string
, struct config_line_t
**result
)
454 struct config_line_t
*list
= NULL
, **next
;
459 string
= parse_line_from_str(string
, &k
, &v
);
461 config_free_lines(list
);
465 /* This list can get long, so we keep a pointer to the end of it
466 * rather than using config_line_append over and over and getting n^2
467 * performance. This is the only really long list. */
468 *next
= tor_malloc(sizeof(struct config_line_t
));
469 (*next
)->key
= tor_strdup(k
);
470 (*next
)->value
= tor_strdup(v
);
471 (*next
)->next
= NULL
;
472 next
= &((*next
)->next
);
481 * Free all the configuration lines on the linked list <b>front</b>.
484 config_free_lines(struct config_line_t
*front
)
486 struct config_line_t
*tmp
;
493 tor_free(tmp
->value
);
498 /** If <b>key</b> is a configuration option, return the corresponding
499 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
500 * warn, and return the corresponding config_var_t. Otherwise return NULL.
502 static config_var_t
*config_find_option(const char *key
)
505 /* First, check for an exact (case-insensitive) match */
506 for (i
=0; config_vars
[i
].name
; ++i
) {
507 if (!strcasecmp(key
, config_vars
[i
].name
))
508 return &config_vars
[i
];
510 /* If none, check for an abbreviated match */
511 for (i
=0; config_vars
[i
].name
; ++i
) {
512 if (!strncasecmp(key
, config_vars
[i
].name
, strlen(key
))) {
513 log_fn(LOG_WARN
, "The abbreviation '%s' is deprecated. "
514 "Tell Nick and Roger to make it official, or just use '%s' instead",
515 key
, config_vars
[i
].name
);
516 return &config_vars
[i
];
519 /* Okay, unrecognized options */
523 /** If <b>c</b> is a syntactically valid configuration line, update
524 * <b>options</b> with its value and return 0. Otherwise return -1 for bad key,
527 * If 'reset' is set, and we get a line containing no value, restore the
528 * option to its default value.
531 config_assign_line(or_options_t
*options
, struct config_line_t
*c
, int reset
)
537 var
= config_find_option(c
->key
);
539 log_fn(LOG_WARN
, "Unknown option '%s'. Failing.", c
->key
);
542 /* Put keyword into canonical case. */
543 if (strcmp(var
->name
, c
->key
)) {
545 c
->key
= tor_strdup(var
->name
);
548 if (reset
&& !strlen(c
->value
)) {
549 option_reset(options
, var
);
553 lvalue
= ((char*)options
) + var
->var_offset
;
556 case CONFIG_TYPE_UINT
:
557 i
= tor_parse_long(c
->value
, 10, 0, INT_MAX
, &ok
, NULL
);
559 log(LOG_WARN
, "Int keyword '%s %s' is malformed or out of bounds.",
566 case CONFIG_TYPE_INTERVAL
: {
567 i
= config_parse_interval(c
->value
, &ok
);
575 case CONFIG_TYPE_MEMUNIT
: {
576 uint64_t u64
= config_parse_memunit(c
->value
, &ok
);
580 *(uint64_t *)lvalue
= u64
;
584 case CONFIG_TYPE_BOOL
:
585 i
= tor_parse_long(c
->value
, 10, 0, 1, &ok
, NULL
);
587 log(LOG_WARN
, "Boolean keyword '%s' expects 0 or 1.", c
->key
);
593 case CONFIG_TYPE_STRING
:
594 tor_free(*(char **)lvalue
);
595 *(char **)lvalue
= tor_strdup(c
->value
);
598 case CONFIG_TYPE_DOUBLE
:
599 *(double *)lvalue
= atof(c
->value
);
602 case CONFIG_TYPE_CSV
:
603 if (*(smartlist_t
**)lvalue
) {
604 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
605 smartlist_clear(*(smartlist_t
**)lvalue
);
607 *(smartlist_t
**)lvalue
= smartlist_create();
610 smartlist_split_string(*(smartlist_t
**)lvalue
, c
->value
, ",",
611 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
614 case CONFIG_TYPE_LINELIST
:
615 case CONFIG_TYPE_LINELIST_S
:
616 config_line_append((struct config_line_t
**)lvalue
, c
->key
, c
->value
);
619 case CONFIG_TYPE_OBSOLETE
:
620 log_fn(LOG_WARN
, "Skipping obsolete configuration option '%s'", c
->key
);
622 case CONFIG_TYPE_LINELIST_V
:
623 log_fn(LOG_WARN
, "Can't provide value for virtual option '%s'", c
->key
);
632 /** restore the option named <b>key</b> in options to its default value. */
634 config_reset_line(or_options_t
*options
, const char *key
)
638 var
= config_find_option(key
);
640 return; /* give error on next pass. */
642 option_reset(options
, var
);
645 /** Return true iff key is a valid configuration option. */
647 config_option_is_recognized(const char *key
)
649 config_var_t
*var
= config_find_option(key
);
650 return (var
!= NULL
);
653 /** Return a canonicalized list of the options assigned for key.
655 struct config_line_t
*
656 config_get_assigned_option(or_options_t
*options
, const char *key
)
661 struct config_line_t
*result
;
662 tor_assert(options
&& key
);
664 var
= config_find_option(key
);
666 log_fn(LOG_WARN
, "Unknown option '%s'. Failing.", key
);
668 } else if (var
->type
== CONFIG_TYPE_LINELIST_S
) {
669 log_fn(LOG_WARN
, "Can't return context-sensitive '%s' on its own", key
);
672 value
= ((char*)options
) + var
->var_offset
;
674 if (var
->type
== CONFIG_TYPE_LINELIST
||
675 var
->type
== CONFIG_TYPE_LINELIST_V
) {
676 /* Linelist requires special handling: we just copy and return it. */
677 const struct config_line_t
*next_in
= *(const struct config_line_t
**)value
;
678 struct config_line_t
**next_out
= &result
;
680 *next_out
= tor_malloc(sizeof(struct config_line_t
));
681 (*next_out
)->key
= tor_strdup(next_in
->key
);
682 (*next_out
)->value
= tor_strdup(next_in
->value
);
683 next_in
= next_in
->next
;
684 next_out
= &((*next_out
)->next
);
690 result
= tor_malloc_zero(sizeof(struct config_line_t
));
691 result
->key
= tor_strdup(var
->name
);
694 case CONFIG_TYPE_STRING
:
695 if (*(char**)value
) {
696 result
->value
= tor_strdup(*(char**)value
);
698 tor_free(result
->key
);
703 case CONFIG_TYPE_INTERVAL
:
704 case CONFIG_TYPE_UINT
:
705 /* This means every or_options_t uint or bool element
706 * needs to be an int. Not, say, a uint16_t or char. */
707 tor_snprintf(buf
, sizeof(buf
), "%d", *(int*)value
);
708 result
->value
= tor_strdup(buf
);
710 case CONFIG_TYPE_MEMUNIT
:
711 tor_snprintf(buf
, sizeof(buf
), U64_FORMAT
,
712 U64_PRINTF_ARG(*(uint64_t*)value
));
713 result
->value
= tor_strdup(buf
);
715 case CONFIG_TYPE_DOUBLE
:
716 tor_snprintf(buf
, sizeof(buf
), "%f", *(double*)value
);
717 result
->value
= tor_strdup(buf
);
719 case CONFIG_TYPE_BOOL
:
720 result
->value
= tor_strdup(*(int*)value
? "1" : "0");
722 case CONFIG_TYPE_CSV
:
723 if (*(smartlist_t
**)value
)
724 result
->value
= smartlist_join_strings(*(smartlist_t
**)value
,",",0,NULL
);
726 result
->value
= tor_strdup("");
728 case CONFIG_TYPE_OBSOLETE
:
729 log_fn(LOG_WARN
,"You asked me for the value of an obsolete config option %s.", key
);
730 tor_free(result
->key
);
734 tor_free(result
->key
);
736 log_fn(LOG_WARN
,"Bug: unknown type %d for known key %s", var
->type
, key
);
743 /** Iterate through the linked list of requested options <b>list</b>.
744 * For each item, convert as appropriate and assign to <b>options</b>.
745 * If an item is unrecognized, return -1 immediately,
746 * else return 0 for success.
748 * If <b>reset</b>, then interpret empty lines as meaning "restore to
749 * default value", and interpret LINELIST* options as replacing (not
750 * extending) their previous values. Return 0 on success, -1 on bad key,
754 config_assign(or_options_t
*options
, struct config_line_t
*list
, int reset
)
756 struct config_line_t
*p
;
759 /* pass 1: normalize keys */
760 for (p
= list
; p
; p
= p
->next
) {
761 const char *full
= expand_abbrev(p
->key
, 0);
762 if (strcmp(full
,p
->key
)) {
764 p
->key
= tor_strdup(full
);
768 /* pass 2: if we're reading from a resetting source, clear all mentioned
771 for (p
= list
; p
; p
= p
->next
)
772 config_reset_line(options
, p
->key
);
775 /* pass 3: assign. */
778 if ((r
=config_assign_line(options
, list
, reset
)))
785 /** Try assigning <b>list</b> to the global options. You do this by duping
786 * options, assigning list to the new one, then validating it. If it's
787 * ok, then throw out the old one and stick with the new one. Else,
788 * revert to old and return failure. Return 0 on success, -1 on bad
789 * keys, -2 on bad values, -3 on bad transition.
792 config_trial_assign(struct config_line_t
*list
, int reset
)
795 or_options_t
*trial_options
= options_dup(get_options());
797 if ((r
=config_assign(trial_options
, list
, reset
)) < 0) {
798 options_free(trial_options
);
802 if (options_validate(trial_options
) < 0) {
803 options_free(trial_options
);
807 if (options_transition_allowed(get_options(), trial_options
) < 0) {
808 options_free(trial_options
);
812 set_options(trial_options
); /* we liked it. put it in place. */
816 /** Replace the option indexed by <b>var</b> in <b>options</b> with its
819 option_reset(or_options_t
*options
, config_var_t
*var
)
821 struct config_line_t
*c
;
824 lvalue
= ((char*)options
) + var
->var_offset
;
826 case CONFIG_TYPE_STRING
:
827 tor_free(*(char**)lvalue
);
829 case CONFIG_TYPE_DOUBLE
:
830 *(double*)lvalue
= 0.0;
832 case CONFIG_TYPE_INTERVAL
:
833 case CONFIG_TYPE_UINT
:
834 case CONFIG_TYPE_BOOL
:
837 case CONFIG_TYPE_MEMUNIT
:
838 *(uint64_t*)lvalue
= 0;
840 case CONFIG_TYPE_CSV
:
841 if (*(smartlist_t
**)lvalue
) {
842 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
843 smartlist_free(*(smartlist_t
**)lvalue
);
844 *(smartlist_t
**)lvalue
= NULL
;
847 case CONFIG_TYPE_LINELIST
:
848 case CONFIG_TYPE_LINELIST_S
:
849 config_free_lines(*(struct config_line_t
**)lvalue
);
850 *(struct config_line_t
**)lvalue
= NULL
;
852 case CONFIG_TYPE_LINELIST_V
:
853 /* handled by linelist_s. */
855 case CONFIG_TYPE_OBSOLETE
:
858 if (var
->initvalue
) {
859 c
= tor_malloc_zero(sizeof(struct config_line_t
));
860 c
->key
= tor_strdup(var
->name
);
861 c
->value
= tor_strdup(var
->initvalue
);
862 config_assign_line(options
,c
,0);
863 config_free_lines(c
);
867 /** Set <b>options</b>->DirServers to contain the default directory
870 add_default_trusted_dirservers(or_options_t
*options
)
873 config_line_append(&options
->DirServers
, "DirServer",
874 "18.244.0.188:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441");
876 config_line_append(&options
->DirServers
, "DirServer",
877 "18.244.0.114:80 719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF");
879 config_line_append(&options
->DirServers
, "DirServer",
880 "62.116.124.106:9030 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D");
881 // "tor.noreply.org:9030 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D");
884 /** Print a usage message for tor. */
889 "Copyright 2001-2004 Roger Dingledine, Nick Mathewson, Matej Pfajfar.\n\n"
890 "tor -f <torrc> [args]\n"
891 "See man page for options, or http://tor.eff.org/ for documentation.\n");
895 * Based on <b>address</b>, guess our public IP address and put it
899 resolve_my_address(const char *address
, uint32_t *addr
)
902 struct hostent
*rent
;
909 strlcpy(hostname
, address
, sizeof(hostname
));
910 } else { /* then we need to guess our address */
911 explicit_ip
= 0; /* it's implicit */
913 if (gethostname(hostname
, sizeof(hostname
)) < 0) {
914 log_fn(LOG_WARN
,"Error obtaining local hostname");
917 log_fn(LOG_DEBUG
,"Guessed local host name as '%s'",hostname
);
920 /* now we know hostname. resolve it and keep only the IP */
922 if (tor_inet_aton(hostname
, &in
) == 0) {
923 /* then we have to resolve it */
925 rent
= (struct hostent
*)gethostbyname(hostname
);
927 log_fn(LOG_WARN
,"Could not resolve local Address %s. Failing.", hostname
);
930 tor_assert(rent
->h_length
== 4);
931 memcpy(&in
.s_addr
, rent
->h_addr
, rent
->h_length
);
934 if (!explicit_ip
&& is_internal_IP(htonl(in
.s_addr
))) {
935 log_fn(LOG_WARN
,"Address '%s' resolves to private IP '%s'. "
936 "Please set the Address config option to be the IP you want to use.",
937 hostname
, inet_ntoa(in
));
941 log_fn(LOG_DEBUG
, "Resolved Address to %s.", inet_ntoa(in
));
942 *addr
= ntohl(in
.s_addr
);
946 /** Called when we don't have a nickname set. Try to guess a good
947 * nickname based on the hostname, and return it in a newly allocated string. */
949 get_default_nickname(void)
951 char localhostname
[256];
952 char *cp
, *out
, *outp
;
954 if (gethostname(localhostname
, sizeof(localhostname
)) < 0) {
955 log_fn(LOG_WARN
,"Error obtaining local hostname");
959 /* Put it in lowercase; stop at the first dot. */
960 for (cp
= localhostname
; *cp
; ++cp
) {
968 /* Strip invalid characters. */
970 out
= outp
= tor_malloc(strlen(localhostname
) + 1);
972 if (strchr(LEGAL_NICKNAME_CHARACTERS
, *cp
))
979 /* Enforce length. */
980 if (strlen(out
) > MAX_NICKNAME_LEN
)
981 out
[MAX_NICKNAME_LEN
]='\0';
986 /** Release storage held by <b>options</b> */
988 options_free(or_options_t
*options
)
995 for (i
=0; config_vars
[i
].name
; ++i
) {
996 lvalue
= ((char*)options
) + config_vars
[i
].var_offset
;
997 switch (config_vars
[i
].type
) {
998 case CONFIG_TYPE_MEMUNIT
:
999 case CONFIG_TYPE_INTERVAL
:
1000 case CONFIG_TYPE_UINT
:
1001 case CONFIG_TYPE_BOOL
:
1002 case CONFIG_TYPE_DOUBLE
:
1003 case CONFIG_TYPE_OBSOLETE
:
1004 break; /* nothing to free for these config types */
1005 case CONFIG_TYPE_STRING
:
1006 tor_free(*(char **)lvalue
);
1008 case CONFIG_TYPE_LINELIST
:
1009 case CONFIG_TYPE_LINELIST_V
:
1010 config_free_lines(*(struct config_line_t
**)lvalue
);
1011 *(struct config_line_t
**)lvalue
= NULL
;
1013 case CONFIG_TYPE_CSV
:
1014 if (*(smartlist_t
**)lvalue
) {
1015 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
1016 smartlist_free(*(smartlist_t
**)lvalue
);
1017 *(smartlist_t
**)lvalue
= NULL
;
1020 case CONFIG_TYPE_LINELIST_S
:
1021 /* will be freed by corresponding LINELIST_V. */
1028 /** Return true iff the option <b>var</b> has the same value in <b>o1</b>
1029 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
1032 option_is_same(or_options_t
*o1
, or_options_t
*o2
, const char *name
)
1034 struct config_line_t
*c1
, *c2
;
1036 c1
= config_get_assigned_option(o1
, name
);
1037 c2
= config_get_assigned_option(o2
, name
);
1039 if (strcasecmp(c1
->key
, c2
->key
) ||
1040 strcmp(c1
->value
, c2
->value
)) {
1047 if (r
&& (c1
|| c2
)) {
1050 config_free_lines(c1
);
1051 config_free_lines(c2
);
1055 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
1056 static or_options_t
*
1057 options_dup(or_options_t
*old
)
1059 or_options_t
*newopts
;
1061 struct config_line_t
*line
;
1063 newopts
= tor_malloc_zero(sizeof(or_options_t
));
1064 for (i
=0; config_vars
[i
].name
; ++i
) {
1065 if (config_vars
[i
].type
== CONFIG_TYPE_LINELIST_S
)
1067 if (config_vars
[i
].type
== CONFIG_TYPE_OBSOLETE
)
1069 line
= config_get_assigned_option(old
, config_vars
[i
].name
);
1071 if (config_assign(newopts
, line
, 0) < 0) {
1072 log_fn(LOG_WARN
,"Bug: config_get_assigned_option() generated "
1073 "something we couldn't config_assign().");
1077 config_free_lines(line
);
1082 /** Set <b>options</b> to hold reasonable defaults for most options.
1083 * Each option defaults to zero. */
1085 options_init(or_options_t
*options
)
1090 for (i
=0; config_vars
[i
].name
; ++i
) {
1091 var
= &config_vars
[i
];
1092 if (!var
->initvalue
)
1093 continue; /* defaults to NULL or 0 */
1094 option_reset(options
, var
);
1098 /** Return a string containing a possible configuration file that would give
1099 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
1100 * include options that are the same as Tor's defaults.
1103 config_dump_options(or_options_t
*options
, int minimal
)
1105 smartlist_t
*elements
;
1106 or_options_t
*defaults
;
1107 struct config_line_t
*line
;
1111 defaults
= tor_malloc_zero(sizeof(or_options_t
));
1112 options_init(defaults
);
1113 options_validate(defaults
); /* ??? will this work? */
1115 elements
= smartlist_create();
1116 for (i
=0; config_vars
[i
].name
; ++i
) {
1117 if (config_vars
[i
].type
== CONFIG_TYPE_OBSOLETE
||
1118 config_vars
[i
].type
== CONFIG_TYPE_LINELIST_S
)
1120 if (minimal
&& option_is_same(options
, defaults
, config_vars
[i
].name
))
1122 line
= config_get_assigned_option(options
, config_vars
[i
].name
);
1123 for (; line
; line
= line
->next
) {
1124 size_t len
= strlen(line
->key
) + strlen(line
->value
) + 3;
1126 tmp
= tor_malloc(len
);
1127 if (tor_snprintf(tmp
, len
, "%s %s\n", line
->key
, line
->value
)<0) {
1128 log_fn(LOG_ERR
, "Internal error writing log option");
1131 smartlist_add(elements
, tmp
);
1133 config_free_lines(line
);
1136 result
= smartlist_join_strings(elements
, "", 0, NULL
);
1137 SMARTLIST_FOREACH(elements
, char *, cp
, tor_free(cp
));
1138 smartlist_free(elements
);
1143 validate_ports_csv(smartlist_t
*sl
, char *name
) {
1151 SMARTLIST_FOREACH(sl
, const char *, cp
,
1154 if (i
< 1 || i
> 65535) {
1155 log(LOG_WARN
, "Port '%s' out of range in %s", cp
, name
);
1162 /** Return 0 if every setting in <b>options</b> is reasonable. Else
1163 * warn and return -1. Should have no side effects, except for
1164 * normalizing the contents of <b>options</b>. */
1166 options_validate(or_options_t
*options
)
1169 struct config_line_t
*cl
;
1170 addr_policy_t
*addr_policy
=NULL
;
1172 if (options
->ORPort
< 0 || options
->ORPort
> 65535) {
1173 log(LOG_WARN
, "ORPort option out of bounds.");
1177 /* XXX might similarly want to check the other *BindAddress options */
1178 if (options
->ORPort
== 0 && options
->ORBindAddress
!= NULL
) {
1179 log(LOG_WARN
, "ORPort must be defined if ORBindAddress is defined.");
1183 if (validate_data_directory(options
)<0) {
1184 log(LOG_WARN
, "Invalid DataDirectory");
1188 if (options
->Nickname
== NULL
) {
1189 if (server_mode(options
)) {
1190 if (!(options
->Nickname
= get_default_nickname()))
1192 log_fn(LOG_NOTICE
, "Choosing default nickname %s", options
->Nickname
);
1195 if (strspn(options
->Nickname
, LEGAL_NICKNAME_CHARACTERS
) !=
1196 strlen(options
->Nickname
)) {
1197 log_fn(LOG_WARN
, "Nickname '%s' contains illegal characters.", options
->Nickname
);
1200 if (strlen(options
->Nickname
) == 0) {
1201 log_fn(LOG_WARN
, "Nickname must have at least one character");
1204 if (strlen(options
->Nickname
) > MAX_NICKNAME_LEN
) {
1205 log_fn(LOG_WARN
, "Nickname '%s' has more than %d characters.",
1206 options
->Nickname
, MAX_NICKNAME_LEN
);
1211 if (normalize_log_options(options
))
1214 /* Special case if no options are given. */
1215 if (!options
->Logs
) {
1216 config_line_append(&options
->Logs
, "Log", "notice stdout");
1219 if (config_init_logs(options
, 1)<0) /* Validate the log(s) */
1222 if (server_mode(options
)) {
1223 /* confirm that our address isn't broken, so we can complain now */
1225 if (resolve_my_address(options
->Address
, &tmp
) < 0)
1229 if (options
->SocksPort
< 0 || options
->SocksPort
> 65535) {
1230 log(LOG_WARN
, "SocksPort option out of bounds.");
1234 if (options
->SocksPort
== 0 && options
->ORPort
== 0) {
1235 log(LOG_WARN
, "SocksPort and ORPort are both undefined? Quitting.");
1239 if (options
->ControlPort
< 0 || options
->ControlPort
> 65535) {
1240 log(LOG_WARN
, "ControlPort option out of bounds.");
1244 if (options
->DirPort
< 0 || options
->DirPort
> 65535) {
1245 log(LOG_WARN
, "DirPort option out of bounds.");
1249 if (options
->StrictExitNodes
&&
1250 (!options
->ExitNodes
|| !strlen(options
->ExitNodes
))) {
1251 log(LOG_WARN
, "StrictExitNodes set, but no ExitNodes listed.");
1254 if (options
->StrictEntryNodes
&&
1255 (!options
->EntryNodes
|| !strlen(options
->EntryNodes
))) {
1256 log(LOG_WARN
, "StrictEntryNodes set, but no EntryNodes listed.");
1259 if (options
->AuthoritativeDir
&& options
->RecommendedVersions
== NULL
) {
1260 log(LOG_WARN
, "Directory servers must configure RecommendedVersions.");
1264 if (options
->AuthoritativeDir
&& !options
->DirPort
) {
1265 log(LOG_WARN
, "Running as authoritative directory, but no DirPort set.");
1269 if (options
->AuthoritativeDir
&& !options
->ORPort
) {
1270 log(LOG_WARN
, "Running as authoritative directory, but no ORPort set.");
1274 if (options
->AuthoritativeDir
&& options
->ClientOnly
) {
1275 log(LOG_WARN
, "Running as authoritative directory, but ClientOnly also set.");
1279 if (options
->_AccountingMaxKB
) {
1280 log(LOG_WARN
, "AccountingMaxKB is deprecated. Say 'AccountingMax %d KB' instead.", options
->_AccountingMaxKB
);
1281 options
->AccountingMax
= U64_LITERAL(1024)*options
->_AccountingMaxKB
;
1282 options
->_AccountingMaxKB
= 0;
1285 if (validate_ports_csv(options
->FirewallPorts
,
1286 "FirewallPorts") < 0)
1289 if (validate_ports_csv(options
->LongLivedPorts
,
1290 "LongLivedPorts") < 0)
1293 options
->_AllowUnverified
= 0;
1294 if (options
->AllowUnverifiedNodes
) {
1295 SMARTLIST_FOREACH(options
->AllowUnverifiedNodes
, const char *, cp
, {
1296 if (!strcasecmp(cp
, "entry"))
1297 options
->_AllowUnverified
|= ALLOW_UNVERIFIED_ENTRY
;
1298 else if (!strcasecmp(cp
, "exit"))
1299 options
->_AllowUnverified
|= ALLOW_UNVERIFIED_EXIT
;
1300 else if (!strcasecmp(cp
, "middle"))
1301 options
->_AllowUnverified
|= ALLOW_UNVERIFIED_MIDDLE
;
1302 else if (!strcasecmp(cp
, "introduction"))
1303 options
->_AllowUnverified
|= ALLOW_UNVERIFIED_INTRODUCTION
;
1304 else if (!strcasecmp(cp
, "rendezvous"))
1305 options
->_AllowUnverified
|= ALLOW_UNVERIFIED_RENDEZVOUS
;
1307 log(LOG_WARN
, "Unrecognized value '%s' in AllowUnverifiedNodes",
1314 if (options
->SocksPort
>= 1 &&
1315 (options
->PathlenCoinWeight
< 0.0 || options
->PathlenCoinWeight
>= 1.0)) {
1316 log(LOG_WARN
, "PathlenCoinWeight option must be >=0.0 and <1.0.");
1320 if (options
->MaxConn
< 1) {
1321 log(LOG_WARN
, "MaxConn option must be a non-zero positive integer.");
1325 if (options
->MaxConn
>= MAXCONNECTIONS
) {
1326 log(LOG_WARN
, "MaxConn option must be less than %d.", MAXCONNECTIONS
);
1330 #define MIN_DIR_FETCH_PERIOD 600
1331 #define MIN_DIR_POST_PERIOD 300
1332 #define MIN_REND_POST_PERIOD 300
1333 #define MIN_STATUS_FETCH_PERIOD 60
1335 /* After 0.0.8 is dead, change this to MIN_ONION_KEY_LIFETIME. */
1336 #define MAX_DIR_PERIOD (OLD_MIN_ONION_KEY_LIFETIME/2)
1337 #define MAX_CACHE_DIR_FETCH_PERIOD 3600
1338 #define MAX_CACHE_STATUS_FETCH_PERIOD 900
1340 if (options
->DirFetchPeriod
< MIN_DIR_FETCH_PERIOD
) {
1341 log(LOG_WARN
, "DirFetchPeriod option must be at least %d seconds. Clipping.", MIN_DIR_FETCH_PERIOD
);
1342 options
->DirFetchPeriod
= MIN_DIR_FETCH_PERIOD
;
1344 if (options
->StatusFetchPeriod
< MIN_STATUS_FETCH_PERIOD
) {
1345 log(LOG_WARN
, "StatusFetchPeriod option must be at least %d seconds. Clipping.", MIN_STATUS_FETCH_PERIOD
);
1346 options
->StatusFetchPeriod
= MIN_STATUS_FETCH_PERIOD
;
1348 if (options
->DirPostPeriod
< MIN_DIR_POST_PERIOD
) {
1349 log(LOG_WARN
, "DirPostPeriod option must be at least %d seconds. Clipping.",
1350 MIN_DIR_POST_PERIOD
);
1351 options
->DirPostPeriod
= MIN_DIR_POST_PERIOD
;
1353 if (options
->RendPostPeriod
< MIN_REND_POST_PERIOD
) {
1354 log(LOG_WARN
,"RendPostPeriod option must be at least %d seconds. Clipping.",
1355 MIN_REND_POST_PERIOD
);
1356 options
->RendPostPeriod
= MIN_REND_POST_PERIOD
;
1359 if (options
->DirPort
&& ! options
->AuthoritativeDir
) {
1360 if (options
->DirFetchPeriod
> MAX_CACHE_DIR_FETCH_PERIOD
) {
1361 log(LOG_WARN
, "Caching directory servers must have DirFetchPeriod less than %d seconds. Clipping.", MAX_CACHE_DIR_FETCH_PERIOD
);
1362 options
->DirFetchPeriod
= MAX_CACHE_DIR_FETCH_PERIOD
;
1364 if (options
->StatusFetchPeriod
> MAX_CACHE_STATUS_FETCH_PERIOD
) {
1365 log(LOG_WARN
, "Caching directory servers must have StatusFetchPeriod less than %d seconds. Clipping.", MAX_CACHE_STATUS_FETCH_PERIOD
);
1366 options
->StatusFetchPeriod
= MAX_CACHE_STATUS_FETCH_PERIOD
;
1370 if (options
->DirFetchPeriod
> MAX_DIR_PERIOD
) {
1371 log(LOG_WARN
, "DirFetchPeriod is too large; clipping.");
1372 options
->DirFetchPeriod
= MAX_DIR_PERIOD
;
1374 if (options
->DirPostPeriod
> MAX_DIR_PERIOD
) {
1375 log(LOG_WARN
, "DirPostPeriod is too large; clipping.");
1376 options
->DirPostPeriod
= MAX_DIR_PERIOD
;
1378 if (options
->StatusFetchPeriod
> MAX_DIR_PERIOD
) {
1379 log(LOG_WARN
, "StatusFetchPeriod is too large; clipping.");
1380 options
->StatusFetchPeriod
= MAX_DIR_PERIOD
;
1382 if (options
->RendPostPeriod
> MAX_DIR_PERIOD
) {
1383 log(LOG_WARN
, "RendPostPeriod is too large; clipping.");
1384 options
->RendPostPeriod
= MAX_DIR_PERIOD
;
1387 if (options
->KeepalivePeriod
< 1) {
1388 log(LOG_WARN
,"KeepalivePeriod option must be positive.");
1392 if (2*options
->BandwidthRate
>= options
->BandwidthBurst
) {
1393 log(LOG_WARN
,"BandwidthBurst must be more than twice BandwidthRate.");
1396 if (options
->BandwidthRate
> INT_MAX
) {
1397 log(LOG_WARN
,"BandwidthRate must be less than %d",INT_MAX
);
1400 if (options
->BandwidthBurst
> INT_MAX
) {
1401 log(LOG_WARN
,"BandwidthBurst must be less than %d",INT_MAX
);
1404 if (server_mode(options
) &&
1405 options
->BandwidthRate
< ROUTER_REQUIRED_MIN_BANDWIDTH
*2) {
1406 log(LOG_WARN
,"BandwidthRate is set to %d bytes/second. For servers, it must be at least %d.", (int)options
->BandwidthRate
, ROUTER_REQUIRED_MIN_BANDWIDTH
*2);
1410 if (options
->_MonthlyAccountingStart
) {
1411 if (options
->AccountingStart
) {
1412 log(LOG_WARN
,"Can't specify AccountingStart and MonthlyAccountingStart");
1415 options
->AccountingStart
= tor_malloc(32);
1416 if (tor_snprintf(options
->AccountingStart
, 32, "month %d 0:00",
1417 options
->_MonthlyAccountingStart
)<0) {
1418 log_fn(LOG_WARN
,"Error translating MonthlyAccountingStart");
1421 log_fn(LOG_WARN
,"MonthlyAccountingStart is deprecated. Use 'AccountingStart %s' instead.", options
->AccountingStart
);
1426 if (accounting_parse_options(options
, 1)<0) {
1430 if (options
->HttpProxy
) { /* parse it now */
1431 if (parse_addr_port(options
->HttpProxy
, NULL
,
1432 &options
->HttpProxyAddr
, &options
->HttpProxyPort
) < 0) {
1433 log(LOG_WARN
,"HttpProxy failed to parse or resolve. Please fix.");
1436 if (options
->HttpProxyPort
== 0) { /* give it a default */
1437 options
->HttpProxyPort
= 80;
1441 if (options
->HashedControlPassword
) {
1442 if (decode_hashed_password(NULL
, options
->HashedControlPassword
)<0) {
1443 log_fn(LOG_WARN
,"Bad HashedControlPassword: wrong length or bad base64");
1447 if (options
->HashedControlPassword
&& options
->CookieAuthentication
) {
1448 log_fn(LOG_WARN
,"Cannot enable both HashedControlPassword and CookieAuthentication");
1452 if (check_nickname_list(options
->ExitNodes
, "ExitNodes"))
1454 if (check_nickname_list(options
->EntryNodes
, "EntryNodes"))
1456 if (check_nickname_list(options
->ExcludeNodes
, "ExcludeNodes"))
1458 if (check_nickname_list(options
->RendNodes
, "RendNodes"))
1460 if (check_nickname_list(options
->RendNodes
, "RendExcludeNodes"))
1462 if (check_nickname_list(options
->MyFamily
, "MyFamily"))
1464 for (cl
= options
->NodeFamilies
; cl
; cl
= cl
->next
) {
1465 if (check_nickname_list(cl
->value
, "NodeFamily"))
1469 if (config_parse_addr_policy(options
->ExitPolicy
, &addr_policy
)) {
1470 log_fn(LOG_WARN
, "Error in Exit Policy entry.");
1473 if (config_parse_addr_policy(options
->DirPolicy
, &addr_policy
)) {
1474 log_fn(LOG_WARN
, "Error in DirPolicy entry.");
1477 if (config_parse_addr_policy(options
->SocksPolicy
, &addr_policy
)) {
1478 log_fn(LOG_WARN
, "Error in SocksPolicy entry.");
1481 addr_policy_free(addr_policy
);
1483 for (cl
= options
->RedirectExit
; cl
; cl
= cl
->next
) {
1484 if (parse_redirect_line(NULL
, cl
)<0)
1488 if (!options
->DirServers
) {
1489 add_default_trusted_dirservers(options
);
1491 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
) {
1492 if (parse_dir_server_line(cl
->value
, 1)<0)
1497 if (rend_config_services(options
, 1) < 0)
1503 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
1506 opt_streq(const char *s1
, const char *s2
)
1510 else if (s1
&& s2
&& !strcmp(s1
,s2
))
1516 /** Check if any of the previous options have changed but aren't allowed to. */
1518 options_transition_allowed(or_options_t
*old
, or_options_t
*new_val
) {
1523 if (!opt_streq(old
->PidFile
, new_val
->PidFile
)) {
1524 log_fn(LOG_WARN
,"PidFile is not allowed to change. Failing.");
1528 if (old
->RunAsDaemon
&& !new_val
->RunAsDaemon
) {
1529 log_fn(LOG_WARN
,"During reload, change from RunAsDaemon=1 to =0 not allowed. Failing.");
1533 if (old
->ORPort
!= new_val
->ORPort
) {
1534 log_fn(LOG_WARN
,"During reload, changing ORPort is not allowed. Failing.");
1538 if (strcmp(old
->DataDirectory
,new_val
->DataDirectory
)!=0) {
1539 log_fn(LOG_WARN
,"During reload, changing DataDirectory (%s->%s) is not allowed. Failing.", old
->DataDirectory
, new_val
->DataDirectory
);
1543 if (!opt_streq(old
->User
, new_val
->User
)) {
1544 log_fn(LOG_WARN
,"During reload, changing User is not allowed. Failing.");
1548 if (!opt_streq(old
->Group
, new_val
->Group
)) {
1549 log_fn(LOG_WARN
,"During reload, changing User is not allowed. Failing.");
1557 /** Return the directory on windows where we expect to find our application
1559 static char *get_windows_conf_root(void)
1561 static int is_set
= 0;
1562 static char path
[MAX_PATH
+1];
1571 /* Find X:\documents and settings\username\application data\ .
1572 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
1574 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL
, CSIDL_APPDATA
,
1576 GetCurrentDirectory(MAX_PATH
, path
);
1578 log_fn(LOG_WARN
, "I couldn't find your application data folder: are you running an ancient version of Windows 95? Defaulting to '%s'", path
);
1581 /* Convert the path from an "ID List" (whatever that is!) to a path. */
1582 result
= SHGetPathFromIDList(idl
, path
);
1583 /* Now we need to free the */
1586 m
->lpVtbl
->Free(m
, idl
);
1587 m
->lpVtbl
->Release(m
);
1589 if (!SUCCEEDED(result
)) {
1592 strlcat(path
,"\\tor",MAX_PATH
);
1598 /** Return the default location for our torrc file. */
1600 get_default_conf_file(void)
1603 char *path
= tor_malloc(MAX_PATH
);
1604 strlcpy(path
, get_windows_conf_root(), MAX_PATH
);
1605 strlcat(path
,"\\torrc",MAX_PATH
);
1608 return tor_strdup(CONFDIR
"/torrc");
1612 /** Verify whether lst is a string containing valid-looking space-separated
1613 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
1615 static int check_nickname_list(const char *lst
, const char *name
)
1622 sl
= smartlist_create();
1623 smartlist_split_string(sl
, lst
, ",", SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1624 SMARTLIST_FOREACH(sl
, const char *, s
,
1626 if (!is_legal_nickname_or_hexdigest(s
)) {
1627 log_fn(LOG_WARN
, "Invalid nickname '%s' in %s line", s
, name
);
1631 SMARTLIST_FOREACH(sl
, char *, s
, tor_free(s
));
1636 /** Read a configuration file into <b>options</b>, finding the configuration
1637 * file location based on the command line. After loading the options,
1638 * validate them for consistency, then take actions based on them.
1639 * Return 0 if success, -1 if failure. */
1641 init_from_config(int argc
, char **argv
)
1643 or_options_t
*oldoptions
, *newoptions
;
1644 struct config_line_t
*cl
;
1645 char *cf
=NULL
, *fname
=NULL
;
1647 int using_default_torrc
;
1648 static char **backup_argv
;
1649 static int backup_argc
;
1651 if (argv
) { /* first time we're called. save commandline args */
1655 } else { /* we're reloading. need to clean up old options first. */
1658 oldoptions
= get_options();
1660 if (argc
> 1 && (!strcmp(argv
[1], "-h") || !strcmp(argv
[1],"--help"))) {
1665 if (argc
> 1 && (!strcmp(argv
[1],"--version"))) {
1666 printf("Tor version %s.\n",VERSION
);
1667 if (argc
> 2 && (!strcmp(argv
[2],"--version"))) {
1668 print_cvs_version();
1673 newoptions
= tor_malloc_zero(sizeof(or_options_t
));
1674 options_init(newoptions
);
1676 /* learn config file name, get config lines, assign them */
1678 using_default_torrc
= 1;
1679 newoptions
->command
= CMD_RUN_TOR
;
1680 for (i
= 1; i
< argc
; ++i
) {
1681 if (i
< argc
-1 && !strcmp(argv
[i
],"-f")) {
1683 log(LOG_WARN
, "Duplicate -f options on command line.");
1686 fname
= tor_strdup(argv
[i
+1]);
1687 using_default_torrc
= 0;
1689 } else if (!strcmp(argv
[i
],"--list-fingerprint")) {
1690 newoptions
->command
= CMD_LIST_FINGERPRINT
;
1691 } else if (!strcmp(argv
[i
],"--hash-password")) {
1692 newoptions
->command
= CMD_HASH_PASSWORD
;
1693 newoptions
->command_arg
= tor_strdup( (i
< argc
-1) ? argv
[i
+1] : "");
1698 if (using_default_torrc
) {
1699 /* didn't find one, try CONFDIR */
1701 fn
= get_default_conf_file();
1702 if (fn
&& file_status(fn
) == FN_FILE
) {
1707 fn
= expand_filename("~/.torrc");
1708 if (fn
&& file_status(fn
) == FN_FILE
) {
1712 fname
= get_default_conf_file();
1715 fname
= get_default_conf_file();
1720 log(LOG_DEBUG
, "Opening config file '%s'", fname
);
1722 if (file_status(fname
) != FN_FILE
||
1723 !(cf
= read_file_to_str(fname
,0))) {
1724 if (using_default_torrc
== 1) {
1725 log(LOG_NOTICE
, "Configuration file '%s' not present, "
1726 "using reasonable defaults.", fname
);
1727 tor_free(fname
); /* sets fname to NULL */
1729 log(LOG_WARN
, "Unable to open configuration file '%s'.", fname
);
1733 } else { /* it opened successfully. use it. */
1734 retval
= config_get_lines(cf
, &cl
);
1738 retval
= config_assign(newoptions
, cl
, 0);
1739 config_free_lines(cl
);
1744 /* Go through command-line variables too */
1745 cl
= config_get_commandlines(argc
,argv
);
1746 retval
= config_assign(newoptions
,cl
,0);
1747 config_free_lines(cl
);
1751 /* Validate newoptions */
1752 if (options_validate(newoptions
) < 0)
1755 if (options_transition_allowed(oldoptions
, newoptions
) < 0)
1758 set_options(newoptions
); /* frees and replaces old options */
1759 if (options_act() < 0) { /* acting on them failed. die. */
1760 log_fn(LOG_ERR
,"Acting on config options left us in a broken state. Dying.");
1763 tor_free(config_fname
);
1764 config_fname
= fname
;
1768 options_free(newoptions
);
1772 /** If <b>range</b> is of the form MIN-MAX, for MIN and MAX both
1773 * recognized log severity levels, set *<b>min_out</b> to MIN and
1774 * *<b>max_out</b> to MAX and return 0. Else, if <b>range<b> is of
1775 * the form MIN, act as if MIN-err had been specified. Else, warn and
1779 parse_log_severity_range(const char *range
, int *min_out
, int *max_out
)
1781 int levelMin
, levelMax
;
1783 cp
= strchr(range
, '-');
1786 levelMin
= LOG_DEBUG
;
1788 char *tmp_sev
= tor_strndup(range
, cp
- range
);
1789 levelMin
= parse_log_level(tmp_sev
);
1791 log_fn(LOG_WARN
, "Unrecognized log severity '%s': must be one of "
1792 "err|warn|notice|info|debug", tmp_sev
);
1801 levelMax
= parse_log_level(cp
+1);
1803 log_fn(LOG_WARN
, "Unrecognized log severity '%s': must be one of "
1804 "err|warn|notice|info|debug", cp
+1);
1809 levelMin
= parse_log_level(range
);
1811 log_fn(LOG_WARN
, "Unrecognized log severity '%s': must be one of "
1812 "err|warn|notice|info|debug", range
);
1818 *min_out
= levelMin
;
1819 *max_out
= levelMax
;
1824 /** Try to convert a pair of old-style logging options [LogLevel, and
1825 * (LogFile/Syslog)] to a new-style option, and add the new option to
1828 convert_log_option(or_options_t
*options
, struct config_line_t
*level_opt
,
1829 struct config_line_t
*file_opt
, int isDaemon
)
1831 int levelMin
= -1, levelMax
= -1;
1834 if (parse_log_severity_range(level_opt
->value
, &levelMin
, &levelMax
))
1837 if (levelMin
< 0 && levelMax
< 0) {
1838 levelMin
= LOG_NOTICE
;
1840 } else if (levelMin
< 0) {
1841 levelMin
= levelMax
;
1846 if (file_opt
&& !strcasecmp(file_opt
->key
, "LogFile")) {
1847 if (add_single_log_option(options
, levelMin
, levelMax
, "file", file_opt
->value
) < 0) {
1848 log_fn(LOG_WARN
, "Cannot write to LogFile '%s': %s.", file_opt
->value
,
1852 } else if (file_opt
&& !strcasecmp(file_opt
->key
, "SysLog")) {
1853 if (add_single_log_option(options
, levelMin
, levelMax
, "syslog", NULL
) < 0)
1855 } else if (!isDaemon
) {
1856 add_single_log_option(options
, levelMin
, levelMax
, "stdout", NULL
);
1862 * Initialize the logs based on the configuration file.
1865 config_init_logs(or_options_t
*options
, int validate_only
)
1867 struct config_line_t
*opt
;
1872 elts
= smartlist_create();
1873 for (opt
= options
->Logs
; opt
; opt
= opt
->next
) {
1874 int levelMin
=LOG_DEBUG
, levelMax
=LOG_ERR
;
1875 smartlist_split_string(elts
, opt
->value
, NULL
,
1876 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 3);
1877 if (smartlist_len(elts
) == 0) {
1878 log_fn(LOG_WARN
, "Bad syntax on Log option 'Log %s'", opt
->value
);
1879 ok
= 0; goto cleanup
;
1881 if (parse_log_severity_range(smartlist_get(elts
,0), &levelMin
, &levelMax
)) {
1882 ok
= 0; goto cleanup
;
1884 if (smartlist_len(elts
) < 2) { /* only loglevels were provided */
1886 add_stream_log(levelMin
, levelMax
, "<stdout>", stdout
);
1889 if (!strcasecmp(smartlist_get(elts
,1), "file")) {
1890 if (smartlist_len(elts
) != 3) {
1891 log_fn(LOG_WARN
, "Bad syntax on Log option 'Log %s'", opt
->value
);
1892 ok
= 0; goto cleanup
;
1895 add_file_log(levelMin
, levelMax
, smartlist_get(elts
, 2));
1898 if (smartlist_len(elts
) != 2) {
1899 log_fn(LOG_WARN
, "Bad syntax on Log option 'Log %s'", opt
->value
);
1900 ok
= 0; goto cleanup
;
1902 if (!strcasecmp(smartlist_get(elts
,1), "stdout")) {
1903 if (!validate_only
) {
1904 add_stream_log(levelMin
, levelMax
, "<stdout>", stdout
);
1907 } else if (!strcasecmp(smartlist_get(elts
,1), "stderr")) {
1908 if (!validate_only
) {
1909 add_stream_log(levelMin
, levelMax
, "<stderr>", stderr
);
1912 } else if (!strcasecmp(smartlist_get(elts
,1), "syslog")) {
1913 #ifdef HAVE_SYSLOG_H
1915 add_syslog_log(levelMin
, levelMax
);
1917 log_fn(LOG_WARN
, "Syslog is not supported in this compilation.");
1920 log_fn(LOG_WARN
, "Unrecognized log type %s",
1921 (const char*)smartlist_get(elts
,1));
1922 if (strchr(smartlist_get(elts
,1), '/')) {
1923 log_fn(LOG_WARN
, "Did you mean to say 'Log file %s' ?",
1924 (const char *)smartlist_get(elts
,1));
1926 ok
= 0; goto cleanup
;
1929 SMARTLIST_FOREACH(elts
, char*, cp
, tor_free(cp
));
1930 smartlist_clear(elts
);
1932 smartlist_free(elts
);
1939 /** Add a single option of the form Log min-max <type> [fname] to options. */
1941 add_single_log_option(or_options_t
*options
, int minSeverity
, int maxSeverity
,
1942 const char *type
, const char *fname
)
1947 n
= tor_snprintf(buf
, sizeof(buf
), "%s%s%s %s%s%s",
1948 log_level_to_string(minSeverity
),
1949 maxSeverity
== LOG_ERR
? "" : "-",
1950 maxSeverity
== LOG_ERR
? "" : log_level_to_string(maxSeverity
),
1951 type
, fname
?" ":"", fname
?fname
:"");
1953 log_fn(LOG_WARN
, "Normalized log option too long.");
1957 log(LOG_WARN
, "The old LogLevel/LogFile/DebugLogFile/SysLog options are deprecated, and will go away soon. Your new torrc line should be: 'Log %s'", buf
);
1958 config_line_append(&options
->Logs
, "Log", buf
);
1962 /** Convert all old-style logging options to new-style Log options. Return 0
1963 * on success, -1 on failure. */
1965 normalize_log_options(or_options_t
*options
)
1967 /* The order of options is: Level? (File Level?)+
1969 struct config_line_t
*opt
= options
->OldLogOptions
;
1971 /* Special case for if first option is LogLevel. */
1972 if (opt
&& !strcasecmp(opt
->key
, "LogLevel")) {
1973 if (opt
->next
&& (!strcasecmp(opt
->next
->key
, "LogFile") ||
1974 !strcasecmp(opt
->next
->key
, "SysLog"))) {
1975 if (convert_log_option(options
, opt
, opt
->next
, options
->RunAsDaemon
) < 0)
1977 opt
= opt
->next
->next
;
1978 } else if (!opt
->next
) {
1979 if (convert_log_option(options
, opt
, NULL
, options
->RunAsDaemon
) < 0)
1983 ; /* give warning below */
1988 if (!strcasecmp(opt
->key
, "LogLevel")) {
1989 log_fn(LOG_WARN
, "Two LogLevel options in a row without intervening LogFile or SysLog");
1992 tor_assert(!strcasecmp(opt
->key
, "LogFile") ||
1993 !strcasecmp(opt
->key
, "SysLog"));
1994 if (opt
->next
&& !strcasecmp(opt
->next
->key
, "LogLevel")) {
1995 /* LogFile/SysLog followed by LogLevel */
1996 if (convert_log_option(options
,opt
->next
,opt
, options
->RunAsDaemon
) < 0)
1998 opt
= opt
->next
->next
;
2000 /* LogFile/SysLog followed by LogFile/SysLog or end of list. */
2001 if (convert_log_option(options
,NULL
, opt
, options
->RunAsDaemon
) < 0)
2008 if (options
->DebugLogFile
) {
2009 if (add_single_log_option(options
, LOG_DEBUG
, LOG_ERR
, "file", options
->DebugLogFile
) < 0)
2013 tor_free(options
->DebugLogFile
);
2014 config_free_lines(options
->OldLogOptions
);
2015 options
->OldLogOptions
= NULL
;
2021 * Given a linked list of config lines containing "allow" and "deny" tokens,
2022 * parse them and append the result to <b>dest</b>. Return -1 if any tokens
2023 * are malformed, else return 0.
2026 config_parse_addr_policy(struct config_line_t
*cfg
,
2027 addr_policy_t
**dest
)
2029 addr_policy_t
**nextp
;
2030 smartlist_t
*entries
;
2039 nextp
= &((*nextp
)->next
);
2041 entries
= smartlist_create();
2042 for (; cfg
; cfg
= cfg
->next
) {
2043 smartlist_split_string(entries
, cfg
->value
, ",", SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2044 SMARTLIST_FOREACH(entries
, const char *, ent
,
2046 log_fn(LOG_DEBUG
,"Adding new entry '%s'",ent
);
2047 *nextp
= router_parse_addr_policy_from_string(ent
);
2049 nextp
= &((*nextp
)->next
);
2051 log_fn(LOG_WARN
,"Malformed policy %s.", ent
);
2055 SMARTLIST_FOREACH(entries
, char *, ent
, tor_free(ent
));
2056 smartlist_clear(entries
);
2058 smartlist_free(entries
);
2062 /** Release all storage held by <b>p</b> */
2064 addr_policy_free(addr_policy_t
*p
) {
2070 tor_free(e
->string
);
2075 /** Parse a single RedirectExit line's contents from <b>line</b>. If
2076 * they are valid, and <b>result</b> is not NULL, add an element to
2077 * <b>result</b> and return 0. Else if they are valid, return 0.
2078 * Else return -1. */
2080 parse_redirect_line(smartlist_t
*result
, struct config_line_t
*line
)
2082 smartlist_t
*elements
= NULL
;
2087 r
= tor_malloc_zero(sizeof(exit_redirect_t
));
2088 elements
= smartlist_create();
2089 smartlist_split_string(elements
, line
->value
, NULL
,
2090 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2091 if (smartlist_len(elements
) != 2) {
2092 log_fn(LOG_WARN
, "Wrong number of elements in RedirectExit line");
2095 if (parse_addr_and_port_range(smartlist_get(elements
,0),&r
->addr
,&r
->mask
,
2096 &r
->port_min
,&r
->port_max
)) {
2097 log_fn(LOG_WARN
, "Error parsing source address in RedirectExit line");
2100 if (0==strcasecmp(smartlist_get(elements
,1), "pass")) {
2103 if (parse_addr_port(smartlist_get(elements
,1),NULL
,&r
->addr_dest
,
2105 log_fn(LOG_WARN
, "Error parsing dest address in RedirectExit line");
2115 SMARTLIST_FOREACH(elements
, char *, cp
, tor_free(cp
));
2116 smartlist_free(elements
);
2119 smartlist_add(result
, r
);
2128 /** Read the contents of a DirServer line from <b>line</b>. Return 0
2129 * if the line is well-formed, and 0 if it isn't. If
2130 * <b>validate_only</b> is 0, and the line is well-formed, then add
2131 * the dirserver described in the line as a valid server. */
2133 parse_dir_server_line(const char *line
, int validate_only
)
2135 smartlist_t
*items
= NULL
;
2137 char *addrport
, *address
=NULL
;
2139 char digest
[DIGEST_LEN
];
2141 items
= smartlist_create();
2142 smartlist_split_string(items
, line
, NULL
,
2143 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
2144 if (smartlist_len(items
) < 2) {
2145 log_fn(LOG_WARN
, "Too few arguments to DirServer line.");
2148 addrport
= smartlist_get(items
, 0);
2149 if (parse_addr_port(addrport
, &address
, NULL
, &port
)<0) {
2150 log_fn(LOG_WARN
, "Error parsing DirServer address '%s'", addrport
);
2154 log_fn(LOG_WARN
, "Missing port in DirServer address '%s'",addrport
);
2158 tor_strstrip(smartlist_get(items
, 1), " ");
2159 if (strlen(smartlist_get(items
, 1)) != HEX_DIGEST_LEN
) {
2160 log_fn(LOG_WARN
, "Key digest for DirServer is wrong length.");
2163 if (base16_decode(digest
, DIGEST_LEN
,
2164 smartlist_get(items
,1), HEX_DIGEST_LEN
)<0) {
2165 log_fn(LOG_WARN
, "Unable to decode DirServer key digest.");
2169 if (!validate_only
) {
2170 log_fn(LOG_DEBUG
, "Trusted dirserver at %s:%d (%s)", address
, (int)port
,
2171 (char*)smartlist_get(items
,1));
2172 add_trusted_dir_server(address
, port
, digest
);
2182 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
2183 smartlist_free(items
);
2188 /** Adjust the value of options->DataDirectory, or fill it in if it's
2189 * absent. Return 0 on success, -1 on failure. */
2191 normalize_data_directory(or_options_t
*options
) {
2194 if (options
->DataDirectory
)
2195 return 0; /* all set */
2196 p
= tor_malloc(MAX_PATH
);
2197 strlcpy(p
,get_windows_conf_root(),MAX_PATH
);
2198 options
->DataDirectory
= p
;
2201 const char *d
= options
->DataDirectory
;
2205 if (strncmp(d
,"~/",2) == 0) {
2206 char *fn
= expand_filename(d
);
2208 log_fn(LOG_ERR
,"Failed to expand filename '%s'.", d
);
2211 if (!options
->DataDirectory
&& !strcmp(fn
,"/.tor")) {
2212 /* If our homedir is /, we probably don't want to use it. */
2213 /* XXXX Default to /var/lib/tor? */
2214 log_fn(LOG_WARN
, "Defaulting to 'DataDirectory %s', which may not be what you want", fn
);
2216 tor_free(options
->DataDirectory
);
2217 options
->DataDirectory
= fn
;
2223 /** Check and normalize the value of options->DataDirectory; return 0 if it
2224 * sane, -1 otherwise. */
2226 validate_data_directory(or_options_t
*options
) {
2227 if (normalize_data_directory(options
) < 0)
2229 tor_assert(options
->DataDirectory
);
2230 if (strlen(options
->DataDirectory
) > (512-128)) {
2231 log_fn(LOG_ERR
, "DataDirectory is too long.");
2235 if (check_private_dir(options
->DataDirectory
, CPD_CHECK
!= 0)) {
2236 log_fn(LOG_WARN
, "Can't create directory %s", options
->DataDirectory
);
2243 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; if you edit it, comments will not be preserved"
2245 /** Save a configuration file for the configuration in <b>options</b>
2246 * into the file <b>fname</b>. If the file already exists, and
2247 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
2248 * replace it. Return 0 on success, -1 on failure. */
2250 write_configuration_file(const char *fname
, or_options_t
*options
)
2253 char *old_val
=NULL
, *new_val
=NULL
, *new_conf
=NULL
;
2254 int rename_old
= 0, r
;
2258 switch (file_status(fname
)) {
2260 old_val
= read_file_to_str(fname
, 0);
2261 if (strcmpstart(old_val
, GENERATED_FILE_PREFIX
)) {
2269 log_fn(LOG_WARN
,"Config file %s is not a file? Failing.", fname
);
2274 if (!(new_conf
= config_dump_options(options
, 1))) {
2275 log_fn(LOG_WARN
, "Couldn't get configuration string");
2279 len
= strlen(new_conf
)+128;
2280 new_val
= tor_malloc(len
);
2281 tor_snprintf(new_val
, len
, "%s\n\n%s", GENERATED_FILE_PREFIX
, new_conf
);
2286 if (tor_snprintf(fn_tmp
, sizeof(fn_tmp
), "%s.orig.%d", fname
, i
)<0) {
2287 log_fn(LOG_WARN
, "Filename too long");
2290 if (file_status(fn_tmp
) == FN_NOENT
)
2294 log_fn(LOG_NOTICE
, "Renaming old configuration file to %s", fn_tmp
);
2295 rename(fname
, fn_tmp
);
2298 write_str_to_file(fname
, new_val
, 0);
2311 * Save the current configuration file value to disk. Return 0 on
2312 * success, -1 on failure.
2315 save_current_config(void)
2319 /* XXX This fails if we can't write to our configuration file.
2320 * Arguably, we should try falling back to datadirectory or something.
2321 * But just as arguably, we shouldn't. */
2322 return write_configuration_file(config_fname
, get_options());
2324 fn
= get_default_conf_file();
2325 return write_configuration_file(fn
, get_options());
2328 struct unit_table_t
{
2330 uint64_t multiplier
;
2333 static struct unit_table_t memory_units
[] = {
2339 { "kilobyte", 1<<10 },
2340 { "kilobytes", 1<<10 },
2343 { "megabyte", 1<<20 },
2344 { "megabytes", 1<<20 },
2346 { "gigabyte", 1<<30 },
2347 { "gigabytes", 1<<30 },
2348 { "tb", U64_LITERAL(1)<<40 },
2349 { "terabyte", U64_LITERAL(1)<<40 },
2350 { "terabytes", U64_LITERAL(1)<<40 },
2354 static struct unit_table_t time_units
[] = {
2362 { "day", 24*60*60 },
2363 { "days", 24*60*60 },
2364 { "week", 7*24*60*60 },
2365 { "weeks", 7*24*60*60 },
2369 /** Parse a string <b>val</b> containing a number, zero or more
2370 * spaces, and an optional unit string. If the unit appears in the
2371 * table <b>u</b>, then multiply the number by the unit multiplier.
2372 * On success, set *<b>ok</b> to 1 and return this product.
2373 * Otherwise, set *<b>ok</b> to 0.
2376 config_parse_units(const char *val
, struct unit_table_t
*u
, int *ok
)
2383 v
= tor_parse_uint64(val
, 10, 0, UINT64_MAX
, ok
, &cp
);
2390 while (TOR_ISSPACE(*cp
))
2392 for ( ;u
->unit
;++u
) {
2393 if (!strcasecmp(u
->unit
, cp
)) {
2399 log_fn(LOG_WARN
, "Unknown unit '%s'.", cp
);
2404 /** Parse a string in the format "number unit", where unit is a unit of
2405 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
2406 * and return the number of bytes specified. Otherwise, set
2407 * *<b>ok</b> to false and return 0. */
2409 config_parse_memunit(const char *s
, int *ok
) {
2410 return config_parse_units(s
, memory_units
, ok
);
2413 /** Parse a string in the format "number unit", where unit is a unit of time.
2414 * On success, set *<b>ok</b> to true and return the number of seconds in
2415 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
2418 config_parse_interval(const char *s
, int *ok
) {
2420 r
= config_parse_units(s
, time_units
, ok
);
2424 log_fn(LOG_WARN
, "Interval '%s' is too long", s
);
2432 print_cvs_version(void)
2434 extern const char aes_c_id
[];
2435 extern const char compat_c_id
[];
2436 extern const char container_c_id
[];
2437 extern const char crypto_c_id
[];
2438 extern const char fakepoll_c_id
[];
2439 extern const char log_c_id
[];
2440 extern const char torgzip_c_id
[];
2441 extern const char tortls_c_id
[];
2442 extern const char util_c_id
[];
2444 extern const char buffers_c_id
[];
2445 extern const char circuitbuild_c_id
[];
2446 extern const char circuitlist_c_id
[];
2447 extern const char circuituse_c_id
[];
2448 extern const char command_c_id
[];
2449 // extern const char config_c_id[];
2450 extern const char connection_c_id
[];
2451 extern const char connection_edge_c_id
[];
2452 extern const char connection_or_c_id
[];
2453 extern const char control_c_id
[];
2454 extern const char cpuworker_c_id
[];
2455 extern const char directory_c_id
[];
2456 extern const char dirserv_c_id
[];
2457 extern const char dns_c_id
[];
2458 extern const char hibernate_c_id
[];
2459 extern const char main_c_id
[];
2460 extern const char onion_c_id
[];
2461 extern const char relay_c_id
[];
2462 extern const char rendclient_c_id
[];
2463 extern const char rendcommon_c_id
[];
2464 extern const char rendmid_c_id
[];
2465 extern const char rendservice_c_id
[];
2466 extern const char rephist_c_id
[];
2467 extern const char router_c_id
[];
2468 extern const char routerlist_c_id
[];
2469 extern const char routerparse_c_id
[];
2473 puts(CONTAINER_H_ID
);
2475 puts(FAKEPOLL_H_ID
);
2483 puts(container_c_id
);
2485 puts(fakepoll_c_id
);
2493 puts(circuitbuild_c_id
);
2494 puts(circuitlist_c_id
);
2495 puts(circuituse_c_id
);
2498 puts(connection_c_id
);
2499 puts(connection_edge_c_id
);
2500 puts(connection_or_c_id
);
2502 puts(cpuworker_c_id
);
2503 puts(directory_c_id
);
2506 puts(hibernate_c_id
);
2510 puts(rendclient_c_id
);
2511 puts(rendcommon_c_id
);
2513 puts(rendservice_c_id
);
2516 puts(routerlist_c_id
);
2517 puts(routerparse_c_id
);