Document most undocumented variables.
[tor/rransom.git] / src / or / config.c
blobadb4b1950bbb2caf9b256a1ef0ea0e901f7048bd
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2008, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 /* $Id$ */
7 const char config_c_id[] = \
8 "$Id$";
10 /**
11 * \file config.c
12 * \brief Code to parse and interpret configuration files.
13 **/
15 #define CONFIG_PRIVATE
17 #include "or.h"
18 #ifdef MS_WINDOWS
19 #include <shlobj.h>
20 #endif
22 /** Enumeration of types which option values can take */
23 typedef enum config_type_t {
24 CONFIG_TYPE_STRING = 0, /**< An arbitrary string. */
25 CONFIG_TYPE_FILENAME, /**< A filename: some prefixes get expanded. */
26 CONFIG_TYPE_UINT, /**< A non-negative integer less than MAX_INT */
27 CONFIG_TYPE_INTERVAL, /**< A number of seconds, with optional units*/
28 CONFIG_TYPE_MEMUNIT, /**< A number of bytes, with optional units*/
29 CONFIG_TYPE_DOUBLE, /**< A floating-point value */
30 CONFIG_TYPE_BOOL, /**< A boolean value, expressed as 0 or 1. */
31 CONFIG_TYPE_ISOTIME, /**< An ISO-formated time relative to GMT. */
32 CONFIG_TYPE_CSV, /**< A list of strings, separated by commas and
33 * optional whitespace. */
34 CONFIG_TYPE_LINELIST, /**< Uninterpreted config lines */
35 CONFIG_TYPE_LINELIST_S, /**< Uninterpreted, context-sensitive config lines,
36 * mixed with other keywords. */
37 CONFIG_TYPE_LINELIST_V, /**< Catch-all "virtual" option to summarize
38 * context-sensitive config lines when fetching.
40 CONFIG_TYPE_ROUTERSET, /**< A list of router names, addrs, and fps,
41 * parsed into a routerset_t. */
42 CONFIG_TYPE_OBSOLETE, /**< Obsolete (ignored) option. */
43 } config_type_t;
45 /** An abbreviation for a configuration option allowed on the command line. */
46 typedef struct config_abbrev_t {
47 const char *abbreviated;
48 const char *full;
49 int commandline_only;
50 int warn;
51 } config_abbrev_t;
53 /* Handy macro for declaring "In the config file or on the command line,
54 * you can abbreviate <b>tok</b>s as <b>tok</b>". */
55 #define PLURAL(tok) { #tok, #tok "s", 0, 0 }
57 /** A list of abbreviations and aliases to map command-line options, obsolete
58 * option names, or alternative option names, to their current values. */
59 static config_abbrev_t _option_abbrevs[] = {
60 PLURAL(ExitNode),
61 PLURAL(EntryNode),
62 PLURAL(ExcludeNode),
63 PLURAL(FirewallPort),
64 PLURAL(LongLivedPort),
65 PLURAL(HiddenServiceNode),
66 PLURAL(HiddenServiceExcludeNode),
67 PLURAL(NumCpu),
68 PLURAL(RendNode),
69 PLURAL(RendExcludeNode),
70 PLURAL(StrictEntryNode),
71 PLURAL(StrictExitNode),
72 { "l", "Log", 1, 0},
73 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
74 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
75 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
76 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
77 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
78 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
79 { "MaxConn", "ConnLimit", 0, 1},
80 { "ORBindAddress", "ORListenAddress", 0, 0},
81 { "DirBindAddress", "DirListenAddress", 0, 0},
82 { "SocksBindAddress", "SocksListenAddress", 0, 0},
83 { "UseHelperNodes", "UseEntryGuards", 0, 0},
84 { "NumHelperNodes", "NumEntryGuards", 0, 0},
85 { "UseEntryNodes", "UseEntryGuards", 0, 0},
86 { "NumEntryNodes", "NumEntryGuards", 0, 0},
87 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
88 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
89 { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0 },
90 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
91 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
92 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
93 { NULL, NULL, 0, 0},
96 /** A list of state-file "abbreviations," for compatibility. */
97 static config_abbrev_t _state_abbrevs[] = {
98 { "AccountingBytesReadInterval", "AccountingBytesReadInInterval", 0, 0 },
99 { "HelperNode", "EntryGuard", 0, 0 },
100 { "HelperNodeDownSince", "EntryGuardDownSince", 0, 0 },
101 { "HelperNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
102 { "EntryNode", "EntryGuard", 0, 0 },
103 { "EntryNodeDownSince", "EntryGuardDownSince", 0, 0 },
104 { "EntryNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
105 { NULL, NULL, 0, 0},
107 #undef PLURAL
109 /** A variable allowed in the configuration file or on the command line. */
110 typedef struct config_var_t {
111 const char *name; /**< The full keyword (case insensitive). */
112 config_type_t type; /**< How to interpret the type and turn it into a
113 * value. */
114 off_t var_offset; /**< Offset of the corresponding member of or_options_t. */
115 const char *initvalue; /**< String (or null) describing initial value. */
116 } config_var_t;
118 /** An entry for config_vars: "The option <b>name</b> has type
119 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
120 * or_options_t.<b>member</b>"
122 #define VAR(name,conftype,member,initvalue) \
123 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
124 initvalue }
125 /** As VAR, but the option name and member name are the same. */
126 #define V(member,conftype,initvalue) \
127 VAR(#member, conftype, member, initvalue)
128 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
129 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
131 /** Array of configuration options. Until we disallow nonstandard
132 * abbreviations, order is significant, since the first matching option will
133 * be chosen first.
135 static config_var_t _option_vars[] = {
136 OBSOLETE("AccountingMaxKB"),
137 V(AccountingMax, MEMUNIT, "0 bytes"),
138 V(AccountingStart, STRING, NULL),
139 V(Address, STRING, NULL),
140 V(AllowInvalidNodes, CSV, "middle,rendezvous"),
141 V(AllowNonRFC953Hostnames, BOOL, "0"),
142 V(AllowSingleHopCircuits, BOOL, "0"),
143 V(AllowSingleHopExits, BOOL, "0"),
144 V(AlternateBridgeAuthority, LINELIST, NULL),
145 V(AlternateDirAuthority, LINELIST, NULL),
146 V(AlternateHSAuthority, LINELIST, NULL),
147 V(AssumeReachable, BOOL, "0"),
148 V(AuthDirBadDir, LINELIST, NULL),
149 V(AuthDirBadExit, LINELIST, NULL),
150 V(AuthDirInvalid, LINELIST, NULL),
151 V(AuthDirReject, LINELIST, NULL),
152 V(AuthDirRejectUnlisted, BOOL, "0"),
153 V(AuthDirListBadDirs, BOOL, "0"),
154 V(AuthDirListBadExits, BOOL, "0"),
155 V(AuthDirMaxServersPerAddr, UINT, "2"),
156 V(AuthDirMaxServersPerAuthAddr,UINT, "5"),
157 VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
158 V(AutomapHostsOnResolve, BOOL, "0"),
159 V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
160 V(AvoidDiskWrites, BOOL, "0"),
161 V(BandwidthBurst, MEMUNIT, "10 MB"),
162 V(BandwidthRate, MEMUNIT, "5 MB"),
163 V(BridgeAuthoritativeDir, BOOL, "0"),
164 VAR("Bridge", LINELIST, Bridges, NULL),
165 V(BridgePassword, STRING, NULL),
166 V(BridgeRecordUsageByCountry, BOOL, "1"),
167 V(BridgeRelay, BOOL, "0"),
168 V(CircuitBuildTimeout, INTERVAL, "1 minute"),
169 V(CircuitIdleTimeout, INTERVAL, "1 hour"),
170 V(ClientDNSRejectInternalAddresses, BOOL,"1"),
171 V(ClientOnly, BOOL, "0"),
172 V(ConnLimit, UINT, "1000"),
173 V(ConstrainedSockets, BOOL, "0"),
174 V(ConstrainedSockSize, MEMUNIT, "8192"),
175 V(ContactInfo, STRING, NULL),
176 V(ControlListenAddress, LINELIST, NULL),
177 V(ControlPort, UINT, "0"),
178 V(ControlSocket, LINELIST, NULL),
179 V(CookieAuthentication, BOOL, "0"),
180 V(CookieAuthFileGroupReadable, BOOL, "0"),
181 V(CookieAuthFile, STRING, NULL),
182 V(DataDirectory, FILENAME, NULL),
183 OBSOLETE("DebugLogFile"),
184 V(DirAllowPrivateAddresses, BOOL, NULL),
185 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
186 V(DirListenAddress, LINELIST, NULL),
187 OBSOLETE("DirFetchPeriod"),
188 V(DirPolicy, LINELIST, NULL),
189 V(DirPort, UINT, "0"),
190 V(DirPortFrontPage, FILENAME, NULL),
191 OBSOLETE("DirPostPeriod"),
192 #ifdef ENABLE_GEOIP_STATS
193 V(DirRecordUsageByCountry, BOOL, "0"),
194 V(DirRecordUsageGranularity, UINT, "4"),
195 V(DirRecordUsageRetainIPs, INTERVAL, "14 days"),
196 V(DirRecordUsageSaveInterval, INTERVAL, "6 hours"),
197 #endif
198 VAR("DirServer", LINELIST, DirServers, NULL),
199 V(DNSPort, UINT, "0"),
200 V(DNSListenAddress, LINELIST, NULL),
201 V(DownloadExtraInfo, BOOL, "0"),
202 V(EnforceDistinctSubnets, BOOL, "1"),
203 V(EntryNodes, ROUTERSET, NULL),
204 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
205 V(ExcludeNodes, ROUTERSET, NULL),
206 V(ExcludeExitNodes, ROUTERSET, NULL),
207 V(ExcludeSingleHopRelays, BOOL, "1"),
208 V(ExitNodes, ROUTERSET, NULL),
209 V(ExitPolicy, LINELIST, NULL),
210 V(ExitPolicyRejectPrivate, BOOL, "1"),
211 V(FallbackNetworkstatusFile, FILENAME,
212 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "fallback-consensus"),
213 V(FascistFirewall, BOOL, "0"),
214 V(FirewallPorts, CSV, ""),
215 V(FastFirstHopPK, BOOL, "1"),
216 V(FetchDirInfoEarly, BOOL, "0"),
217 V(FetchServerDescriptors, BOOL, "1"),
218 V(FetchHidServDescriptors, BOOL, "1"),
219 V(FetchUselessDescriptors, BOOL, "0"),
220 #ifdef WIN32
221 V(GeoIPFile, FILENAME, "<default>"),
222 #else
223 V(GeoIPFile, FILENAME,
224 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
225 #endif
226 OBSOLETE("Group"),
227 V(HardwareAccel, BOOL, "0"),
228 V(HashedControlPassword, LINELIST, NULL),
229 V(HidServDirectoryV2, BOOL, "1"),
230 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
231 OBSOLETE("HiddenServiceExcludeNodes"),
232 OBSOLETE("HiddenServiceNodes"),
233 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
234 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
235 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
236 VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
237 V(HidServAuth, LINELIST, NULL),
238 V(HSAuthoritativeDir, BOOL, "0"),
239 V(HSAuthorityRecordStats, BOOL, "0"),
240 V(HttpProxy, STRING, NULL),
241 V(HttpProxyAuthenticator, STRING, NULL),
242 V(HttpsProxy, STRING, NULL),
243 V(HttpsProxyAuthenticator, STRING, NULL),
244 OBSOLETE("IgnoreVersion"),
245 V(KeepalivePeriod, INTERVAL, "5 minutes"),
246 VAR("Log", LINELIST, Logs, NULL),
247 OBSOLETE("LinkPadding"),
248 OBSOLETE("LogLevel"),
249 OBSOLETE("LogFile"),
250 V(LongLivedPorts, CSV,
251 "21,22,706,1863,5050,5190,5222,5223,6667,6697,8300"),
252 VAR("MapAddress", LINELIST, AddressMap, NULL),
253 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
254 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
255 V(MaxOnionsPending, UINT, "100"),
256 OBSOLETE("MonthlyAccountingStart"),
257 V(MyFamily, STRING, NULL),
258 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
259 VAR("NamingAuthoritativeDirectory",BOOL, NamingAuthoritativeDir, "0"),
260 V(NatdListenAddress, LINELIST, NULL),
261 V(NatdPort, UINT, "0"),
262 V(Nickname, STRING, NULL),
263 V(NoPublish, BOOL, "0"),
264 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
265 V(NumCpus, UINT, "1"),
266 V(NumEntryGuards, UINT, "3"),
267 V(ORListenAddress, LINELIST, NULL),
268 V(ORPort, UINT, "0"),
269 V(OutboundBindAddress, STRING, NULL),
270 OBSOLETE("PathlenCoinWeight"),
271 V(PidFile, STRING, NULL),
272 V(TestingTorNetwork, BOOL, "0"),
273 V(PreferTunneledDirConns, BOOL, "1"),
274 V(ProtocolWarnings, BOOL, "0"),
275 V(PublishServerDescriptor, CSV, "1"),
276 V(PublishHidServDescriptors, BOOL, "1"),
277 V(ReachableAddresses, LINELIST, NULL),
278 V(ReachableDirAddresses, LINELIST, NULL),
279 V(ReachableORAddresses, LINELIST, NULL),
280 V(RecommendedVersions, LINELIST, NULL),
281 V(RecommendedClientVersions, LINELIST, NULL),
282 V(RecommendedServerVersions, LINELIST, NULL),
283 OBSOLETE("RedirectExit"),
284 V(RejectPlaintextPorts, CSV, ""),
285 V(RelayBandwidthBurst, MEMUNIT, "0"),
286 V(RelayBandwidthRate, MEMUNIT, "0"),
287 OBSOLETE("RendExcludeNodes"),
288 OBSOLETE("RendNodes"),
289 V(RendPostPeriod, INTERVAL, "1 hour"),
290 V(RephistTrackTime, INTERVAL, "24 hours"),
291 OBSOLETE("RouterFile"),
292 V(RunAsDaemon, BOOL, "0"),
293 V(RunTesting, BOOL, "0"),
294 V(SafeLogging, BOOL, "1"),
295 V(SafeSocks, BOOL, "0"),
296 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
297 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
298 V(ServerDNSDetectHijacking, BOOL, "1"),
299 V(ServerDNSRandomizeCase, BOOL, "1"),
300 V(ServerDNSResolvConfFile, STRING, NULL),
301 V(ServerDNSSearchDomains, BOOL, "0"),
302 V(ServerDNSTestAddresses, CSV,
303 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
304 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
305 V(SocksListenAddress, LINELIST, NULL),
306 V(SocksPolicy, LINELIST, NULL),
307 V(SocksPort, UINT, "9050"),
308 V(SocksTimeout, INTERVAL, "2 minutes"),
309 OBSOLETE("StatusFetchPeriod"),
310 V(StrictEntryNodes, BOOL, "0"),
311 V(StrictExitNodes, BOOL, "0"),
312 OBSOLETE("SysLog"),
313 V(TestSocks, BOOL, "0"),
314 OBSOLETE("TestVia"),
315 V(TrackHostExits, CSV, NULL),
316 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
317 OBSOLETE("TrafficShaping"),
318 V(TransListenAddress, LINELIST, NULL),
319 V(TransPort, UINT, "0"),
320 V(TunnelDirConns, BOOL, "1"),
321 V(UpdateBridgesFromAuthority, BOOL, "0"),
322 V(UseBridges, BOOL, "0"),
323 V(UseEntryGuards, BOOL, "1"),
324 V(User, STRING, NULL),
325 VAR("V1AuthoritativeDirectory",BOOL, V1AuthoritativeDir, "0"),
326 VAR("V2AuthoritativeDirectory",BOOL, V2AuthoritativeDir, "0"),
327 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
328 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
329 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
330 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
331 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
332 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
333 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
334 V(V3AuthNIntervalsValid, UINT, "3"),
335 V(V3AuthUseLegacyKey, BOOL, "0"),
336 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
337 V(VirtualAddrNetwork, STRING, "127.192.0.0/10"),
338 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
339 VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
340 VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
341 VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
342 VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
343 VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
344 NULL),
345 V(MinUptimeHidServDirectoryV2, INTERVAL, "24 hours"),
346 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
349 /** Override default values with these if the user sets the TestingTorNetwork
350 * option. */
351 static config_var_t testing_tor_network_defaults[] = {
352 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
353 V(DirAllowPrivateAddresses, BOOL, "1"),
354 V(EnforceDistinctSubnets, BOOL, "0"),
355 V(AssumeReachable, BOOL, "1"),
356 V(AuthDirMaxServersPerAddr, UINT, "0"),
357 V(AuthDirMaxServersPerAuthAddr,UINT, "0"),
358 V(ClientDNSRejectInternalAddresses, BOOL,"0"),
359 V(ExitPolicyRejectPrivate, BOOL, "0"),
360 V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
361 V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
362 V(V3AuthDistDelay, INTERVAL, "20 seconds"),
363 V(TestingV3AuthInitialVotingInterval, INTERVAL, "5 minutes"),
364 V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
365 V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
366 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
367 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
368 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
370 #undef VAR
372 #define VAR(name,conftype,member,initvalue) \
373 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
374 initvalue }
376 /** Array of "state" variables saved to the ~/.tor/state file. */
377 static config_var_t _state_vars[] = {
378 V(AccountingBytesReadInInterval, MEMUNIT, NULL),
379 V(AccountingBytesWrittenInInterval, MEMUNIT, NULL),
380 V(AccountingExpectedUsage, MEMUNIT, NULL),
381 V(AccountingIntervalStart, ISOTIME, NULL),
382 V(AccountingSecondsActive, INTERVAL, NULL),
384 VAR("EntryGuard", LINELIST_S, EntryGuards, NULL),
385 VAR("EntryGuardDownSince", LINELIST_S, EntryGuards, NULL),
386 VAR("EntryGuardUnlistedSince", LINELIST_S, EntryGuards, NULL),
387 VAR("EntryGuardAddedBy", LINELIST_S, EntryGuards, NULL),
388 V(EntryGuards, LINELIST_V, NULL),
390 V(BWHistoryReadEnds, ISOTIME, NULL),
391 V(BWHistoryReadInterval, UINT, "900"),
392 V(BWHistoryReadValues, CSV, ""),
393 V(BWHistoryWriteEnds, ISOTIME, NULL),
394 V(BWHistoryWriteInterval, UINT, "900"),
395 V(BWHistoryWriteValues, CSV, ""),
397 V(TorVersion, STRING, NULL),
399 V(LastRotatedOnionKey, ISOTIME, NULL),
400 V(LastWritten, ISOTIME, NULL),
402 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
405 #undef VAR
406 #undef V
407 #undef OBSOLETE
409 /** Represents an English description of a configuration variable; used when
410 * generating configuration file comments. */
411 typedef struct config_var_description_t {
412 const char *name;
413 const char *description;
414 } config_var_description_t;
416 /** Descriptions of the configuration options, to be displayed by online
417 * option browsers */
418 /* XXXX022 did anybody want this? at all? If not, kill it.*/
419 static config_var_description_t options_description[] = {
420 /* ==== general options */
421 { "AvoidDiskWrites", "If non-zero, try to write to disk less frequently than"
422 " we would otherwise." },
423 { "BandwidthRate", "A token bucket limits the average incoming bandwidth on "
424 "this node to the specified number of bytes per second." },
425 { "BandwidthBurst", "Limit the maximum token buffer size (also known as "
426 "burst) to the given number of bytes." },
427 { "ConnLimit", "Minimum number of simultaneous sockets we must have." },
428 { "ConstrainedSockets", "Shrink tx and rx buffers for sockets to avoid "
429 "system limits on vservers and related environments. See man page for "
430 "more information regarding this option." },
431 { "ConstrainedSockSize", "Limit socket buffers to this size when "
432 "ConstrainedSockets is enabled." },
433 /* ControlListenAddress */
434 { "ControlPort", "If set, Tor will accept connections from the same machine "
435 "(localhost only) on this port, and allow those connections to control "
436 "the Tor process using the Tor Control Protocol (described in "
437 "control-spec.txt).", },
438 { "CookieAuthentication", "If this option is set to 1, don't allow any "
439 "connections to the control port except when the connecting process "
440 "can read a file that Tor creates in its data directory." },
441 { "DataDirectory", "Store working data, state, keys, and caches here." },
442 { "DirServer", "Tor only trusts directories signed with one of these "
443 "servers' keys. Used to override the standard list of directory "
444 "authorities." },
445 /* { "FastFirstHopPK", "" }, */
446 /* FetchServerDescriptors, FetchHidServDescriptors,
447 * FetchUselessDescriptors */
448 { "HardwareAccel", "If set, Tor tries to use hardware crypto accelerators "
449 "when it can." },
450 /* HashedControlPassword */
451 { "HTTPProxy", "Force Tor to make all HTTP directory requests through this "
452 "host:port (or host:80 if port is not set)." },
453 { "HTTPProxyAuthenticator", "A username:password pair to be used with "
454 "HTTPProxy." },
455 { "HTTPSProxy", "Force Tor to make all TLS (SSL) connectinos through this "
456 "host:port (or host:80 if port is not set)." },
457 { "HTTPSProxyAuthenticator", "A username:password pair to be used with "
458 "HTTPSProxy." },
459 { "KeepalivePeriod", "Send a padding cell every N seconds to keep firewalls "
460 "from closing our connections while Tor is not in use." },
461 { "Log", "Where to send logging messages. Format is "
462 "minSeverity[-maxSeverity] (stderr|stdout|syslog|file FILENAME)." },
463 { "OutboundBindAddress", "Make all outbound connections originate from the "
464 "provided IP address (only useful for multiple network interfaces)." },
465 { "PIDFile", "On startup, write our PID to this file. On clean shutdown, "
466 "remove the file." },
467 { "PreferTunneledDirConns", "If non-zero, avoid directory servers that "
468 "don't support tunneled connections." },
469 /* PreferTunneledDirConns */
470 /* ProtocolWarnings */
471 /* RephistTrackTime */
472 { "RunAsDaemon", "If set, Tor forks and daemonizes to the background when "
473 "started. Unix only." },
474 { "SafeLogging", "If set to 0, Tor logs potentially sensitive strings "
475 "rather than replacing them with the string [scrubbed]." },
476 { "TunnelDirConns", "If non-zero, when a directory server we contact "
477 "supports it, we will build a one-hop circuit and make an encrypted "
478 "connection via its ORPort." },
479 { "User", "On startup, setuid to this user." },
481 /* ==== client options */
482 { "AllowInvalidNodes", "Where on our circuits should Tor allow servers "
483 "that the directory authorities haven't called \"valid\"?" },
484 { "AllowNonRFC953Hostnames", "If set to 1, we don't automatically reject "
485 "hostnames for having invalid characters." },
486 /* CircuitBuildTimeout, CircuitIdleTimeout */
487 { "ClientOnly", "If set to 1, Tor will under no circumstances run as a "
488 "server, even if ORPort is enabled." },
489 { "EntryNodes", "A list of preferred entry nodes to use for the first hop "
490 "in circuits, when possible." },
491 /* { "EnforceDistinctSubnets" , "" }, */
492 { "ExitNodes", "A list of preferred nodes to use for the last hop in "
493 "circuits, when possible." },
494 { "ExcludeNodes", "A list of nodes never to use when building a circuit." },
495 { "FascistFirewall", "If set, Tor will only create outgoing connections to "
496 "servers running on the ports listed in FirewallPorts." },
497 { "FirewallPorts", "A list of ports that we can connect to. Only used "
498 "when FascistFirewall is set." },
499 { "LongLivedPorts", "A list of ports for services that tend to require "
500 "high-uptime connections." },
501 { "MapAddress", "Force Tor to treat all requests for one address as if "
502 "they were for another." },
503 { "NewCircuitPeriod", "Force Tor to consider whether to build a new circuit "
504 "every NUM seconds." },
505 { "MaxCircuitDirtiness", "Do not attach new streams to a circuit that has "
506 "been used more than this many seconds ago." },
507 /* NatdPort, NatdListenAddress */
508 { "NodeFamily", "A list of servers that constitute a 'family' and should "
509 "never be used in the same circuit." },
510 { "NumEntryGuards", "How many entry guards should we keep at a time?" },
511 /* PathlenCoinWeight */
512 { "ReachableAddresses", "Addresses we can connect to, as IP/bits:port-port. "
513 "By default, we assume all addresses are reachable." },
514 /* reachablediraddresses, reachableoraddresses. */
515 /* SafeSOCKS */
516 { "SOCKSPort", "The port where we listen for SOCKS connections from "
517 "applications." },
518 { "SOCKSListenAddress", "Bind to this address to listen to connections from "
519 "SOCKS-speaking applications." },
520 { "SOCKSPolicy", "Set an entry policy to limit which addresses can connect "
521 "to the SOCKSPort." },
522 /* SocksTimeout */
523 { "StrictExitNodes", "If set, Tor will fail to operate when none of the "
524 "configured ExitNodes can be used." },
525 { "StrictEntryNodes", "If set, Tor will fail to operate when none of the "
526 "configured EntryNodes can be used." },
527 /* TestSocks */
528 { "TrackHostsExit", "Hosts and domains which should, if possible, be "
529 "accessed from the same exit node each time we connect to them." },
530 { "TrackHostsExitExpire", "Time after which we forget which exit we were "
531 "using to connect to hosts in TrackHostsExit." },
532 /* "TransPort", "TransListenAddress */
533 { "UseEntryGuards", "Set to 0 if we want to pick from the whole set of "
534 "servers for the first position in each circuit, rather than picking a "
535 "set of 'Guards' to prevent profiling attacks." },
537 /* === server options */
538 { "Address", "The advertised (external) address we should use." },
539 /* Accounting* options. */
540 /* AssumeReachable */
541 { "ContactInfo", "Administrative contact information to advertise for this "
542 "server." },
543 { "ExitPolicy", "Address/port ranges for which to accept or reject outgoing "
544 "connections on behalf of Tor users." },
545 /* { "ExitPolicyRejectPrivate, "" }, */
546 { "MaxAdvertisedBandwidth", "If set, we will not advertise more than this "
547 "amount of bandwidth for our bandwidth rate, regardless of how much "
548 "bandwidth we actually detect." },
549 { "MaxOnionsPending", "Reject new attempts to extend circuits when we "
550 "already have this many pending." },
551 { "MyFamily", "Declare a list of other servers as belonging to the same "
552 "family as this one, so that clients will not use two from the same "
553 "family in the same circuit." },
554 { "Nickname", "Set the server nickname." },
555 { "NoPublish", "{DEPRECATED}" },
556 { "NumCPUs", "How many processes to use at once for public-key crypto." },
557 { "ORPort", "Advertise this port to listen for connections from Tor clients "
558 "and servers." },
559 { "ORListenAddress", "Bind to this address to listen for connections from "
560 "clients and servers, instead of the default 0.0.0.0:ORPort." },
561 { "PublishServerDescriptor", "Set to 0 to keep the server from "
562 "uploading info to the directory authorities." },
563 /* ServerDNS: DetectHijacking, ResolvConfFile, SearchDomains */
564 { "ShutdownWaitLength", "Wait this long for clients to finish when "
565 "shutting down because of a SIGINT." },
567 /* === directory cache options */
568 { "DirPort", "Serve directory information from this port, and act as a "
569 "directory cache." },
570 { "DirPortFrontPage", "Serve a static html disclaimer on DirPort." },
571 { "DirListenAddress", "Bind to this address to listen for connections from "
572 "clients and servers, instead of the default 0.0.0.0:DirPort." },
573 { "DirPolicy", "Set a policy to limit who can connect to the directory "
574 "port." },
576 /* Authority options: AuthDirBadExit, AuthDirInvalid, AuthDirReject,
577 * AuthDirRejectUnlisted, AuthDirListBadExits, AuthoritativeDirectory,
578 * DirAllowPrivateAddresses, HSAuthoritativeDir,
579 * NamingAuthoritativeDirectory, RecommendedVersions,
580 * RecommendedClientVersions, RecommendedServerVersions, RendPostPeriod,
581 * RunTesting, V1AuthoritativeDirectory, VersioningAuthoritativeDirectory, */
583 /* Hidden service options: HiddenService: dir,excludenodes, nodes,
584 * options, port. PublishHidServDescriptor */
586 /* Nonpersistent options: __LeaveStreamsUnattached, __AllDirActionsPrivate */
587 { NULL, NULL },
590 /** Online description of state variables. */
591 static config_var_description_t state_description[] = {
592 { "AccountingBytesReadInInterval",
593 "How many bytes have we read in this accounting period?" },
594 { "AccountingBytesWrittenInInterval",
595 "How many bytes have we written in this accounting period?" },
596 { "AccountingExpectedUsage",
597 "How many bytes did we expect to use per minute? (0 for no estimate.)" },
598 { "AccountingIntervalStart", "When did this accounting period begin?" },
599 { "AccountingSecondsActive", "How long have we been awake in this period?" },
601 { "BWHistoryReadEnds", "When does the last-recorded read-interval end?" },
602 { "BWHistoryReadInterval", "How long is each read-interval (in seconds)?" },
603 { "BWHistoryReadValues", "Number of bytes read in each interval." },
604 { "BWHistoryWriteEnds", "When does the last-recorded write-interval end?" },
605 { "BWHistoryWriteInterval", "How long is each write-interval (in seconds)?"},
606 { "BWHistoryWriteValues", "Number of bytes written in each interval." },
608 { "EntryGuard", "One of the nodes we have chosen as a fixed entry" },
609 { "EntryGuardDownSince",
610 "The last entry guard has been unreachable since this time." },
611 { "EntryGuardUnlistedSince",
612 "The last entry guard has been unusable since this time." },
614 { "LastRotatedOnionKey",
615 "The last time at which we changed the medium-term private key used for "
616 "building circuits." },
617 { "LastWritten", "When was this state file last regenerated?" },
619 { "TorVersion", "Which version of Tor generated this state file?" },
620 { NULL, NULL },
623 /** Type of a callback to validate whether a given configuration is
624 * well-formed and consistent. See options_trial_assign() for documentation
625 * of arguments. */
626 typedef int (*validate_fn_t)(void*,void*,int,char**);
628 /** Information on the keys, value types, key-to-struct-member mappings,
629 * variable descriptions, validation functions, and abbreviations for a
630 * configuration or storage format. */
631 typedef struct {
632 size_t size; /**< Size of the struct that everything gets parsed into. */
633 uint32_t magic; /**< Required 'magic value' to make sure we have a struct
634 * of the right type. */
635 off_t magic_offset; /**< Offset of the magic value within the struct. */
636 config_abbrev_t *abbrevs; /**< List of abbreviations that we expand when
637 * parsing this format. */
638 config_var_t *vars; /**< List of variables we recognize, their default
639 * values, and where we stick them in the structure. */
640 validate_fn_t validate_fn; /**< Function to validate config. */
641 /** Documentation for configuration variables. */
642 config_var_description_t *descriptions;
643 /** If present, extra is a LINELIST variable for unrecognized
644 * lines. Otherwise, unrecognized lines are an error. */
645 config_var_t *extra;
646 } config_format_t;
648 /** Macro: assert that <b>cfg</b> has the right magic field for format
649 * <b>fmt</b>. */
650 #define CHECK(fmt, cfg) STMT_BEGIN \
651 tor_assert(fmt && cfg); \
652 tor_assert((fmt)->magic == \
653 *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
654 STMT_END
656 #ifdef MS_WINDOWS
657 static char *get_windows_conf_root(void);
658 #endif
659 static void config_line_append(config_line_t **lst,
660 const char *key, const char *val);
661 static void option_clear(config_format_t *fmt, or_options_t *options,
662 config_var_t *var);
663 static void option_reset(config_format_t *fmt, or_options_t *options,
664 config_var_t *var, int use_defaults);
665 static void config_free(config_format_t *fmt, void *options);
666 static int config_lines_eq(config_line_t *a, config_line_t *b);
667 static int option_is_same(config_format_t *fmt,
668 or_options_t *o1, or_options_t *o2,
669 const char *name);
670 static or_options_t *options_dup(config_format_t *fmt, or_options_t *old);
671 static int options_validate(or_options_t *old_options, or_options_t *options,
672 int from_setconf, char **msg);
673 static int options_act_reversible(or_options_t *old_options, char **msg);
674 static int options_act(or_options_t *old_options);
675 static int options_transition_allowed(or_options_t *old, or_options_t *new,
676 char **msg);
677 static int options_transition_affects_workers(or_options_t *old_options,
678 or_options_t *new_options);
679 static int options_transition_affects_descriptor(or_options_t *old_options,
680 or_options_t *new_options);
681 static int check_nickname_list(const char *lst, const char *name, char **msg);
682 static void config_register_addressmaps(or_options_t *options);
684 static int parse_bridge_line(const char *line, int validate_only);
685 static int parse_dir_server_line(const char *line,
686 authority_type_t required_type,
687 int validate_only);
688 static int validate_data_directory(or_options_t *options);
689 static int write_configuration_file(const char *fname, or_options_t *options);
690 static config_line_t *get_assigned_option(config_format_t *fmt,
691 or_options_t *options, const char *key,
692 int escape_val);
693 static void config_init(config_format_t *fmt, void *options);
694 static int or_state_validate(or_state_t *old_options, or_state_t *options,
695 int from_setconf, char **msg);
696 static int or_state_load(void);
697 static int options_init_logs(or_options_t *options, int validate_only);
699 static uint64_t config_parse_memunit(const char *s, int *ok);
700 static int config_parse_interval(const char *s, int *ok);
701 static void print_svn_version(void);
702 static void init_libevent(void);
703 static int opt_streq(const char *s1, const char *s2);
704 /** Versions of libevent. */
705 typedef enum {
706 /* Note: we compare these, so it's important that "old" precede everything,
707 * and that "other" come last. */
708 LE_OLD=0, LE_10C, LE_10D, LE_10E, LE_11, LE_11A, LE_11B, LE_12, LE_12A,
709 LE_13, LE_13A, LE_13B, LE_13C, LE_13D,
710 LE_OTHER
711 } le_version_t;
712 static le_version_t decode_libevent_version(void);
713 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
714 static void check_libevent_version(const char *m, int server);
715 #endif
717 /** Magic value for or_options_t. */
718 #define OR_OPTIONS_MAGIC 9090909
720 /** Configuration format for or_options_t. */
721 static config_format_t options_format = {
722 sizeof(or_options_t),
723 OR_OPTIONS_MAGIC,
724 STRUCT_OFFSET(or_options_t, _magic),
725 _option_abbrevs,
726 _option_vars,
727 (validate_fn_t)options_validate,
728 options_description,
729 NULL
732 /** Magic value for or_state_t. */
733 #define OR_STATE_MAGIC 0x57A73f57
735 /** "Extra" variable in the state that receives lines we can't parse. This
736 * lets us preserve options from versions of Tor newer than us. */
737 static config_var_t state_extra_var = {
738 "__extra", CONFIG_TYPE_LINELIST, STRUCT_OFFSET(or_state_t, ExtraLines), NULL
741 /** Configuration format for or_state_t. */
742 static config_format_t state_format = {
743 sizeof(or_state_t),
744 OR_STATE_MAGIC,
745 STRUCT_OFFSET(or_state_t, _magic),
746 _state_abbrevs,
747 _state_vars,
748 (validate_fn_t)or_state_validate,
749 state_description,
750 &state_extra_var,
754 * Functions to read and write the global options pointer.
757 /** Command-line and config-file options. */
758 static or_options_t *global_options = NULL;
759 /** Name of most recently read torrc file. */
760 static char *torrc_fname = NULL;
761 /** Persistent serialized state. */
762 static or_state_t *global_state = NULL;
763 /** Configuration Options set by command line. */
764 static config_line_t *global_cmdline_options = NULL;
765 /** Contents of most recently read DirPortFrontPage file. */
766 static char *global_dirfrontpagecontents = NULL;
768 /** Return the contents of our frontpage string, or NULL if not configured. */
769 const char *
770 get_dirportfrontpage(void)
772 return global_dirfrontpagecontents;
775 /** Allocate an empty configuration object of a given format type. */
776 static void *
777 config_alloc(config_format_t *fmt)
779 void *opts = tor_malloc_zero(fmt->size);
780 *(uint32_t*)STRUCT_VAR_P(opts, fmt->magic_offset) = fmt->magic;
781 CHECK(fmt, opts);
782 return opts;
785 /** Return the currently configured options. */
786 or_options_t *
787 get_options(void)
789 tor_assert(global_options);
790 return global_options;
793 /** Change the current global options to contain <b>new_val</b> instead of
794 * their current value; take action based on the new value; free the old value
795 * as necessary. Returns 0 on success, -1 on failure.
798 set_options(or_options_t *new_val, char **msg)
800 or_options_t *old_options = global_options;
801 global_options = new_val;
802 /* Note that we pass the *old* options below, for comparison. It
803 * pulls the new options directly out of global_options. */
804 if (options_act_reversible(old_options, msg)<0) {
805 tor_assert(*msg);
806 global_options = old_options;
807 return -1;
809 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
810 log_err(LD_BUG,
811 "Acting on config options left us in a broken state. Dying.");
812 exit(1);
814 if (old_options)
815 config_free(&options_format, old_options);
817 return 0;
820 extern const char tor_svn_revision[]; /* from tor_main.c */
822 /** The version of this Tor process, as parsed. */
823 static char *_version = NULL;
825 /** Return the current Tor version. */
826 const char *
827 get_version(void)
829 if (_version == NULL) {
830 if (strlen(tor_svn_revision)) {
831 size_t len = strlen(VERSION)+strlen(tor_svn_revision)+8;
832 _version = tor_malloc(len);
833 tor_snprintf(_version, len, "%s (r%s)", VERSION, tor_svn_revision);
834 } else {
835 _version = tor_strdup(VERSION);
838 return _version;
841 /** Release additional memory allocated in options
843 static void
844 or_options_free(or_options_t *options)
846 if (options->_ExcludeExitNodesUnion)
847 routerset_free(options->_ExcludeExitNodesUnion);
848 config_free(&options_format, options);
851 /** Release all memory and resources held by global configuration structures.
853 void
854 config_free_all(void)
856 if (global_options) {
857 or_options_free(global_options);
858 global_options = NULL;
860 if (global_state) {
861 config_free(&state_format, global_state);
862 global_state = NULL;
864 if (global_cmdline_options) {
865 config_free_lines(global_cmdline_options);
866 global_cmdline_options = NULL;
868 tor_free(torrc_fname);
869 tor_free(_version);
870 tor_free(global_dirfrontpagecontents);
873 /** If options->SafeLogging is on, return a not very useful string,
874 * else return address.
876 const char *
877 safe_str(const char *address)
879 tor_assert(address);
880 if (get_options()->SafeLogging)
881 return "[scrubbed]";
882 else
883 return address;
886 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
887 * escaped(): don't use this outside the main thread, or twice in the same
888 * log statement. */
889 const char *
890 escaped_safe_str(const char *address)
892 if (get_options()->SafeLogging)
893 return "[scrubbed]";
894 else
895 return escaped(address);
898 /** Add the default directory authorities directly into the trusted dir list,
899 * but only add them insofar as they share bits with <b>type</b>. */
900 static void
901 add_default_trusted_dir_authorities(authority_type_t type)
903 int i;
904 const char *dirservers[] = {
905 "moria1 v1 orport=9001 v3ident=E2A2AF570166665D738736D0DD58169CC61D8A8B "
906 "128.31.0.34:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441",
907 "moria2 v1 orport=9002 128.31.0.34:9032 "
908 "719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF",
909 "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
910 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
911 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
912 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
913 "Tonga orport=443 bridge no-v2 82.94.251.206:80 "
914 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
915 "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
916 "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
917 "gabelmoo orport=443 no-v2 "
918 "v3ident=81349FC1F2DBA2C2C11B45CB9706637D480AB913 "
919 "80.190.246.100:80 6833 3D07 61BC F397 A587 A0C0 B963 E4A9 E99E C4D3",
920 "dannenberg orport=443 no-v2 "
921 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
922 "213.73.91.31:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
923 NULL
925 for (i=0; dirservers[i]; i++) {
926 if (parse_dir_server_line(dirservers[i], type, 0)<0) {
927 log_err(LD_BUG, "Couldn't parse internal dirserver line %s",
928 dirservers[i]);
933 /** Look at all the config options for using alternate directory
934 * authorities, and make sure none of them are broken. Also, warn the
935 * user if we changed any dangerous ones.
937 static int
938 validate_dir_authorities(or_options_t *options, or_options_t *old_options)
940 config_line_t *cl;
942 if (options->DirServers &&
943 (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
944 options->AlternateHSAuthority)) {
945 log_warn(LD_CONFIG,
946 "You cannot set both DirServers and Alternate*Authority.");
947 return -1;
950 /* do we want to complain to the user about being partitionable? */
951 if ((options->DirServers &&
952 (!old_options ||
953 !config_lines_eq(options->DirServers, old_options->DirServers))) ||
954 (options->AlternateDirAuthority &&
955 (!old_options ||
956 !config_lines_eq(options->AlternateDirAuthority,
957 old_options->AlternateDirAuthority)))) {
958 log_warn(LD_CONFIG,
959 "You have used DirServer or AlternateDirAuthority to "
960 "specify alternate directory authorities in "
961 "your configuration. This is potentially dangerous: it can "
962 "make you look different from all other Tor users, and hurt "
963 "your anonymity. Even if you've specified the same "
964 "authorities as Tor uses by default, the defaults could "
965 "change in the future. Be sure you know what you're doing.");
968 /* Now go through the four ways you can configure an alternate
969 * set of directory authorities, and make sure none are broken. */
970 for (cl = options->DirServers; cl; cl = cl->next)
971 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
972 return -1;
973 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
974 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
975 return -1;
976 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
977 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
978 return -1;
979 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
980 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
981 return -1;
982 return 0;
985 /** Look at all the config options and assign new dir authorities
986 * as appropriate.
988 static int
989 consider_adding_dir_authorities(or_options_t *options,
990 or_options_t *old_options)
992 config_line_t *cl;
993 int need_to_update =
994 !smartlist_len(router_get_trusted_dir_servers()) || !old_options ||
995 !config_lines_eq(options->DirServers, old_options->DirServers) ||
996 !config_lines_eq(options->AlternateBridgeAuthority,
997 old_options->AlternateBridgeAuthority) ||
998 !config_lines_eq(options->AlternateDirAuthority,
999 old_options->AlternateDirAuthority) ||
1000 !config_lines_eq(options->AlternateHSAuthority,
1001 old_options->AlternateHSAuthority);
1003 if (!need_to_update)
1004 return 0; /* all done */
1006 /* Start from a clean slate. */
1007 clear_trusted_dir_servers();
1009 if (!options->DirServers) {
1010 /* then we may want some of the defaults */
1011 authority_type_t type = NO_AUTHORITY;
1012 if (!options->AlternateBridgeAuthority)
1013 type |= BRIDGE_AUTHORITY;
1014 if (!options->AlternateDirAuthority)
1015 type |= V1_AUTHORITY | V2_AUTHORITY | V3_AUTHORITY;
1016 if (!options->AlternateHSAuthority)
1017 type |= HIDSERV_AUTHORITY;
1018 add_default_trusted_dir_authorities(type);
1021 for (cl = options->DirServers; cl; cl = cl->next)
1022 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1023 return -1;
1024 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1025 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1026 return -1;
1027 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1028 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1029 return -1;
1030 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
1031 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1032 return -1;
1033 return 0;
1036 /** Fetch the active option list, and take actions based on it. All of the
1037 * things we do should survive being done repeatedly. If present,
1038 * <b>old_options</b> contains the previous value of the options.
1040 * Return 0 if all goes well, return -1 if things went badly.
1042 static int
1043 options_act_reversible(or_options_t *old_options, char **msg)
1045 smartlist_t *new_listeners = smartlist_create();
1046 smartlist_t *replaced_listeners = smartlist_create();
1047 static int libevent_initialized = 0;
1048 or_options_t *options = get_options();
1049 int running_tor = options->command == CMD_RUN_TOR;
1050 int set_conn_limit = 0;
1051 int r = -1;
1052 int logs_marked = 0;
1054 /* Daemonize _first_, since we only want to open most of this stuff in
1055 * the subprocess. Libevent bases can't be reliably inherited across
1056 * processes. */
1057 if (running_tor && options->RunAsDaemon) {
1058 /* No need to roll back, since you can't change the value. */
1059 start_daemon();
1062 #ifndef HAVE_SYS_UN_H
1063 if (options->ControlSocket) {
1064 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported"
1065 " on this OS/with this build.");
1066 goto rollback;
1068 #endif
1070 if (running_tor) {
1071 /* We need to set the connection limit before we can open the listeners. */
1072 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1073 &options->_ConnLimit) < 0) {
1074 *msg = tor_strdup("Problem with ConnLimit value. See logs for details.");
1075 goto rollback;
1077 set_conn_limit = 1;
1079 /* Set up libevent. (We need to do this before we can register the
1080 * listeners as listeners.) */
1081 if (running_tor && !libevent_initialized) {
1082 init_libevent();
1083 libevent_initialized = 1;
1086 /* Launch the listeners. (We do this before we setuid, so we can bind to
1087 * ports under 1024.) */
1088 if (retry_all_listeners(replaced_listeners, new_listeners) < 0) {
1089 *msg = tor_strdup("Failed to bind one of the listener ports.");
1090 goto rollback;
1094 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1095 /* Open /dev/pf before dropping privileges. */
1096 if (options->TransPort) {
1097 if (get_pf_socket() < 0) {
1098 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1099 goto rollback;
1102 #endif
1104 /* Setuid/setgid as appropriate */
1105 if (options->User) {
1106 if (switch_id(options->User) != 0) {
1107 /* No need to roll back, since you can't change the value. */
1108 *msg = tor_strdup("Problem with User value. See logs for details.");
1109 goto done;
1113 /* Ensure data directory is private; create if possible. */
1114 if (check_private_dir(options->DataDirectory,
1115 running_tor ? CPD_CREATE : CPD_CHECK)<0) {
1116 char buf[1024];
1117 int tmp = tor_snprintf(buf, sizeof(buf),
1118 "Couldn't access/create private data directory \"%s\"",
1119 options->DataDirectory);
1120 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1121 goto done;
1122 /* No need to roll back, since you can't change the value. */
1125 if (directory_caches_v2_dir_info(options)) {
1126 size_t len = strlen(options->DataDirectory)+32;
1127 char *fn = tor_malloc(len);
1128 tor_snprintf(fn, len, "%s"PATH_SEPARATOR"cached-status",
1129 options->DataDirectory);
1130 if (check_private_dir(fn, running_tor ? CPD_CREATE : CPD_CHECK) < 0) {
1131 char buf[1024];
1132 int tmp = tor_snprintf(buf, sizeof(buf),
1133 "Couldn't access/create private data directory \"%s\"", fn);
1134 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1135 tor_free(fn);
1136 goto done;
1138 tor_free(fn);
1141 /* Bail out at this point if we're not going to be a client or server:
1142 * we don't run Tor itself. */
1143 if (!running_tor)
1144 goto commit;
1146 mark_logs_temp(); /* Close current logs once new logs are open. */
1147 logs_marked = 1;
1148 if (options_init_logs(options, 0)<0) { /* Configure the log(s) */
1149 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1150 goto rollback;
1153 commit:
1154 r = 0;
1155 if (logs_marked) {
1156 log_severity_list_t *severity =
1157 tor_malloc_zero(sizeof(log_severity_list_t));
1158 close_temp_logs();
1159 add_callback_log(severity, control_event_logmsg);
1160 control_adjust_event_log_severity();
1161 tor_free(severity);
1163 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1165 log_notice(LD_NET, "Closing old %s on %s:%d",
1166 conn_type_to_string(conn->type), conn->address, conn->port);
1167 connection_close_immediate(conn);
1168 connection_mark_for_close(conn);
1170 goto done;
1172 rollback:
1173 r = -1;
1174 tor_assert(*msg);
1176 if (logs_marked) {
1177 rollback_log_changes();
1178 control_adjust_event_log_severity();
1181 if (set_conn_limit && old_options)
1182 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1183 &options->_ConnLimit);
1185 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1187 log_notice(LD_NET, "Closing partially-constructed listener %s on %s:%d",
1188 conn_type_to_string(conn->type), conn->address, conn->port);
1189 connection_close_immediate(conn);
1190 connection_mark_for_close(conn);
1193 done:
1194 smartlist_free(new_listeners);
1195 smartlist_free(replaced_listeners);
1196 return r;
1199 /** If we need to have a GEOIP ip-to-country map to run with our configured
1200 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1202 options_need_geoip_info(or_options_t *options, const char **reason_out)
1204 int bridge_usage =
1205 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1206 int routerset_usage =
1207 routerset_needs_geoip(options->EntryNodes) ||
1208 routerset_needs_geoip(options->ExitNodes) ||
1209 routerset_needs_geoip(options->ExcludeExitNodes) ||
1210 routerset_needs_geoip(options->ExcludeNodes);
1212 if (routerset_usage && reason_out) {
1213 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1214 "contries, and we need GEOIP information to figure out which ones they "
1215 "are.";
1216 } else if (bridge_usage && reason_out) {
1217 *reason_out = "We've been configured to see which countries can access "
1218 "us as a bridge, and we need GEOIP information to tell which countries "
1219 "clients are in.";
1221 return bridge_usage || routerset_usage;
1224 /** Fetch the active option list, and take actions based on it. All of the
1225 * things we do should survive being done repeatedly. If present,
1226 * <b>old_options</b> contains the previous value of the options.
1228 * Return 0 if all goes well, return -1 if it's time to die.
1230 * Note: We haven't moved all the "act on new configuration" logic
1231 * here yet. Some is still in do_hup() and other places.
1233 static int
1234 options_act(or_options_t *old_options)
1236 config_line_t *cl;
1237 or_options_t *options = get_options();
1238 int running_tor = options->command == CMD_RUN_TOR;
1239 char *msg;
1241 if (running_tor && !have_lockfile()) {
1242 if (try_locking(options, 1) < 0)
1243 return -1;
1246 if (consider_adding_dir_authorities(options, old_options) < 0)
1247 return -1;
1249 if (options->Bridges) {
1250 clear_bridge_list();
1251 for (cl = options->Bridges; cl; cl = cl->next) {
1252 if (parse_bridge_line(cl->value, 0)<0) {
1253 log_warn(LD_BUG,
1254 "Previously validated Bridge line could not be added!");
1255 return -1;
1260 if (running_tor && rend_config_services(options, 0)<0) {
1261 log_warn(LD_BUG,
1262 "Previously validated hidden services line could not be added!");
1263 return -1;
1266 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1267 log_warn(LD_BUG, "Previously validated client authorization for "
1268 "hidden services could not be added!");
1269 return -1;
1272 /* Load state */
1273 if (! global_state && running_tor) {
1274 if (or_state_load())
1275 return -1;
1276 rep_hist_load_mtbf_data(time(NULL));
1279 /* Bail out at this point if we're not going to be a client or server:
1280 * we want to not fork, and to log stuff to stderr. */
1281 if (!running_tor)
1282 return 0;
1284 /* Finish backgrounding the process */
1285 if (running_tor && options->RunAsDaemon) {
1286 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1287 finish_daemon(options->DataDirectory);
1290 /* Write our pid to the pid file. If we do not have write permissions we
1291 * will log a warning */
1292 if (running_tor && options->PidFile)
1293 write_pidfile(options->PidFile);
1295 /* Register addressmap directives */
1296 config_register_addressmaps(options);
1297 parse_virtual_addr_network(options->VirtualAddrNetwork, 0, &msg);
1299 /* Update address policies. */
1300 if (policies_parse_from_options(options) < 0) {
1301 /* This should be impossible, but let's be sure. */
1302 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1303 return -1;
1306 if (init_cookie_authentication(options->CookieAuthentication) < 0) {
1307 log_warn(LD_CONFIG,"Error creating cookie authentication file.");
1308 return -1;
1311 /* reload keys as needed for rendezvous services. */
1312 if (rend_service_load_keys()<0) {
1313 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1314 return -1;
1317 /* Set up accounting */
1318 if (accounting_parse_options(options, 0)<0) {
1319 log_warn(LD_CONFIG,"Error in accounting options");
1320 return -1;
1322 if (accounting_is_enabled(options))
1323 configure_accounting(time(NULL));
1325 /* Check for transitions that need action. */
1326 if (old_options) {
1327 if (options->UseEntryGuards && !old_options->UseEntryGuards) {
1328 log_info(LD_CIRC,
1329 "Switching to entry guards; abandoning previous circuits");
1330 circuit_mark_all_unused_circs();
1331 circuit_expire_all_dirty_circs();
1334 if (options_transition_affects_workers(old_options, options)) {
1335 log_info(LD_GENERAL,
1336 "Worker-related options changed. Rotating workers.");
1337 if (server_mode(options) && !server_mode(old_options)) {
1338 if (init_keys() < 0) {
1339 log_warn(LD_BUG,"Error initializing keys; exiting");
1340 return -1;
1342 ip_address_changed(0);
1343 if (has_completed_circuit || !any_predicted_circuits(time(NULL)))
1344 inform_testing_reachability();
1346 cpuworkers_rotate();
1347 if (dns_reset())
1348 return -1;
1349 } else {
1350 if (dns_reset())
1351 return -1;
1354 if (options->V3AuthoritativeDir && !old_options->V3AuthoritativeDir)
1355 init_keys();
1358 /* Maybe load geoip file */
1359 if (options->GeoIPFile &&
1360 ((!old_options || !opt_streq(old_options->GeoIPFile, options->GeoIPFile))
1361 || !geoip_is_loaded())) {
1362 /* XXXX Don't use this "<default>" junk; make our filename options
1363 * understand prefixes somehow. -NM */
1364 /* XXXX021 Reload GeoIPFile on SIGHUP. -NM */
1365 char *actual_fname = tor_strdup(options->GeoIPFile);
1366 #ifdef WIN32
1367 if (!strcmp(actual_fname, "<default>")) {
1368 const char *conf_root = get_windows_conf_root();
1369 size_t len = strlen(conf_root)+16;
1370 tor_free(actual_fname);
1371 actual_fname = tor_malloc(len+1);
1372 tor_snprintf(actual_fname, len, "%s\\geoip", conf_root);
1374 #endif
1375 geoip_load_file(actual_fname, options);
1376 tor_free(actual_fname);
1378 /* XXXX Would iterating through all option_var's routersets be better? */
1379 if (options->EntryNodes)
1380 routerset_refresh_countries(options->EntryNodes);
1381 if (options->ExitNodes)
1382 routerset_refresh_countries(options->ExitNodes);
1383 if (options->ExcludeNodes)
1384 routerset_refresh_countries(options->ExcludeNodes);
1385 if (options->ExcludeExitNodes)
1386 routerset_refresh_countries(options->ExcludeExitNodes);
1387 routerlist_refresh_countries();
1389 /* Check if we need to parse and add the EntryNodes config option. */
1390 if (options->EntryNodes &&
1391 (!old_options ||
1392 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
1393 entry_nodes_should_be_added();
1395 /* Since our options changed, we might need to regenerate and upload our
1396 * server descriptor.
1398 if (!old_options ||
1399 options_transition_affects_descriptor(old_options, options))
1400 mark_my_descriptor_dirty();
1402 /* We may need to reschedule some directory stuff if our status changed. */
1403 if (old_options) {
1404 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1405 dirvote_recalculate_timing(options, time(NULL));
1406 if (!bool_eq(directory_fetches_dir_info_early(options),
1407 directory_fetches_dir_info_early(old_options)) ||
1408 !bool_eq(directory_fetches_dir_info_later(options),
1409 directory_fetches_dir_info_later(old_options))) {
1410 /* Make sure update_router_have_min_dir_info gets called. */
1411 router_dir_info_changed();
1412 /* We might need to download a new consensus status later or sooner than
1413 * we had expected. */
1414 update_consensus_networkstatus_fetch_time(time(NULL));
1418 /* Load the webpage we're going to serve everytime someone asks for '/' on
1419 our DirPort. */
1420 tor_free(global_dirfrontpagecontents);
1421 if (options->DirPortFrontPage) {
1422 global_dirfrontpagecontents =
1423 read_file_to_str(options->DirPortFrontPage, 0, NULL);
1424 if (!global_dirfrontpagecontents) {
1425 log_warn(LD_CONFIG,
1426 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1427 options->DirPortFrontPage);
1431 return 0;
1435 * Functions to parse config options
1438 /** If <b>option</b> is an official abbreviation for a longer option,
1439 * return the longer option. Otherwise return <b>option</b>.
1440 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1441 * apply abbreviations that work for the config file and the command line.
1442 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1443 static const char *
1444 expand_abbrev(config_format_t *fmt, const char *option, int command_line,
1445 int warn_obsolete)
1447 int i;
1448 if (! fmt->abbrevs)
1449 return option;
1450 for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
1451 /* Abbreviations are casei. */
1452 if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
1453 (command_line || !fmt->abbrevs[i].commandline_only)) {
1454 if (warn_obsolete && fmt->abbrevs[i].warn) {
1455 log_warn(LD_CONFIG,
1456 "The configuration option '%s' is deprecated; "
1457 "use '%s' instead.",
1458 fmt->abbrevs[i].abbreviated,
1459 fmt->abbrevs[i].full);
1461 return fmt->abbrevs[i].full;
1464 return option;
1467 /** Helper: Read a list of configuration options from the command line.
1468 * If successful, put them in *<b>result</b> and return 0, and return
1469 * -1 and leave *<b>result</b> alone. */
1470 static int
1471 config_get_commandlines(int argc, char **argv, config_line_t **result)
1473 config_line_t *front = NULL;
1474 config_line_t **new = &front;
1475 char *s;
1476 int i = 1;
1478 while (i < argc) {
1479 if (!strcmp(argv[i],"-f") ||
1480 !strcmp(argv[i],"--hash-password")) {
1481 i += 2; /* command-line option with argument. ignore them. */
1482 continue;
1483 } else if (!strcmp(argv[i],"--list-fingerprint") ||
1484 !strcmp(argv[i],"--verify-config") ||
1485 !strcmp(argv[i],"--ignore-missing-torrc") ||
1486 !strcmp(argv[i],"--quiet") ||
1487 !strcmp(argv[i],"--hush")) {
1488 i += 1; /* command-line option. ignore it. */
1489 continue;
1490 } else if (!strcmp(argv[i],"--nt-service") ||
1491 !strcmp(argv[i],"-nt-service")) {
1492 i += 1;
1493 continue;
1496 if (i == argc-1) {
1497 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1498 argv[i]);
1499 config_free_lines(front);
1500 return -1;
1503 *new = tor_malloc_zero(sizeof(config_line_t));
1504 s = argv[i];
1506 while (*s == '-')
1507 s++;
1509 (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1, 1));
1510 (*new)->value = tor_strdup(argv[i+1]);
1511 (*new)->next = NULL;
1512 log(LOG_DEBUG, LD_CONFIG, "Commandline: parsed keyword '%s', value '%s'",
1513 (*new)->key, (*new)->value);
1515 new = &((*new)->next);
1516 i += 2;
1518 *result = front;
1519 return 0;
1522 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1523 * append it to *<b>lst</b>. */
1524 static void
1525 config_line_append(config_line_t **lst,
1526 const char *key,
1527 const char *val)
1529 config_line_t *newline;
1531 newline = tor_malloc(sizeof(config_line_t));
1532 newline->key = tor_strdup(key);
1533 newline->value = tor_strdup(val);
1534 newline->next = NULL;
1535 while (*lst)
1536 lst = &((*lst)->next);
1538 (*lst) = newline;
1541 /** Helper: parse the config string and strdup into key/value
1542 * strings. Set *result to the list, or NULL if parsing the string
1543 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1544 * misformatted lines. */
1546 config_get_lines(const char *string, config_line_t **result)
1548 config_line_t *list = NULL, **next;
1549 char *k, *v;
1551 next = &list;
1552 do {
1553 k = v = NULL;
1554 string = parse_config_line_from_str(string, &k, &v);
1555 if (!string) {
1556 config_free_lines(list);
1557 tor_free(k);
1558 tor_free(v);
1559 return -1;
1561 if (k && v) {
1562 /* This list can get long, so we keep a pointer to the end of it
1563 * rather than using config_line_append over and over and getting
1564 * n^2 performance. */
1565 *next = tor_malloc(sizeof(config_line_t));
1566 (*next)->key = k;
1567 (*next)->value = v;
1568 (*next)->next = NULL;
1569 next = &((*next)->next);
1570 } else {
1571 tor_free(k);
1572 tor_free(v);
1574 } while (*string);
1576 *result = list;
1577 return 0;
1581 * Free all the configuration lines on the linked list <b>front</b>.
1583 void
1584 config_free_lines(config_line_t *front)
1586 config_line_t *tmp;
1588 while (front) {
1589 tmp = front;
1590 front = tmp->next;
1592 tor_free(tmp->key);
1593 tor_free(tmp->value);
1594 tor_free(tmp);
1598 /** Return the description for a given configuration variable, or NULL if no
1599 * description exists. */
1600 static const char *
1601 config_find_description(config_format_t *fmt, const char *name)
1603 int i;
1604 for (i=0; fmt->descriptions[i].name; ++i) {
1605 if (!strcasecmp(name, fmt->descriptions[i].name))
1606 return fmt->descriptions[i].description;
1608 return NULL;
1611 /** If <b>key</b> is a configuration option, return the corresponding
1612 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1613 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1615 static config_var_t *
1616 config_find_option(config_format_t *fmt, const char *key)
1618 int i;
1619 size_t keylen = strlen(key);
1620 if (!keylen)
1621 return NULL; /* if they say "--" on the commandline, it's not an option */
1622 /* First, check for an exact (case-insensitive) match */
1623 for (i=0; fmt->vars[i].name; ++i) {
1624 if (!strcasecmp(key, fmt->vars[i].name)) {
1625 return &fmt->vars[i];
1628 /* If none, check for an abbreviated match */
1629 for (i=0; fmt->vars[i].name; ++i) {
1630 if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
1631 log_warn(LD_CONFIG, "The abbreviation '%s' is deprecated. "
1632 "Please use '%s' instead",
1633 key, fmt->vars[i].name);
1634 return &fmt->vars[i];
1637 /* Okay, unrecognized option */
1638 return NULL;
1642 * Functions to assign config options.
1645 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1646 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1648 * Called from config_assign_line() and option_reset().
1650 static int
1651 config_assign_value(config_format_t *fmt, or_options_t *options,
1652 config_line_t *c, char **msg)
1654 int i, r, ok;
1655 char buf[1024];
1656 config_var_t *var;
1657 void *lvalue;
1659 CHECK(fmt, options);
1661 var = config_find_option(fmt, c->key);
1662 tor_assert(var);
1664 lvalue = STRUCT_VAR_P(options, var->var_offset);
1666 switch (var->type) {
1668 case CONFIG_TYPE_UINT:
1669 i = (int)tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
1670 if (!ok) {
1671 r = tor_snprintf(buf, sizeof(buf),
1672 "Int keyword '%s %s' is malformed or out of bounds.",
1673 c->key, c->value);
1674 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1675 return -1;
1677 *(int *)lvalue = i;
1678 break;
1680 case CONFIG_TYPE_INTERVAL: {
1681 i = config_parse_interval(c->value, &ok);
1682 if (!ok) {
1683 r = tor_snprintf(buf, sizeof(buf),
1684 "Interval '%s %s' is malformed or out of bounds.",
1685 c->key, c->value);
1686 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1687 return -1;
1689 *(int *)lvalue = i;
1690 break;
1693 case CONFIG_TYPE_MEMUNIT: {
1694 uint64_t u64 = config_parse_memunit(c->value, &ok);
1695 if (!ok) {
1696 r = tor_snprintf(buf, sizeof(buf),
1697 "Value '%s %s' is malformed or out of bounds.",
1698 c->key, c->value);
1699 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1700 return -1;
1702 *(uint64_t *)lvalue = u64;
1703 break;
1706 case CONFIG_TYPE_BOOL:
1707 i = (int)tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
1708 if (!ok) {
1709 r = tor_snprintf(buf, sizeof(buf),
1710 "Boolean '%s %s' expects 0 or 1.",
1711 c->key, c->value);
1712 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1713 return -1;
1715 *(int *)lvalue = i;
1716 break;
1718 case CONFIG_TYPE_STRING:
1719 case CONFIG_TYPE_FILENAME:
1720 tor_free(*(char **)lvalue);
1721 *(char **)lvalue = tor_strdup(c->value);
1722 break;
1724 case CONFIG_TYPE_DOUBLE:
1725 *(double *)lvalue = atof(c->value);
1726 break;
1728 case CONFIG_TYPE_ISOTIME:
1729 if (parse_iso_time(c->value, (time_t *)lvalue)) {
1730 r = tor_snprintf(buf, sizeof(buf),
1731 "Invalid time '%s' for keyword '%s'", c->value, c->key);
1732 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1733 return -1;
1735 break;
1737 case CONFIG_TYPE_ROUTERSET:
1738 if (*(routerset_t**)lvalue) {
1739 routerset_free(*(routerset_t**)lvalue);
1741 *(routerset_t**)lvalue = routerset_new();
1742 if (routerset_parse(*(routerset_t**)lvalue, c->value, c->key)<0) {
1743 tor_snprintf(buf, sizeof(buf), "Invalid exit list '%s' for option '%s'",
1744 c->value, c->key);
1745 *msg = tor_strdup(buf);
1746 return -1;
1748 break;
1750 case CONFIG_TYPE_CSV:
1751 if (*(smartlist_t**)lvalue) {
1752 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
1753 smartlist_clear(*(smartlist_t**)lvalue);
1754 } else {
1755 *(smartlist_t**)lvalue = smartlist_create();
1758 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
1759 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1760 break;
1762 case CONFIG_TYPE_LINELIST:
1763 case CONFIG_TYPE_LINELIST_S:
1764 config_line_append((config_line_t**)lvalue, c->key, c->value);
1765 break;
1766 case CONFIG_TYPE_OBSOLETE:
1767 log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
1768 break;
1769 case CONFIG_TYPE_LINELIST_V:
1770 r = tor_snprintf(buf, sizeof(buf),
1771 "You may not provide a value for virtual option '%s'", c->key);
1772 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1773 return -1;
1774 default:
1775 tor_assert(0);
1776 break;
1778 return 0;
1781 /** If <b>c</b> is a syntactically valid configuration line, update
1782 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1783 * key, -2 for bad value.
1785 * If <b>clear_first</b> is set, clear the value first. Then if
1786 * <b>use_defaults</b> is set, set the value to the default.
1788 * Called from config_assign().
1790 static int
1791 config_assign_line(config_format_t *fmt, or_options_t *options,
1792 config_line_t *c, int use_defaults,
1793 int clear_first, char **msg)
1795 config_var_t *var;
1797 CHECK(fmt, options);
1799 var = config_find_option(fmt, c->key);
1800 if (!var) {
1801 if (fmt->extra) {
1802 void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
1803 log_info(LD_CONFIG,
1804 "Found unrecognized option '%s'; saving it.", c->key);
1805 config_line_append((config_line_t**)lvalue, c->key, c->value);
1806 return 0;
1807 } else {
1808 char buf[1024];
1809 int tmp = tor_snprintf(buf, sizeof(buf),
1810 "Unknown option '%s'. Failing.", c->key);
1811 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1812 return -1;
1815 /* Put keyword into canonical case. */
1816 if (strcmp(var->name, c->key)) {
1817 tor_free(c->key);
1818 c->key = tor_strdup(var->name);
1821 if (!strlen(c->value)) {
1822 /* reset or clear it, then return */
1823 if (!clear_first) {
1824 if (var->type == CONFIG_TYPE_LINELIST ||
1825 var->type == CONFIG_TYPE_LINELIST_S) {
1826 /* We got an empty linelist from the torrc or commandline.
1827 As a special case, call this an error. Warn and ignore. */
1828 log_warn(LD_CONFIG,
1829 "Linelist option '%s' has no value. Skipping.", c->key);
1830 } else { /* not already cleared */
1831 option_reset(fmt, options, var, use_defaults);
1834 return 0;
1837 if (config_assign_value(fmt, options, c, msg) < 0)
1838 return -2;
1839 return 0;
1842 /** Restore the option named <b>key</b> in options to its default value.
1843 * Called from config_assign(). */
1844 static void
1845 config_reset_line(config_format_t *fmt, or_options_t *options,
1846 const char *key, int use_defaults)
1848 config_var_t *var;
1850 CHECK(fmt, options);
1852 var = config_find_option(fmt, key);
1853 if (!var)
1854 return; /* give error on next pass. */
1856 option_reset(fmt, options, var, use_defaults);
1859 /** Return true iff key is a valid configuration option. */
1861 option_is_recognized(const char *key)
1863 config_var_t *var = config_find_option(&options_format, key);
1864 return (var != NULL);
1867 /** Return the canonical name of a configuration option, or NULL
1868 * if no such option exists. */
1869 const char *
1870 option_get_canonical_name(const char *key)
1872 config_var_t *var = config_find_option(&options_format, key);
1873 return var ? var->name : NULL;
1876 /** Return a canonicalized list of the options assigned for key.
1878 config_line_t *
1879 option_get_assignment(or_options_t *options, const char *key)
1881 return get_assigned_option(&options_format, options, key, 1);
1884 /** Return true iff value needs to be quoted and escaped to be used in
1885 * a configuration file. */
1886 static int
1887 config_value_needs_escape(const char *value)
1889 if (*value == '\"')
1890 return 1;
1891 while (*value) {
1892 switch (*value)
1894 case '\r':
1895 case '\n':
1896 case '#':
1897 /* Note: quotes and backspaces need special handling when we are using
1898 * quotes, not otherwise, so they don't trigger escaping on their
1899 * own. */
1900 return 1;
1901 default:
1902 if (!TOR_ISPRINT(*value))
1903 return 1;
1905 ++value;
1907 return 0;
1910 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1911 static config_line_t *
1912 config_lines_dup(const config_line_t *inp)
1914 config_line_t *result = NULL;
1915 config_line_t **next_out = &result;
1916 while (inp) {
1917 *next_out = tor_malloc(sizeof(config_line_t));
1918 (*next_out)->key = tor_strdup(inp->key);
1919 (*next_out)->value = tor_strdup(inp->value);
1920 inp = inp->next;
1921 next_out = &((*next_out)->next);
1923 (*next_out) = NULL;
1924 return result;
1927 /** Return newly allocated line or lines corresponding to <b>key</b> in the
1928 * configuration <b>options</b>. If <b>escape_val</b> is true and a
1929 * value needs to be quoted before it's put in a config file, quote and
1930 * escape that value. Return NULL if no such key exists. */
1931 static config_line_t *
1932 get_assigned_option(config_format_t *fmt, or_options_t *options,
1933 const char *key, int escape_val)
1934 /* XXXX argument is options, but fmt is provided. Inconsistent. */
1936 config_var_t *var;
1937 const void *value;
1938 char buf[32];
1939 config_line_t *result;
1940 tor_assert(options && key);
1942 CHECK(fmt, options);
1944 var = config_find_option(fmt, key);
1945 if (!var) {
1946 log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
1947 return NULL;
1949 value = STRUCT_VAR_P(options, var->var_offset);
1951 result = tor_malloc_zero(sizeof(config_line_t));
1952 result->key = tor_strdup(var->name);
1953 switch (var->type)
1955 case CONFIG_TYPE_STRING:
1956 case CONFIG_TYPE_FILENAME:
1957 if (*(char**)value) {
1958 result->value = tor_strdup(*(char**)value);
1959 } else {
1960 tor_free(result->key);
1961 tor_free(result);
1962 return NULL;
1964 break;
1965 case CONFIG_TYPE_ISOTIME:
1966 if (*(time_t*)value) {
1967 result->value = tor_malloc(ISO_TIME_LEN+1);
1968 format_iso_time(result->value, *(time_t*)value);
1969 } else {
1970 tor_free(result->key);
1971 tor_free(result);
1973 escape_val = 0; /* Can't need escape. */
1974 break;
1975 case CONFIG_TYPE_INTERVAL:
1976 case CONFIG_TYPE_UINT:
1977 /* This means every or_options_t uint or bool element
1978 * needs to be an int. Not, say, a uint16_t or char. */
1979 tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
1980 result->value = tor_strdup(buf);
1981 escape_val = 0; /* Can't need escape. */
1982 break;
1983 case CONFIG_TYPE_MEMUNIT:
1984 tor_snprintf(buf, sizeof(buf), U64_FORMAT,
1985 U64_PRINTF_ARG(*(uint64_t*)value));
1986 result->value = tor_strdup(buf);
1987 escape_val = 0; /* Can't need escape. */
1988 break;
1989 case CONFIG_TYPE_DOUBLE:
1990 tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
1991 result->value = tor_strdup(buf);
1992 escape_val = 0; /* Can't need escape. */
1993 break;
1994 case CONFIG_TYPE_BOOL:
1995 result->value = tor_strdup(*(int*)value ? "1" : "0");
1996 escape_val = 0; /* Can't need escape. */
1997 break;
1998 case CONFIG_TYPE_ROUTERSET:
1999 result->value = routerset_to_string(*(routerset_t**)value);
2000 break;
2001 case CONFIG_TYPE_CSV:
2002 if (*(smartlist_t**)value)
2003 result->value =
2004 smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
2005 else
2006 result->value = tor_strdup("");
2007 break;
2008 case CONFIG_TYPE_OBSOLETE:
2009 log_fn(LOG_PROTOCOL_WARN, LD_CONFIG,
2010 "You asked me for the value of an obsolete config option '%s'.",
2011 key);
2012 tor_free(result->key);
2013 tor_free(result);
2014 return NULL;
2015 case CONFIG_TYPE_LINELIST_S:
2016 log_warn(LD_CONFIG,
2017 "Can't return context-sensitive '%s' on its own", key);
2018 tor_free(result->key);
2019 tor_free(result);
2020 return NULL;
2021 case CONFIG_TYPE_LINELIST:
2022 case CONFIG_TYPE_LINELIST_V:
2023 tor_free(result->key);
2024 tor_free(result);
2025 result = config_lines_dup(*(const config_line_t**)value);
2026 break;
2027 default:
2028 tor_free(result->key);
2029 tor_free(result);
2030 log_warn(LD_BUG,"Unknown type %d for known key '%s'",
2031 var->type, key);
2032 return NULL;
2035 if (escape_val) {
2036 config_line_t *line;
2037 for (line = result; line; line = line->next) {
2038 if (line->value && config_value_needs_escape(line->value)) {
2039 char *newval = esc_for_log(line->value);
2040 tor_free(line->value);
2041 line->value = newval;
2046 return result;
2049 /** Iterate through the linked list of requested options <b>list</b>.
2050 * For each item, convert as appropriate and assign to <b>options</b>.
2051 * If an item is unrecognized, set *msg and return -1 immediately,
2052 * else return 0 for success.
2054 * If <b>clear_first</b>, interpret config options as replacing (not
2055 * extending) their previous values. If <b>clear_first</b> is set,
2056 * then <b>use_defaults</b> to decide if you set to defaults after
2057 * clearing, or make the value 0 or NULL.
2059 * Here are the use cases:
2060 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
2061 * if linelist, replaces current if csv.
2062 * 2. An empty AllowInvalid line in your torrc. Should clear it.
2063 * 3. "RESETCONF AllowInvalid" sets it to default.
2064 * 4. "SETCONF AllowInvalid" makes it NULL.
2065 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
2067 * Use_defaults Clear_first
2068 * 0 0 "append"
2069 * 1 0 undefined, don't use
2070 * 0 1 "set to null first"
2071 * 1 1 "set to defaults first"
2072 * Return 0 on success, -1 on bad key, -2 on bad value.
2074 * As an additional special case, if a LINELIST config option has
2075 * no value and clear_first is 0, then warn and ignore it.
2079 There are three call cases for config_assign() currently.
2081 Case one: Torrc entry
2082 options_init_from_torrc() calls config_assign(0, 0)
2083 calls config_assign_line(0, 0).
2084 if value is empty, calls option_reset(0) and returns.
2085 calls config_assign_value(), appends.
2087 Case two: setconf
2088 options_trial_assign() calls config_assign(0, 1)
2089 calls config_reset_line(0)
2090 calls option_reset(0)
2091 calls option_clear().
2092 calls config_assign_line(0, 1).
2093 if value is empty, returns.
2094 calls config_assign_value(), appends.
2096 Case three: resetconf
2097 options_trial_assign() calls config_assign(1, 1)
2098 calls config_reset_line(1)
2099 calls option_reset(1)
2100 calls option_clear().
2101 calls config_assign_value(default)
2102 calls config_assign_line(1, 1).
2103 returns.
2105 static int
2106 config_assign(config_format_t *fmt, void *options, config_line_t *list,
2107 int use_defaults, int clear_first, char **msg)
2109 config_line_t *p;
2111 CHECK(fmt, options);
2113 /* pass 1: normalize keys */
2114 for (p = list; p; p = p->next) {
2115 const char *full = expand_abbrev(fmt, p->key, 0, 1);
2116 if (strcmp(full,p->key)) {
2117 tor_free(p->key);
2118 p->key = tor_strdup(full);
2122 /* pass 2: if we're reading from a resetting source, clear all
2123 * mentioned config options, and maybe set to their defaults. */
2124 if (clear_first) {
2125 for (p = list; p; p = p->next)
2126 config_reset_line(fmt, options, p->key, use_defaults);
2129 /* pass 3: assign. */
2130 while (list) {
2131 int r;
2132 if ((r=config_assign_line(fmt, options, list, use_defaults,
2133 clear_first, msg)))
2134 return r;
2135 list = list->next;
2137 return 0;
2140 /** Try assigning <b>list</b> to the global options. You do this by duping
2141 * options, assigning list to the new one, then validating it. If it's
2142 * ok, then throw out the old one and stick with the new one. Else,
2143 * revert to old and return failure. Return SETOPT_OK on success, or
2144 * a setopt_err_t on failure.
2146 * If not success, point *<b>msg</b> to a newly allocated string describing
2147 * what went wrong.
2149 setopt_err_t
2150 options_trial_assign(config_line_t *list, int use_defaults,
2151 int clear_first, char **msg)
2153 int r;
2154 or_options_t *trial_options = options_dup(&options_format, get_options());
2156 if ((r=config_assign(&options_format, trial_options,
2157 list, use_defaults, clear_first, msg)) < 0) {
2158 config_free(&options_format, trial_options);
2159 return r;
2162 if (options_validate(get_options(), trial_options, 1, msg) < 0) {
2163 config_free(&options_format, trial_options);
2164 return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2167 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2168 config_free(&options_format, trial_options);
2169 return SETOPT_ERR_TRANSITION;
2172 if (set_options(trial_options, msg)<0) {
2173 config_free(&options_format, trial_options);
2174 return SETOPT_ERR_SETTING;
2177 /* we liked it. put it in place. */
2178 return SETOPT_OK;
2181 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2182 * Called from option_reset() and config_free(). */
2183 static void
2184 option_clear(config_format_t *fmt, or_options_t *options, config_var_t *var)
2186 void *lvalue = STRUCT_VAR_P(options, var->var_offset);
2187 (void)fmt; /* unused */
2188 switch (var->type) {
2189 case CONFIG_TYPE_STRING:
2190 case CONFIG_TYPE_FILENAME:
2191 tor_free(*(char**)lvalue);
2192 break;
2193 case CONFIG_TYPE_DOUBLE:
2194 *(double*)lvalue = 0.0;
2195 break;
2196 case CONFIG_TYPE_ISOTIME:
2197 *(time_t*)lvalue = 0;
2198 case CONFIG_TYPE_INTERVAL:
2199 case CONFIG_TYPE_UINT:
2200 case CONFIG_TYPE_BOOL:
2201 *(int*)lvalue = 0;
2202 break;
2203 case CONFIG_TYPE_MEMUNIT:
2204 *(uint64_t*)lvalue = 0;
2205 break;
2206 case CONFIG_TYPE_ROUTERSET:
2207 if (*(routerset_t**)lvalue) {
2208 routerset_free(*(routerset_t**)lvalue);
2209 *(routerset_t**)lvalue = NULL;
2211 case CONFIG_TYPE_CSV:
2212 if (*(smartlist_t**)lvalue) {
2213 SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
2214 smartlist_free(*(smartlist_t **)lvalue);
2215 *(smartlist_t **)lvalue = NULL;
2217 break;
2218 case CONFIG_TYPE_LINELIST:
2219 case CONFIG_TYPE_LINELIST_S:
2220 config_free_lines(*(config_line_t **)lvalue);
2221 *(config_line_t **)lvalue = NULL;
2222 break;
2223 case CONFIG_TYPE_LINELIST_V:
2224 /* handled by linelist_s. */
2225 break;
2226 case CONFIG_TYPE_OBSOLETE:
2227 break;
2231 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2232 * <b>use_defaults</b>, set it to its default value.
2233 * Called by config_init() and option_reset_line() and option_assign_line(). */
2234 static void
2235 option_reset(config_format_t *fmt, or_options_t *options,
2236 config_var_t *var, int use_defaults)
2238 config_line_t *c;
2239 char *msg = NULL;
2240 CHECK(fmt, options);
2241 option_clear(fmt, options, var); /* clear it first */
2242 if (!use_defaults)
2243 return; /* all done */
2244 if (var->initvalue) {
2245 c = tor_malloc_zero(sizeof(config_line_t));
2246 c->key = tor_strdup(var->name);
2247 c->value = tor_strdup(var->initvalue);
2248 if (config_assign_value(fmt, options, c, &msg) < 0) {
2249 log_warn(LD_BUG, "Failed to assign default: %s", msg);
2250 tor_free(msg); /* if this happens it's a bug */
2252 config_free_lines(c);
2256 /** Print a usage message for tor. */
2257 static void
2258 print_usage(void)
2260 printf(
2261 "Copyright (c) 2001-2004, Roger Dingledine\n"
2262 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2263 "Copyright (c) 2007-2008, The Tor Project, Inc.\n\n"
2264 "tor -f <torrc> [args]\n"
2265 "See man page for options, or https://www.torproject.org/ for "
2266 "documentation.\n");
2269 /** Print all non-obsolete torrc options. */
2270 static void
2271 list_torrc_options(void)
2273 int i;
2274 smartlist_t *lines = smartlist_create();
2275 for (i = 0; _option_vars[i].name; ++i) {
2276 config_var_t *var = &_option_vars[i];
2277 const char *desc;
2278 if (var->type == CONFIG_TYPE_OBSOLETE ||
2279 var->type == CONFIG_TYPE_LINELIST_V)
2280 continue;
2281 desc = config_find_description(&options_format, var->name);
2282 printf("%s\n", var->name);
2283 if (desc) {
2284 wrap_string(lines, desc, 76, " ", " ");
2285 SMARTLIST_FOREACH(lines, char *, cp, {
2286 printf("%s", cp);
2287 tor_free(cp);
2289 smartlist_clear(lines);
2292 smartlist_free(lines);
2295 /** Last value actually set by resolve_my_address. */
2296 static uint32_t last_resolved_addr = 0;
2298 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2299 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2300 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2301 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2302 * public IP address.
2305 resolve_my_address(int warn_severity, or_options_t *options,
2306 uint32_t *addr_out, char **hostname_out)
2308 struct in_addr in;
2309 struct hostent *rent;
2310 char hostname[256];
2311 int explicit_ip=1;
2312 int explicit_hostname=1;
2313 int from_interface=0;
2314 char tmpbuf[INET_NTOA_BUF_LEN];
2315 const char *address = options->Address;
2316 int notice_severity = warn_severity <= LOG_NOTICE ?
2317 LOG_NOTICE : warn_severity;
2319 tor_assert(addr_out);
2321 if (address && *address) {
2322 strlcpy(hostname, address, sizeof(hostname));
2323 } else { /* then we need to guess our address */
2324 explicit_ip = 0; /* it's implicit */
2325 explicit_hostname = 0; /* it's implicit */
2327 if (gethostname(hostname, sizeof(hostname)) < 0) {
2328 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2329 return -1;
2331 log_debug(LD_CONFIG,"Guessed local host name as '%s'",hostname);
2334 /* now we know hostname. resolve it and keep only the IP address */
2336 if (tor_inet_aton(hostname, &in) == 0) {
2337 /* then we have to resolve it */
2338 explicit_ip = 0;
2339 rent = (struct hostent *)gethostbyname(hostname);
2340 if (!rent) {
2341 uint32_t interface_ip;
2343 if (explicit_hostname) {
2344 log_fn(warn_severity, LD_CONFIG,
2345 "Could not resolve local Address '%s'. Failing.", hostname);
2346 return -1;
2348 log_fn(notice_severity, LD_CONFIG,
2349 "Could not resolve guessed local hostname '%s'. "
2350 "Trying something else.", hostname);
2351 if (get_interface_address(warn_severity, &interface_ip)) {
2352 log_fn(warn_severity, LD_CONFIG,
2353 "Could not get local interface IP address. Failing.");
2354 return -1;
2356 from_interface = 1;
2357 in.s_addr = htonl(interface_ip);
2358 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2359 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2360 "local interface. Using that.", tmpbuf);
2361 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2362 } else {
2363 tor_assert(rent->h_length == 4);
2364 memcpy(&in.s_addr, rent->h_addr, rent->h_length);
2366 if (!explicit_hostname &&
2367 is_internal_IP(ntohl(in.s_addr), 0)) {
2368 uint32_t interface_ip;
2370 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2371 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2372 "resolves to a private IP address (%s). Trying something "
2373 "else.", hostname, tmpbuf);
2375 if (get_interface_address(warn_severity, &interface_ip)) {
2376 log_fn(warn_severity, LD_CONFIG,
2377 "Could not get local interface IP address. Too bad.");
2378 } else if (is_internal_IP(interface_ip, 0)) {
2379 struct in_addr in2;
2380 in2.s_addr = htonl(interface_ip);
2381 tor_inet_ntoa(&in2,tmpbuf,sizeof(tmpbuf));
2382 log_fn(notice_severity, LD_CONFIG,
2383 "Interface IP address '%s' is a private address too. "
2384 "Ignoring.", tmpbuf);
2385 } else {
2386 from_interface = 1;
2387 in.s_addr = htonl(interface_ip);
2388 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2389 log_fn(notice_severity, LD_CONFIG,
2390 "Learned IP address '%s' for local interface."
2391 " Using that.", tmpbuf);
2392 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2398 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2399 if (is_internal_IP(ntohl(in.s_addr), 0) &&
2400 options->_PublishServerDescriptor) {
2401 /* make sure we're ok with publishing an internal IP */
2402 if (!options->DirServers && !options->AlternateDirAuthority) {
2403 /* if they are using the default dirservers, disallow internal IPs
2404 * always. */
2405 log_fn(warn_severity, LD_CONFIG,
2406 "Address '%s' resolves to private IP address '%s'. "
2407 "Tor servers that use the default DirServers must have public "
2408 "IP addresses.", hostname, tmpbuf);
2409 return -1;
2411 if (!explicit_ip) {
2412 /* even if they've set their own dirservers, require an explicit IP if
2413 * they're using an internal address. */
2414 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2415 "IP address '%s'. Please set the Address config option to be "
2416 "the IP address you want to use.", hostname, tmpbuf);
2417 return -1;
2421 log_debug(LD_CONFIG, "Resolved Address to '%s'.", tmpbuf);
2422 *addr_out = ntohl(in.s_addr);
2423 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2424 /* Leave this as a notice, regardless of the requested severity,
2425 * at least until dynamic IP address support becomes bulletproof. */
2426 log_notice(LD_NET,
2427 "Your IP address seems to have changed to %s. Updating.",
2428 tmpbuf);
2429 ip_address_changed(0);
2431 if (last_resolved_addr != *addr_out) {
2432 const char *method;
2433 const char *h = hostname;
2434 if (explicit_ip) {
2435 method = "CONFIGURED";
2436 h = NULL;
2437 } else if (explicit_hostname) {
2438 method = "RESOLVED";
2439 } else if (from_interface) {
2440 method = "INTERFACE";
2441 h = NULL;
2442 } else {
2443 method = "GETHOSTNAME";
2445 control_event_server_status(LOG_NOTICE,
2446 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2447 tmpbuf, method, h?"HOSTNAME=":"", h);
2449 last_resolved_addr = *addr_out;
2450 if (hostname_out)
2451 *hostname_out = tor_strdup(hostname);
2452 return 0;
2455 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2456 * on a private network.
2459 is_local_addr(const tor_addr_t *addr)
2461 if (tor_addr_is_internal(addr, 0))
2462 return 1;
2463 /* Check whether ip is on the same /24 as we are. */
2464 if (get_options()->EnforceDistinctSubnets == 0)
2465 return 0;
2466 if (tor_addr_family(addr) == AF_INET) {
2467 /*XXXX021 IP6 what corresponds to an /24? */
2468 uint32_t ip = tor_addr_to_ipv4h(addr);
2470 /* It's possible that this next check will hit before the first time
2471 * resolve_my_address actually succeeds. (For clients, it is likely that
2472 * resolve_my_address will never be called at all). In those cases,
2473 * last_resolved_addr will be 0, and so checking to see whether ip is on
2474 * the same /24 as last_resolved_addr will be the same as checking whether
2475 * it was on net 0, which is already done by is_internal_IP.
2477 if ((last_resolved_addr & 0xffffff00ul) == (ip & 0xffffff00ul))
2478 return 1;
2480 return 0;
2483 /** Called when we don't have a nickname set. Try to guess a good nickname
2484 * based on the hostname, and return it in a newly allocated string. If we
2485 * can't, return NULL and let the caller warn if it wants to. */
2486 static char *
2487 get_default_nickname(void)
2489 static const char * const bad_default_nicknames[] = {
2490 "localhost",
2491 NULL,
2493 char localhostname[256];
2494 char *cp, *out, *outp;
2495 int i;
2497 if (gethostname(localhostname, sizeof(localhostname)) < 0)
2498 return NULL;
2500 /* Put it in lowercase; stop at the first dot. */
2501 if ((cp = strchr(localhostname, '.')))
2502 *cp = '\0';
2503 tor_strlower(localhostname);
2505 /* Strip invalid characters. */
2506 cp = localhostname;
2507 out = outp = tor_malloc(strlen(localhostname) + 1);
2508 while (*cp) {
2509 if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
2510 *outp++ = *cp++;
2511 else
2512 cp++;
2514 *outp = '\0';
2516 /* Enforce length. */
2517 if (strlen(out) > MAX_NICKNAME_LEN)
2518 out[MAX_NICKNAME_LEN]='\0';
2520 /* Check for dumb names. */
2521 for (i = 0; bad_default_nicknames[i]; ++i) {
2522 if (!strcmp(out, bad_default_nicknames[i])) {
2523 tor_free(out);
2524 return NULL;
2528 return out;
2531 /** Release storage held by <b>options</b>. */
2532 static void
2533 config_free(config_format_t *fmt, void *options)
2535 int i;
2537 tor_assert(options);
2539 for (i=0; fmt->vars[i].name; ++i)
2540 option_clear(fmt, options, &(fmt->vars[i]));
2541 if (fmt->extra) {
2542 config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
2543 config_free_lines(*linep);
2544 *linep = NULL;
2546 tor_free(options);
2549 /** Return true iff a and b contain identical keys and values in identical
2550 * order. */
2551 static int
2552 config_lines_eq(config_line_t *a, config_line_t *b)
2554 while (a && b) {
2555 if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
2556 return 0;
2557 a = a->next;
2558 b = b->next;
2560 if (a || b)
2561 return 0;
2562 return 1;
2565 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2566 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2568 static int
2569 option_is_same(config_format_t *fmt,
2570 or_options_t *o1, or_options_t *o2, const char *name)
2572 config_line_t *c1, *c2;
2573 int r = 1;
2574 CHECK(fmt, o1);
2575 CHECK(fmt, o2);
2577 c1 = get_assigned_option(fmt, o1, name, 0);
2578 c2 = get_assigned_option(fmt, o2, name, 0);
2579 r = config_lines_eq(c1, c2);
2580 config_free_lines(c1);
2581 config_free_lines(c2);
2582 return r;
2585 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2586 static or_options_t *
2587 options_dup(config_format_t *fmt, or_options_t *old)
2589 or_options_t *newopts;
2590 int i;
2591 config_line_t *line;
2593 newopts = config_alloc(fmt);
2594 for (i=0; fmt->vars[i].name; ++i) {
2595 if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2596 continue;
2597 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
2598 continue;
2599 line = get_assigned_option(fmt, old, fmt->vars[i].name, 0);
2600 if (line) {
2601 char *msg = NULL;
2602 if (config_assign(fmt, newopts, line, 0, 0, &msg) < 0) {
2603 log_err(LD_BUG, "Config_get_assigned_option() generated "
2604 "something we couldn't config_assign(): %s", msg);
2605 tor_free(msg);
2606 tor_assert(0);
2609 config_free_lines(line);
2611 return newopts;
2614 /** Return a new empty or_options_t. Used for testing. */
2615 or_options_t *
2616 options_new(void)
2618 return config_alloc(&options_format);
2621 /** Set <b>options</b> to hold reasonable defaults for most options.
2622 * Each option defaults to zero. */
2623 void
2624 options_init(or_options_t *options)
2626 config_init(&options_format, options);
2629 /** Set all vars in the configuration object <b>options</b> to their default
2630 * values. */
2631 static void
2632 config_init(config_format_t *fmt, void *options)
2634 int i;
2635 config_var_t *var;
2636 CHECK(fmt, options);
2638 for (i=0; fmt->vars[i].name; ++i) {
2639 var = &fmt->vars[i];
2640 if (!var->initvalue)
2641 continue; /* defaults to NULL or 0 */
2642 option_reset(fmt, options, var, 1);
2646 /** Allocate and return a new string holding the written-out values of the vars
2647 * in 'options'. If 'minimal', do not write out any default-valued vars.
2648 * Else, if comment_defaults, write default values as comments.
2650 static char *
2651 config_dump(config_format_t *fmt, void *options, int minimal,
2652 int comment_defaults)
2654 smartlist_t *elements;
2655 or_options_t *defaults;
2656 config_line_t *line, *assigned;
2657 char *result;
2658 int i;
2659 const char *desc;
2660 char *msg = NULL;
2662 defaults = config_alloc(fmt);
2663 config_init(fmt, defaults);
2665 /* XXX use a 1 here so we don't add a new log line while dumping */
2666 if (fmt->validate_fn(NULL,defaults, 1, &msg) < 0) {
2667 log_err(LD_BUG, "Failed to validate default config.");
2668 tor_free(msg);
2669 tor_assert(0);
2672 elements = smartlist_create();
2673 for (i=0; fmt->vars[i].name; ++i) {
2674 int comment_option = 0;
2675 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
2676 fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2677 continue;
2678 /* Don't save 'hidden' control variables. */
2679 if (!strcmpstart(fmt->vars[i].name, "__"))
2680 continue;
2681 if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
2682 continue;
2683 else if (comment_defaults &&
2684 option_is_same(fmt, options, defaults, fmt->vars[i].name))
2685 comment_option = 1;
2687 desc = config_find_description(fmt, fmt->vars[i].name);
2688 line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name, 1);
2690 if (line && desc) {
2691 /* Only dump the description if there's something to describe. */
2692 wrap_string(elements, desc, 78, "# ", "# ");
2695 for (; line; line = line->next) {
2696 size_t len = strlen(line->key) + strlen(line->value) + 5;
2697 char *tmp;
2698 tmp = tor_malloc(len);
2699 if (tor_snprintf(tmp, len, "%s%s %s\n",
2700 comment_option ? "# " : "",
2701 line->key, line->value)<0) {
2702 log_err(LD_BUG,"Internal error writing option value");
2703 tor_assert(0);
2705 smartlist_add(elements, tmp);
2707 config_free_lines(assigned);
2710 if (fmt->extra) {
2711 line = *(config_line_t**)STRUCT_VAR_P(options, fmt->extra->var_offset);
2712 for (; line; line = line->next) {
2713 size_t len = strlen(line->key) + strlen(line->value) + 3;
2714 char *tmp;
2715 tmp = tor_malloc(len);
2716 if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
2717 log_err(LD_BUG,"Internal error writing option value");
2718 tor_assert(0);
2720 smartlist_add(elements, tmp);
2724 result = smartlist_join_strings(elements, "", 0, NULL);
2725 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2726 smartlist_free(elements);
2727 config_free(fmt, defaults);
2728 return result;
2731 /** Return a string containing a possible configuration file that would give
2732 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2733 * include options that are the same as Tor's defaults.
2735 static char *
2736 options_dump(or_options_t *options, int minimal)
2738 return config_dump(&options_format, options, minimal, 0);
2741 /** Return 0 if every element of sl is a string holding a decimal
2742 * representation of a port number, or if sl is NULL.
2743 * Otherwise set *msg and return -1. */
2744 static int
2745 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2747 int i;
2748 char buf[1024];
2749 tor_assert(name);
2751 if (!sl)
2752 return 0;
2754 SMARTLIST_FOREACH(sl, const char *, cp,
2756 i = atoi(cp);
2757 if (i < 1 || i > 65535) {
2758 int r = tor_snprintf(buf, sizeof(buf),
2759 "Port '%s' out of range in %s", cp, name);
2760 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2761 return -1;
2764 return 0;
2767 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2768 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2769 * Else return 0.
2771 static int
2772 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2774 int r;
2775 char buf[1024];
2776 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2777 /* This handles an understandable special case where somebody says "2gb"
2778 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2779 --*value;
2781 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2782 r = tor_snprintf(buf, sizeof(buf), "%s ("U64_FORMAT") must be at most %d",
2783 desc, U64_PRINTF_ARG(*value),
2784 ROUTER_MAX_DECLARED_BANDWIDTH);
2785 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2786 return -1;
2788 return 0;
2791 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2792 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2793 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2794 * Treat "0" as "".
2795 * Return 0 on success or -1 if not a recognized authority type (in which
2796 * case the value of _PublishServerDescriptor is undefined). */
2797 static int
2798 compute_publishserverdescriptor(or_options_t *options)
2800 smartlist_t *list = options->PublishServerDescriptor;
2801 authority_type_t *auth = &options->_PublishServerDescriptor;
2802 *auth = NO_AUTHORITY;
2803 if (!list) /* empty list, answer is none */
2804 return 0;
2805 SMARTLIST_FOREACH(list, const char *, string, {
2806 if (!strcasecmp(string, "v1"))
2807 *auth |= V1_AUTHORITY;
2808 else if (!strcmp(string, "1"))
2809 if (options->BridgeRelay)
2810 *auth |= BRIDGE_AUTHORITY;
2811 else
2812 *auth |= V2_AUTHORITY | V3_AUTHORITY;
2813 else if (!strcasecmp(string, "v2"))
2814 *auth |= V2_AUTHORITY;
2815 else if (!strcasecmp(string, "v3"))
2816 *auth |= V3_AUTHORITY;
2817 else if (!strcasecmp(string, "bridge"))
2818 *auth |= BRIDGE_AUTHORITY;
2819 else if (!strcasecmp(string, "hidserv"))
2820 *auth |= HIDSERV_AUTHORITY;
2821 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2822 /* no authority */;
2823 else
2824 return -1;
2826 return 0;
2829 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2830 * services can overload the directory system. */
2831 #define MIN_REND_POST_PERIOD (10*60)
2833 /** Highest allowable value for RendPostPeriod. */
2834 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2836 /** Lowest allowable value for CircuitBuildTimeout; values too low will
2837 * increase network load because of failing connections being retried, and
2838 * might prevent users from connecting to the network at all. */
2839 #define MIN_CIRCUIT_BUILD_TIMEOUT 30
2841 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2842 * will generate too many circuits and potentially overload the network. */
2843 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2845 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2846 * permissible transition from <b>old_options</b>. Else return -1.
2847 * Should have no side effects, except for normalizing the contents of
2848 * <b>options</b>.
2850 * On error, tor_strdup an error explanation into *<b>msg</b>.
2852 * XXX
2853 * If <b>from_setconf</b>, we were called by the controller, and our
2854 * Log line should stay empty. If it's 0, then give us a default log
2855 * if there are no logs defined.
2857 static int
2858 options_validate(or_options_t *old_options, or_options_t *options,
2859 int from_setconf, char **msg)
2861 int i, r;
2862 config_line_t *cl;
2863 const char *uname = get_uname();
2864 char buf[1024];
2865 #define REJECT(arg) \
2866 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2867 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2869 tor_assert(msg);
2870 *msg = NULL;
2872 if (options->ORPort < 0 || options->ORPort > 65535)
2873 REJECT("ORPort option out of bounds.");
2875 if (server_mode(options) &&
2876 (!strcmpstart(uname, "Windows 95") ||
2877 !strcmpstart(uname, "Windows 98") ||
2878 !strcmpstart(uname, "Windows Me"))) {
2879 log(LOG_WARN, LD_CONFIG, "Tor is running as a server, but you are "
2880 "running %s; this probably won't work. See "
2881 "http://wiki.noreply.org/noreply/TheOnionRouter/TorFAQ#ServerOS "
2882 "for details.", uname);
2885 if (options->ORPort == 0 && options->ORListenAddress != NULL)
2886 REJECT("ORPort must be defined if ORListenAddress is defined.");
2888 if (options->DirPort == 0 && options->DirListenAddress != NULL)
2889 REJECT("DirPort must be defined if DirListenAddress is defined.");
2891 if (options->DNSPort == 0 && options->DNSListenAddress != NULL)
2892 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
2894 if (options->ControlPort == 0 && options->ControlListenAddress != NULL)
2895 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
2897 if (options->TransPort == 0 && options->TransListenAddress != NULL)
2898 REJECT("TransPort must be defined if TransListenAddress is defined.");
2900 if (options->NatdPort == 0 && options->NatdListenAddress != NULL)
2901 REJECT("NatdPort must be defined if NatdListenAddress is defined.");
2903 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
2904 * configuration does this. */
2906 for (i = 0; i < 3; ++i) {
2907 int is_socks = i==0;
2908 int is_trans = i==1;
2909 config_line_t *line, *opt, *old;
2910 const char *tp;
2911 if (is_socks) {
2912 opt = options->SocksListenAddress;
2913 old = old_options ? old_options->SocksListenAddress : NULL;
2914 tp = "SOCKS proxy";
2915 } else if (is_trans) {
2916 opt = options->TransListenAddress;
2917 old = old_options ? old_options->TransListenAddress : NULL;
2918 tp = "transparent proxy";
2919 } else {
2920 opt = options->NatdListenAddress;
2921 old = old_options ? old_options->NatdListenAddress : NULL;
2922 tp = "natd proxy";
2925 for (line = opt; line; line = line->next) {
2926 char *address = NULL;
2927 uint16_t port;
2928 uint32_t addr;
2929 if (parse_addr_port(LOG_WARN, line->value, &address, &addr, &port)<0)
2930 continue; /* We'll warn about this later. */
2931 if (!is_internal_IP(addr, 1) &&
2932 (!old_options || !config_lines_eq(old, opt))) {
2933 log_warn(LD_CONFIG,
2934 "You specified a public address '%s' for a %s. Other "
2935 "people on the Internet might find your computer and use it as "
2936 "an open %s. Please don't allow this unless you have "
2937 "a good reason.", address, tp, tp);
2939 tor_free(address);
2943 if (validate_data_directory(options)<0)
2944 REJECT("Invalid DataDirectory");
2946 if (options->Nickname == NULL) {
2947 if (server_mode(options)) {
2948 if (!(options->Nickname = get_default_nickname())) {
2949 log_notice(LD_CONFIG, "Couldn't pick a nickname based on "
2950 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME);
2951 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
2952 } else {
2953 log_notice(LD_CONFIG, "Choosing default nickname '%s'",
2954 options->Nickname);
2957 } else {
2958 if (!is_legal_nickname(options->Nickname)) {
2959 r = tor_snprintf(buf, sizeof(buf),
2960 "Nickname '%s' is wrong length or contains illegal characters.",
2961 options->Nickname);
2962 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2963 return -1;
2967 if (server_mode(options) && !options->ContactInfo)
2968 log(LOG_NOTICE, LD_CONFIG, "Your ContactInfo config option is not set. "
2969 "Please consider setting it, so we can contact you if your server is "
2970 "misconfigured or something else goes wrong.");
2972 /* Special case on first boot if no Log options are given. */
2973 if (!options->Logs && !options->RunAsDaemon && !from_setconf)
2974 config_line_append(&options->Logs, "Log", "notice stdout");
2976 if (options_init_logs(options, 1)<0) /* Validate the log(s) */
2977 REJECT("Failed to validate Log options. See logs for details.");
2979 if (options->NoPublish) {
2980 log(LOG_WARN, LD_CONFIG,
2981 "NoPublish is obsolete. Use PublishServerDescriptor instead.");
2982 SMARTLIST_FOREACH(options->PublishServerDescriptor, char *, s,
2983 tor_free(s));
2984 smartlist_clear(options->PublishServerDescriptor);
2987 if (authdir_mode(options)) {
2988 /* confirm that our address isn't broken, so we can complain now */
2989 uint32_t tmp;
2990 if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
2991 REJECT("Failed to resolve/guess local address. See logs for details.");
2994 #ifndef MS_WINDOWS
2995 if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
2996 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
2997 #endif
2999 if (options->SocksPort < 0 || options->SocksPort > 65535)
3000 REJECT("SocksPort option out of bounds.");
3002 if (options->DNSPort < 0 || options->DNSPort > 65535)
3003 REJECT("DNSPort option out of bounds.");
3005 if (options->TransPort < 0 || options->TransPort > 65535)
3006 REJECT("TransPort option out of bounds.");
3008 if (options->NatdPort < 0 || options->NatdPort > 65535)
3009 REJECT("NatdPort option out of bounds.");
3011 if (options->SocksPort == 0 && options->TransPort == 0 &&
3012 options->NatdPort == 0 && options->ORPort == 0 &&
3013 options->DNSPort == 0 && !options->RendConfigLines)
3014 log(LOG_WARN, LD_CONFIG,
3015 "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
3016 "undefined, and there aren't any hidden services configured. "
3017 "Tor will still run, but probably won't do anything.");
3019 if (options->ControlPort < 0 || options->ControlPort > 65535)
3020 REJECT("ControlPort option out of bounds.");
3022 if (options->DirPort < 0 || options->DirPort > 65535)
3023 REJECT("DirPort option out of bounds.");
3025 #ifndef USE_TRANSPARENT
3026 if (options->TransPort || options->TransListenAddress)
3027 REJECT("TransPort and TransListenAddress are disabled in this build.");
3028 #endif
3030 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3031 options->_ExcludeExitNodesUnion = routerset_new();
3032 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeExitNodes);
3033 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeNodes);
3036 if (options->StrictExitNodes &&
3037 (!options->ExitNodes) &&
3038 (!old_options ||
3039 (old_options->StrictExitNodes != options->StrictExitNodes) ||
3040 (!routerset_equal(old_options->ExitNodes,options->ExitNodes))))
3041 COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
3043 if (options->StrictEntryNodes &&
3044 (!options->EntryNodes) &&
3045 (!old_options ||
3046 (old_options->StrictEntryNodes != options->StrictEntryNodes) ||
3047 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
3048 COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
3050 if (options->EntryNodes && !routerset_is_list(options->EntryNodes)) {
3051 /* XXXX fix this; see entry_guards_prepend_from_config(). */
3052 REJECT("IPs or countries are not yet supported in EntryNodes.");
3055 if (options->AuthoritativeDir) {
3056 if (!options->ContactInfo)
3057 REJECT("Authoritative directory servers must set ContactInfo");
3058 if (options->V1AuthoritativeDir && !options->RecommendedVersions)
3059 REJECT("V1 auth dir servers must set RecommendedVersions.");
3060 if (!options->RecommendedClientVersions)
3061 options->RecommendedClientVersions =
3062 config_lines_dup(options->RecommendedVersions);
3063 if (!options->RecommendedServerVersions)
3064 options->RecommendedServerVersions =
3065 config_lines_dup(options->RecommendedVersions);
3066 if (options->VersioningAuthoritativeDir &&
3067 (!options->RecommendedClientVersions ||
3068 !options->RecommendedServerVersions))
3069 REJECT("Versioning auth dir servers must set Recommended*Versions.");
3070 if (options->UseEntryGuards) {
3071 log_info(LD_CONFIG, "Authoritative directory servers can't set "
3072 "UseEntryGuards. Disabling.");
3073 options->UseEntryGuards = 0;
3075 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
3076 log_info(LD_CONFIG, "Authoritative directories always try to download "
3077 "extra-info documents. Setting DownloadExtraInfo.");
3078 options->DownloadExtraInfo = 1;
3080 if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
3081 options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
3082 options->V3AuthoritativeDir))
3083 REJECT("AuthoritativeDir is set, but none of "
3084 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
3087 if (options->AuthoritativeDir && !options->DirPort)
3088 REJECT("Running as authoritative directory, but no DirPort set.");
3090 if (options->AuthoritativeDir && !options->ORPort)
3091 REJECT("Running as authoritative directory, but no ORPort set.");
3093 if (options->AuthoritativeDir && options->ClientOnly)
3094 REJECT("Running as authoritative directory, but ClientOnly also set.");
3096 if (options->HSAuthorityRecordStats && !options->HSAuthoritativeDir)
3097 REJECT("HSAuthorityRecordStats is set but we're not running as "
3098 "a hidden service authority.");
3100 if (options->ConnLimit <= 0) {
3101 r = tor_snprintf(buf, sizeof(buf),
3102 "ConnLimit must be greater than 0, but was set to %d",
3103 options->ConnLimit);
3104 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3105 return -1;
3108 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3109 return -1;
3111 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3112 return -1;
3114 if (validate_ports_csv(options->RejectPlaintextPorts,
3115 "RejectPlaintextPorts", msg) < 0)
3116 return -1;
3118 if (validate_ports_csv(options->WarnPlaintextPorts,
3119 "WarnPlaintextPorts", msg) < 0)
3120 return -1;
3122 if (options->FascistFirewall && !options->ReachableAddresses) {
3123 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3124 /* We already have firewall ports set, so migrate them to
3125 * ReachableAddresses, which will set ReachableORAddresses and
3126 * ReachableDirAddresses if they aren't set explicitly. */
3127 smartlist_t *instead = smartlist_create();
3128 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3129 new_line->key = tor_strdup("ReachableAddresses");
3130 /* If we're configured with the old format, we need to prepend some
3131 * open ports. */
3132 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3134 int p = atoi(portno);
3135 char *s;
3136 if (p<0) continue;
3137 s = tor_malloc(16);
3138 tor_snprintf(s, 16, "*:%d", p);
3139 smartlist_add(instead, s);
3141 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3142 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3143 log(LOG_NOTICE, LD_CONFIG,
3144 "Converting FascistFirewall and FirewallPorts "
3145 "config options to new format: \"ReachableAddresses %s\"",
3146 new_line->value);
3147 options->ReachableAddresses = new_line;
3148 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3149 smartlist_free(instead);
3150 } else {
3151 /* We do not have FirewallPorts set, so add 80 to
3152 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3153 if (!options->ReachableDirAddresses) {
3154 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3155 new_line->key = tor_strdup("ReachableDirAddresses");
3156 new_line->value = tor_strdup("*:80");
3157 options->ReachableDirAddresses = new_line;
3158 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3159 "to new format: \"ReachableDirAddresses *:80\"");
3161 if (!options->ReachableORAddresses) {
3162 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3163 new_line->key = tor_strdup("ReachableORAddresses");
3164 new_line->value = tor_strdup("*:443");
3165 options->ReachableORAddresses = new_line;
3166 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3167 "to new format: \"ReachableORAddresses *:443\"");
3172 for (i=0; i<3; i++) {
3173 config_line_t **linep =
3174 (i==0) ? &options->ReachableAddresses :
3175 (i==1) ? &options->ReachableORAddresses :
3176 &options->ReachableDirAddresses;
3177 if (!*linep)
3178 continue;
3179 /* We need to end with a reject *:*, not an implicit accept *:* */
3180 for (;;) {
3181 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
3182 break;
3183 linep = &((*linep)->next);
3184 if (!*linep) {
3185 *linep = tor_malloc_zero(sizeof(config_line_t));
3186 (*linep)->key = tor_strdup(
3187 (i==0) ? "ReachableAddresses" :
3188 (i==1) ? "ReachableORAddresses" :
3189 "ReachableDirAddresses");
3190 (*linep)->value = tor_strdup("reject *:*");
3191 break;
3196 if ((options->ReachableAddresses ||
3197 options->ReachableORAddresses ||
3198 options->ReachableDirAddresses) &&
3199 server_mode(options))
3200 REJECT("Servers must be able to freely connect to the rest "
3201 "of the Internet, so they must not set Reachable*Addresses "
3202 "or FascistFirewall.");
3204 if (options->UseBridges &&
3205 server_mode(options))
3206 REJECT("Servers must be able to freely connect to the rest "
3207 "of the Internet, so they must not set UseBridges.");
3209 options->_AllowInvalid = 0;
3210 if (options->AllowInvalidNodes) {
3211 SMARTLIST_FOREACH(options->AllowInvalidNodes, const char *, cp, {
3212 if (!strcasecmp(cp, "entry"))
3213 options->_AllowInvalid |= ALLOW_INVALID_ENTRY;
3214 else if (!strcasecmp(cp, "exit"))
3215 options->_AllowInvalid |= ALLOW_INVALID_EXIT;
3216 else if (!strcasecmp(cp, "middle"))
3217 options->_AllowInvalid |= ALLOW_INVALID_MIDDLE;
3218 else if (!strcasecmp(cp, "introduction"))
3219 options->_AllowInvalid |= ALLOW_INVALID_INTRODUCTION;
3220 else if (!strcasecmp(cp, "rendezvous"))
3221 options->_AllowInvalid |= ALLOW_INVALID_RENDEZVOUS;
3222 else {
3223 r = tor_snprintf(buf, sizeof(buf),
3224 "Unrecognized value '%s' in AllowInvalidNodes", cp);
3225 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3226 return -1;
3231 if (compute_publishserverdescriptor(options) < 0) {
3232 r = tor_snprintf(buf, sizeof(buf),
3233 "Unrecognized value in PublishServerDescriptor");
3234 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3235 return -1;
3238 if (options->MinUptimeHidServDirectoryV2 < 0) {
3239 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3240 "least 0 seconds. Changing to 0.");
3241 options->MinUptimeHidServDirectoryV2 = 0;
3244 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
3245 log(LOG_WARN,LD_CONFIG,"RendPostPeriod option is too short; "
3246 "raising to %d seconds.", MIN_REND_POST_PERIOD);
3247 options->RendPostPeriod = MIN_REND_POST_PERIOD;
3250 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3251 log(LOG_WARN, LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3252 MAX_DIR_PERIOD);
3253 options->RendPostPeriod = MAX_DIR_PERIOD;
3256 if (options->CircuitBuildTimeout < MIN_CIRCUIT_BUILD_TIMEOUT) {
3257 log(LOG_WARN, LD_CONFIG, "CircuitBuildTimeout option is too short; "
3258 "raising to %d seconds.", MIN_CIRCUIT_BUILD_TIMEOUT);
3259 options->CircuitBuildTimeout = MIN_CIRCUIT_BUILD_TIMEOUT;
3262 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3263 log(LOG_WARN, LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3264 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3265 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3268 if (options->KeepalivePeriod < 1)
3269 REJECT("KeepalivePeriod option must be positive.");
3271 if (ensure_bandwidth_cap(&options->BandwidthRate,
3272 "BandwidthRate", msg) < 0)
3273 return -1;
3274 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3275 "BandwidthBurst", msg) < 0)
3276 return -1;
3277 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3278 "MaxAdvertisedBandwidth", msg) < 0)
3279 return -1;
3280 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3281 "RelayBandwidthRate", msg) < 0)
3282 return -1;
3283 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3284 "RelayBandwidthBurst", msg) < 0)
3285 return -1;
3287 if (server_mode(options)) {
3288 if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH*2) {
3289 r = tor_snprintf(buf, sizeof(buf),
3290 "BandwidthRate is set to %d bytes/second. "
3291 "For servers, it must be at least %d.",
3292 (int)options->BandwidthRate,
3293 ROUTER_REQUIRED_MIN_BANDWIDTH*2);
3294 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3295 return -1;
3296 } else if (options->MaxAdvertisedBandwidth <
3297 ROUTER_REQUIRED_MIN_BANDWIDTH) {
3298 r = tor_snprintf(buf, sizeof(buf),
3299 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3300 "For servers, it must be at least %d.",
3301 (int)options->MaxAdvertisedBandwidth,
3302 ROUTER_REQUIRED_MIN_BANDWIDTH);
3303 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3304 return -1;
3306 if (options->RelayBandwidthRate &&
3307 options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3308 r = tor_snprintf(buf, sizeof(buf),
3309 "RelayBandwidthRate is set to %d bytes/second. "
3310 "For servers, it must be at least %d.",
3311 (int)options->RelayBandwidthRate,
3312 ROUTER_REQUIRED_MIN_BANDWIDTH);
3313 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3314 return -1;
3318 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3319 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3321 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3322 REJECT("RelayBandwidthBurst must be at least equal "
3323 "to RelayBandwidthRate.");
3325 if (options->BandwidthRate > options->BandwidthBurst)
3326 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3328 /* if they set relaybandwidth* really high but left bandwidth*
3329 * at the default, raise the defaults. */
3330 if (options->RelayBandwidthRate > options->BandwidthRate)
3331 options->BandwidthRate = options->RelayBandwidthRate;
3332 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3333 options->BandwidthBurst = options->RelayBandwidthBurst;
3335 if (accounting_parse_options(options, 1)<0)
3336 REJECT("Failed to parse accounting options. See logs for details.");
3338 if (options->HttpProxy) { /* parse it now */
3339 if (parse_addr_port(LOG_WARN, options->HttpProxy, NULL,
3340 &options->HttpProxyAddr, &options->HttpProxyPort) < 0)
3341 REJECT("HttpProxy failed to parse or resolve. Please fix.");
3342 if (options->HttpProxyPort == 0) { /* give it a default */
3343 options->HttpProxyPort = 80;
3347 if (options->HttpProxyAuthenticator) {
3348 if (strlen(options->HttpProxyAuthenticator) >= 48)
3349 REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
3352 if (options->HttpsProxy) { /* parse it now */
3353 if (parse_addr_port(LOG_WARN, options->HttpsProxy, NULL,
3354 &options->HttpsProxyAddr, &options->HttpsProxyPort) <0)
3355 REJECT("HttpsProxy failed to parse or resolve. Please fix.");
3356 if (options->HttpsProxyPort == 0) { /* give it a default */
3357 options->HttpsProxyPort = 443;
3361 if (options->HttpsProxyAuthenticator) {
3362 if (strlen(options->HttpsProxyAuthenticator) >= 48)
3363 REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
3366 if (options->HashedControlPassword) {
3367 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3368 if (!sl) {
3369 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3370 } else {
3371 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3372 smartlist_free(sl);
3376 if (options->HashedControlSessionPassword) {
3377 smartlist_t *sl = decode_hashed_passwords(
3378 options->HashedControlSessionPassword);
3379 if (!sl) {
3380 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3381 } else {
3382 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3383 smartlist_free(sl);
3387 if (options->ControlListenAddress) {
3388 int all_are_local = 1;
3389 config_line_t *ln;
3390 for (ln = options->ControlListenAddress; ln; ln = ln->next) {
3391 if (strcmpstart(ln->value, "127."))
3392 all_are_local = 0;
3394 if (!all_are_local) {
3395 if (!options->HashedControlPassword &&
3396 !options->HashedControlSessionPassword &&
3397 !options->CookieAuthentication) {
3398 log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
3399 "connections from a non-local address. This means that "
3400 "any program on the internet can reconfigure your Tor. "
3401 "That's so bad that I'm closing your ControlPort for you.");
3402 options->ControlPort = 0;
3403 } else {
3404 log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
3405 "connections from a non-local address. This means that "
3406 "programs not running on your computer can reconfigure your "
3407 "Tor. That's pretty bad!");
3412 if (options->ControlPort && !options->HashedControlPassword &&
3413 !options->HashedControlSessionPassword &&
3414 !options->CookieAuthentication) {
3415 log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
3416 "has been configured. This means that any program on your "
3417 "computer can reconfigure your Tor. That's bad! You should "
3418 "upgrade your Tor controller as soon as possible.");
3421 if (options->UseEntryGuards && ! options->NumEntryGuards)
3422 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3424 if (check_nickname_list(options->MyFamily, "MyFamily", msg))
3425 return -1;
3426 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3427 if (check_nickname_list(cl->value, "NodeFamily", msg))
3428 return -1;
3431 if (validate_addr_policies(options, msg) < 0)
3432 return -1;
3434 if (validate_dir_authorities(options, old_options) < 0)
3435 REJECT("Directory authority line did not parse. See logs for details.");
3437 if (options->UseBridges && !options->Bridges)
3438 REJECT("If you set UseBridges, you must specify at least one bridge.");
3439 if (options->UseBridges && !options->TunnelDirConns)
3440 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3441 if (options->Bridges) {
3442 for (cl = options->Bridges; cl; cl = cl->next) {
3443 if (parse_bridge_line(cl->value, 1)<0)
3444 REJECT("Bridge line did not parse. See logs for details.");
3448 if (options->ConstrainedSockets) {
3449 /* If the user wants to constrain socket buffer use, make sure the desired
3450 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3451 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3452 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3453 options->ConstrainedSockSize % 1024) {
3454 r = tor_snprintf(buf, sizeof(buf),
3455 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3456 "in 1024 byte increments.",
3457 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3458 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3459 return -1;
3461 if (options->DirPort) {
3462 /* Providing cached directory entries while system TCP buffers are scarce
3463 * will exacerbate the socket errors. Suggest that this be disabled. */
3464 COMPLAIN("You have requested constrained socket buffers while also "
3465 "serving directory entries via DirPort. It is strongly "
3466 "suggested that you disable serving directory requests when "
3467 "system TCP buffer resources are scarce.");
3471 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3472 options->V3AuthVotingInterval/2) {
3473 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3474 "V3AuthVotingInterval");
3476 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
3477 REJECT("V3AuthVoteDelay is way too low.");
3478 if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
3479 REJECT("V3AuthDistDelay is way too low.");
3481 if (options->V3AuthNIntervalsValid < 2)
3482 REJECT("V3AuthNIntervalsValid must be at least 2.");
3484 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3485 REJECT("V3AuthVotingInterval is insanely low.");
3486 } else if (options->V3AuthVotingInterval > 24*60*60) {
3487 REJECT("V3AuthVotingInterval is insanely high.");
3488 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3489 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3492 if (rend_config_services(options, 1) < 0)
3493 REJECT("Failed to configure rendezvous options. See logs for details.");
3495 /* Parse client-side authorization for hidden services. */
3496 if (rend_parse_service_authorization(options, 1) < 0)
3497 REJECT("Failed to configure client authorization for hidden services. "
3498 "See logs for details.");
3500 if (parse_virtual_addr_network(options->VirtualAddrNetwork, 1, NULL)<0)
3501 return -1;
3503 if (options->PreferTunneledDirConns && !options->TunnelDirConns)
3504 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3506 if (options->AutomapHostsSuffixes) {
3507 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
3509 size_t len = strlen(suf);
3510 if (len && suf[len-1] == '.')
3511 suf[len-1] = '\0';
3515 if (options->TestingTorNetwork && !options->DirServers) {
3516 REJECT("TestingTorNetwork may only be configured in combination with "
3517 "a non-default set of DirServers.");
3520 /*XXXX021 checking for defaults manually like this is a bit fragile.*/
3522 /* Keep changes to hard-coded values synchronous to man page and default
3523 * values table. */
3524 if (options->TestingV3AuthInitialVotingInterval != 30*60 &&
3525 !options->TestingTorNetwork) {
3526 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
3527 "Tor networks!");
3528 } else if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
3529 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3530 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
3531 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3532 "30 minutes.");
3535 if (options->TestingV3AuthInitialVoteDelay != 5*60 &&
3536 !options->TestingTorNetwork) {
3537 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
3538 "Tor networks!");
3539 } else if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
3540 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3543 if (options->TestingV3AuthInitialDistDelay != 5*60 &&
3544 !options->TestingTorNetwork) {
3545 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
3546 "Tor networks!");
3547 } else if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
3548 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3551 if (options->TestingV3AuthInitialVoteDelay +
3552 options->TestingV3AuthInitialDistDelay >=
3553 options->TestingV3AuthInitialVotingInterval/2) {
3554 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3555 "must be less than half TestingV3AuthInitialVotingInterval");
3558 if (options->TestingAuthDirTimeToLearnReachability != 30*60 &&
3559 !options->TestingTorNetwork) {
3560 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
3561 "testing Tor networks!");
3562 } else if (options->TestingAuthDirTimeToLearnReachability < 0) {
3563 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3564 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
3565 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3568 if (options->TestingEstimatedDescriptorPropagationTime != 10*60 &&
3569 !options->TestingTorNetwork) {
3570 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
3571 "testing Tor networks!");
3572 } else if (options->TestingEstimatedDescriptorPropagationTime < 0) {
3573 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3574 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
3575 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3578 if (options->TestingTorNetwork) {
3579 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
3580 "almost unusable in the public Tor network, and is "
3581 "therefore only advised if you are building a "
3582 "testing Tor network!");
3585 return 0;
3586 #undef REJECT
3587 #undef COMPLAIN
3590 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3591 * equal strings. */
3592 static int
3593 opt_streq(const char *s1, const char *s2)
3595 if (!s1 && !s2)
3596 return 1;
3597 else if (s1 && s2 && !strcmp(s1,s2))
3598 return 1;
3599 else
3600 return 0;
3603 /** Check if any of the previous options have changed but aren't allowed to. */
3604 static int
3605 options_transition_allowed(or_options_t *old, or_options_t *new_val,
3606 char **msg)
3608 if (!old)
3609 return 0;
3611 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3612 *msg = tor_strdup("PidFile is not allowed to change.");
3613 return -1;
3616 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3617 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3618 "is not allowed.");
3619 return -1;
3622 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
3623 char buf[1024];
3624 int r = tor_snprintf(buf, sizeof(buf),
3625 "While Tor is running, changing DataDirectory "
3626 "(\"%s\"->\"%s\") is not allowed.",
3627 old->DataDirectory, new_val->DataDirectory);
3628 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3629 return -1;
3632 if (!opt_streq(old->User, new_val->User)) {
3633 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
3634 return -1;
3637 if (!opt_streq(old->Group, new_val->Group)) {
3638 *msg = tor_strdup("While Tor is running, changing Group is not allowed.");
3639 return -1;
3642 if (old->HardwareAccel != new_val->HardwareAccel) {
3643 *msg = tor_strdup("While Tor is running, changing HardwareAccel is "
3644 "not allowed.");
3645 return -1;
3648 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
3649 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
3650 "is not allowed.");
3651 return -1;
3654 return 0;
3657 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3658 * will require us to rotate the cpu and dns workers; else return 0. */
3659 static int
3660 options_transition_affects_workers(or_options_t *old_options,
3661 or_options_t *new_options)
3663 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3664 old_options->NumCpus != new_options->NumCpus ||
3665 old_options->ORPort != new_options->ORPort ||
3666 old_options->ServerDNSSearchDomains !=
3667 new_options->ServerDNSSearchDomains ||
3668 old_options->SafeLogging != new_options->SafeLogging ||
3669 old_options->ClientOnly != new_options->ClientOnly ||
3670 !config_lines_eq(old_options->Logs, new_options->Logs))
3671 return 1;
3673 /* Check whether log options match. */
3675 /* Nothing that changed matters. */
3676 return 0;
3679 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3680 * will require us to generate a new descriptor; else return 0. */
3681 static int
3682 options_transition_affects_descriptor(or_options_t *old_options,
3683 or_options_t *new_options)
3685 /* XXX We can be smarter here. If your DirPort isn't being
3686 * published and you just turned it off, no need to republish. If
3687 * you changed your bandwidthrate but maxadvertisedbandwidth still
3688 * trumps, no need to republish. Etc. */
3689 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3690 !opt_streq(old_options->Nickname,new_options->Nickname) ||
3691 !opt_streq(old_options->Address,new_options->Address) ||
3692 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
3693 old_options->ExitPolicyRejectPrivate !=
3694 new_options->ExitPolicyRejectPrivate ||
3695 old_options->ORPort != new_options->ORPort ||
3696 old_options->DirPort != new_options->DirPort ||
3697 old_options->ClientOnly != new_options->ClientOnly ||
3698 old_options->NoPublish != new_options->NoPublish ||
3699 old_options->_PublishServerDescriptor !=
3700 new_options->_PublishServerDescriptor ||
3701 old_options->BandwidthRate != new_options->BandwidthRate ||
3702 old_options->BandwidthBurst != new_options->BandwidthBurst ||
3703 old_options->MaxAdvertisedBandwidth !=
3704 new_options->MaxAdvertisedBandwidth ||
3705 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
3706 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
3707 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
3708 old_options->AccountingMax != new_options->AccountingMax)
3709 return 1;
3711 return 0;
3714 #ifdef MS_WINDOWS
3715 /** Return the directory on windows where we expect to find our application
3716 * data. */
3717 static char *
3718 get_windows_conf_root(void)
3720 static int is_set = 0;
3721 static char path[MAX_PATH+1];
3723 LPITEMIDLIST idl;
3724 IMalloc *m;
3725 HRESULT result;
3727 if (is_set)
3728 return path;
3730 /* Find X:\documents and settings\username\application data\ .
3731 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3733 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA,
3734 &idl))) {
3735 GetCurrentDirectory(MAX_PATH, path);
3736 is_set = 1;
3737 log_warn(LD_CONFIG,
3738 "I couldn't find your application data folder: are you "
3739 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3740 path);
3741 return path;
3743 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3744 result = SHGetPathFromIDList(idl, path);
3745 /* Now we need to free the */
3746 SHGetMalloc(&m);
3747 if (m) {
3748 m->lpVtbl->Free(m, idl);
3749 m->lpVtbl->Release(m);
3751 if (!SUCCEEDED(result)) {
3752 return NULL;
3754 strlcat(path,"\\tor",MAX_PATH);
3755 is_set = 1;
3756 return path;
3758 #endif
3760 /** Return the default location for our torrc file. */
3761 static const char *
3762 get_default_conf_file(void)
3764 #ifdef MS_WINDOWS
3765 static char path[MAX_PATH+1];
3766 strlcpy(path, get_windows_conf_root(), MAX_PATH);
3767 strlcat(path,"\\torrc",MAX_PATH);
3768 return path;
3769 #else
3770 return (CONFDIR "/torrc");
3771 #endif
3774 /** Verify whether lst is a string containing valid-looking comma-separated
3775 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3777 static int
3778 check_nickname_list(const char *lst, const char *name, char **msg)
3780 int r = 0;
3781 smartlist_t *sl;
3783 if (!lst)
3784 return 0;
3785 sl = smartlist_create();
3787 smartlist_split_string(sl, lst, ",",
3788 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
3790 SMARTLIST_FOREACH(sl, const char *, s,
3792 if (!is_legal_nickname_or_hexdigest(s)) {
3793 char buf[1024];
3794 int tmp = tor_snprintf(buf, sizeof(buf),
3795 "Invalid nickname '%s' in %s line", s, name);
3796 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
3797 r = -1;
3798 break;
3801 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
3802 smartlist_free(sl);
3803 return r;
3806 /** Learn config file name from command line arguments, or use the default */
3807 static char *
3808 find_torrc_filename(int argc, char **argv,
3809 int *using_default_torrc, int *ignore_missing_torrc)
3811 char *fname=NULL;
3812 int i;
3814 for (i = 1; i < argc; ++i) {
3815 if (i < argc-1 && !strcmp(argv[i],"-f")) {
3816 if (fname) {
3817 log(LOG_WARN, LD_CONFIG, "Duplicate -f options on command line.");
3818 tor_free(fname);
3820 #ifdef MS_WINDOWS
3821 /* XXX one day we might want to extend expand_filename to work
3822 * under Windows as well. */
3823 fname = tor_strdup(argv[i+1]);
3824 #else
3825 fname = expand_filename(argv[i+1]);
3826 #endif
3827 *using_default_torrc = 0;
3828 ++i;
3829 } else if (!strcmp(argv[i],"--ignore-missing-torrc")) {
3830 *ignore_missing_torrc = 1;
3834 if (*using_default_torrc) {
3835 /* didn't find one, try CONFDIR */
3836 const char *dflt = get_default_conf_file();
3837 if (dflt && file_status(dflt) == FN_FILE) {
3838 fname = tor_strdup(dflt);
3839 } else {
3840 #ifndef MS_WINDOWS
3841 char *fn;
3842 fn = expand_filename("~/.torrc");
3843 if (fn && file_status(fn) == FN_FILE) {
3844 fname = fn;
3845 } else {
3846 tor_free(fn);
3847 fname = tor_strdup(dflt);
3849 #else
3850 fname = tor_strdup(dflt);
3851 #endif
3854 return fname;
3857 /** Load torrc from disk, setting torrc_fname if successful */
3858 static char *
3859 load_torrc_from_disk(int argc, char **argv)
3861 char *fname=NULL;
3862 char *cf = NULL;
3863 int using_default_torrc = 1;
3864 int ignore_missing_torrc = 0;
3866 fname = find_torrc_filename(argc, argv,
3867 &using_default_torrc, &ignore_missing_torrc);
3868 tor_assert(fname);
3869 log(LOG_DEBUG, LD_CONFIG, "Opening config file \"%s\"", fname);
3871 tor_free(torrc_fname);
3872 torrc_fname = fname;
3874 /* Open config file */
3875 if (file_status(fname) != FN_FILE ||
3876 !(cf = read_file_to_str(fname,0,NULL))) {
3877 if (using_default_torrc == 1 || ignore_missing_torrc ) {
3878 log(LOG_NOTICE, LD_CONFIG, "Configuration file \"%s\" not present, "
3879 "using reasonable defaults.", fname);
3880 tor_free(fname); /* sets fname to NULL */
3881 torrc_fname = NULL;
3882 cf = tor_strdup("");
3883 } else {
3884 log(LOG_WARN, LD_CONFIG,
3885 "Unable to open configuration file \"%s\".", fname);
3886 goto err;
3890 return cf;
3891 err:
3892 tor_free(fname);
3893 torrc_fname = NULL;
3894 return NULL;
3897 /** Read a configuration file into <b>options</b>, finding the configuration
3898 * file location based on the command line. After loading the file
3899 * call options_init_from_string() to load the config.
3900 * Return 0 if success, -1 if failure. */
3902 options_init_from_torrc(int argc, char **argv)
3904 char *cf=NULL;
3905 int i, retval, command;
3906 static char **backup_argv;
3907 static int backup_argc;
3908 char *command_arg = NULL;
3909 char *errmsg=NULL;
3911 if (argv) { /* first time we're called. save commandline args */
3912 backup_argv = argv;
3913 backup_argc = argc;
3914 } else { /* we're reloading. need to clean up old options first. */
3915 argv = backup_argv;
3916 argc = backup_argc;
3918 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
3919 print_usage();
3920 exit(0);
3922 if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
3923 /* For documenting validating whether we've documented everything. */
3924 list_torrc_options();
3925 exit(0);
3928 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
3929 printf("Tor version %s.\n",get_version());
3930 if (argc > 2 && (!strcmp(argv[2],"--version"))) {
3931 print_svn_version();
3933 exit(0);
3936 /* Go through command-line variables */
3937 if (!global_cmdline_options) {
3938 /* Or we could redo the list every time we pass this place.
3939 * It does not really matter */
3940 if (config_get_commandlines(argc, argv, &global_cmdline_options) < 0) {
3941 goto err;
3945 command = CMD_RUN_TOR;
3946 for (i = 1; i < argc; ++i) {
3947 if (!strcmp(argv[i],"--list-fingerprint")) {
3948 command = CMD_LIST_FINGERPRINT;
3949 } else if (!strcmp(argv[i],"--hash-password")) {
3950 command = CMD_HASH_PASSWORD;
3951 command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
3952 ++i;
3953 } else if (!strcmp(argv[i],"--verify-config")) {
3954 command = CMD_VERIFY_CONFIG;
3958 if (command == CMD_HASH_PASSWORD) {
3959 cf = tor_strdup("");
3960 } else {
3961 cf = load_torrc_from_disk(argc, argv);
3962 if (!cf)
3963 goto err;
3966 retval = options_init_from_string(cf, command, command_arg, &errmsg);
3967 tor_free(cf);
3968 if (retval < 0)
3969 goto err;
3971 return 0;
3973 err:
3974 if (errmsg) {
3975 log(LOG_WARN,LD_CONFIG,"%s", errmsg);
3976 tor_free(errmsg);
3978 return -1;
3981 /** Load the options from the configuration in <b>cf</b>, validate
3982 * them for consistency and take actions based on them.
3984 * Return 0 if success, negative on error:
3985 * * -1 for general errors.
3986 * * -2 for failure to parse/validate,
3987 * * -3 for transition not allowed
3988 * * -4 for error while setting the new options
3990 setopt_err_t
3991 options_init_from_string(const char *cf,
3992 int command, const char *command_arg,
3993 char **msg)
3995 or_options_t *oldoptions, *newoptions;
3996 config_line_t *cl;
3997 int retval;
3998 setopt_err_t err = SETOPT_ERR_MISC;
3999 tor_assert(msg);
4001 oldoptions = global_options; /* get_options unfortunately asserts if
4002 this is the first time we run*/
4004 newoptions = tor_malloc_zero(sizeof(or_options_t));
4005 newoptions->_magic = OR_OPTIONS_MAGIC;
4006 options_init(newoptions);
4007 newoptions->command = command;
4008 newoptions->command_arg = command_arg;
4010 /* get config lines, assign them */
4011 retval = config_get_lines(cf, &cl);
4012 if (retval < 0) {
4013 err = SETOPT_ERR_PARSE;
4014 goto err;
4016 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4017 config_free_lines(cl);
4018 if (retval < 0) {
4019 err = SETOPT_ERR_PARSE;
4020 goto err;
4023 /* Go through command-line variables too */
4024 retval = config_assign(&options_format, newoptions,
4025 global_cmdline_options, 0, 0, msg);
4026 if (retval < 0) {
4027 err = SETOPT_ERR_PARSE;
4028 goto err;
4031 /* If this is a testing network configuration, change defaults
4032 * for a list of dependent config options, re-initialize newoptions
4033 * with the new defaults, and assign all options to it second time. */
4034 if (newoptions->TestingTorNetwork) {
4035 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4036 * this? We could, for example, make the parsing algorithm do two passes
4037 * over the configuration. If it finds any "suite" options like
4038 * TestingTorNetwork, it could change the defaults before its second pass.
4039 * Not urgent so long as this seems to work, but at any sign of trouble,
4040 * let's clean it up. -NM */
4042 /* Change defaults. */
4043 int i;
4044 for (i = 0; testing_tor_network_defaults[i].name; ++i) {
4045 config_var_t *new_var = &testing_tor_network_defaults[i];
4046 config_var_t *old_var =
4047 config_find_option(&options_format, new_var->name);
4048 tor_assert(new_var);
4049 tor_assert(old_var);
4050 old_var->initvalue = new_var->initvalue;
4053 /* Clear newoptions and re-initialize them with new defaults. */
4054 config_free(&options_format, newoptions);
4055 newoptions = tor_malloc_zero(sizeof(or_options_t));
4056 newoptions->_magic = OR_OPTIONS_MAGIC;
4057 options_init(newoptions);
4058 newoptions->command = command;
4059 newoptions->command_arg = command_arg;
4061 /* Assign all options a second time. */
4062 retval = config_get_lines(cf, &cl);
4063 if (retval < 0) {
4064 err = SETOPT_ERR_PARSE;
4065 goto err;
4067 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4068 config_free_lines(cl);
4069 if (retval < 0) {
4070 err = SETOPT_ERR_PARSE;
4071 goto err;
4073 retval = config_assign(&options_format, newoptions,
4074 global_cmdline_options, 0, 0, msg);
4075 if (retval < 0) {
4076 err = SETOPT_ERR_PARSE;
4077 goto err;
4081 /* Validate newoptions */
4082 if (options_validate(oldoptions, newoptions, 0, msg) < 0) {
4083 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
4084 goto err;
4087 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
4088 err = SETOPT_ERR_TRANSITION;
4089 goto err;
4092 if (set_options(newoptions, msg)) {
4093 err = SETOPT_ERR_SETTING;
4094 goto err; /* frees and replaces old options */
4097 return SETOPT_OK;
4099 err:
4100 config_free(&options_format, newoptions);
4101 if (*msg) {
4102 int len = strlen(*msg)+256;
4103 char *newmsg = tor_malloc(len);
4105 tor_snprintf(newmsg, len, "Failed to parse/validate config: %s", *msg);
4106 tor_free(*msg);
4107 *msg = newmsg;
4109 return err;
4112 /** Return the location for our configuration file.
4114 const char *
4115 get_torrc_fname(void)
4117 if (torrc_fname)
4118 return torrc_fname;
4119 else
4120 return get_default_conf_file();
4123 /** Adjust the address map mased on the MapAddress elements in the
4124 * configuration <b>options</b>
4126 static void
4127 config_register_addressmaps(or_options_t *options)
4129 smartlist_t *elts;
4130 config_line_t *opt;
4131 char *from, *to;
4133 addressmap_clear_configured();
4134 elts = smartlist_create();
4135 for (opt = options->AddressMap; opt; opt = opt->next) {
4136 smartlist_split_string(elts, opt->value, NULL,
4137 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4138 if (smartlist_len(elts) >= 2) {
4139 from = smartlist_get(elts,0);
4140 to = smartlist_get(elts,1);
4141 if (address_is_invalid_destination(to, 1)) {
4142 log_warn(LD_CONFIG,
4143 "Skipping invalid argument '%s' to MapAddress", to);
4144 } else {
4145 addressmap_register(from, tor_strdup(to), 0, ADDRMAPSRC_TORRC);
4146 if (smartlist_len(elts)>2) {
4147 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
4150 } else {
4151 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
4152 opt->value);
4154 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4155 smartlist_clear(elts);
4157 smartlist_free(elts);
4161 * Initialize the logs based on the configuration file.
4163 static int
4164 options_init_logs(or_options_t *options, int validate_only)
4166 config_line_t *opt;
4167 int ok;
4168 smartlist_t *elts;
4169 int daemon =
4170 #ifdef MS_WINDOWS
4172 #else
4173 options->RunAsDaemon;
4174 #endif
4176 ok = 1;
4177 elts = smartlist_create();
4179 for (opt = options->Logs; opt; opt = opt->next) {
4180 log_severity_list_t *severity;
4181 const char *cfg = opt->value;
4182 severity = tor_malloc_zero(sizeof(log_severity_list_t));
4183 if (parse_log_severity_config(&cfg, severity) < 0) {
4184 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
4185 opt->value);
4186 ok = 0; goto cleanup;
4189 smartlist_split_string(elts, cfg, NULL,
4190 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4192 if (smartlist_len(elts) == 0)
4193 smartlist_add(elts, tor_strdup("stdout"));
4195 if (smartlist_len(elts) == 1 &&
4196 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
4197 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
4198 int err = smartlist_len(elts) &&
4199 !strcasecmp(smartlist_get(elts,0), "stderr");
4200 if (!validate_only) {
4201 if (daemon) {
4202 log_warn(LD_CONFIG,
4203 "Can't log to %s with RunAsDaemon set; skipping stdout",
4204 err?"stderr":"stdout");
4205 } else {
4206 add_stream_log(severity, err?"<stderr>":"<stdout>",
4207 fileno(err?stderr:stdout));
4210 goto cleanup;
4212 if (smartlist_len(elts) == 1 &&
4213 !strcasecmp(smartlist_get(elts,0), "syslog")) {
4214 #ifdef HAVE_SYSLOG_H
4215 if (!validate_only) {
4216 add_syslog_log(severity);
4218 #else
4219 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
4220 #endif
4221 goto cleanup;
4224 if (smartlist_len(elts) == 2 &&
4225 !strcasecmp(smartlist_get(elts,0), "file")) {
4226 if (!validate_only) {
4227 if (add_file_log(severity, smartlist_get(elts, 1)) < 0) {
4228 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
4229 opt->value, strerror(errno));
4230 ok = 0;
4233 goto cleanup;
4236 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
4237 opt->value);
4238 ok = 0; goto cleanup;
4240 cleanup:
4241 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4242 smartlist_clear(elts);
4243 tor_free(severity);
4245 smartlist_free(elts);
4247 return ok?0:-1;
4250 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4251 * if the line is well-formed, and -1 if it isn't. If
4252 * <b>validate_only</b> is 0, and the line is well-formed, then add
4253 * the bridge described in the line to our internal bridge list. */
4254 static int
4255 parse_bridge_line(const char *line, int validate_only)
4257 smartlist_t *items = NULL;
4258 int r;
4259 char *addrport=NULL, *fingerprint=NULL;
4260 tor_addr_t addr;
4261 uint16_t port = 0;
4262 char digest[DIGEST_LEN];
4264 items = smartlist_create();
4265 smartlist_split_string(items, line, NULL,
4266 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4267 if (smartlist_len(items) < 1) {
4268 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
4269 goto err;
4271 addrport = smartlist_get(items, 0);
4272 smartlist_del_keeporder(items, 0);
4273 if (tor_addr_port_parse(addrport, &addr, &port)<0) {
4274 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
4275 goto err;
4277 if (!port) {
4278 log_warn(LD_CONFIG, "Missing port in Bridge address '%s'",addrport);
4279 goto err;
4282 if (smartlist_len(items)) {
4283 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4284 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4285 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
4286 goto err;
4288 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4289 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
4290 goto err;
4294 if (!validate_only) {
4295 log_debug(LD_DIR, "Bridge at %s:%d (%s)", fmt_addr(&addr),
4296 (int)port,
4297 fingerprint ? fingerprint : "no key listed");
4298 bridge_add_from_config(&addr, port, fingerprint ? digest : NULL);
4301 r = 0;
4302 goto done;
4304 err:
4305 r = -1;
4307 done:
4308 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4309 smartlist_free(items);
4310 tor_free(addrport);
4311 tor_free(fingerprint);
4312 return r;
4315 /** Read the contents of a DirServer line from <b>line</b>. If
4316 * <b>validate_only</b> is 0, and the line is well-formed, and it
4317 * shares any bits with <b>required_type</b> or <b>required_type</b>
4318 * is 0, then add the dirserver described in the line (minus whatever
4319 * bits it's missing) as a valid authority. Return 0 on success,
4320 * or -1 if the line isn't well-formed or if we can't add it. */
4321 static int
4322 parse_dir_server_line(const char *line, authority_type_t required_type,
4323 int validate_only)
4325 smartlist_t *items = NULL;
4326 int r;
4327 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
4328 uint16_t dir_port = 0, or_port = 0;
4329 char digest[DIGEST_LEN];
4330 char v3_digest[DIGEST_LEN];
4331 authority_type_t type = V2_AUTHORITY;
4332 int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
4334 items = smartlist_create();
4335 smartlist_split_string(items, line, NULL,
4336 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4337 if (smartlist_len(items) < 1) {
4338 log_warn(LD_CONFIG, "No arguments on DirServer line.");
4339 goto err;
4342 if (is_legal_nickname(smartlist_get(items, 0))) {
4343 nickname = smartlist_get(items, 0);
4344 smartlist_del_keeporder(items, 0);
4347 while (smartlist_len(items)) {
4348 char *flag = smartlist_get(items, 0);
4349 if (TOR_ISDIGIT(flag[0]))
4350 break;
4351 if (!strcasecmp(flag, "v1")) {
4352 type |= (V1_AUTHORITY | HIDSERV_AUTHORITY);
4353 } else if (!strcasecmp(flag, "hs")) {
4354 type |= HIDSERV_AUTHORITY;
4355 } else if (!strcasecmp(flag, "no-hs")) {
4356 is_not_hidserv_authority = 1;
4357 } else if (!strcasecmp(flag, "bridge")) {
4358 type |= BRIDGE_AUTHORITY;
4359 } else if (!strcasecmp(flag, "no-v2")) {
4360 is_not_v2_authority = 1;
4361 } else if (!strcasecmpstart(flag, "orport=")) {
4362 int ok;
4363 char *portstring = flag + strlen("orport=");
4364 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
4365 if (!ok)
4366 log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
4367 portstring);
4368 } else if (!strcasecmpstart(flag, "v3ident=")) {
4369 char *idstr = flag + strlen("v3ident=");
4370 if (strlen(idstr) != HEX_DIGEST_LEN ||
4371 base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
4372 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirServer line",
4373 flag);
4374 } else {
4375 type |= V3_AUTHORITY;
4377 } else {
4378 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
4379 flag);
4381 tor_free(flag);
4382 smartlist_del_keeporder(items, 0);
4384 if (is_not_hidserv_authority)
4385 type &= ~HIDSERV_AUTHORITY;
4386 if (is_not_v2_authority)
4387 type &= ~V2_AUTHORITY;
4389 if (smartlist_len(items) < 2) {
4390 log_warn(LD_CONFIG, "Too few arguments to DirServer line.");
4391 goto err;
4393 addrport = smartlist_get(items, 0);
4394 smartlist_del_keeporder(items, 0);
4395 if (parse_addr_port(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
4396 log_warn(LD_CONFIG, "Error parsing DirServer address '%s'", addrport);
4397 goto err;
4399 if (!dir_port) {
4400 log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
4401 goto err;
4404 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4405 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4406 log_warn(LD_CONFIG, "Key digest for DirServer is wrong length %d.",
4407 (int)strlen(fingerprint));
4408 goto err;
4410 if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4411 /* a known bad fingerprint. refuse to use it. We can remove this
4412 * clause once Tor 0.1.2.17 is obsolete. */
4413 log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
4414 "torrc file (%s), or reinstall Tor and use the default torrc.",
4415 get_torrc_fname());
4416 goto err;
4418 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4419 log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
4420 goto err;
4423 if (!validate_only && (!required_type || required_type & type)) {
4424 if (required_type)
4425 type &= required_type; /* pare down what we think of them as an
4426 * authority for. */
4427 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
4428 address, (int)dir_port, (char*)smartlist_get(items,0));
4429 if (!add_trusted_dir_server(nickname, address, dir_port, or_port,
4430 digest, v3_digest, type))
4431 goto err;
4434 r = 0;
4435 goto done;
4437 err:
4438 r = -1;
4440 done:
4441 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4442 smartlist_free(items);
4443 tor_free(addrport);
4444 tor_free(address);
4445 tor_free(nickname);
4446 tor_free(fingerprint);
4447 return r;
4450 /** Adjust the value of options->DataDirectory, or fill it in if it's
4451 * absent. Return 0 on success, -1 on failure. */
4452 static int
4453 normalize_data_directory(or_options_t *options)
4455 #ifdef MS_WINDOWS
4456 char *p;
4457 if (options->DataDirectory)
4458 return 0; /* all set */
4459 p = tor_malloc(MAX_PATH);
4460 strlcpy(p,get_windows_conf_root(),MAX_PATH);
4461 options->DataDirectory = p;
4462 return 0;
4463 #else
4464 const char *d = options->DataDirectory;
4465 if (!d)
4466 d = "~/.tor";
4468 if (strncmp(d,"~/",2) == 0) {
4469 char *fn = expand_filename(d);
4470 if (!fn) {
4471 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
4472 return -1;
4474 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
4475 /* If our homedir is /, we probably don't want to use it. */
4476 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4477 * want. */
4478 log_warn(LD_CONFIG,
4479 "Default DataDirectory is \"~/.tor\". This expands to "
4480 "\"%s\", which is probably not what you want. Using "
4481 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
4482 tor_free(fn);
4483 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
4485 tor_free(options->DataDirectory);
4486 options->DataDirectory = fn;
4488 return 0;
4489 #endif
4492 /** Check and normalize the value of options->DataDirectory; return 0 if it
4493 * sane, -1 otherwise. */
4494 static int
4495 validate_data_directory(or_options_t *options)
4497 if (normalize_data_directory(options) < 0)
4498 return -1;
4499 tor_assert(options->DataDirectory);
4500 if (strlen(options->DataDirectory) > (512-128)) {
4501 log_warn(LD_CONFIG, "DataDirectory is too long.");
4502 return -1;
4504 return 0;
4507 /** This string must remain the same forevermore. It is how we
4508 * recognize that the torrc file doesn't need to be backed up. */
4509 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4510 "if you edit it, comments will not be preserved"
4511 /** This string can change; it tries to give the reader an idea
4512 * that editing this file by hand is not a good plan. */
4513 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4514 "to torrc.orig.1 or similar, and Tor will ignore it"
4516 /** Save a configuration file for the configuration in <b>options</b>
4517 * into the file <b>fname</b>. If the file already exists, and
4518 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4519 * replace it. Return 0 on success, -1 on failure. */
4520 static int
4521 write_configuration_file(const char *fname, or_options_t *options)
4523 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4524 int rename_old = 0, r;
4525 size_t len;
4527 tor_assert(fname);
4529 switch (file_status(fname)) {
4530 case FN_FILE:
4531 old_val = read_file_to_str(fname, 0, NULL);
4532 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4533 rename_old = 1;
4535 tor_free(old_val);
4536 break;
4537 case FN_NOENT:
4538 break;
4539 case FN_ERROR:
4540 case FN_DIR:
4541 default:
4542 log_warn(LD_CONFIG,
4543 "Config file \"%s\" is not a file? Failing.", fname);
4544 return -1;
4547 if (!(new_conf = options_dump(options, 1))) {
4548 log_warn(LD_BUG, "Couldn't get configuration string");
4549 goto err;
4552 len = strlen(new_conf)+256;
4553 new_val = tor_malloc(len);
4554 tor_snprintf(new_val, len, "%s\n%s\n\n%s",
4555 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4557 if (rename_old) {
4558 int i = 1;
4559 size_t fn_tmp_len = strlen(fname)+32;
4560 char *fn_tmp;
4561 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4562 fn_tmp = tor_malloc(fn_tmp_len);
4563 while (1) {
4564 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4565 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4566 tor_free(fn_tmp);
4567 goto err;
4569 if (file_status(fn_tmp) == FN_NOENT)
4570 break;
4571 ++i;
4573 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4574 if (rename(fname, fn_tmp) < 0) {
4575 log_warn(LD_FS,
4576 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4577 fname, fn_tmp, strerror(errno));
4578 tor_free(fn_tmp);
4579 goto err;
4581 tor_free(fn_tmp);
4584 if (write_str_to_file(fname, new_val, 0) < 0)
4585 goto err;
4587 r = 0;
4588 goto done;
4589 err:
4590 r = -1;
4591 done:
4592 tor_free(new_val);
4593 tor_free(new_conf);
4594 return r;
4598 * Save the current configuration file value to disk. Return 0 on
4599 * success, -1 on failure.
4602 options_save_current(void)
4604 if (torrc_fname) {
4605 /* This fails if we can't write to our configuration file.
4607 * If we try falling back to datadirectory or something, we have a better
4608 * chance of saving the configuration, but a better chance of doing
4609 * something the user never expected. Let's just warn instead. */
4610 return write_configuration_file(torrc_fname, get_options());
4612 return write_configuration_file(get_default_conf_file(), get_options());
4615 /** Mapping from a unit name to a multiplier for converting that unit into a
4616 * base unit. */
4617 struct unit_table_t {
4618 const char *unit;
4619 uint64_t multiplier;
4622 /** Table to map the names of memory units to the number of bytes they
4623 * contain. */
4624 static struct unit_table_t memory_units[] = {
4625 { "", 1 },
4626 { "b", 1<< 0 },
4627 { "byte", 1<< 0 },
4628 { "bytes", 1<< 0 },
4629 { "kb", 1<<10 },
4630 { "kbyte", 1<<10 },
4631 { "kbytes", 1<<10 },
4632 { "kilobyte", 1<<10 },
4633 { "kilobytes", 1<<10 },
4634 { "m", 1<<20 },
4635 { "mb", 1<<20 },
4636 { "mbyte", 1<<20 },
4637 { "mbytes", 1<<20 },
4638 { "megabyte", 1<<20 },
4639 { "megabytes", 1<<20 },
4640 { "gb", 1<<30 },
4641 { "gbyte", 1<<30 },
4642 { "gbytes", 1<<30 },
4643 { "gigabyte", 1<<30 },
4644 { "gigabytes", 1<<30 },
4645 { "tb", U64_LITERAL(1)<<40 },
4646 { "terabyte", U64_LITERAL(1)<<40 },
4647 { "terabytes", U64_LITERAL(1)<<40 },
4648 { NULL, 0 },
4651 /** Table to map the names of time units to the number of seconds they
4652 * contain. */
4653 static struct unit_table_t time_units[] = {
4654 { "", 1 },
4655 { "second", 1 },
4656 { "seconds", 1 },
4657 { "minute", 60 },
4658 { "minutes", 60 },
4659 { "hour", 60*60 },
4660 { "hours", 60*60 },
4661 { "day", 24*60*60 },
4662 { "days", 24*60*60 },
4663 { "week", 7*24*60*60 },
4664 { "weeks", 7*24*60*60 },
4665 { NULL, 0 },
4668 /** Parse a string <b>val</b> containing a number, zero or more
4669 * spaces, and an optional unit string. If the unit appears in the
4670 * table <b>u</b>, then multiply the number by the unit multiplier.
4671 * On success, set *<b>ok</b> to 1 and return this product.
4672 * Otherwise, set *<b>ok</b> to 0.
4674 static uint64_t
4675 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4677 uint64_t v;
4678 char *cp;
4680 tor_assert(ok);
4682 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4683 if (!*ok)
4684 return 0;
4685 if (!cp) {
4686 *ok = 1;
4687 return v;
4689 while (TOR_ISSPACE(*cp))
4690 ++cp;
4691 for ( ;u->unit;++u) {
4692 if (!strcasecmp(u->unit, cp)) {
4693 v *= u->multiplier;
4694 *ok = 1;
4695 return v;
4698 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4699 *ok = 0;
4700 return 0;
4703 /** Parse a string in the format "number unit", where unit is a unit of
4704 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4705 * and return the number of bytes specified. Otherwise, set
4706 * *<b>ok</b> to false and return 0. */
4707 static uint64_t
4708 config_parse_memunit(const char *s, int *ok)
4710 return config_parse_units(s, memory_units, ok);
4713 /** Parse a string in the format "number unit", where unit is a unit of time.
4714 * On success, set *<b>ok</b> to true and return the number of seconds in
4715 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4717 static int
4718 config_parse_interval(const char *s, int *ok)
4720 uint64_t r;
4721 r = config_parse_units(s, time_units, ok);
4722 if (!ok)
4723 return -1;
4724 if (r > INT_MAX) {
4725 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4726 *ok = 0;
4727 return -1;
4729 return (int)r;
4733 * Initialize the libevent library.
4735 static void
4736 init_libevent(void)
4738 configure_libevent_logging();
4739 /* If the kernel complains that some method (say, epoll) doesn't
4740 * exist, we don't care about it, since libevent will cope.
4742 suppress_libevent_log_msg("Function not implemented");
4743 #ifdef __APPLE__
4744 if (decode_libevent_version() < LE_11B) {
4745 setenv("EVENT_NOKQUEUE","1",1);
4747 #endif
4748 event_init();
4749 suppress_libevent_log_msg(NULL);
4750 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4751 /* Making this a NOTICE for now so we can link bugs to a libevent versions
4752 * or methods better. */
4753 log(LOG_NOTICE, LD_GENERAL,
4754 "Initialized libevent version %s using method %s. Good.",
4755 event_get_version(), event_get_method());
4756 check_libevent_version(event_get_method(), get_options()->ORPort != 0);
4757 #else
4758 log(LOG_NOTICE, LD_GENERAL,
4759 "Initialized old libevent (version 1.0b or earlier).");
4760 log(LOG_WARN, LD_GENERAL,
4761 "You have a *VERY* old version of libevent. It is likely to be buggy; "
4762 "please build Tor with a more recent version.");
4763 #endif
4766 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4767 /** Table mapping return value of event_get_version() to le_version_t. */
4768 static const struct {
4769 const char *name; le_version_t version;
4770 } le_version_table[] = {
4771 /* earlier versions don't have get_version. */
4772 { "1.0c", LE_10C },
4773 { "1.0d", LE_10D },
4774 { "1.0e", LE_10E },
4775 { "1.1", LE_11 },
4776 { "1.1a", LE_11A },
4777 { "1.1b", LE_11B },
4778 { "1.2", LE_12 },
4779 { "1.2a", LE_12A },
4780 { "1.3", LE_13 },
4781 { "1.3a", LE_13A },
4782 { "1.3b", LE_13B },
4783 { "1.3c", LE_13C },
4784 { "1.3d", LE_13D },
4785 { NULL, LE_OTHER }
4788 /** Return the le_version_t for the current version of libevent. If the
4789 * version is very new, return LE_OTHER. If the version is so old that it
4790 * doesn't support event_get_version(), return LE_OLD. */
4791 static le_version_t
4792 decode_libevent_version(void)
4794 const char *v = event_get_version();
4795 int i;
4796 for (i=0; le_version_table[i].name; ++i) {
4797 if (!strcmp(le_version_table[i].name, v)) {
4798 return le_version_table[i].version;
4801 return LE_OTHER;
4805 * Compare the given libevent method and version to a list of versions
4806 * which are known not to work. Warn the user as appropriate.
4808 static void
4809 check_libevent_version(const char *m, int server)
4811 int buggy = 0, iffy = 0, slow = 0, thread_unsafe = 0;
4812 le_version_t version;
4813 const char *v = event_get_version();
4814 const char *badness = NULL;
4815 const char *sad_os = "";
4817 version = decode_libevent_version();
4819 /* XXX Would it be worthwhile disabling the methods that we know
4820 * are buggy, rather than just warning about them and then proceeding
4821 * to use them? If so, we should probably not wrap this whole thing
4822 * in HAVE_EVENT_GET_VERSION and HAVE_EVENT_GET_METHOD. -RD */
4823 /* XXXX The problem is that it's not trivial to get libevent to change it's
4824 * method once it's initialized, and it's not trivial to tell what method it
4825 * will use without initializing it. I guess we could preemptively disable
4826 * buggy libevent modes based on the version _before_ initializing it,
4827 * though, but then there's no good way (afaict) to warn "I would have used
4828 * kqueue, but instead I'm using select." -NM */
4829 if (!strcmp(m, "kqueue")) {
4830 if (version < LE_11B)
4831 buggy = 1;
4832 } else if (!strcmp(m, "epoll")) {
4833 if (version < LE_11)
4834 iffy = 1;
4835 } else if (!strcmp(m, "poll")) {
4836 if (version < LE_10E)
4837 buggy = 1;
4838 else if (version < LE_11)
4839 slow = 1;
4840 } else if (!strcmp(m, "select")) {
4841 if (version < LE_11)
4842 slow = 1;
4843 } else if (!strcmp(m, "win32")) {
4844 if (version < LE_11B)
4845 buggy = 1;
4848 /* Libevent versions before 1.3b do very badly on operating systems with
4849 * user-space threading implementations. */
4850 #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
4851 if (server && version < LE_13B) {
4852 thread_unsafe = 1;
4853 sad_os = "BSD variants";
4855 #elif defined(__APPLE__) || defined(__darwin__)
4856 if (server && version < LE_13B) {
4857 thread_unsafe = 1;
4858 sad_os = "Mac OS X";
4860 #endif
4862 if (thread_unsafe) {
4863 log(LOG_WARN, LD_GENERAL,
4864 "Libevent version %s often crashes when running a Tor server with %s. "
4865 "Please use the latest version of libevent (1.3b or later)",v,sad_os);
4866 badness = "BROKEN";
4867 } else if (buggy) {
4868 log(LOG_WARN, LD_GENERAL,
4869 "There are serious bugs in using %s with libevent %s. "
4870 "Please use the latest version of libevent.", m, v);
4871 badness = "BROKEN";
4872 } else if (iffy) {
4873 log(LOG_WARN, LD_GENERAL,
4874 "There are minor bugs in using %s with libevent %s. "
4875 "You may want to use the latest version of libevent.", m, v);
4876 badness = "BUGGY";
4877 } else if (slow && server) {
4878 log(LOG_WARN, LD_GENERAL,
4879 "libevent %s can be very slow with %s. "
4880 "When running a server, please use the latest version of libevent.",
4881 v,m);
4882 badness = "SLOW";
4884 if (badness) {
4885 control_event_general_status(LOG_WARN,
4886 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
4887 v, m, badness);
4891 #else
4892 static le_version_t
4893 decode_libevent_version(void)
4895 return LE_OLD;
4897 #endif
4899 /** Return the persistent state struct for this Tor. */
4900 or_state_t *
4901 get_or_state(void)
4903 tor_assert(global_state);
4904 return global_state;
4907 /** Return a newly allocated string holding a filename relative to the data
4908 * directory. If <b>sub1</b> is present, it is the first path component after
4909 * the data directory. If <b>sub2</b> is also present, it is the second path
4910 * component after the data directory. If <b>suffix</b> is present, it
4911 * is appended to the filename.
4913 * Examples:
4914 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
4915 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
4916 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
4917 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
4919 * Note: Consider using the get_datadir_fname* macros in or.h.
4921 char *
4922 options_get_datadir_fname2_suffix(or_options_t *options,
4923 const char *sub1, const char *sub2,
4924 const char *suffix)
4926 char *fname = NULL;
4927 size_t len;
4928 tor_assert(options);
4929 tor_assert(options->DataDirectory);
4930 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
4931 len = strlen(options->DataDirectory);
4932 if (sub1) {
4933 len += strlen(sub1)+1;
4934 if (sub2)
4935 len += strlen(sub2)+1;
4937 if (suffix)
4938 len += strlen(suffix);
4939 len++;
4940 fname = tor_malloc(len);
4941 if (sub1) {
4942 if (sub2) {
4943 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
4944 options->DataDirectory, sub1, sub2);
4945 } else {
4946 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
4947 options->DataDirectory, sub1);
4949 } else {
4950 strlcpy(fname, options->DataDirectory, len);
4952 if (suffix)
4953 strlcat(fname, suffix, len);
4954 return fname;
4957 /** Return 0 if every setting in <b>state</b> is reasonable, and a
4958 * permissible transition from <b>old_state</b>. Else warn and return -1.
4959 * Should have no side effects, except for normalizing the contents of
4960 * <b>state</b>.
4962 /* XXX from_setconf is here because of bug 238 */
4963 static int
4964 or_state_validate(or_state_t *old_state, or_state_t *state,
4965 int from_setconf, char **msg)
4967 /* We don't use these; only options do. Still, we need to match that
4968 * signature. */
4969 (void) from_setconf;
4970 (void) old_state;
4972 if (entry_guards_parse_state(state, 0, msg)<0)
4973 return -1;
4975 return 0;
4978 /** Replace the current persistent state with <b>new_state</b> */
4979 static void
4980 or_state_set(or_state_t *new_state)
4982 char *err = NULL;
4983 tor_assert(new_state);
4984 if (global_state)
4985 config_free(&state_format, global_state);
4986 global_state = new_state;
4987 if (entry_guards_parse_state(global_state, 1, &err)<0) {
4988 log_warn(LD_GENERAL,"%s",err);
4989 tor_free(err);
4991 if (rep_hist_load_state(global_state, &err)<0) {
4992 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
4993 tor_free(err);
4997 /** Reload the persistent state from disk, generating a new state as needed.
4998 * Return 0 on success, less than 0 on failure.
5000 static int
5001 or_state_load(void)
5003 or_state_t *new_state = NULL;
5004 char *contents = NULL, *fname;
5005 char *errmsg = NULL;
5006 int r = -1, badstate = 0;
5008 fname = get_datadir_fname("state");
5009 switch (file_status(fname)) {
5010 case FN_FILE:
5011 if (!(contents = read_file_to_str(fname, 0, NULL))) {
5012 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
5013 goto done;
5015 break;
5016 case FN_NOENT:
5017 break;
5018 case FN_ERROR:
5019 case FN_DIR:
5020 default:
5021 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
5022 goto done;
5024 new_state = tor_malloc_zero(sizeof(or_state_t));
5025 new_state->_magic = OR_STATE_MAGIC;
5026 config_init(&state_format, new_state);
5027 if (contents) {
5028 config_line_t *lines=NULL;
5029 int assign_retval;
5030 if (config_get_lines(contents, &lines)<0)
5031 goto done;
5032 assign_retval = config_assign(&state_format, new_state,
5033 lines, 0, 0, &errmsg);
5034 config_free_lines(lines);
5035 if (assign_retval<0)
5036 badstate = 1;
5037 if (errmsg) {
5038 log_warn(LD_GENERAL, "%s", errmsg);
5039 tor_free(errmsg);
5043 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
5044 badstate = 1;
5046 if (errmsg) {
5047 log_warn(LD_GENERAL, "%s", errmsg);
5048 tor_free(errmsg);
5051 if (badstate && !contents) {
5052 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
5053 " This is a bug in Tor.");
5054 goto done;
5055 } else if (badstate && contents) {
5056 int i;
5057 file_status_t status;
5058 size_t len = strlen(fname)+16;
5059 char *fname2 = tor_malloc(len);
5060 for (i = 0; i < 100; ++i) {
5061 tor_snprintf(fname2, len, "%s.%d", fname, i);
5062 status = file_status(fname2);
5063 if (status == FN_NOENT)
5064 break;
5066 if (i == 100) {
5067 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
5068 "state files to move aside. Discarding the old state file.",
5069 fname);
5070 unlink(fname);
5071 } else {
5072 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
5073 "to \"%s\". This could be a bug in Tor; please tell "
5074 "the developers.", fname, fname2);
5075 if (rename(fname, fname2) < 0) {
5076 log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
5077 "OS gave an error of %s", strerror(errno));
5080 tor_free(fname2);
5081 tor_free(contents);
5082 config_free(&state_format, new_state);
5084 new_state = tor_malloc_zero(sizeof(or_state_t));
5085 new_state->_magic = OR_STATE_MAGIC;
5086 config_init(&state_format, new_state);
5087 } else if (contents) {
5088 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
5089 } else {
5090 log_info(LD_GENERAL, "Initialized state");
5092 or_state_set(new_state);
5093 new_state = NULL;
5094 if (!contents) {
5095 global_state->next_write = 0;
5096 or_state_save(time(NULL));
5098 r = 0;
5100 done:
5101 tor_free(fname);
5102 tor_free(contents);
5103 if (new_state)
5104 config_free(&state_format, new_state);
5106 return r;
5109 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
5111 or_state_save(time_t now)
5113 char *state, *contents;
5114 char tbuf[ISO_TIME_LEN+1];
5115 size_t len;
5116 char *fname;
5118 tor_assert(global_state);
5120 if (global_state->next_write > now)
5121 return 0;
5123 /* Call everything else that might dirty the state even more, in order
5124 * to avoid redundant writes. */
5125 entry_guards_update_state(global_state);
5126 rep_hist_update_state(global_state);
5127 if (accounting_is_enabled(get_options()))
5128 accounting_run_housekeeping(now);
5130 global_state->LastWritten = time(NULL);
5131 tor_free(global_state->TorVersion);
5132 len = strlen(get_version())+8;
5133 global_state->TorVersion = tor_malloc(len);
5134 tor_snprintf(global_state->TorVersion, len, "Tor %s", get_version());
5136 state = config_dump(&state_format, global_state, 1, 0);
5137 len = strlen(state)+256;
5138 contents = tor_malloc(len);
5139 format_local_iso_time(tbuf, time(NULL));
5140 tor_snprintf(contents, len,
5141 "# Tor state file last generated on %s local time\n"
5142 "# Other times below are in GMT\n"
5143 "# You *do not* need to edit this file.\n\n%s",
5144 tbuf, state);
5145 tor_free(state);
5146 fname = get_datadir_fname("state");
5147 if (write_str_to_file(fname, contents, 0)<0) {
5148 log_warn(LD_FS, "Unable to write state to file \"%s\"", fname);
5149 tor_free(fname);
5150 tor_free(contents);
5151 return -1;
5153 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
5154 tor_free(fname);
5155 tor_free(contents);
5157 global_state->next_write = TIME_MAX;
5158 return 0;
5161 /** Given a file name check to see whether the file exists but has not been
5162 * modified for a very long time. If so, remove it. */
5163 void
5164 remove_file_if_very_old(const char *fname, time_t now)
5166 #define VERY_OLD_FILE_AGE (28*24*60*60)
5167 struct stat st;
5169 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
5170 char buf[ISO_TIME_LEN+1];
5171 format_local_iso_time(buf, st.st_mtime);
5172 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
5173 "Removing it.", fname, buf);
5174 unlink(fname);
5178 /** Helper to implement GETINFO functions about configuration variables (not
5179 * their values). Given a "config/names" question, set *<b>answer</b> to a
5180 * new string describing the supported configuration variables and their
5181 * types. */
5183 getinfo_helper_config(control_connection_t *conn,
5184 const char *question, char **answer)
5186 (void) conn;
5187 if (!strcmp(question, "config/names")) {
5188 smartlist_t *sl = smartlist_create();
5189 int i;
5190 for (i = 0; _option_vars[i].name; ++i) {
5191 config_var_t *var = &_option_vars[i];
5192 const char *type, *desc;
5193 char *line;
5194 size_t len;
5195 desc = config_find_description(&options_format, var->name);
5196 switch (var->type) {
5197 case CONFIG_TYPE_STRING: type = "String"; break;
5198 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
5199 case CONFIG_TYPE_UINT: type = "Integer"; break;
5200 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
5201 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
5202 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
5203 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
5204 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
5205 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
5206 case CONFIG_TYPE_CSV: type = "CommaList"; break;
5207 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
5208 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
5209 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
5210 default:
5211 case CONFIG_TYPE_OBSOLETE:
5212 type = NULL; break;
5214 if (!type)
5215 continue;
5216 len = strlen(var->name)+strlen(type)+16;
5217 if (desc)
5218 len += strlen(desc);
5219 line = tor_malloc(len);
5220 if (desc)
5221 tor_snprintf(line, len, "%s %s %s\n",var->name,type,desc);
5222 else
5223 tor_snprintf(line, len, "%s %s\n",var->name,type);
5224 smartlist_add(sl, line);
5226 *answer = smartlist_join_strings(sl, "", 0, NULL);
5227 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
5228 smartlist_free(sl);
5230 return 0;
5233 #include "aes.h"
5234 #include "ht.h"
5235 #include "test.h"
5237 extern const char address_c_id[];
5238 extern const char aes_c_id[];
5239 extern const char compat_c_id[];
5240 extern const char container_c_id[];
5241 extern const char crypto_c_id[];
5242 extern const char log_c_id[];
5243 extern const char torgzip_c_id[];
5244 extern const char tortls_c_id[];
5245 extern const char util_c_id[];
5247 extern const char buffers_c_id[];
5248 extern const char circuitbuild_c_id[];
5249 extern const char circuitlist_c_id[];
5250 extern const char circuituse_c_id[];
5251 extern const char command_c_id[];
5252 // extern const char config_c_id[];
5253 extern const char connection_c_id[];
5254 extern const char connection_edge_c_id[];
5255 extern const char connection_or_c_id[];
5256 extern const char control_c_id[];
5257 extern const char cpuworker_c_id[];
5258 extern const char directory_c_id[];
5259 extern const char dirserv_c_id[];
5260 extern const char dns_c_id[];
5261 extern const char hibernate_c_id[];
5262 extern const char main_c_id[];
5263 #ifdef NT_SERVICE
5264 extern const char ntmain_c_id[];
5265 #endif
5266 extern const char onion_c_id[];
5267 extern const char policies_c_id[];
5268 extern const char relay_c_id[];
5269 extern const char rendclient_c_id[];
5270 extern const char rendcommon_c_id[];
5271 extern const char rendmid_c_id[];
5272 extern const char rendservice_c_id[];
5273 extern const char rephist_c_id[];
5274 extern const char router_c_id[];
5275 extern const char routerlist_c_id[];
5276 extern const char routerparse_c_id[];
5278 /** Dump the version of every file to the log. */
5279 static void
5280 print_svn_version(void)
5282 puts(ADDRESS_H_ID);
5283 puts(AES_H_ID);
5284 puts(COMPAT_H_ID);
5285 puts(CONTAINER_H_ID);
5286 puts(CRYPTO_H_ID);
5287 puts(HT_H_ID);
5288 puts(TEST_H_ID);
5289 puts(LOG_H_ID);
5290 puts(TORGZIP_H_ID);
5291 puts(TORINT_H_ID);
5292 puts(TORTLS_H_ID);
5293 puts(UTIL_H_ID);
5294 puts(address_c_id);
5295 puts(aes_c_id);
5296 puts(compat_c_id);
5297 puts(container_c_id);
5298 puts(crypto_c_id);
5299 puts(log_c_id);
5300 puts(torgzip_c_id);
5301 puts(tortls_c_id);
5302 puts(util_c_id);
5304 puts(OR_H_ID);
5305 puts(buffers_c_id);
5306 puts(circuitbuild_c_id);
5307 puts(circuitlist_c_id);
5308 puts(circuituse_c_id);
5309 puts(command_c_id);
5310 puts(config_c_id);
5311 puts(connection_c_id);
5312 puts(connection_edge_c_id);
5313 puts(connection_or_c_id);
5314 puts(control_c_id);
5315 puts(cpuworker_c_id);
5316 puts(directory_c_id);
5317 puts(dirserv_c_id);
5318 puts(dns_c_id);
5319 puts(hibernate_c_id);
5320 puts(main_c_id);
5321 #ifdef NT_SERVICE
5322 puts(ntmain_c_id);
5323 #endif
5324 puts(onion_c_id);
5325 puts(policies_c_id);
5326 puts(relay_c_id);
5327 puts(rendclient_c_id);
5328 puts(rendcommon_c_id);
5329 puts(rendmid_c_id);
5330 puts(rendservice_c_id);
5331 puts(rephist_c_id);
5332 puts(router_c_id);
5333 puts(routerlist_c_id);
5334 puts(routerparse_c_id);