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.
19 #include "../common/aes.h"
21 /** Enumeration of types which option values can take */
22 typedef enum config_type_t
{
23 CONFIG_TYPE_STRING
= 0, /**< An arbitrary string. */
24 CONFIG_TYPE_UINT
, /**< A non-negative integer less than MAX_INT */
25 CONFIG_TYPE_INTERVAL
, /**< A number of seconds, with optional units*/
26 CONFIG_TYPE_MEMUNIT
, /**< A number of bytes, with optional units*/
27 CONFIG_TYPE_DOUBLE
, /**< A floating-point value */
28 CONFIG_TYPE_BOOL
, /**< A boolean value, expressed as 0 or 1. */
29 CONFIG_TYPE_CSV
, /**< A list of strings, separated by commas and optional
31 CONFIG_TYPE_LINELIST
, /**< Uninterpreted config lines */
32 CONFIG_TYPE_LINELIST_S
, /**< Uninterpreted, context-sensitive config lines,
33 * mixed with other keywords. */
34 CONFIG_TYPE_LINELIST_V
, /**< Catch-all "virtual" option to summarize
35 * context-sensitive config lines when fetching.
37 CONFIG_TYPE_OBSOLETE
, /**< Obsolete (ignored) option. */
40 /* An abbreviation for a configuration option allowed on the command line */
41 typedef struct config_abbrev_t
{
42 const char *abbreviated
;
47 /* Handy macro for declaring "In the config file or on the command line,
48 * you can abbreviate <b>tok</b>s as <b>tok</b>". */
49 #define PLURAL(tok) { #tok, #tok "s", 0 }
51 /* A list of command-line abbreviations. */
52 static config_abbrev_t config_abbrevs
[] = {
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("DirPort", UINT
, DirPort
, "0"),
108 VAR("DirBindAddress", LINELIST
, DirBindAddress
, NULL
),
109 VAR("DirFetchPeriod", INTERVAL
, DirFetchPeriod
, "1 hours"),
110 VAR("DirPostPeriod", INTERVAL
, DirPostPeriod
, "20 minutes"),
111 VAR("RendPostPeriod", INTERVAL
, RendPostPeriod
, "20 minutes"),
112 VAR("DirPolicy", LINELIST
, DirPolicy
, NULL
),
113 VAR("DirServer", LINELIST
, DirServers
, NULL
),
114 VAR("ExitNodes", STRING
, ExitNodes
, NULL
),
115 VAR("EntryNodes", STRING
, EntryNodes
, NULL
),
116 VAR("StrictExitNodes", BOOL
, StrictExitNodes
, "0"),
117 VAR("StrictEntryNodes", BOOL
, StrictEntryNodes
, "0"),
118 VAR("ExitPolicy", LINELIST
, ExitPolicy
, NULL
),
119 VAR("ExcludeNodes", STRING
, ExcludeNodes
, NULL
),
120 VAR("FascistFirewall", BOOL
, FascistFirewall
, "0"),
121 VAR("FirewallPorts", CSV
, FirewallPorts
, "80,443"),
122 VAR("MyFamily", STRING
, MyFamily
, NULL
),
123 VAR("NodeFamily", LINELIST
, NodeFamilies
, NULL
),
124 VAR("Group", STRING
, Group
, NULL
),
125 VAR("HashedControlPassword",STRING
, HashedControlPassword
, NULL
),
126 VAR("HttpProxy", STRING
, HttpProxy
, NULL
),
127 VAR("HiddenServiceOptions",LINELIST_V
, RendConfigLines
, NULL
),
128 VAR("HiddenServiceDir", LINELIST_S
, RendConfigLines
, NULL
),
129 VAR("HiddenServicePort", LINELIST_S
, RendConfigLines
, NULL
),
130 VAR("HiddenServiceNodes", LINELIST_S
, RendConfigLines
, NULL
),
131 VAR("HiddenServiceExcludeNodes", LINELIST_S
, RendConfigLines
, NULL
),
132 VAR("IgnoreVersion", BOOL
, IgnoreVersion
, "0"),
133 VAR("KeepalivePeriod", INTERVAL
, KeepalivePeriod
, "5 minutes"),
134 VAR("Log", LINELIST
, Logs
, NULL
),
135 VAR("LogLevel", LINELIST_S
, OldLogOptions
, NULL
),
136 VAR("LogFile", LINELIST_S
, OldLogOptions
, NULL
),
137 OBSOLETE("LinkPadding"),
138 VAR("MaxConn", UINT
, MaxConn
, "1024"),
139 VAR("MaxOnionsPending", UINT
, MaxOnionsPending
, "100"),
140 VAR("MonthlyAccountingStart",UINT
, _MonthlyAccountingStart
,"0"),
141 VAR("AccountingMaxKB", UINT
, _AccountingMaxKB
, "0"),
142 VAR("AccountingMax", MEMUNIT
, AccountingMax
, "0 bytes"),
143 VAR("Nickname", STRING
, Nickname
, NULL
),
144 VAR("NewCircuitPeriod", INTERVAL
, NewCircuitPeriod
, "30 seconds"),
145 VAR("NumCpus", UINT
, NumCpus
, "1"),
146 VAR("ORPort", UINT
, ORPort
, "0"),
147 VAR("ORBindAddress", LINELIST
, ORBindAddress
, NULL
),
148 VAR("OutboundBindAddress", STRING
, OutboundBindAddress
, NULL
),
149 VAR("PidFile", STRING
, PidFile
, NULL
),
150 VAR("PathlenCoinWeight", DOUBLE
, PathlenCoinWeight
, "0.3"),
151 VAR("RedirectExit", LINELIST
, RedirectExit
, NULL
),
152 OBSOLETE("RouterFile"),
153 VAR("RunAsDaemon", BOOL
, RunAsDaemon
, "0"),
154 VAR("RunTesting", BOOL
, RunTesting
, "0"),
155 VAR("RecommendedVersions", LINELIST
, RecommendedVersions
, NULL
),
156 VAR("RendNodes", STRING
, RendNodes
, NULL
),
157 VAR("RendExcludeNodes", STRING
, RendExcludeNodes
, NULL
),
158 VAR("SocksPort", UINT
, SocksPort
, "9050"),
159 VAR("SocksBindAddress", LINELIST
, SocksBindAddress
, NULL
),
160 VAR("SocksPolicy", LINELIST
, SocksPolicy
, NULL
),
161 VAR("StatusFetchPeriod", INTERVAL
, StatusFetchPeriod
, "20 minutes"),
162 VAR("SysLog", LINELIST_S
, OldLogOptions
, NULL
),
163 OBSOLETE("TrafficShaping"),
164 VAR("User", STRING
, User
, NULL
),
165 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
170 /** Largest allowed config line */
171 #define CONFIG_LINE_T_MAXLEN 4096
173 static void option_reset(or_options_t
*options
, config_var_t
*var
);
174 static void options_free(or_options_t
*options
);
175 static int option_is_same(or_options_t
*o1
, or_options_t
*o2
,const char *name
);
176 static or_options_t
*options_dup(or_options_t
*old
);
177 static int options_validate(or_options_t
*options
);
178 static int options_transition_allowed(or_options_t
*old
, or_options_t
*new);
179 static int check_nickname_list(const char *lst
, const char *name
);
181 static int parse_dir_server_line(const char *line
, int validate_only
);
182 static int parse_redirect_line(smartlist_t
*result
,
183 struct config_line_t
*line
);
184 static int parse_log_severity_range(const char *range
, int *min_out
,
186 static int convert_log_option(or_options_t
*options
,
187 struct config_line_t
*level_opt
,
188 struct config_line_t
*file_opt
, int isDaemon
);
189 static int add_single_log_option(or_options_t
*options
, int minSeverity
,
191 const char *type
, const char *fname
);
192 static int normalize_log_options(or_options_t
*options
);
193 static int validate_data_directory(or_options_t
*options
);
194 static int write_configuration_file(const char *fname
, or_options_t
*options
);
196 static uint64_t config_parse_memunit(const char *s
, int *ok
);
197 static int config_parse_interval(const char *s
, int *ok
);
198 static void print_cvs_version(void);
201 * Functions to read and write the global options pointer.
204 /** Command-line and config-file options. */
205 static or_options_t
*global_options
=NULL
;
206 /** Name of most recently read torrc file. */
207 static char *config_fname
= NULL
;
209 /** Return the currently configured options. */
212 tor_assert(global_options
);
213 return global_options
;
216 /** Change the current global options to contain <b>new_val</b> instead
217 * of their current value; free the old value as necessary. Where
218 * <b>new_val</b> is different from the old value, update the process to
219 * use the new value instead.
221 * Note 1: <b>new_val</b> must have previously been validated with
222 * options_validate(), or Tor may freak out and exit.
224 * Note 2: We haven't moved all the "act on new configuration" logic
225 * here yet. Some is still in do_hup() and other places.
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.
240 struct config_line_t
*cl
;
241 or_options_t
*options
= get_options();
243 clear_trusted_dir_servers();
244 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
) {
245 if (parse_dir_server_line(cl
->value
, 0)<0) {
247 "Previously validated DirServer line could not be added!");
252 if (rend_config_services(options
, 0)<0) {
254 "Previously validated hidden services line could not be added!");
258 /* Setuid/setgid as appropriate */
259 if (options
->User
|| options
->Group
) {
260 if (switch_id(options
->User
, options
->Group
) != 0) {
265 /* Ensure data directory is private; create if possible. */
266 if (check_private_dir(options
->DataDirectory
, CPD_CREATE
) != 0) {
267 log_fn(LOG_ERR
, "Couldn't access/create private data directory %s",
268 options
->DataDirectory
);
272 /* Bail out at this point if we're not going to be a server: we want
273 * to not fork, and to log stuff to stderr. */
274 if (options
->command
!= CMD_RUN_TOR
)
277 mark_logs_temp(); /* Close current logs once new logs are open. */
278 if (config_init_logs(options
, 0)<0) /* Configure the log(s) */
280 /* Close the temporary log we used while starting up, if it isn't already
283 add_callback_log(LOG_NOTICE
, LOG_ERR
, control_event_logmsg
);
285 if (set_max_file_descriptors(options
->MaxConn
) < 0)
289 smartlist_t
*sl
= smartlist_create();
290 for (cl
= options
->RedirectExit
; cl
; cl
= cl
->next
) {
291 if (parse_redirect_line(sl
, cl
)<0)
294 set_exit_redirects(sl
);
297 /* Start backgrounding the process, if requested. */
299 /* XXXX009 We once had a reason to separate start_daemon and finish_daemon:
300 * It let us have the parent process stick around until we were sure Tor
301 * was started. Should we make start_daemon get called earlier? -NM */
302 if (options
->RunAsDaemon
) {
303 start_daemon(options
->DataDirectory
);
306 /* Finish backgrounding the process */
307 if (options
->RunAsDaemon
) {
308 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
312 /* Write our pid to the pid file. If we do not have write permissions we
313 * will log a warning */
314 if (options
->PidFile
)
315 write_pidfile(options
->PidFile
);
317 /* Update address policies. */
318 parse_socks_policy();
321 init_cookie_authentication(options
->CookieAuthentication
);
323 /* reload keys as needed for rendezvous services. */
324 if (rend_service_load_keys()<0) {
325 log_fn(LOG_ERR
,"Error reloading rendezvous service keys");
329 /* Set up accounting */
330 if (accounting_parse_options(options
, 0)<0) {
331 log_fn(LOG_ERR
,"Error in accouting options");
334 if (accounting_is_enabled(options
))
335 configure_accounting(time(NULL
));
337 if (retry_all_listeners(1) < 0) {
338 log_fn(LOG_ERR
,"Failed to bind one of the listener ports.");
345 smin
= config_dump_options(options
, 1);
346 smax
= config_dump_options(options
, 0);
347 log_fn(LOG_DEBUG
, "These are our options:\n%s",smax
);
348 log_fn(LOG_DEBUG
, "We changed these options:\n%s",smin
);
354 /* Since our options changed, we might need to regenerate and upload our
355 * server descriptor. (We could probably be more clever about only calling
356 * this when something significant changed.)
358 mark_my_descriptor_dirty();
364 * Functions to parse config options
367 /** If <b>option</b> is an official abbreviation for a longer option,
368 * return the longer option. Otherwise return <b>option</b>.
369 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
370 * apply abbreviations that work for the config file and the command line. */
372 expand_abbrev(const char *option
, int command_line
)
375 for (i
=0; config_abbrevs
[i
].abbreviated
; ++i
) {
376 /* Abbreviations aren't casei. */
377 if (!strcasecmp(option
,config_abbrevs
[i
].abbreviated
) &&
378 (command_line
|| !config_abbrevs
[i
].commandline_only
)) {
379 return config_abbrevs
[i
].full
;
385 /** Helper: Read a list of configuration options from the command line. */
386 static struct config_line_t
*
387 config_get_commandlines(int argc
, char **argv
)
389 struct config_line_t
*new;
390 struct config_line_t
*front
= NULL
;
395 if (!strcmp(argv
[i
],"-f") ||
396 !strcmp(argv
[i
],"--hash-password")) {
397 i
+= 2; /* command-line option with argument. ignore them. */
399 } else if (!strcmp(argv
[i
],"--list-fingerprint")) {
400 i
+= 1; /* command-line option. ignore it. */
404 new = tor_malloc(sizeof(struct config_line_t
));
410 new->key
= tor_strdup(expand_abbrev(s
, 1));
411 new->value
= tor_strdup(argv
[i
+1]);
413 log(LOG_DEBUG
,"Commandline: parsed keyword '%s', value '%s'",
414 new->key
, new->value
);
422 /** Helper: allocate a new configuration option mapping 'key' to 'val',
423 * prepend it to 'front', and return the newly allocated config_line_t */
424 struct config_line_t
*
425 config_line_prepend(struct config_line_t
*front
,
429 struct config_line_t
*newline
;
431 newline
= tor_malloc(sizeof(struct config_line_t
));
432 newline
->key
= tor_strdup(key
);
433 newline
->value
= tor_strdup(val
);
434 newline
->next
= front
;
438 /** Helper: parse the config string and strdup into key/value
439 * strings. Set *result to the list, or NULL if parsing the string
440 * failed. Return 0 on success, -1 on failure. Warn and ignore any
441 * misformatted lines. */
443 config_get_lines(char *string
, struct config_line_t
**result
)
445 struct config_line_t
*list
= NULL
;
449 string
= parse_line_from_str(string
, &k
, &v
);
451 config_free_lines(list
);
455 list
= config_line_prepend(list
, k
, v
);
463 * Free all the configuration lines on the linked list <b>front</b>.
466 config_free_lines(struct config_line_t
*front
)
468 struct config_line_t
*tmp
;
475 tor_free(tmp
->value
);
480 /** If <b>key</b> is a configuration option, return the corresponding
481 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
482 * warn, and return the corresponding config_var_t. Otherwise return NULL.
484 static config_var_t
*config_find_option(const char *key
)
487 /* First, check for an exact (case-insensitive) match */
488 for (i
=0; config_vars
[i
].name
; ++i
) {
489 if (!strcasecmp(key
, config_vars
[i
].name
))
490 return &config_vars
[i
];
492 /* If none, check for an abbreviated match */
493 for (i
=0; config_vars
[i
].name
; ++i
) {
494 if (!strncasecmp(key
, config_vars
[i
].name
, strlen(key
))) {
495 log_fn(LOG_WARN
, "The abbreviation '%s' is deprecated. "
496 "Tell Nick and Roger to make it official, or just use '%s' instead",
497 key
, config_vars
[i
].name
);
498 return &config_vars
[i
];
501 /* Okay, unrecogized options */
505 /** If <b>c</b> is a syntactically valid configuration line, update
506 * <b>options</b> with its value and return 0. Otherwise return -1 for bad key,
509 * If 'reset' is set, and we get a line containing no value, restore the
510 * option to its default value.
513 config_assign_line(or_options_t
*options
, struct config_line_t
*c
, int reset
)
519 var
= config_find_option(c
->key
);
521 log_fn(LOG_WARN
, "Unknown option '%s'. Failing.", c
->key
);
524 /* Put keyword into canonical case. */
525 if (strcmp(var
->name
, c
->key
)) {
527 c
->key
= tor_strdup(var
->name
);
530 if (reset
&& !strlen(c
->value
)) {
531 option_reset(options
, var
);
535 lvalue
= ((char*)options
) + var
->var_offset
;
538 case CONFIG_TYPE_UINT
:
539 i
= tor_parse_long(c
->value
, 10, 0, INT_MAX
, &ok
, NULL
);
541 log(LOG_WARN
, "Int keyword '%s %s' is malformed or out of bounds.",
548 case CONFIG_TYPE_INTERVAL
: {
549 i
= config_parse_interval(c
->value
, &ok
);
557 case CONFIG_TYPE_MEMUNIT
: {
558 uint64_t u64
= config_parse_memunit(c
->value
, &ok
);
562 *(uint64_t *)lvalue
= u64
;
566 case CONFIG_TYPE_BOOL
:
567 i
= tor_parse_long(c
->value
, 10, 0, 1, &ok
, NULL
);
569 log(LOG_WARN
, "Boolean keyword '%s' expects 0 or 1.", c
->key
);
575 case CONFIG_TYPE_STRING
:
576 tor_free(*(char **)lvalue
);
577 *(char **)lvalue
= tor_strdup(c
->value
);
580 case CONFIG_TYPE_DOUBLE
:
581 *(double *)lvalue
= atof(c
->value
);
584 case CONFIG_TYPE_CSV
:
585 if (*(smartlist_t
**)lvalue
== NULL
)
586 *(smartlist_t
**)lvalue
= smartlist_create();
588 smartlist_split_string(*(smartlist_t
**)lvalue
, c
->value
, ",",
589 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
592 case CONFIG_TYPE_LINELIST
:
593 case CONFIG_TYPE_LINELIST_S
:
594 /* Note: this reverses the order that the lines appear in. That's
595 * just fine, since we build up the list of lines reversed in the
597 *(struct config_line_t
**)lvalue
=
598 config_line_prepend(*(struct config_line_t
**)lvalue
, c
->key
, c
->value
);
601 case CONFIG_TYPE_OBSOLETE
:
602 log_fn(LOG_WARN
, "Skipping obsolete configuration option '%s'", c
->key
);
604 case CONFIG_TYPE_LINELIST_V
:
605 log_fn(LOG_WARN
, "Can't provide value for virtual option '%s'", c
->key
);
614 /** restore the option named <b>key</b> in options to its default value. */
616 config_reset_line(or_options_t
*options
, const char *key
)
620 var
= config_find_option(key
);
622 return; /* give error on next pass. */
624 option_reset(options
, var
);
627 /** Return true iff key is a valid configuration option. */
629 config_option_is_recognized(const char *key
)
631 config_var_t
*var
= config_find_option(key
);
632 return (var
!= NULL
);
635 /** Return a canonicalized list of the options assigned for key.
637 struct config_line_t
*
638 config_get_assigned_option(or_options_t
*options
, const char *key
)
643 struct config_line_t
*result
;
644 tor_assert(options
&& key
);
646 var
= config_find_option(key
);
648 log_fn(LOG_WARN
, "Unknown option '%s'. Failing.", key
);
650 } else if (var
->type
== CONFIG_TYPE_LINELIST_S
) {
651 log_fn(LOG_WARN
, "Can't return context-sensitive '%s' on its own", key
);
654 value
= ((char*)options
) + var
->var_offset
;
656 if (var
->type
== CONFIG_TYPE_LINELIST
||
657 var
->type
== CONFIG_TYPE_LINELIST_V
) {
658 /* Linelist requires special handling: we just copy and return it. */
659 const struct config_line_t
*next_in
= *(const struct config_line_t
**)value
;
660 struct config_line_t
**next_out
= &result
;
662 *next_out
= tor_malloc(sizeof(struct config_line_t
));
663 (*next_out
)->key
= tor_strdup(next_in
->key
);
664 (*next_out
)->value
= tor_strdup(next_in
->value
);
665 next_in
= next_in
->next
;
666 next_out
= &((*next_out
)->next
);
672 result
= tor_malloc_zero(sizeof(struct config_line_t
));
673 result
->key
= tor_strdup(var
->name
);
676 case CONFIG_TYPE_STRING
:
677 if (*(char**)value
) {
678 result
->value
= tor_strdup(*(char**)value
);
680 tor_free(result
->key
);
685 case CONFIG_TYPE_INTERVAL
:
686 case CONFIG_TYPE_UINT
:
687 /* This means every or_options_t uint or bool element
688 * needs to be an int. Not, say, a uint16_t or char. */
689 tor_snprintf(buf
, sizeof(buf
), "%d", *(int*)value
);
690 result
->value
= tor_strdup(buf
);
692 case CONFIG_TYPE_MEMUNIT
:
693 tor_snprintf(buf
, sizeof(buf
), U64_FORMAT
,
694 U64_PRINTF_ARG(*(uint64_t*)value
));
695 result
->value
= tor_strdup(buf
);
697 case CONFIG_TYPE_DOUBLE
:
698 tor_snprintf(buf
, sizeof(buf
), "%f", *(double*)value
);
699 result
->value
= tor_strdup(buf
);
701 case CONFIG_TYPE_BOOL
:
702 result
->value
= tor_strdup(*(int*)value
? "1" : "0");
704 case CONFIG_TYPE_CSV
:
705 if (*(smartlist_t
**)value
)
706 result
->value
= smartlist_join_strings(*(smartlist_t
**)value
,",",0,NULL
);
708 result
->value
= tor_strdup("");
710 case CONFIG_TYPE_OBSOLETE
:
711 log_fn(LOG_WARN
,"You asked me for the value of an obsolete config option %s.", key
);
712 tor_free(result
->key
);
716 tor_free(result
->key
);
718 log_fn(LOG_WARN
,"Bug: unknown type %d for known key %s", var
->type
, key
);
725 /** Iterate through the linked list of requested options <b>list</b>.
726 * For each item, convert as appropriate and assign to <b>options</b>.
727 * If an item is unrecognized, return -1 immediately,
728 * else return 0 for success.
730 * If <b>reset</b>, then interpret empty lines as meaning "restore to
731 * default value", and interpret LINELIST* options as replacing (not
732 * extending) their previous values. Return 0 on success, -1 on bad key,
736 config_assign(or_options_t
*options
, struct config_line_t
*list
, int reset
)
738 struct config_line_t
*p
;
741 /* pass 1: normalize keys */
742 for (p
= list
; p
; p
= p
->next
) {
743 const char *full
= expand_abbrev(p
->key
, 0);
744 if (strcmp(full
,p
->key
)) {
746 p
->key
= tor_strdup(full
);
750 /* pass 2: if we're reading from a resetting source, clear all mentioned
753 for (p
= list
; p
; p
= p
->next
)
754 config_reset_line(options
, p
->key
);
757 /* pass 3: assign. */
760 if ((r
=config_assign_line(options
, list
, reset
)))
767 /** Try assigning <b>list</b> to the global options. You do this by duping
768 * options, assigning list to the new one, then validating it. If it's
769 * ok, then throw out the old one and stick with the new one. Else,
770 * revert to old and return failure. Return 0 on success, -1 on bad
771 * keys, -2 on bad values, -3 on bad transition.
774 config_trial_assign(struct config_line_t
*list
, int reset
)
777 or_options_t
*trial_options
= options_dup(get_options());
779 if ((r
=config_assign(trial_options
, list
, reset
)) < 0) {
780 options_free(trial_options
);
784 if (options_validate(trial_options
) < 0) {
785 options_free(trial_options
);
789 if (options_transition_allowed(get_options(), trial_options
) < 0) {
790 options_free(trial_options
);
794 set_options(trial_options
); /* we liked it. put it in place. */
798 /** Replace the option indexed by <b>var</b> in <b>options</b> with its
801 option_reset(or_options_t
*options
, config_var_t
*var
)
803 struct config_line_t
*c
;
806 lvalue
= ((char*)options
) + var
->var_offset
;
808 case CONFIG_TYPE_STRING
:
809 tor_free(*(char**)lvalue
);
811 case CONFIG_TYPE_DOUBLE
:
812 *(double*)lvalue
= 0.0;
814 case CONFIG_TYPE_INTERVAL
:
815 case CONFIG_TYPE_UINT
:
816 case CONFIG_TYPE_BOOL
:
819 case CONFIG_TYPE_MEMUNIT
:
820 *(uint64_t*)lvalue
= 0;
822 case CONFIG_TYPE_CSV
:
823 if (*(smartlist_t
**)lvalue
) {
824 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
825 smartlist_free(*(smartlist_t
**)lvalue
);
826 *(smartlist_t
**)lvalue
= NULL
;
829 case CONFIG_TYPE_LINELIST
:
830 case CONFIG_TYPE_LINELIST_S
:
831 config_free_lines(*(struct config_line_t
**)lvalue
);
832 *(struct config_line_t
**)lvalue
= NULL
;
834 case CONFIG_TYPE_LINELIST_V
:
835 /* handled by linelist_s. */
837 case CONFIG_TYPE_OBSOLETE
:
840 if (var
->initvalue
) {
841 c
= tor_malloc_zero(sizeof(struct config_line_t
));
842 c
->key
= tor_strdup(var
->name
);
843 c
->value
= tor_strdup(var
->initvalue
);
844 config_assign_line(options
,c
,0);
845 config_free_lines(c
);
849 /** Set <b>options</b>->DirServers to contain the default directory
852 add_default_trusted_dirservers(or_options_t
*options
)
855 options
->DirServers
= config_line_prepend(options
->DirServers
, "DirServer",
856 "18.244.0.188:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441");
858 options
->DirServers
= config_line_prepend(options
->DirServers
, "DirServer",
859 "18.244.0.114:80 719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF");
861 options
->DirServers
= config_line_prepend(options
->DirServers
, "DirServer",
862 "62.116.124.106:9030 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D");
865 /** Print a usage message for tor. */
870 "Copyright 2001-2004 Roger Dingledine, Nick Mathewson, Matej Pfajfar.\n\n"
871 "tor -f <torrc> [args]\n"
872 "See man page for options, or http://freehaven.net/tor/ for documentation.\n");
876 * Based on <b>address</b>, guess our public IP address and put it
880 resolve_my_address(const char *address
, uint32_t *addr
)
883 struct hostent
*rent
;
890 strlcpy(hostname
, address
, sizeof(hostname
));
891 } else { /* then we need to guess our address */
892 explicit_ip
= 0; /* it's implicit */
894 if (gethostname(hostname
, sizeof(hostname
)) < 0) {
895 log_fn(LOG_WARN
,"Error obtaining local hostname");
898 log_fn(LOG_DEBUG
,"Guessed local host name as '%s'",hostname
);
901 /* now we know hostname. resolve it and keep only the IP */
903 if (tor_inet_aton(hostname
, &in
) == 0) {
904 /* then we have to resolve it */
906 rent
= (struct hostent
*)gethostbyname(hostname
);
908 log_fn(LOG_WARN
,"Could not resolve local Address %s. Failing.", hostname
);
911 tor_assert(rent
->h_length
== 4);
912 memcpy(&in
.s_addr
, rent
->h_addr
, rent
->h_length
);
915 if (!explicit_ip
&& is_internal_IP(htonl(in
.s_addr
))) {
916 log_fn(LOG_WARN
,"Address '%s' resolves to private IP '%s'. "
917 "Please set the Address config option to be the IP you want to use.",
918 hostname
, inet_ntoa(in
));
922 log_fn(LOG_DEBUG
, "Resolved Address to %s.", inet_ntoa(in
));
923 *addr
= ntohl(in
.s_addr
);
927 /** Called when we don't have a nickname set. Try to guess a good
928 * nickname based on the hostname, and return it. */
930 get_default_nickname(void)
932 char localhostname
[256];
933 char *cp
, *out
, *outp
;
935 if (gethostname(localhostname
, sizeof(localhostname
)) < 0) {
936 log_fn(LOG_WARN
,"Error obtaining local hostname");
940 /* Put it in lowercase; stop at the first dot. */
941 for (cp
= localhostname
; *cp
; ++cp
) {
949 /* Strip invalid characters. */
951 out
= outp
= tor_malloc(strlen(localhostname
) + 1);
953 if (strchr(LEGAL_NICKNAME_CHARACTERS
, *cp
))
960 /* Enforce length. */
961 if (strlen(out
) > MAX_NICKNAME_LEN
)
962 out
[MAX_NICKNAME_LEN
]='\0';
967 /** Release storage held by <b>options</b> */
969 options_free(or_options_t
*options
)
974 for (i
=0; config_vars
[i
].name
; ++i
) {
975 lvalue
= ((char*)options
) + config_vars
[i
].var_offset
;
976 switch (config_vars
[i
].type
) {
977 case CONFIG_TYPE_MEMUNIT
:
978 case CONFIG_TYPE_INTERVAL
:
979 case CONFIG_TYPE_UINT
:
980 case CONFIG_TYPE_BOOL
:
981 case CONFIG_TYPE_DOUBLE
:
982 case CONFIG_TYPE_OBSOLETE
:
983 break; /* nothing to free for these config types */
984 case CONFIG_TYPE_STRING
:
985 tor_free(*(char **)lvalue
);
987 case CONFIG_TYPE_LINELIST
:
988 case CONFIG_TYPE_LINELIST_V
:
989 config_free_lines(*(struct config_line_t
**)lvalue
);
990 *(struct config_line_t
**)lvalue
= NULL
;
992 case CONFIG_TYPE_CSV
:
993 if (*(smartlist_t
**)lvalue
) {
994 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
995 smartlist_free(*(smartlist_t
**)lvalue
);
996 *(smartlist_t
**)lvalue
= NULL
;
999 case CONFIG_TYPE_LINELIST_S
:
1000 /* will be freed by corresponding LINELIST_V. */
1006 /** Return true iff the option <b>var</b> has the same value in <b>o1</b>
1007 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
1010 option_is_same(or_options_t
*o1
, or_options_t
*o2
, const char *name
)
1012 struct config_line_t
*c1
, *c2
;
1014 c1
= config_get_assigned_option(o1
, name
);
1015 c2
= config_get_assigned_option(o2
, name
);
1017 if (strcasecmp(c1
->key
, c2
->key
) ||
1018 strcmp(c1
->value
, c2
->value
)) {
1025 if (r
&& (c1
|| c2
)) {
1028 config_free_lines(c1
);
1029 config_free_lines(c2
);
1033 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
1034 static or_options_t
*
1035 options_dup(or_options_t
*old
)
1037 or_options_t
*newopts
;
1039 struct config_line_t
*line
;
1041 newopts
= tor_malloc_zero(sizeof(or_options_t
));
1042 for (i
=0; config_vars
[i
].name
; ++i
) {
1043 if (config_vars
[i
].type
== CONFIG_TYPE_LINELIST_S
)
1045 if (config_vars
[i
].type
== CONFIG_TYPE_OBSOLETE
)
1047 line
= config_get_assigned_option(old
, config_vars
[i
].name
);
1049 if (config_assign(newopts
, line
, 0) < 0) {
1050 log_fn(LOG_WARN
,"Bug: config_get_assigned_option() generated "
1051 "something we couldn't config_assign().");
1055 config_free_lines(line
);
1060 /** Set <b>options</b> to hold reasonable defaults for most options.
1061 * Each option defaults to zero. */
1063 options_init(or_options_t
*options
)
1068 for (i
=0; config_vars
[i
].name
; ++i
) {
1069 var
= &config_vars
[i
];
1070 if (!var
->initvalue
)
1071 continue; /* defaults to NULL or 0 */
1072 option_reset(options
, var
);
1076 /** Return a string containing a possible configuration file that would give
1077 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
1078 * include options that are the same as Tor's defaults.
1081 config_dump_options(or_options_t
*options
, int minimal
)
1083 smartlist_t
*elements
;
1084 or_options_t
*defaults
;
1085 struct config_line_t
*line
;
1089 defaults
= tor_malloc_zero(sizeof(or_options_t
));
1090 options_init(defaults
);
1091 options_validate(defaults
); /* ??? will this work? */
1093 elements
= smartlist_create();
1094 for (i
=0; config_vars
[i
].name
; ++i
) {
1095 if (config_vars
[i
].type
== CONFIG_TYPE_OBSOLETE
||
1096 config_vars
[i
].type
== CONFIG_TYPE_LINELIST_S
)
1098 if (minimal
&& option_is_same(options
, defaults
, config_vars
[i
].name
))
1100 line
= config_get_assigned_option(options
, config_vars
[i
].name
);
1101 for (; line
; line
= line
->next
) {
1102 size_t len
= strlen(line
->key
) + strlen(line
->value
) + 3;
1104 tmp
= tor_malloc(len
);
1105 if (tor_snprintf(tmp
, len
, "%s %s\n", line
->key
, line
->value
)<0) {
1106 log_fn(LOG_ERR
, "Internal error writing log option");
1109 smartlist_add(elements
, tmp
);
1111 config_free_lines(line
);
1114 result
= smartlist_join_strings(elements
, "", 0, NULL
);
1115 SMARTLIST_FOREACH(elements
, char *, cp
, tor_free(cp
));
1116 smartlist_free(elements
);
1120 /** Return 0 if every setting in <b>options</b> is reasonable. Else
1121 * warn and return -1. Should have no side effects, except for
1122 * normalizing the contents of <b>options</b>. */
1124 options_validate(or_options_t
*options
)
1128 struct config_line_t
*cl
;
1129 struct addr_policy_t
*addr_policy
=NULL
;
1131 if (options
->ORPort
< 0 || options
->ORPort
> 65535) {
1132 log(LOG_WARN
, "ORPort option out of bounds.");
1136 if (validate_data_directory(options
)<0) {
1137 log(LOG_WARN
, "Invalid DataDirectory");
1141 if (options
->Nickname
== NULL
) {
1142 if (server_mode(options
)) {
1143 if (!(options
->Nickname
= get_default_nickname()))
1145 log_fn(LOG_NOTICE
, "Choosing default nickname %s", options
->Nickname
);
1148 if (strspn(options
->Nickname
, LEGAL_NICKNAME_CHARACTERS
) !=
1149 strlen(options
->Nickname
)) {
1150 log_fn(LOG_WARN
, "Nickname '%s' contains illegal characters.", options
->Nickname
);
1153 if (strlen(options
->Nickname
) == 0) {
1154 log_fn(LOG_WARN
, "Nickname must have at least one character");
1157 if (strlen(options
->Nickname
) > MAX_NICKNAME_LEN
) {
1158 log_fn(LOG_WARN
, "Nickname '%s' has more than %d characters.",
1159 options
->Nickname
, MAX_NICKNAME_LEN
);
1164 if (normalize_log_options(options
))
1167 /* Special case if no options are given. */
1168 if (!options
->Logs
) {
1169 options
->Logs
= config_line_prepend(NULL
, "Log", "notice-err stdout");
1172 if (config_init_logs(options
, 1)<0) /* Validate the log(s) */
1175 if (server_mode(options
)) {
1176 /* confirm that our address isn't broken, so we can complain now */
1178 if (resolve_my_address(options
->Address
, &tmp
) < 0)
1182 if (options
->SocksPort
< 0 || options
->SocksPort
> 65535) {
1183 log(LOG_WARN
, "SocksPort option out of bounds.");
1187 if (options
->SocksPort
== 0 && options
->ORPort
== 0) {
1188 log(LOG_WARN
, "SocksPort and ORPort are both undefined? Quitting.");
1192 if (options
->ControlPort
< 0 || options
->ControlPort
> 65535) {
1193 log(LOG_WARN
, "ControlPort option out of bounds.");
1197 if (options
->DirPort
< 0 || options
->DirPort
> 65535) {
1198 log(LOG_WARN
, "DirPort option out of bounds.");
1202 if (options
->StrictExitNodes
&&
1203 (!options
->ExitNodes
|| !strlen(options
->ExitNodes
))) {
1204 log(LOG_WARN
, "StrictExitNodes set, but no ExitNodes listed.");
1207 if (options
->StrictEntryNodes
&&
1208 (!options
->EntryNodes
|| !strlen(options
->EntryNodes
))) {
1209 log(LOG_WARN
, "StrictEntryNodes set, but no EntryNodes listed.");
1212 if (options
->AuthoritativeDir
&& options
->RecommendedVersions
== NULL
) {
1213 log(LOG_WARN
, "Directory servers must configure RecommendedVersions.");
1217 if (options
->AuthoritativeDir
&& !options
->DirPort
) {
1218 log(LOG_WARN
, "Running as authoritative directory, but no DirPort set.");
1222 if (options
->AuthoritativeDir
&& !options
->ORPort
) {
1223 log(LOG_WARN
, "Running as authoritative directory, but no ORPort set.");
1227 if (options
->AuthoritativeDir
&& options
->ClientOnly
) {
1228 log(LOG_WARN
, "Running as authoritative directory, but ClientOnly also set.");
1232 if (options
->_AccountingMaxKB
) {
1233 log(LOG_WARN
, "AccountingMaxKB is deprecated. Say 'AccountingMax %d KB' instead.", options
->_AccountingMaxKB
);
1234 options
->AccountingMax
= U64_LITERAL(1024)*options
->_AccountingMaxKB
;
1235 options
->_AccountingMaxKB
= 0;
1238 if (options
->FirewallPorts
) {
1239 SMARTLIST_FOREACH(options
->FirewallPorts
, const char *, cp
,
1242 if (i
< 1 || i
> 65535) {
1243 log(LOG_WARN
, "Port '%s' out of range in FirewallPorts", cp
);
1248 options
->_AllowUnverified
= 0;
1249 if (options
->AllowUnverifiedNodes
) {
1250 SMARTLIST_FOREACH(options
->AllowUnverifiedNodes
, const char *, cp
, {
1251 if (!strcasecmp(cp
, "entry"))
1252 options
->_AllowUnverified
|= ALLOW_UNVERIFIED_ENTRY
;
1253 else if (!strcasecmp(cp
, "exit"))
1254 options
->_AllowUnverified
|= ALLOW_UNVERIFIED_EXIT
;
1255 else if (!strcasecmp(cp
, "middle"))
1256 options
->_AllowUnverified
|= ALLOW_UNVERIFIED_MIDDLE
;
1257 else if (!strcasecmp(cp
, "introduction"))
1258 options
->_AllowUnverified
|= ALLOW_UNVERIFIED_INTRODUCTION
;
1259 else if (!strcasecmp(cp
, "rendezvous"))
1260 options
->_AllowUnverified
|= ALLOW_UNVERIFIED_RENDEZVOUS
;
1262 log(LOG_WARN
, "Unrecognized value '%s' in AllowUnverifiedNodes",
1269 if (options
->SocksPort
>= 1 &&
1270 (options
->PathlenCoinWeight
< 0.0 || options
->PathlenCoinWeight
>= 1.0)) {
1271 log(LOG_WARN
, "PathlenCoinWeight option must be >=0.0 and <1.0.");
1275 if (options
->MaxConn
< 1) {
1276 log(LOG_WARN
, "MaxConn option must be a non-zero positive integer.");
1280 if (options
->MaxConn
>= MAXCONNECTIONS
) {
1281 log(LOG_WARN
, "MaxConn option must be less than %d.", MAXCONNECTIONS
);
1285 #define MIN_DIR_FETCH_PERIOD 600
1286 #define MIN_DIR_POST_PERIOD 300
1287 #define MIN_REND_POST_PERIOD 300
1288 #define MIN_STATUS_FETCH_PERIOD 60
1290 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
1291 #define MAX_CACHE_DIR_FETCH_PERIOD 3600
1292 #define MAX_CACHE_STATUS_FETCH_PERIOD 900
1294 if (options
->DirFetchPeriod
< MIN_DIR_FETCH_PERIOD
) {
1295 log(LOG_WARN
, "DirFetchPeriod option must be at least %d seconds. Clipping.", MIN_DIR_FETCH_PERIOD
);
1296 options
->DirFetchPeriod
= MIN_DIR_FETCH_PERIOD
;
1298 if (options
->StatusFetchPeriod
< MIN_STATUS_FETCH_PERIOD
) {
1299 log(LOG_WARN
, "StatusFetchPeriod option must be at least %d seconds. Clipping.", MIN_STATUS_FETCH_PERIOD
);
1300 options
->StatusFetchPeriod
= MIN_STATUS_FETCH_PERIOD
;
1302 if (options
->DirPostPeriod
< MIN_DIR_POST_PERIOD
) {
1303 log(LOG_WARN
, "DirPostPeriod option must be at least %d seconds. Clipping.",
1304 MIN_DIR_POST_PERIOD
);
1305 options
->DirPostPeriod
= MIN_DIR_POST_PERIOD
;
1307 if (options
->RendPostPeriod
< MIN_REND_POST_PERIOD
) {
1308 log(LOG_WARN
,"RendPostPeriod option must be at least %d seconds. Clipping.",
1309 MIN_REND_POST_PERIOD
);
1310 options
->RendPostPeriod
= MIN_REND_POST_PERIOD
;
1313 if (options
->DirPort
&& ! options
->AuthoritativeDir
) {
1314 if (options
->DirFetchPeriod
> MAX_CACHE_DIR_FETCH_PERIOD
) {
1315 log(LOG_WARN
, "Caching directory servers must have DirFetchPeriod less than %d seconds. Clipping.", MAX_CACHE_DIR_FETCH_PERIOD
);
1316 options
->DirFetchPeriod
= MAX_CACHE_DIR_FETCH_PERIOD
;
1318 if (options
->StatusFetchPeriod
> MAX_CACHE_STATUS_FETCH_PERIOD
) {
1319 log(LOG_WARN
, "Caching directory servers must have StatusFetchPeriod less than %d seconds. Clipping.", MAX_CACHE_STATUS_FETCH_PERIOD
);
1320 options
->StatusFetchPeriod
= MAX_CACHE_STATUS_FETCH_PERIOD
;
1324 if (options
->DirFetchPeriod
> MAX_DIR_PERIOD
) {
1325 log(LOG_WARN
, "DirFetchPeriod is too large; clipping.");
1326 options
->DirFetchPeriod
= MAX_DIR_PERIOD
;
1328 if (options
->DirPostPeriod
> MAX_DIR_PERIOD
) {
1329 log(LOG_WARN
, "DirPostPeriod is too large; clipping.");
1330 options
->DirPostPeriod
= MAX_DIR_PERIOD
;
1332 if (options
->StatusFetchPeriod
> MAX_DIR_PERIOD
) {
1333 log(LOG_WARN
, "StatusFetchPeriod is too large; clipping.");
1334 options
->StatusFetchPeriod
= MAX_DIR_PERIOD
;
1336 if (options
->RendPostPeriod
> MAX_DIR_PERIOD
) {
1337 log(LOG_WARN
, "RendPostPeriod is too large; clipping.");
1338 options
->RendPostPeriod
= MAX_DIR_PERIOD
;
1341 if (options
->KeepalivePeriod
< 1) {
1342 log(LOG_WARN
,"KeepalivePeriod option must be positive.");
1346 if (2*options
->BandwidthRate
>= options
->BandwidthBurst
) {
1347 log(LOG_WARN
,"BandwidthBurst must be more than twice BandwidthRate.");
1350 if (options
->BandwidthRate
> INT_MAX
) {
1351 log(LOG_WARN
,"BandwidthRate must be less than %d",INT_MAX
);
1354 if (options
->BandwidthBurst
> INT_MAX
) {
1355 log(LOG_WARN
,"BandwidthBurst must be less than %d",INT_MAX
);
1359 if (options
->_MonthlyAccountingStart
) {
1360 if (options
->AccountingStart
) {
1361 log(LOG_WARN
,"Can't specify AccountingStart and MonthlyAccountingStart");
1364 options
->AccountingStart
= tor_malloc(32);
1365 if (tor_snprintf(options
->AccountingStart
, 32, "month %d 0:00",
1366 options
->_MonthlyAccountingStart
)<0) {
1367 log_fn(LOG_WARN
,"Error translating MonthlyAccountingStart");
1370 log_fn(LOG_WARN
,"MonthlyAccountingStart is deprecated. Use 'AccountingStart %s' instead.", options
->AccountingStart
);
1375 if (accounting_parse_options(options
, 1)<0) {
1379 if (options
->HttpProxy
) { /* parse it now */
1380 if (parse_addr_port(options
->HttpProxy
, NULL
,
1381 &options
->HttpProxyAddr
, &options
->HttpProxyPort
) < 0) {
1382 log(LOG_WARN
,"HttpProxy failed to parse or resolve. Please fix.");
1385 if (options
->HttpProxyPort
== 0) { /* give it a default */
1386 options
->HttpProxyPort
= 80;
1390 if (options
->HashedControlPassword
) {
1391 char buf
[S2K_SPECIFIER_LEN
+DIGEST_LEN
];
1392 if (base64_decode(buf
,sizeof(buf
),options
->HashedControlPassword
,
1393 strlen(options
->HashedControlPassword
)!=sizeof(buf
))) {
1394 log_fn(LOG_WARN
,"Bad HashedControlPassword: wrong length or bad base64");
1398 if (options
->HashedControlPassword
&& options
->CookieAuthentication
) {
1399 log_fn(LOG_WARN
,"Cannot enable both HashedControlPassword and CookieAuthentication");
1403 if (check_nickname_list(options
->ExitNodes
, "ExitNodes"))
1405 if (check_nickname_list(options
->EntryNodes
, "EntryNodes"))
1407 if (check_nickname_list(options
->ExcludeNodes
, "ExcludeNodes"))
1409 if (check_nickname_list(options
->RendNodes
, "RendNodes"))
1411 if (check_nickname_list(options
->RendNodes
, "RendExcludeNodes"))
1413 if (check_nickname_list(options
->MyFamily
, "MyFamily"))
1415 for (cl
= options
->NodeFamilies
; cl
; cl
= cl
->next
) {
1416 if (check_nickname_list(cl
->value
, "NodeFamily"))
1420 if (config_parse_addr_policy(options
->ExitPolicy
, &addr_policy
)) {
1421 log_fn(LOG_WARN
, "Error in Exit Policy entry.");
1424 if (config_parse_addr_policy(options
->DirPolicy
, &addr_policy
)) {
1425 log_fn(LOG_WARN
, "Error in DirPolicy entry.");
1428 if (config_parse_addr_policy(options
->SocksPolicy
, &addr_policy
)) {
1429 log_fn(LOG_WARN
, "Error in SocksPolicy entry.");
1432 addr_policy_free(addr_policy
);
1434 for (cl
= options
->RedirectExit
; cl
; cl
= cl
->next
) {
1435 if (parse_redirect_line(NULL
, cl
)<0)
1439 if (!options
->DirServers
) {
1440 add_default_trusted_dirservers(options
);
1442 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
) {
1443 if (parse_dir_server_line(cl
->value
, 1)<0)
1448 if (rend_config_services(options
, 1) < 0)
1454 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
1457 opt_streq(const char *s1
, const char *s2
)
1461 else if (s1
&& s2
&& !strcmp(s1
,s2
))
1467 /** Check if any of the previous options have changed but aren't allowed to. */
1469 options_transition_allowed(or_options_t
*old
, or_options_t
*new_val
) {
1474 if (!opt_streq(old
->PidFile
, new_val
->PidFile
)) {
1475 log_fn(LOG_WARN
,"PidFile is not allowed to change. Failing.");
1479 if (old
->RunAsDaemon
&& !new_val
->RunAsDaemon
) {
1480 log_fn(LOG_WARN
,"During reload, change from RunAsDaemon=1 to =0 not allowed. Failing.");
1484 if (old
->ORPort
!= new_val
->ORPort
) {
1485 log_fn(LOG_WARN
,"During reload, changing ORPort is not allowed. Failing.");
1489 if (strcmp(old
->DataDirectory
,new_val
->DataDirectory
)!=0) {
1490 log_fn(LOG_WARN
,"During reload, changing DataDirectory (%s->%s) is not allowed. Failing.", old
->DataDirectory
, new_val
->DataDirectory
);
1494 if (!opt_streq(old
->User
, new_val
->User
)) {
1495 log_fn(LOG_WARN
,"During reload, changing User is not allowed. Failing.");
1499 if (!opt_streq(old
->Group
, new_val
->Group
)) {
1500 log_fn(LOG_WARN
,"During reload, changing User is not allowed. Failing.");
1508 /** Return the directory on windows where we expect to find our application
1510 static char *get_windows_conf_root(void)
1512 static int is_set
= 0;
1513 static char path
[MAX_PATH
+1];
1522 /* Find X:\documents and settings\username\applicatation data\ .
1523 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
1525 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL
, CSIDL_APPDATA
,
1527 GetCurrentDirectory(MAX_PATH
, path
);
1529 log_fn(LOG_WARN
, "I couldn't find your application data folder: are you running an ancient version of Windows 95? Defaulting to '%s'", path
);
1532 /* Convert the path from an "ID List" (whatever that is!) to a path. */
1533 result
= SHGetPathFromIDList(idl
, path
);
1534 /* Now we need to free the */
1537 m
->lpVtbl
->Free(m
, idl
);
1538 m
->lpVtbl
->Release(m
);
1540 if (!SUCCEEDED(result
)) {
1543 strlcat(path
,"\\tor",MAX_PATH
);
1549 /** Return the default location for our torrc file. */
1551 get_default_conf_file(void)
1554 char *path
= tor_malloc(MAX_PATH
);
1555 strlcpy(path
, get_windows_conf_root(), MAX_PATH
);
1556 strlcat(path
,"\\torrc",MAX_PATH
);
1559 return tor_strdup(CONFDIR
"/torrc");
1563 /** Verify whether lst is a string containing valid-looking space-separated
1564 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
1566 static int check_nickname_list(const char *lst
, const char *name
)
1573 sl
= smartlist_create();
1574 smartlist_split_string(sl
, lst
, ",", SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1575 SMARTLIST_FOREACH(sl
, const char *, s
,
1577 if (!is_legal_nickname_or_hexdigest(s
)) {
1578 log_fn(LOG_WARN
, "Invalid nickname '%s' in %s line", s
, name
);
1582 SMARTLIST_FOREACH(sl
, char *, s
, tor_free(s
));
1587 /** Read a configuration file into <b>options</b>, finding the configuration
1588 * file location based on the command line. After loading the options,
1589 * validate them for consistency, then take actions based on them.
1590 * Return 0 if success, -1 if failure. */
1592 init_from_config(int argc
, char **argv
)
1594 or_options_t
*oldoptions
, *newoptions
;
1595 struct config_line_t
*cl
;
1596 char *cf
=NULL
, *fname
=NULL
;
1598 int using_default_torrc
;
1599 static char **backup_argv
;
1600 static int backup_argc
;
1602 if (argv
) { /* first time we're called. save commandline args */
1606 } else { /* we're reloading. need to clean up old options first. */
1609 oldoptions
= get_options();
1611 if (argc
> 1 && (!strcmp(argv
[1], "-h") || !strcmp(argv
[1],"--help"))) {
1616 if (argc
> 1 && (!strcmp(argv
[1],"--version"))) {
1617 printf("Tor version %s.\n",VERSION
);
1618 if (argc
> 2 && (!strcmp(argv
[2],"--version"))) {
1619 print_cvs_version();
1624 newoptions
= tor_malloc_zero(sizeof(or_options_t
));
1625 options_init(newoptions
);
1627 /* learn config file name, get config lines, assign them */
1629 using_default_torrc
= 1;
1630 newoptions
->command
= CMD_RUN_TOR
;
1631 for (i
= 1; i
< argc
; ++i
) {
1632 if (i
< argc
-1 && !strcmp(argv
[i
],"-f")) {
1634 log(LOG_WARN
, "Duplicate -f options on command line.");
1637 fname
= tor_strdup(argv
[i
+1]);
1638 using_default_torrc
= 0;
1640 } else if (!strcmp(argv
[i
],"--list-fingerprint")) {
1641 newoptions
->command
= CMD_LIST_FINGERPRINT
;
1642 } else if (!strcmp(argv
[i
],"--hash-password")) {
1643 newoptions
->command
= CMD_HASH_PASSWORD
;
1644 newoptions
->command_arg
= tor_strdup( (i
< argc
-1) ? argv
[i
+1] : "");
1649 if (using_default_torrc
) {
1650 /* didn't find one, try CONFDIR */
1652 fn
= get_default_conf_file();
1653 if (fn
&& file_status(fn
) == FN_FILE
) {
1657 fn
= expand_filename("~/.torrc");
1658 if (fn
&& file_status(fn
) == FN_FILE
) {
1662 fname
= get_default_conf_file();
1667 log(LOG_DEBUG
, "Opening config file '%s'", fname
);
1669 cf
= read_file_to_str(fname
, 0);
1671 if (using_default_torrc
== 1) {
1672 log(LOG_NOTICE
, "Configuration file '%s' not present, "
1673 "using reasonable defaults.", fname
);
1674 tor_free(fname
); /* sets fname to NULL */
1676 log(LOG_WARN
, "Unable to open configuration file '%s'.", fname
);
1680 } else { /* it opened successfully. use it. */
1681 retval
= config_get_lines(cf
, &cl
);
1685 retval
= config_assign(newoptions
, cl
, 0);
1686 config_free_lines(cl
);
1691 /* Go through command-line variables too */
1692 cl
= config_get_commandlines(argc
,argv
);
1693 retval
= config_assign(newoptions
,cl
,0);
1694 config_free_lines(cl
);
1698 /* Validate newoptions */
1699 if (options_validate(newoptions
) < 0)
1702 if (options_transition_allowed(oldoptions
, newoptions
) < 0)
1705 set_options(newoptions
); /* frees and replaces old options */
1706 if (options_act() < 0) { /* acting on them failed. die. */
1707 log_fn(LOG_ERR
,"Acting on config options left us in a broken state. Dying.");
1710 tor_free(config_fname
);
1711 config_fname
= fname
;
1715 options_free(newoptions
);
1719 /** If <b>range</b> is of the form MIN-MAX, for MIN and MAX both
1720 * recognized log severity levels, set *<b>min_out</b> to MIN and
1721 * *<b>max_out</b> to MAX and return 0. Else, if <b>range<b> is of
1722 * the form MIN, act as if MIN-err had been specified. Else, warn and
1726 parse_log_severity_range(const char *range
, int *min_out
, int *max_out
)
1728 int levelMin
, levelMax
;
1730 cp
= strchr(range
, '-');
1733 levelMin
= LOG_DEBUG
;
1735 char *tmp_sev
= tor_strndup(range
, cp
- range
);
1736 levelMin
= parse_log_level(tmp_sev
);
1738 log_fn(LOG_WARN
, "Unrecognized log severity '%s': must be one of "
1739 "err|warn|notice|info|debug", tmp_sev
);
1748 levelMax
= parse_log_level(cp
+1);
1750 log_fn(LOG_WARN
, "Unrecognized log severity '%s': must be one of "
1751 "err|warn|notice|info|debug", cp
+1);
1756 levelMin
= parse_log_level(range
);
1758 log_fn(LOG_WARN
, "Unrecognized log severity '%s': must be one of "
1759 "err|warn|notice|info|debug", range
);
1765 *min_out
= levelMin
;
1766 *max_out
= levelMax
;
1771 /** Try to convert a pair of old-style logging options [LogLevel, and
1772 * (LogFile/Syslog)] to a new-style option, and add the new option to
1775 convert_log_option(or_options_t
*options
, struct config_line_t
*level_opt
,
1776 struct config_line_t
*file_opt
, int isDaemon
)
1778 int levelMin
= -1, levelMax
= -1;
1781 if (parse_log_severity_range(level_opt
->value
, &levelMin
, &levelMax
))
1784 if (levelMin
< 0 && levelMax
< 0) {
1785 levelMin
= LOG_NOTICE
;
1787 } else if (levelMin
< 0) {
1788 levelMin
= levelMax
;
1793 if (file_opt
&& !strcasecmp(file_opt
->key
, "LogFile")) {
1794 if (add_single_log_option(options
, levelMin
, levelMax
, "file", file_opt
->value
) < 0) {
1795 log_fn(LOG_WARN
, "Cannot write to LogFile '%s': %s.", file_opt
->value
,
1799 } else if (file_opt
&& !strcasecmp(file_opt
->key
, "SysLog")) {
1800 if (add_single_log_option(options
, levelMin
, levelMax
, "syslog", NULL
) < 0)
1802 } else if (!isDaemon
) {
1803 add_single_log_option(options
, levelMin
, levelMax
, "stdout", NULL
);
1809 * Initialize the logs based on the configuration file.
1812 config_init_logs(or_options_t
*options
, int validate_only
)
1814 struct config_line_t
*opt
;
1819 elts
= smartlist_create();
1820 for (opt
= options
->Logs
; opt
; opt
= opt
->next
) {
1821 int levelMin
=LOG_DEBUG
, levelMax
=LOG_ERR
;
1822 smartlist_split_string(elts
, opt
->value
, " ",
1823 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 3);
1824 if (smartlist_len(elts
) == 0) {
1825 log_fn(LOG_WARN
, "Bad syntax on Log option 'Log %s'", opt
->value
);
1826 ok
= 0; goto cleanup
;
1828 if (parse_log_severity_range(smartlist_get(elts
,0), &levelMin
, &levelMax
)) {
1829 ok
= 0; goto cleanup
;
1831 if (smartlist_len(elts
) < 2) { /* only loglevels were provided */
1833 add_stream_log(levelMin
, levelMax
, "<stdout>", stdout
);
1836 if (!strcasecmp(smartlist_get(elts
,1), "file")) {
1837 if (smartlist_len(elts
) != 3) {
1838 log_fn(LOG_WARN
, "Bad syntax on Log option 'Log %s'", opt
->value
);
1839 ok
= 0; goto cleanup
;
1842 add_file_log(levelMin
, levelMax
, smartlist_get(elts
, 2));
1845 if (smartlist_len(elts
) != 2) {
1846 log_fn(LOG_WARN
, "Bad syntax on Log option 'Log %s'", opt
->value
);
1847 ok
= 0; goto cleanup
;
1849 if (!strcasecmp(smartlist_get(elts
,1), "stdout")) {
1850 if (!validate_only
) {
1851 add_stream_log(levelMin
, levelMax
, "<stdout>", stdout
);
1854 } else if (!strcasecmp(smartlist_get(elts
,1), "stderr")) {
1855 if (!validate_only
) {
1856 add_stream_log(levelMin
, levelMax
, "<stderr>", stderr
);
1859 } else if (!strcasecmp(smartlist_get(elts
,1), "syslog")) {
1860 #ifdef HAVE_SYSLOG_H
1862 add_syslog_log(levelMin
, levelMax
);
1864 log_fn(LOG_WARN
, "Syslog is not supported in this compilation.");
1867 log_fn(LOG_WARN
, "Unrecognized log type %s",
1868 (const char*)smartlist_get(elts
,1));
1869 if (strchr(smartlist_get(elts
,1), '/')) {
1870 log_fn(LOG_WARN
, "Did you mean to say 'Log file %s' ?",
1871 (const char *)smartlist_get(elts
,1));
1873 ok
= 0; goto cleanup
;
1876 SMARTLIST_FOREACH(elts
, char*, cp
, tor_free(cp
));
1877 smartlist_clear(elts
);
1879 smartlist_free(elts
);
1886 /** Add a single option of the form Log min-max <type> [fname] to options. */
1888 add_single_log_option(or_options_t
*options
, int minSeverity
, int maxSeverity
,
1889 const char *type
, const char *fname
)
1894 n
= tor_snprintf(buf
, sizeof(buf
), "%s-%s %s%s%s",
1895 log_level_to_string(minSeverity
),
1896 log_level_to_string(maxSeverity
),
1897 type
, fname
?" ":"", fname
?fname
:"");
1899 log_fn(LOG_WARN
, "Normalized log option too long.");
1903 log(LOG_WARN
, "The old LogLevel/LogFile/DebugLogFile/SysLog options are deprecated, and will go away soon. Your new torrc line should be: 'Log %s'", buf
);
1904 options
->Logs
= config_line_prepend(options
->Logs
, "Log", buf
);
1908 /** Convert all old-style logging options to new-style Log options. Return 0
1909 * on success, -1 on faulure. */
1911 normalize_log_options(or_options_t
*options
)
1913 /* The order of options is: Level? (File Level?)+
1915 struct config_line_t
*opt
= options
->OldLogOptions
;
1917 /* Special case for if first option is LogLevel. */
1918 if (opt
&& !strcasecmp(opt
->key
, "LogLevel")) {
1919 if (opt
->next
&& (!strcasecmp(opt
->next
->key
, "LogFile") ||
1920 !strcasecmp(opt
->next
->key
, "SysLog"))) {
1921 if (convert_log_option(options
, opt
, opt
->next
, options
->RunAsDaemon
) < 0)
1923 opt
= opt
->next
->next
;
1924 } else if (!opt
->next
) {
1925 if (convert_log_option(options
, opt
, NULL
, options
->RunAsDaemon
) < 0)
1929 ; /* give warning below */
1934 if (!strcasecmp(opt
->key
, "LogLevel")) {
1935 log_fn(LOG_WARN
, "Two LogLevel options in a row without intervening LogFile or SysLog");
1938 tor_assert(!strcasecmp(opt
->key
, "LogFile") ||
1939 !strcasecmp(opt
->key
, "SysLog"));
1940 if (opt
->next
&& !strcasecmp(opt
->next
->key
, "LogLevel")) {
1941 /* LogFile/SysLog followed by LogLevel */
1942 if (convert_log_option(options
,opt
->next
,opt
, options
->RunAsDaemon
) < 0)
1944 opt
= opt
->next
->next
;
1946 /* LogFile/SysLog followed by LogFile/SysLog or end of list. */
1947 if (convert_log_option(options
,NULL
, opt
, options
->RunAsDaemon
) < 0)
1954 if (options
->DebugLogFile
) {
1955 if (add_single_log_option(options
, LOG_DEBUG
, LOG_ERR
, "file", options
->DebugLogFile
) < 0)
1959 tor_free(options
->DebugLogFile
);
1960 config_free_lines(options
->OldLogOptions
);
1961 options
->OldLogOptions
= NULL
;
1967 * Given a linked list of config lines containing "allow" and "deny" tokens,
1968 * parse them and append the result to <b>dest</b>. Return -1 if any tokens
1969 * are malformed, else return 0.
1972 config_parse_addr_policy(struct config_line_t
*cfg
,
1973 struct addr_policy_t
**dest
)
1975 struct addr_policy_t
**nextp
;
1976 smartlist_t
*entries
;
1985 nextp
= &((*nextp
)->next
);
1987 entries
= smartlist_create();
1988 for (; cfg
; cfg
= cfg
->next
) {
1989 smartlist_split_string(entries
, cfg
->value
, ",", SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1990 SMARTLIST_FOREACH(entries
, const char *, ent
,
1992 log_fn(LOG_DEBUG
,"Adding new entry '%s'",ent
);
1993 *nextp
= router_parse_addr_policy_from_string(ent
);
1995 nextp
= &((*nextp
)->next
);
1997 log_fn(LOG_WARN
,"Malformed policy %s.", ent
);
2001 SMARTLIST_FOREACH(entries
, char *, ent
, tor_free(ent
));
2002 smartlist_clear(entries
);
2004 smartlist_free(entries
);
2008 /** Release all storage held by <b>p</b> */
2010 addr_policy_free(struct addr_policy_t
*p
) {
2011 struct addr_policy_t
*e
;
2016 tor_free(e
->string
);
2021 /** Parse a single RedirectExit line's contents from <b>line</b>. If
2022 * they are valid, and <b>result</b> is not NULL, add an element to
2023 * <b>result</b> and return 0. Else if they are valid, return 0.
2024 * Else return -1. */
2026 parse_redirect_line(smartlist_t
*result
, struct config_line_t
*line
)
2028 smartlist_t
*elements
= NULL
;
2033 r
= tor_malloc_zero(sizeof(exit_redirect_t
));
2034 elements
= smartlist_create();
2035 smartlist_split_string(elements
, line
->value
, " ",
2036 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2037 if (smartlist_len(elements
) != 2) {
2038 log_fn(LOG_WARN
, "Wrong number of elements in RedirectExit line");
2041 if (parse_addr_and_port_range(smartlist_get(elements
,0),&r
->addr
,&r
->mask
,
2042 &r
->port_min
,&r
->port_max
)) {
2043 log_fn(LOG_WARN
, "Error parsing source address in RedirectExit line");
2046 if (0==strcasecmp(smartlist_get(elements
,1), "pass")) {
2049 if (parse_addr_port(smartlist_get(elements
,1),NULL
,&r
->addr_dest
,
2051 log_fn(LOG_WARN
, "Error parsing dest address in RedirectExit line");
2061 SMARTLIST_FOREACH(elements
, char *, cp
, tor_free(cp
));
2062 smartlist_free(elements
);
2065 smartlist_add(result
, r
);
2074 /** Read the contents of a DirServer line from <b>line</b>. Return 0
2075 * if the line is well-formed, and 0 if it isn't. If
2076 * <b>validate_only</b> is 0, and the line is well-formed, then add
2077 * the dirserver desribed in the line as a valid server. */
2079 parse_dir_server_line(const char *line
, int validate_only
)
2081 smartlist_t
*items
= NULL
;
2083 char *addrport
, *address
=NULL
;
2085 char digest
[DIGEST_LEN
];
2087 items
= smartlist_create();
2088 smartlist_split_string(items
, line
, " ",
2089 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
2090 if (smartlist_len(items
) < 2) {
2091 log_fn(LOG_WARN
, "Too few arguments to DirServer line.");
2094 addrport
= smartlist_get(items
, 0);
2095 if (parse_addr_port(addrport
, &address
, NULL
, &port
)<0) {
2096 log_fn(LOG_WARN
, "Error parsing DirServer address '%s'", addrport
);
2100 log_fn(LOG_WARN
, "Missing port in DirServe address '%s'",addrport
);
2104 tor_strstrip(smartlist_get(items
, 1), " ");
2105 if (strlen(smartlist_get(items
, 1)) != HEX_DIGEST_LEN
) {
2106 log_fn(LOG_WARN
, "Key digest for DirServer is wrong length.");
2109 if (base16_decode(digest
, DIGEST_LEN
,
2110 smartlist_get(items
,1), HEX_DIGEST_LEN
)<0) {
2111 log_fn(LOG_WARN
, "Unable to decode DirServer key digest.");
2115 if (!validate_only
) {
2116 log_fn(LOG_DEBUG
, "Trusted dirserver at %s:%d (%s)", address
, (int)port
,
2117 (char*)smartlist_get(items
,1));
2118 add_trusted_dir_server(address
, port
, digest
);
2128 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
2129 smartlist_free(items
);
2134 /** Adjust the value of options->DataDirectory, or fill it in if it's
2135 * absent. Return 0 on success, -1 on failure. */
2137 normalize_data_directory(or_options_t
*options
) {
2140 if (options
->DataDirectory
)
2141 return 0; /* all set */
2142 p
= tor_malloc(MAX_PATH
);
2143 strlcpy(p
,get_windows_conf_root(),MAX_PATH
);
2144 options
->DataDirectory
= p
;
2147 const char *d
= options
->DataDirectory
;
2151 if (strncmp(d
,"~/",2) == 0) {
2152 char *fn
= expand_filename(d
);
2154 log_fn(LOG_ERR
,"Failed to expand filename '%s'.", d
);
2157 if (!options
->DataDirectory
&& !strcmp(fn
,"/.tor")) {
2158 /* If our homedir is /, we probably don't want to use it. */
2159 /* XXXX Default to /var/lib/tor? */
2160 log_fn(LOG_WARN
, "Defaulting to 'DataDirectory %s', which may not be what you want", fn
);
2162 tor_free(options
->DataDirectory
);
2163 options
->DataDirectory
= fn
;
2169 /** Check and normalize the value of options->DataDirectory; return 0 if it
2170 * sane, -1 otherwise. */
2172 validate_data_directory(or_options_t
*options
) {
2173 if (normalize_data_directory(options
) < 0)
2175 tor_assert(options
->DataDirectory
);
2176 if (strlen(options
->DataDirectory
) > (512-128)) {
2177 log_fn(LOG_ERR
, "DataDirectory is too long.");
2181 if (check_private_dir(options
->DataDirectory
, CPD_CHECK
!= 0)) {
2182 log_fn(LOG_WARN
, "Can't create directory %s", options
->DataDirectory
);
2189 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; if you edit it, comments will not be preserved"
2191 /** Save a configuration file for the configuration in <b>options</b>
2192 * into the file <b>fname</b>. If the file already exists, and
2193 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
2194 * replace it. Return 0 on success, -1 on failure. */
2196 write_configuration_file(const char *fname
, or_options_t
*options
)
2199 char *old_val
=NULL
, *new_val
=NULL
, *new_conf
=NULL
;
2200 int rename_old
= 0, r
;
2204 switch (file_status(fname
)) {
2206 old_val
= read_file_to_str(fname
, 0);
2207 if (strcmpstart(old_val
, GENERATED_FILE_PREFIX
)) {
2215 log_fn(LOG_WARN
,"Config file %s is not a file? Failing.", fname
);
2220 if (!(new_conf
= config_dump_options(options
, 1))) {
2221 log_fn(LOG_WARN
, "Couldn't get configuration string");
2225 len
= strlen(new_conf
)+128;
2226 new_val
= tor_malloc(len
);
2227 tor_snprintf(new_val
, len
, "%s\n\n%s", GENERATED_FILE_PREFIX
, new_conf
);
2232 if (tor_snprintf(fn_tmp
, sizeof(fn_tmp
), "%s.orig.%d", fname
, i
)<0) {
2233 log_fn(LOG_WARN
, "Filename too long");
2236 if (file_status(fn_tmp
) == FN_NOENT
)
2240 log_fn(LOG_NOTICE
, "Renaming old configuration file to %s", fn_tmp
);
2241 rename(fname
, fn_tmp
);
2244 write_str_to_file(fname
, new_val
, 0);
2257 * Save the current configuration file value to disk. Return 0 on
2258 * success, -1 on failure.
2261 save_current_config(void)
2265 /* XXX This fails if we can't write to our configuration file.
2266 * Arguably, we should try falling back to datadirectory or something.
2267 * But just as arguably, we shouldn't. */
2268 return write_configuration_file(config_fname
, get_options());
2270 fn
= get_default_conf_file();
2271 return write_configuration_file(fn
, get_options());
2274 struct unit_table_t
{
2276 uint64_t multiplier
;
2279 static struct unit_table_t memory_units
[] = {
2285 { "kilobyte", 1<<10 },
2286 { "kilobytes", 1<<10 },
2289 { "megabyte", 1<<20 },
2290 { "megabytes", 1<<20 },
2292 { "gigabyte", 1<<30 },
2293 { "gigabytes", 1<<30 },
2294 { "tb", U64_LITERAL(1)<<40 },
2295 { "terabyte", U64_LITERAL(1)<<40 },
2296 { "terabytes", U64_LITERAL(1)<<40 },
2300 static struct unit_table_t time_units
[] = {
2308 { "day", 24*60*60 },
2309 { "days", 24*60*60 },
2310 { "week", 7*24*60*60 },
2311 { "weeks", 7*24*60*60 },
2315 /** Parse a string <b>val</b> containing a number, zero or more
2316 * spaces, and an optional unit string. If the unit appears in the
2317 * table <b>u</b>, then multiply the number by the unit multiplier.
2318 * On success, set *<b>ok</b> to 1 and return this product.
2319 * Otherwise, set *<b>ok</b> to 0.
2322 config_parse_units(const char *val
, struct unit_table_t
*u
, int *ok
)
2329 v
= tor_parse_uint64(val
, 10, 0, UINT64_MAX
, ok
, &cp
);
2336 while (isspace(*cp
))
2338 for ( ;u
->unit
;++u
) {
2339 if (!strcasecmp(u
->unit
, cp
)) {
2345 log_fn(LOG_WARN
, "Unknown unit '%s'.", cp
);
2350 /** Parse a string in the format "number unit", where unit is a unit of
2351 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
2352 * and return the number of bytes specified. Otherwise, set
2353 * *<b>ok</b> to false and return 0. */
2355 config_parse_memunit(const char *s
, int *ok
) {
2356 return config_parse_units(s
, memory_units
, ok
);
2359 /** Parse a string in the format "number unit", where unit is a unit of time.
2360 * On success, set *<b>ok</b> to true and return the number of seconds in
2361 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
2364 config_parse_interval(const char *s
, int *ok
) {
2366 r
= config_parse_units(s
, time_units
, ok
);
2370 log_fn(LOG_WARN
, "Interval '%s' is too long", s
);
2378 print_cvs_version(void)
2380 extern const char aes_c_id
[];
2381 extern const char compat_c_id
[];
2382 extern const char container_c_id
[];
2383 extern const char crypto_c_id
[];
2384 extern const char fakepoll_c_id
[];
2385 extern const char log_c_id
[];
2386 extern const char torgzip_c_id
[];
2387 extern const char tortls_c_id
[];
2388 extern const char util_c_id
[];
2390 extern const char buffers_c_id
[];
2391 extern const char circuitbuild_c_id
[];
2392 extern const char circuitlist_c_id
[];
2393 extern const char circuituse_c_id
[];
2394 extern const char command_c_id
[];
2395 extern const char config_c_id
[];
2396 extern const char connection_c_id
[];
2397 extern const char connection_edge_c_id
[];
2398 extern const char connection_or_c_id
[];
2399 extern const char control_c_id
[];
2400 extern const char cpuworker_c_id
[];
2401 extern const char directory_c_id
[];
2402 extern const char dirserv_c_id
[];
2403 extern const char dns_c_id
[];
2404 extern const char hibernate_c_id
[];
2405 extern const char main_c_id
[];
2406 extern const char onion_c_id
[];
2407 extern const char relay_c_id
[];
2408 extern const char rendclient_c_id
[];
2409 extern const char rendcommon_c_id
[];
2410 extern const char rendmid_c_id
[];
2411 extern const char rendservice_c_id
[];
2412 extern const char rephist_c_id
[];
2413 extern const char router_c_id
[];
2414 extern const char routerlist_c_id
[];
2415 extern const char routerparse_c_id
[];
2419 puts(CONTAINER_H_ID
);
2421 puts(FAKEPOLL_H_ID
);
2429 puts(container_c_id
);
2431 puts(fakepoll_c_id
);
2439 puts(circuitbuild_c_id
);
2440 puts(circuitlist_c_id
);
2441 puts(circuituse_c_id
);
2444 puts(connection_c_id
);
2445 puts(connection_edge_c_id
);
2446 puts(connection_or_c_id
);
2448 puts(cpuworker_c_id
);
2449 puts(directory_c_id
);
2452 puts(hibernate_c_id
);
2456 puts(rendclient_c_id
);
2457 puts(rendcommon_c_id
);
2459 puts(rendservice_c_id
);
2462 puts(routerlist_c_id
);
2463 puts(routerparse_c_id
);