Use S_CASE for ehostunreach, not E_CASE. Partial backport of 69deb22f. Fixes 0.2...
[tor/rransom.git] / src / or / config.c
blob70b99d75544e9633fae7c3426277068b5cb5b9c3
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-2010, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file config.c
9 * \brief Code to parse and interpret configuration files.
10 **/
12 #define CONFIG_PRIVATE
14 #include "or.h"
15 #ifdef MS_WINDOWS
16 #include <shlobj.h>
17 #endif
19 /** Enumeration of types which option values can take */
20 typedef enum config_type_t {
21 CONFIG_TYPE_STRING = 0, /**< An arbitrary string. */
22 CONFIG_TYPE_FILENAME, /**< A filename: some prefixes get expanded. */
23 CONFIG_TYPE_UINT, /**< A non-negative integer less than MAX_INT */
24 CONFIG_TYPE_INTERVAL, /**< A number of seconds, with optional units*/
25 CONFIG_TYPE_MEMUNIT, /**< A number of bytes, with optional units*/
26 CONFIG_TYPE_DOUBLE, /**< A floating-point value */
27 CONFIG_TYPE_BOOL, /**< A boolean value, expressed as 0 or 1. */
28 CONFIG_TYPE_ISOTIME, /**< An ISO-formatted time relative to GMT. */
29 CONFIG_TYPE_CSV, /**< A list of strings, separated by commas and
30 * optional whitespace. */
31 CONFIG_TYPE_LINELIST, /**< Uninterpreted config lines */
32 CONFIG_TYPE_LINELIST_S, /**< Uninterpreted, context-sensitive config lines,
33 * mixed with other keywords. */
34 CONFIG_TYPE_LINELIST_V, /**< Catch-all "virtual" option to summarize
35 * context-sensitive config lines when fetching.
37 CONFIG_TYPE_ROUTERSET, /**< A list of router names, addrs, and fps,
38 * parsed into a routerset_t. */
39 CONFIG_TYPE_OBSOLETE, /**< Obsolete (ignored) option. */
40 } config_type_t;
42 /** An abbreviation for a configuration option allowed on the command line. */
43 typedef struct config_abbrev_t {
44 const char *abbreviated;
45 const char *full;
46 int commandline_only;
47 int warn;
48 } config_abbrev_t;
50 /* Handy macro for declaring "In the config file or on the command line,
51 * you can abbreviate <b>tok</b>s as <b>tok</b>". */
52 #define PLURAL(tok) { #tok, #tok "s", 0, 0 }
54 /** A list of abbreviations and aliases to map command-line options, obsolete
55 * option names, or alternative option names, to their current values. */
56 static config_abbrev_t _option_abbrevs[] = {
57 PLURAL(ExitNode),
58 PLURAL(EntryNode),
59 PLURAL(ExcludeNode),
60 PLURAL(FirewallPort),
61 PLURAL(LongLivedPort),
62 PLURAL(HiddenServiceNode),
63 PLURAL(HiddenServiceExcludeNode),
64 PLURAL(NumCpu),
65 PLURAL(RendNode),
66 PLURAL(RendExcludeNode),
67 PLURAL(StrictEntryNode),
68 PLURAL(StrictExitNode),
69 { "l", "Log", 1, 0},
70 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
71 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
72 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
73 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
74 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
75 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
76 { "MaxConn", "ConnLimit", 0, 1},
77 { "ORBindAddress", "ORListenAddress", 0, 0},
78 { "DirBindAddress", "DirListenAddress", 0, 0},
79 { "SocksBindAddress", "SocksListenAddress", 0, 0},
80 { "UseHelperNodes", "UseEntryGuards", 0, 0},
81 { "NumHelperNodes", "NumEntryGuards", 0, 0},
82 { "UseEntryNodes", "UseEntryGuards", 0, 0},
83 { "NumEntryNodes", "NumEntryGuards", 0, 0},
84 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
85 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
86 { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0 },
87 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
88 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
89 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
90 { NULL, NULL, 0, 0},
93 /** A list of state-file "abbreviations," for compatibility. */
94 static config_abbrev_t _state_abbrevs[] = {
95 { "AccountingBytesReadInterval", "AccountingBytesReadInInterval", 0, 0 },
96 { "HelperNode", "EntryGuard", 0, 0 },
97 { "HelperNodeDownSince", "EntryGuardDownSince", 0, 0 },
98 { "HelperNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
99 { "EntryNode", "EntryGuard", 0, 0 },
100 { "EntryNodeDownSince", "EntryGuardDownSince", 0, 0 },
101 { "EntryNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
102 { NULL, NULL, 0, 0},
104 #undef PLURAL
106 /** A variable allowed in the configuration file or on the command line. */
107 typedef struct config_var_t {
108 const char *name; /**< The full keyword (case insensitive). */
109 config_type_t type; /**< How to interpret the type and turn it into a
110 * value. */
111 off_t var_offset; /**< Offset of the corresponding member of or_options_t. */
112 const char *initvalue; /**< String (or null) describing initial value. */
113 } config_var_t;
115 /** An entry for config_vars: "The option <b>name</b> has type
116 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
117 * or_options_t.<b>member</b>"
119 #define VAR(name,conftype,member,initvalue) \
120 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
121 initvalue }
122 /** As VAR, but the option name and member name are the same. */
123 #define V(member,conftype,initvalue) \
124 VAR(#member, conftype, member, initvalue)
125 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
126 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
128 /** Array of configuration options. Until we disallow nonstandard
129 * abbreviations, order is significant, since the first matching option will
130 * be chosen first.
132 static config_var_t _option_vars[] = {
133 OBSOLETE("AccountingMaxKB"),
134 V(AccountingMax, MEMUNIT, "0 bytes"),
135 V(AccountingStart, STRING, NULL),
136 V(Address, STRING, NULL),
137 V(AllowInvalidNodes, CSV, "middle,rendezvous"),
138 V(AllowNonRFC953Hostnames, BOOL, "0"),
139 V(AllowSingleHopCircuits, BOOL, "0"),
140 V(AllowSingleHopExits, BOOL, "0"),
141 V(AlternateBridgeAuthority, LINELIST, NULL),
142 V(AlternateDirAuthority, LINELIST, NULL),
143 V(AlternateHSAuthority, LINELIST, NULL),
144 V(AssumeReachable, BOOL, "0"),
145 V(AuthDirBadDir, LINELIST, NULL),
146 V(AuthDirBadExit, LINELIST, NULL),
147 V(AuthDirInvalid, LINELIST, NULL),
148 V(AuthDirReject, LINELIST, NULL),
149 V(AuthDirRejectUnlisted, BOOL, "0"),
150 V(AuthDirListBadDirs, BOOL, "0"),
151 V(AuthDirListBadExits, BOOL, "0"),
152 V(AuthDirMaxServersPerAddr, UINT, "2"),
153 V(AuthDirMaxServersPerAuthAddr,UINT, "5"),
154 VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
155 V(AutomapHostsOnResolve, BOOL, "0"),
156 V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
157 V(AvoidDiskWrites, BOOL, "0"),
158 V(BandwidthBurst, MEMUNIT, "10 MB"),
159 V(BandwidthRate, MEMUNIT, "5 MB"),
160 V(BridgeAuthoritativeDir, BOOL, "0"),
161 VAR("Bridge", LINELIST, Bridges, NULL),
162 V(BridgePassword, STRING, NULL),
163 V(BridgeRecordUsageByCountry, BOOL, "1"),
164 V(BridgeRelay, BOOL, "0"),
165 V(CircuitBuildTimeout, INTERVAL, "1 minute"),
166 V(CircuitIdleTimeout, INTERVAL, "1 hour"),
167 V(ClientDNSRejectInternalAddresses, BOOL,"1"),
168 V(ClientOnly, BOOL, "0"),
169 V(ConnLimit, UINT, "1000"),
170 V(ConstrainedSockets, BOOL, "0"),
171 V(ConstrainedSockSize, MEMUNIT, "8192"),
172 V(ContactInfo, STRING, NULL),
173 V(ControlListenAddress, LINELIST, NULL),
174 V(ControlPort, UINT, "0"),
175 V(ControlSocket, LINELIST, NULL),
176 V(CookieAuthentication, BOOL, "0"),
177 V(CookieAuthFileGroupReadable, BOOL, "0"),
178 V(CookieAuthFile, STRING, NULL),
179 V(DataDirectory, FILENAME, NULL),
180 OBSOLETE("DebugLogFile"),
181 V(DirAllowPrivateAddresses, BOOL, NULL),
182 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
183 V(DirListenAddress, LINELIST, NULL),
184 OBSOLETE("DirFetchPeriod"),
185 V(DirPolicy, LINELIST, NULL),
186 V(DirPort, UINT, "0"),
187 V(DirPortFrontPage, FILENAME, NULL),
188 OBSOLETE("DirPostPeriod"),
189 #ifdef ENABLE_GEOIP_STATS
190 V(DirRecordUsageByCountry, BOOL, "0"),
191 V(DirRecordUsageGranularity, UINT, "4"),
192 V(DirRecordUsageRetainIPs, INTERVAL, "14 days"),
193 V(DirRecordUsageSaveInterval, INTERVAL, "6 hours"),
194 #endif
195 VAR("DirServer", LINELIST, DirServers, NULL),
196 V(DNSPort, UINT, "0"),
197 V(DNSListenAddress, LINELIST, NULL),
198 V(DownloadExtraInfo, BOOL, "0"),
199 V(EnforceDistinctSubnets, BOOL, "1"),
200 V(EntryNodes, ROUTERSET, NULL),
201 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
202 V(ExcludeNodes, ROUTERSET, NULL),
203 V(ExcludeExitNodes, ROUTERSET, NULL),
204 V(ExcludeSingleHopRelays, BOOL, "1"),
205 V(ExitNodes, ROUTERSET, NULL),
206 V(ExitPolicy, LINELIST, NULL),
207 V(ExitPolicyRejectPrivate, BOOL, "1"),
208 V(FallbackNetworkstatusFile, FILENAME,
209 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "fallback-consensus"),
210 V(FascistFirewall, BOOL, "0"),
211 V(FirewallPorts, CSV, ""),
212 V(FastFirstHopPK, BOOL, "1"),
213 V(FetchDirInfoEarly, BOOL, "0"),
214 V(FetchServerDescriptors, BOOL, "1"),
215 V(FetchHidServDescriptors, BOOL, "1"),
216 V(FetchUselessDescriptors, BOOL, "0"),
217 #ifdef WIN32
218 V(GeoIPFile, FILENAME, "<default>"),
219 #else
220 V(GeoIPFile, FILENAME,
221 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
222 #endif
223 OBSOLETE("Group"),
224 V(HardwareAccel, BOOL, "0"),
225 V(HashedControlPassword, LINELIST, NULL),
226 V(HidServDirectoryV2, BOOL, "1"),
227 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
228 OBSOLETE("HiddenServiceExcludeNodes"),
229 OBSOLETE("HiddenServiceNodes"),
230 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
231 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
232 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
233 VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
234 V(HidServAuth, LINELIST, NULL),
235 V(HSAuthoritativeDir, BOOL, "0"),
236 V(HSAuthorityRecordStats, BOOL, "0"),
237 V(HttpProxy, STRING, NULL),
238 V(HttpProxyAuthenticator, STRING, NULL),
239 V(HttpsProxy, STRING, NULL),
240 V(HttpsProxyAuthenticator, STRING, NULL),
241 OBSOLETE("IgnoreVersion"),
242 V(KeepalivePeriod, INTERVAL, "5 minutes"),
243 VAR("Log", LINELIST, Logs, NULL),
244 OBSOLETE("LinkPadding"),
245 OBSOLETE("LogLevel"),
246 OBSOLETE("LogFile"),
247 V(LongLivedPorts, CSV,
248 "21,22,706,1863,5050,5190,5222,5223,6667,6697,8300"),
249 VAR("MapAddress", LINELIST, AddressMap, NULL),
250 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
251 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
252 V(MaxOnionsPending, UINT, "100"),
253 OBSOLETE("MonthlyAccountingStart"),
254 V(MyFamily, STRING, NULL),
255 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
256 VAR("NamingAuthoritativeDirectory",BOOL, NamingAuthoritativeDir, "0"),
257 V(NatdListenAddress, LINELIST, NULL),
258 V(NatdPort, UINT, "0"),
259 V(Nickname, STRING, NULL),
260 V(NoPublish, BOOL, "0"),
261 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
262 V(NumCpus, UINT, "1"),
263 V(NumEntryGuards, UINT, "3"),
264 V(ORListenAddress, LINELIST, NULL),
265 V(ORPort, UINT, "0"),
266 V(OutboundBindAddress, STRING, NULL),
267 OBSOLETE("PathlenCoinWeight"),
268 V(PidFile, STRING, NULL),
269 V(TestingTorNetwork, BOOL, "0"),
270 V(PreferTunneledDirConns, BOOL, "1"),
271 V(ProtocolWarnings, BOOL, "0"),
272 V(PublishServerDescriptor, CSV, "1"),
273 V(PublishHidServDescriptors, BOOL, "1"),
274 V(ReachableAddresses, LINELIST, NULL),
275 V(ReachableDirAddresses, LINELIST, NULL),
276 V(ReachableORAddresses, LINELIST, NULL),
277 V(RecommendedVersions, LINELIST, NULL),
278 V(RecommendedClientVersions, LINELIST, NULL),
279 V(RecommendedServerVersions, LINELIST, NULL),
280 OBSOLETE("RedirectExit"),
281 V(RejectPlaintextPorts, CSV, ""),
282 V(RelayBandwidthBurst, MEMUNIT, "0"),
283 V(RelayBandwidthRate, MEMUNIT, "0"),
284 OBSOLETE("RendExcludeNodes"),
285 OBSOLETE("RendNodes"),
286 V(RendPostPeriod, INTERVAL, "1 hour"),
287 V(RephistTrackTime, INTERVAL, "24 hours"),
288 OBSOLETE("RouterFile"),
289 V(RunAsDaemon, BOOL, "0"),
290 V(RunTesting, BOOL, "0"),
291 V(SafeLogging, BOOL, "1"),
292 V(SafeSocks, BOOL, "0"),
293 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
294 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
295 V(ServerDNSDetectHijacking, BOOL, "1"),
296 V(ServerDNSRandomizeCase, BOOL, "1"),
297 V(ServerDNSResolvConfFile, STRING, NULL),
298 V(ServerDNSSearchDomains, BOOL, "0"),
299 V(ServerDNSTestAddresses, CSV,
300 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
301 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
302 V(SocksListenAddress, LINELIST, NULL),
303 V(SocksPolicy, LINELIST, NULL),
304 V(SocksPort, UINT, "9050"),
305 V(SocksTimeout, INTERVAL, "2 minutes"),
306 OBSOLETE("StatusFetchPeriod"),
307 V(StrictEntryNodes, BOOL, "0"),
308 V(StrictExitNodes, BOOL, "0"),
309 OBSOLETE("SysLog"),
310 V(TestSocks, BOOL, "0"),
311 OBSOLETE("TestVia"),
312 V(TrackHostExits, CSV, NULL),
313 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
314 OBSOLETE("TrafficShaping"),
315 V(TransListenAddress, LINELIST, NULL),
316 V(TransPort, UINT, "0"),
317 V(TunnelDirConns, BOOL, "1"),
318 V(UpdateBridgesFromAuthority, BOOL, "0"),
319 V(UseBridges, BOOL, "0"),
320 V(UseEntryGuards, BOOL, "1"),
321 V(User, STRING, NULL),
322 VAR("V1AuthoritativeDirectory",BOOL, V1AuthoritativeDir, "0"),
323 VAR("V2AuthoritativeDirectory",BOOL, V2AuthoritativeDir, "0"),
324 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
325 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
326 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
327 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
328 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
329 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
330 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
331 V(V3AuthNIntervalsValid, UINT, "3"),
332 V(V3AuthUseLegacyKey, BOOL, "0"),
333 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
334 V(VirtualAddrNetwork, STRING, "127.192.0.0/10"),
335 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
336 VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
337 VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
338 VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
339 VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
340 VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
341 NULL),
342 V(MinUptimeHidServDirectoryV2, INTERVAL, "24 hours"),
343 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
346 /** Override default values with these if the user sets the TestingTorNetwork
347 * option. */
348 static config_var_t testing_tor_network_defaults[] = {
349 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
350 V(DirAllowPrivateAddresses, BOOL, "1"),
351 V(EnforceDistinctSubnets, BOOL, "0"),
352 V(AssumeReachable, BOOL, "1"),
353 V(AuthDirMaxServersPerAddr, UINT, "0"),
354 V(AuthDirMaxServersPerAuthAddr,UINT, "0"),
355 V(ClientDNSRejectInternalAddresses, BOOL,"0"),
356 V(ExitPolicyRejectPrivate, BOOL, "0"),
357 V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
358 V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
359 V(V3AuthDistDelay, INTERVAL, "20 seconds"),
360 V(TestingV3AuthInitialVotingInterval, INTERVAL, "5 minutes"),
361 V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
362 V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
363 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
364 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
365 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
367 #undef VAR
369 #define VAR(name,conftype,member,initvalue) \
370 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
371 initvalue }
373 /** Array of "state" variables saved to the ~/.tor/state file. */
374 static config_var_t _state_vars[] = {
375 V(AccountingBytesReadInInterval, MEMUNIT, NULL),
376 V(AccountingBytesWrittenInInterval, MEMUNIT, NULL),
377 V(AccountingExpectedUsage, MEMUNIT, NULL),
378 V(AccountingIntervalStart, ISOTIME, NULL),
379 V(AccountingSecondsActive, INTERVAL, NULL),
381 VAR("EntryGuard", LINELIST_S, EntryGuards, NULL),
382 VAR("EntryGuardDownSince", LINELIST_S, EntryGuards, NULL),
383 VAR("EntryGuardUnlistedSince", LINELIST_S, EntryGuards, NULL),
384 VAR("EntryGuardAddedBy", LINELIST_S, EntryGuards, NULL),
385 V(EntryGuards, LINELIST_V, NULL),
387 V(BWHistoryReadEnds, ISOTIME, NULL),
388 V(BWHistoryReadInterval, UINT, "900"),
389 V(BWHistoryReadValues, CSV, ""),
390 V(BWHistoryWriteEnds, ISOTIME, NULL),
391 V(BWHistoryWriteInterval, UINT, "900"),
392 V(BWHistoryWriteValues, CSV, ""),
394 V(TorVersion, STRING, NULL),
396 V(LastRotatedOnionKey, ISOTIME, NULL),
397 V(LastWritten, ISOTIME, NULL),
399 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
402 #undef VAR
403 #undef V
404 #undef OBSOLETE
406 /** Represents an English description of a configuration variable; used when
407 * generating configuration file comments. */
408 typedef struct config_var_description_t {
409 const char *name;
410 const char *description;
411 } config_var_description_t;
413 /** Descriptions of the configuration options, to be displayed by online
414 * option browsers */
415 /* XXXX022 did anybody want this? at all? If not, kill it.*/
416 static config_var_description_t options_description[] = {
417 /* ==== general options */
418 { "AvoidDiskWrites", "If non-zero, try to write to disk less frequently than"
419 " we would otherwise." },
420 { "BandwidthRate", "A token bucket limits the average incoming bandwidth on "
421 "this node to the specified number of bytes per second." },
422 { "BandwidthBurst", "Limit the maximum token buffer size (also known as "
423 "burst) to the given number of bytes." },
424 { "ConnLimit", "Minimum number of simultaneous sockets we must have." },
425 { "ConstrainedSockets", "Shrink tx and rx buffers for sockets to avoid "
426 "system limits on vservers and related environments. See man page for "
427 "more information regarding this option." },
428 { "ConstrainedSockSize", "Limit socket buffers to this size when "
429 "ConstrainedSockets is enabled." },
430 /* ControlListenAddress */
431 { "ControlPort", "If set, Tor will accept connections from the same machine "
432 "(localhost only) on this port, and allow those connections to control "
433 "the Tor process using the Tor Control Protocol (described in "
434 "control-spec.txt).", },
435 { "CookieAuthentication", "If this option is set to 1, don't allow any "
436 "connections to the control port except when the connecting process "
437 "can read a file that Tor creates in its data directory." },
438 { "DataDirectory", "Store working data, state, keys, and caches here." },
439 { "DirServer", "Tor only trusts directories signed with one of these "
440 "servers' keys. Used to override the standard list of directory "
441 "authorities." },
442 /* { "FastFirstHopPK", "" }, */
443 /* FetchServerDescriptors, FetchHidServDescriptors,
444 * FetchUselessDescriptors */
445 { "HardwareAccel", "If set, Tor tries to use hardware crypto accelerators "
446 "when it can." },
447 /* HashedControlPassword */
448 { "HTTPProxy", "Force Tor to make all HTTP directory requests through this "
449 "host:port (or host:80 if port is not set)." },
450 { "HTTPProxyAuthenticator", "A username:password pair to be used with "
451 "HTTPProxy." },
452 { "HTTPSProxy", "Force Tor to make all TLS (SSL) connections through this "
453 "host:port (or host:80 if port is not set)." },
454 { "HTTPSProxyAuthenticator", "A username:password pair to be used with "
455 "HTTPSProxy." },
456 { "KeepalivePeriod", "Send a padding cell every N seconds to keep firewalls "
457 "from closing our connections while Tor is not in use." },
458 { "Log", "Where to send logging messages. Format is "
459 "minSeverity[-maxSeverity] (stderr|stdout|syslog|file FILENAME)." },
460 { "OutboundBindAddress", "Make all outbound connections originate from the "
461 "provided IP address (only useful for multiple network interfaces)." },
462 { "PIDFile", "On startup, write our PID to this file. On clean shutdown, "
463 "remove the file." },
464 { "PreferTunneledDirConns", "If non-zero, avoid directory servers that "
465 "don't support tunneled connections." },
466 /* PreferTunneledDirConns */
467 /* ProtocolWarnings */
468 /* RephistTrackTime */
469 { "RunAsDaemon", "If set, Tor forks and daemonizes to the background when "
470 "started. Unix only." },
471 { "SafeLogging", "If set to 0, Tor logs potentially sensitive strings "
472 "rather than replacing them with the string [scrubbed]." },
473 { "TunnelDirConns", "If non-zero, when a directory server we contact "
474 "supports it, we will build a one-hop circuit and make an encrypted "
475 "connection via its ORPort." },
476 { "User", "On startup, setuid to this user." },
478 /* ==== client options */
479 { "AllowInvalidNodes", "Where on our circuits should Tor allow servers "
480 "that the directory authorities haven't called \"valid\"?" },
481 { "AllowNonRFC953Hostnames", "If set to 1, we don't automatically reject "
482 "hostnames for having invalid characters." },
483 /* CircuitBuildTimeout, CircuitIdleTimeout */
484 { "ClientOnly", "If set to 1, Tor will under no circumstances run as a "
485 "server, even if ORPort is enabled." },
486 { "EntryNodes", "A list of preferred entry nodes to use for the first hop "
487 "in circuits, when possible." },
488 /* { "EnforceDistinctSubnets" , "" }, */
489 { "ExitNodes", "A list of preferred nodes to use for the last hop in "
490 "circuits, when possible." },
491 { "ExcludeNodes", "A list of nodes never to use when building a circuit." },
492 { "FascistFirewall", "If set, Tor will only create outgoing connections to "
493 "servers running on the ports listed in FirewallPorts." },
494 { "FirewallPorts", "A list of ports that we can connect to. Only used "
495 "when FascistFirewall is set." },
496 { "LongLivedPorts", "A list of ports for services that tend to require "
497 "high-uptime connections." },
498 { "MapAddress", "Force Tor to treat all requests for one address as if "
499 "they were for another." },
500 { "NewCircuitPeriod", "Force Tor to consider whether to build a new circuit "
501 "every NUM seconds." },
502 { "MaxCircuitDirtiness", "Do not attach new streams to a circuit that has "
503 "been used more than this many seconds ago." },
504 /* NatdPort, NatdListenAddress */
505 { "NodeFamily", "A list of servers that constitute a 'family' and should "
506 "never be used in the same circuit." },
507 { "NumEntryGuards", "How many entry guards should we keep at a time?" },
508 /* PathlenCoinWeight */
509 { "ReachableAddresses", "Addresses we can connect to, as IP/bits:port-port. "
510 "By default, we assume all addresses are reachable." },
511 /* reachablediraddresses, reachableoraddresses. */
512 /* SafeSOCKS */
513 { "SOCKSPort", "The port where we listen for SOCKS connections from "
514 "applications." },
515 { "SOCKSListenAddress", "Bind to this address to listen to connections from "
516 "SOCKS-speaking applications." },
517 { "SOCKSPolicy", "Set an entry policy to limit which addresses can connect "
518 "to the SOCKSPort." },
519 /* SocksTimeout */
520 { "StrictExitNodes", "If set, Tor will fail to operate when none of the "
521 "configured ExitNodes can be used." },
522 { "StrictEntryNodes", "If set, Tor will fail to operate when none of the "
523 "configured EntryNodes can be used." },
524 /* TestSocks */
525 { "TrackHostsExit", "Hosts and domains which should, if possible, be "
526 "accessed from the same exit node each time we connect to them." },
527 { "TrackHostsExitExpire", "Time after which we forget which exit we were "
528 "using to connect to hosts in TrackHostsExit." },
529 /* "TransPort", "TransListenAddress */
530 { "UseEntryGuards", "Set to 0 if we want to pick from the whole set of "
531 "servers for the first position in each circuit, rather than picking a "
532 "set of 'Guards' to prevent profiling attacks." },
534 /* === server options */
535 { "Address", "The advertised (external) address we should use." },
536 /* Accounting* options. */
537 /* AssumeReachable */
538 { "ContactInfo", "Administrative contact information to advertise for this "
539 "server." },
540 { "ExitPolicy", "Address/port ranges for which to accept or reject outgoing "
541 "connections on behalf of Tor users." },
542 /* { "ExitPolicyRejectPrivate, "" }, */
543 { "MaxAdvertisedBandwidth", "If set, we will not advertise more than this "
544 "amount of bandwidth for our bandwidth rate, regardless of how much "
545 "bandwidth we actually detect." },
546 { "MaxOnionsPending", "Reject new attempts to extend circuits when we "
547 "already have this many pending." },
548 { "MyFamily", "Declare a list of other servers as belonging to the same "
549 "family as this one, so that clients will not use two from the same "
550 "family in the same circuit." },
551 { "Nickname", "Set the server nickname." },
552 { "NoPublish", "{DEPRECATED}" },
553 { "NumCPUs", "How many processes to use at once for public-key crypto." },
554 { "ORPort", "Advertise this port to listen for connections from Tor clients "
555 "and servers." },
556 { "ORListenAddress", "Bind to this address to listen for connections from "
557 "clients and servers, instead of the default 0.0.0.0:ORPort." },
558 { "PublishServerDescriptor", "Set to 0 to keep the server from "
559 "uploading info to the directory authorities." },
560 /* ServerDNS: DetectHijacking, ResolvConfFile, SearchDomains */
561 { "ShutdownWaitLength", "Wait this long for clients to finish when "
562 "shutting down because of a SIGINT." },
564 /* === directory cache options */
565 { "DirPort", "Serve directory information from this port, and act as a "
566 "directory cache." },
567 { "DirPortFrontPage", "Serve a static html disclaimer on DirPort." },
568 { "DirListenAddress", "Bind to this address to listen for connections from "
569 "clients and servers, instead of the default 0.0.0.0:DirPort." },
570 { "DirPolicy", "Set a policy to limit who can connect to the directory "
571 "port." },
573 /* Authority options: AuthDirBadExit, AuthDirInvalid, AuthDirReject,
574 * AuthDirRejectUnlisted, AuthDirListBadExits, AuthoritativeDirectory,
575 * DirAllowPrivateAddresses, HSAuthoritativeDir,
576 * NamingAuthoritativeDirectory, RecommendedVersions,
577 * RecommendedClientVersions, RecommendedServerVersions, RendPostPeriod,
578 * RunTesting, V1AuthoritativeDirectory, VersioningAuthoritativeDirectory, */
580 /* Hidden service options: HiddenService: dir,excludenodes, nodes,
581 * options, port. PublishHidServDescriptor */
583 /* Nonpersistent options: __LeaveStreamsUnattached, __AllDirActionsPrivate */
584 { NULL, NULL },
587 /** Online description of state variables. */
588 static config_var_description_t state_description[] = {
589 { "AccountingBytesReadInInterval",
590 "How many bytes have we read in this accounting period?" },
591 { "AccountingBytesWrittenInInterval",
592 "How many bytes have we written in this accounting period?" },
593 { "AccountingExpectedUsage",
594 "How many bytes did we expect to use per minute? (0 for no estimate.)" },
595 { "AccountingIntervalStart", "When did this accounting period begin?" },
596 { "AccountingSecondsActive", "How long have we been awake in this period?" },
598 { "BWHistoryReadEnds", "When does the last-recorded read-interval end?" },
599 { "BWHistoryReadInterval", "How long is each read-interval (in seconds)?" },
600 { "BWHistoryReadValues", "Number of bytes read in each interval." },
601 { "BWHistoryWriteEnds", "When does the last-recorded write-interval end?" },
602 { "BWHistoryWriteInterval", "How long is each write-interval (in seconds)?"},
603 { "BWHistoryWriteValues", "Number of bytes written in each interval." },
605 { "EntryGuard", "One of the nodes we have chosen as a fixed entry" },
606 { "EntryGuardDownSince",
607 "The last entry guard has been unreachable since this time." },
608 { "EntryGuardUnlistedSince",
609 "The last entry guard has been unusable since this time." },
611 { "LastRotatedOnionKey",
612 "The last time at which we changed the medium-term private key used for "
613 "building circuits." },
614 { "LastWritten", "When was this state file last regenerated?" },
616 { "TorVersion", "Which version of Tor generated this state file?" },
617 { NULL, NULL },
620 /** Type of a callback to validate whether a given configuration is
621 * well-formed and consistent. See options_trial_assign() for documentation
622 * of arguments. */
623 typedef int (*validate_fn_t)(void*,void*,int,char**);
625 /** Information on the keys, value types, key-to-struct-member mappings,
626 * variable descriptions, validation functions, and abbreviations for a
627 * configuration or storage format. */
628 typedef struct {
629 size_t size; /**< Size of the struct that everything gets parsed into. */
630 uint32_t magic; /**< Required 'magic value' to make sure we have a struct
631 * of the right type. */
632 off_t magic_offset; /**< Offset of the magic value within the struct. */
633 config_abbrev_t *abbrevs; /**< List of abbreviations that we expand when
634 * parsing this format. */
635 config_var_t *vars; /**< List of variables we recognize, their default
636 * values, and where we stick them in the structure. */
637 validate_fn_t validate_fn; /**< Function to validate config. */
638 /** Documentation for configuration variables. */
639 config_var_description_t *descriptions;
640 /** If present, extra is a LINELIST variable for unrecognized
641 * lines. Otherwise, unrecognized lines are an error. */
642 config_var_t *extra;
643 } config_format_t;
645 /** Macro: assert that <b>cfg</b> has the right magic field for format
646 * <b>fmt</b>. */
647 #define CHECK(fmt, cfg) STMT_BEGIN \
648 tor_assert(fmt && cfg); \
649 tor_assert((fmt)->magic == \
650 *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
651 STMT_END
653 #ifdef MS_WINDOWS
654 static char *get_windows_conf_root(void);
655 #endif
656 static void config_line_append(config_line_t **lst,
657 const char *key, const char *val);
658 static void option_clear(config_format_t *fmt, or_options_t *options,
659 config_var_t *var);
660 static void option_reset(config_format_t *fmt, or_options_t *options,
661 config_var_t *var, int use_defaults);
662 static void config_free(config_format_t *fmt, void *options);
663 static int config_lines_eq(config_line_t *a, config_line_t *b);
664 static int option_is_same(config_format_t *fmt,
665 or_options_t *o1, or_options_t *o2,
666 const char *name);
667 static or_options_t *options_dup(config_format_t *fmt, or_options_t *old);
668 static int options_validate(or_options_t *old_options, or_options_t *options,
669 int from_setconf, char **msg);
670 static int options_act_reversible(or_options_t *old_options, char **msg);
671 static int options_act(or_options_t *old_options);
672 static int options_transition_allowed(or_options_t *old, or_options_t *new,
673 char **msg);
674 static int options_transition_affects_workers(or_options_t *old_options,
675 or_options_t *new_options);
676 static int options_transition_affects_descriptor(or_options_t *old_options,
677 or_options_t *new_options);
678 static int check_nickname_list(const char *lst, const char *name, char **msg);
679 static void config_register_addressmaps(or_options_t *options);
681 static int parse_bridge_line(const char *line, int validate_only);
682 static int parse_dir_server_line(const char *line,
683 authority_type_t required_type,
684 int validate_only);
685 static int validate_data_directory(or_options_t *options);
686 static int write_configuration_file(const char *fname, or_options_t *options);
687 static config_line_t *get_assigned_option(config_format_t *fmt,
688 void *options, const char *key,
689 int escape_val);
690 static void config_init(config_format_t *fmt, void *options);
691 static int or_state_validate(or_state_t *old_options, or_state_t *options,
692 int from_setconf, char **msg);
693 static int or_state_load(void);
694 static int options_init_logs(or_options_t *options, int validate_only);
696 static int is_listening_on_low_port(uint16_t port_option,
697 const config_line_t *listen_options);
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 init_libevent(void);
702 static int opt_streq(const char *s1, const char *s2);
703 /** Versions of libevent. */
704 typedef enum {
705 /* Note: we compare these, so it's important that "old" precede everything,
706 * and that "other" come last. */
707 LE_OLD=0, LE_10C, LE_10D, LE_10E, LE_11, LE_11A, LE_11B, LE_12, LE_12A,
708 LE_13, LE_13A, LE_13B, LE_13C, LE_13D, LE_13E,
709 LE_140, LE_141, LE_142, LE_143, LE_144, LE_145, LE_146, LE_147, LE_148,
710 LE_1499,
711 LE_OTHER
712 } le_version_t;
713 static le_version_t decode_libevent_version(const char *v, int *bincompat_out);
714 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
715 static void check_libevent_version(const char *m, int server);
716 #endif
718 /** Magic value for or_options_t. */
719 #define OR_OPTIONS_MAGIC 9090909
721 /** Configuration format for or_options_t. */
722 static config_format_t options_format = {
723 sizeof(or_options_t),
724 OR_OPTIONS_MAGIC,
725 STRUCT_OFFSET(or_options_t, _magic),
726 _option_abbrevs,
727 _option_vars,
728 (validate_fn_t)options_validate,
729 options_description,
730 NULL
733 /** Magic value for or_state_t. */
734 #define OR_STATE_MAGIC 0x57A73f57
736 /** "Extra" variable in the state that receives lines we can't parse. This
737 * lets us preserve options from versions of Tor newer than us. */
738 static config_var_t state_extra_var = {
739 "__extra", CONFIG_TYPE_LINELIST, STRUCT_OFFSET(or_state_t, ExtraLines), NULL
742 /** Configuration format for or_state_t. */
743 static config_format_t state_format = {
744 sizeof(or_state_t),
745 OR_STATE_MAGIC,
746 STRUCT_OFFSET(or_state_t, _magic),
747 _state_abbrevs,
748 _state_vars,
749 (validate_fn_t)or_state_validate,
750 state_description,
751 &state_extra_var,
755 * Functions to read and write the global options pointer.
758 /** Command-line and config-file options. */
759 static or_options_t *global_options = NULL;
760 /** Name of most recently read torrc file. */
761 static char *torrc_fname = NULL;
762 /** Persistent serialized state. */
763 static or_state_t *global_state = NULL;
764 /** Configuration Options set by command line. */
765 static config_line_t *global_cmdline_options = NULL;
766 /** Contents of most recently read DirPortFrontPage file. */
767 static char *global_dirfrontpagecontents = NULL;
769 /** Return the contents of our frontpage string, or NULL if not configured. */
770 const char *
771 get_dirportfrontpage(void)
773 return global_dirfrontpagecontents;
776 /** Allocate an empty configuration object of a given format type. */
777 static void *
778 config_alloc(config_format_t *fmt)
780 void *opts = tor_malloc_zero(fmt->size);
781 *(uint32_t*)STRUCT_VAR_P(opts, fmt->magic_offset) = fmt->magic;
782 CHECK(fmt, opts);
783 return opts;
786 /** Return the currently configured options. */
787 or_options_t *
788 get_options(void)
790 tor_assert(global_options);
791 return global_options;
794 /** Change the current global options to contain <b>new_val</b> instead of
795 * their current value; take action based on the new value; free the old value
796 * as necessary. Returns 0 on success, -1 on failure.
799 set_options(or_options_t *new_val, char **msg)
801 or_options_t *old_options = global_options;
802 global_options = new_val;
803 /* Note that we pass the *old* options below, for comparison. It
804 * pulls the new options directly out of global_options. */
805 if (options_act_reversible(old_options, msg)<0) {
806 tor_assert(*msg);
807 global_options = old_options;
808 return -1;
810 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
811 log_err(LD_BUG,
812 "Acting on config options left us in a broken state. Dying.");
813 exit(1);
815 if (old_options)
816 config_free(&options_format, old_options);
818 return 0;
821 extern const char tor_svn_revision[]; /* from tor_main.c */
823 /** The version of this Tor process, as parsed. */
824 static char *_version = NULL;
826 /** Return the current Tor version. */
827 const char *
828 get_version(void)
830 if (_version == NULL) {
831 if (strlen(tor_svn_revision)) {
832 size_t len = strlen(VERSION)+strlen(tor_svn_revision)+8;
833 _version = tor_malloc(len);
834 tor_snprintf(_version, len, "%s (r%s)", VERSION, tor_svn_revision);
835 } else {
836 _version = tor_strdup(VERSION);
839 return _version;
842 /** Release additional memory allocated in options
844 static void
845 or_options_free(or_options_t *options)
847 if (options->_ExcludeExitNodesUnion)
848 routerset_free(options->_ExcludeExitNodesUnion);
849 config_free(&options_format, options);
852 /** Release all memory and resources held by global configuration structures.
854 void
855 config_free_all(void)
857 if (global_options) {
858 or_options_free(global_options);
859 global_options = NULL;
861 if (global_state) {
862 config_free(&state_format, global_state);
863 global_state = NULL;
865 if (global_cmdline_options) {
866 config_free_lines(global_cmdline_options);
867 global_cmdline_options = NULL;
869 tor_free(torrc_fname);
870 tor_free(_version);
871 tor_free(global_dirfrontpagecontents);
874 /** If options->SafeLogging is on, return a not very useful string,
875 * else return address.
877 const char *
878 safe_str(const char *address)
880 tor_assert(address);
881 if (get_options()->SafeLogging)
882 return "[scrubbed]";
883 else
884 return address;
887 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
888 * escaped(): don't use this outside the main thread, or twice in the same
889 * log statement. */
890 const char *
891 escaped_safe_str(const char *address)
893 if (get_options()->SafeLogging)
894 return "[scrubbed]";
895 else
896 return escaped(address);
899 /** Add the default directory authorities directly into the trusted dir list,
900 * but only add them insofar as they share bits with <b>type</b>. */
901 static void
902 add_default_trusted_dir_authorities(authority_type_t type)
904 int i;
905 const char *dirservers[] = {
906 "moria1 orport=9101 no-v2 "
907 "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
908 "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
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.203: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=8080 no-v2 "
918 "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
919 "80.190.246.100:8180 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
920 "dannenberg orport=443 no-v2 "
921 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
922 "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
923 "urras orport=80 no-v2 v3ident=80550987E1D626E3EBA5E5E75A458DE0626D088C "
924 "208.83.223.34:443 0AD3 FA88 4D18 F89E EA2D 89C0 1937 9E0E 7FD9 4417",
925 "maatuska orport=80 no-v2 "
926 "v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
927 "213.115.239.118:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
928 NULL
930 for (i=0; dirservers[i]; i++) {
931 if (parse_dir_server_line(dirservers[i], type, 0)<0) {
932 log_err(LD_BUG, "Couldn't parse internal dirserver line %s",
933 dirservers[i]);
938 /** Look at all the config options for using alternate directory
939 * authorities, and make sure none of them are broken. Also, warn the
940 * user if we changed any dangerous ones.
942 static int
943 validate_dir_authorities(or_options_t *options, or_options_t *old_options)
945 config_line_t *cl;
947 if (options->DirServers &&
948 (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
949 options->AlternateHSAuthority)) {
950 log_warn(LD_CONFIG,
951 "You cannot set both DirServers and Alternate*Authority.");
952 return -1;
955 /* do we want to complain to the user about being partitionable? */
956 if ((options->DirServers &&
957 (!old_options ||
958 !config_lines_eq(options->DirServers, old_options->DirServers))) ||
959 (options->AlternateDirAuthority &&
960 (!old_options ||
961 !config_lines_eq(options->AlternateDirAuthority,
962 old_options->AlternateDirAuthority)))) {
963 log_warn(LD_CONFIG,
964 "You have used DirServer or AlternateDirAuthority to "
965 "specify alternate directory authorities in "
966 "your configuration. This is potentially dangerous: it can "
967 "make you look different from all other Tor users, and hurt "
968 "your anonymity. Even if you've specified the same "
969 "authorities as Tor uses by default, the defaults could "
970 "change in the future. Be sure you know what you're doing.");
973 /* Now go through the four ways you can configure an alternate
974 * set of directory authorities, and make sure none are broken. */
975 for (cl = options->DirServers; cl; cl = cl->next)
976 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
977 return -1;
978 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
979 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
980 return -1;
981 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
982 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
983 return -1;
984 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
985 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
986 return -1;
987 return 0;
990 /** Look at all the config options and assign new dir authorities
991 * as appropriate.
993 static int
994 consider_adding_dir_authorities(or_options_t *options,
995 or_options_t *old_options)
997 config_line_t *cl;
998 int need_to_update =
999 !smartlist_len(router_get_trusted_dir_servers()) || !old_options ||
1000 !config_lines_eq(options->DirServers, old_options->DirServers) ||
1001 !config_lines_eq(options->AlternateBridgeAuthority,
1002 old_options->AlternateBridgeAuthority) ||
1003 !config_lines_eq(options->AlternateDirAuthority,
1004 old_options->AlternateDirAuthority) ||
1005 !config_lines_eq(options->AlternateHSAuthority,
1006 old_options->AlternateHSAuthority);
1008 if (!need_to_update)
1009 return 0; /* all done */
1011 /* Start from a clean slate. */
1012 clear_trusted_dir_servers();
1014 if (!options->DirServers) {
1015 /* then we may want some of the defaults */
1016 authority_type_t type = NO_AUTHORITY;
1017 if (!options->AlternateBridgeAuthority)
1018 type |= BRIDGE_AUTHORITY;
1019 if (!options->AlternateDirAuthority)
1020 type |= V1_AUTHORITY | V2_AUTHORITY | V3_AUTHORITY;
1021 if (!options->AlternateHSAuthority)
1022 type |= HIDSERV_AUTHORITY;
1023 add_default_trusted_dir_authorities(type);
1026 for (cl = options->DirServers; cl; cl = cl->next)
1027 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1028 return -1;
1029 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1030 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1031 return -1;
1032 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1033 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1034 return -1;
1035 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
1036 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1037 return -1;
1038 return 0;
1041 /** Fetch the active option list, and take actions based on it. All of the
1042 * things we do should survive being done repeatedly. If present,
1043 * <b>old_options</b> contains the previous value of the options.
1045 * Return 0 if all goes well, return -1 if things went badly.
1047 static int
1048 options_act_reversible(or_options_t *old_options, char **msg)
1050 smartlist_t *new_listeners = smartlist_create();
1051 smartlist_t *replaced_listeners = smartlist_create();
1052 static int libevent_initialized = 0;
1053 or_options_t *options = get_options();
1054 int running_tor = options->command == CMD_RUN_TOR;
1055 int set_conn_limit = 0;
1056 int r = -1;
1057 int logs_marked = 0;
1059 /* Daemonize _first_, since we only want to open most of this stuff in
1060 * the subprocess. Libevent bases can't be reliably inherited across
1061 * processes. */
1062 if (running_tor && options->RunAsDaemon) {
1063 /* No need to roll back, since you can't change the value. */
1064 start_daemon();
1067 #ifndef HAVE_SYS_UN_H
1068 if (options->ControlSocket) {
1069 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported"
1070 " on this OS/with this build.");
1071 goto rollback;
1073 #endif
1075 if (running_tor) {
1076 /* We need to set the connection limit before we can open the listeners. */
1077 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1078 &options->_ConnLimit) < 0) {
1079 *msg = tor_strdup("Problem with ConnLimit value. See logs for details.");
1080 goto rollback;
1082 set_conn_limit = 1;
1084 /* Set up libevent. (We need to do this before we can register the
1085 * listeners as listeners.) */
1086 if (running_tor && !libevent_initialized) {
1087 init_libevent();
1088 libevent_initialized = 1;
1091 /* Launch the listeners. (We do this before we setuid, so we can bind to
1092 * ports under 1024.) */
1093 if (retry_all_listeners(replaced_listeners, new_listeners) < 0) {
1094 *msg = tor_strdup("Failed to bind one of the listener ports.");
1095 goto rollback;
1099 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1100 /* Open /dev/pf before dropping privileges. */
1101 if (options->TransPort) {
1102 if (get_pf_socket() < 0) {
1103 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1104 goto rollback;
1107 #endif
1109 /* Setuid/setgid as appropriate */
1110 if (options->User) {
1111 if (switch_id(options->User) != 0) {
1112 /* No need to roll back, since you can't change the value. */
1113 *msg = tor_strdup("Problem with User value. See logs for details.");
1114 goto done;
1118 /* Ensure data directory is private; create if possible. */
1119 if (check_private_dir(options->DataDirectory,
1120 running_tor ? CPD_CREATE : CPD_CHECK)<0) {
1121 char buf[1024];
1122 int tmp = tor_snprintf(buf, sizeof(buf),
1123 "Couldn't access/create private data directory \"%s\"",
1124 options->DataDirectory);
1125 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1126 goto done;
1127 /* No need to roll back, since you can't change the value. */
1130 if (directory_caches_v2_dir_info(options)) {
1131 size_t len = strlen(options->DataDirectory)+32;
1132 char *fn = tor_malloc(len);
1133 tor_snprintf(fn, len, "%s"PATH_SEPARATOR"cached-status",
1134 options->DataDirectory);
1135 if (check_private_dir(fn, running_tor ? CPD_CREATE : CPD_CHECK) < 0) {
1136 char buf[1024];
1137 int tmp = tor_snprintf(buf, sizeof(buf),
1138 "Couldn't access/create private data directory \"%s\"", fn);
1139 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1140 tor_free(fn);
1141 goto done;
1143 tor_free(fn);
1146 /* Bail out at this point if we're not going to be a client or server:
1147 * we don't run Tor itself. */
1148 if (!running_tor)
1149 goto commit;
1151 mark_logs_temp(); /* Close current logs once new logs are open. */
1152 logs_marked = 1;
1153 if (options_init_logs(options, 0)<0) { /* Configure the log(s) */
1154 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1155 goto rollback;
1158 commit:
1159 r = 0;
1160 if (logs_marked) {
1161 log_severity_list_t *severity =
1162 tor_malloc_zero(sizeof(log_severity_list_t));
1163 close_temp_logs();
1164 add_callback_log(severity, control_event_logmsg);
1165 control_adjust_event_log_severity();
1166 tor_free(severity);
1168 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1170 log_notice(LD_NET, "Closing old %s on %s:%d",
1171 conn_type_to_string(conn->type), conn->address, conn->port);
1172 connection_close_immediate(conn);
1173 connection_mark_for_close(conn);
1175 goto done;
1177 rollback:
1178 r = -1;
1179 tor_assert(*msg);
1181 if (logs_marked) {
1182 rollback_log_changes();
1183 control_adjust_event_log_severity();
1186 if (set_conn_limit && old_options)
1187 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1188 &options->_ConnLimit);
1190 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1192 log_notice(LD_NET, "Closing partially-constructed listener %s on %s:%d",
1193 conn_type_to_string(conn->type), conn->address, conn->port);
1194 connection_close_immediate(conn);
1195 connection_mark_for_close(conn);
1198 done:
1199 smartlist_free(new_listeners);
1200 smartlist_free(replaced_listeners);
1201 return r;
1204 /** If we need to have a GEOIP ip-to-country map to run with our configured
1205 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1207 options_need_geoip_info(or_options_t *options, const char **reason_out)
1209 int bridge_usage =
1210 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1211 int routerset_usage =
1212 routerset_needs_geoip(options->EntryNodes) ||
1213 routerset_needs_geoip(options->ExitNodes) ||
1214 routerset_needs_geoip(options->ExcludeExitNodes) ||
1215 routerset_needs_geoip(options->ExcludeNodes);
1217 if (routerset_usage && reason_out) {
1218 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1219 "countries, and we need GEOIP information to figure out which ones they "
1220 "are.";
1221 } else if (bridge_usage && reason_out) {
1222 *reason_out = "We've been configured to see which countries can access "
1223 "us as a bridge, and we need GEOIP information to tell which countries "
1224 "clients are in.";
1226 return bridge_usage || routerset_usage;
1229 /** Return the bandwidthrate that we are going to report to the authorities
1230 * based on the config options. */
1231 uint32_t
1232 get_effective_bwrate(or_options_t *options)
1234 uint64_t bw = options->BandwidthRate;
1235 if (bw > options->MaxAdvertisedBandwidth)
1236 bw = options->MaxAdvertisedBandwidth;
1237 if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1238 bw = options->RelayBandwidthRate;
1240 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1241 return (uint32_t)bw;
1244 /** Return the bandwidthburst that we are going to report to the authorities
1245 * based on the config options. */
1246 uint32_t
1247 get_effective_bwburst(or_options_t *options)
1249 uint64_t bw = options->BandwidthBurst;
1250 if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1251 bw = options->RelayBandwidthBurst;
1252 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1253 return (uint32_t)bw;
1256 /** Fetch the active option list, and take actions based on it. All of the
1257 * things we do should survive being done repeatedly. If present,
1258 * <b>old_options</b> contains the previous value of the options.
1260 * Return 0 if all goes well, return -1 if it's time to die.
1262 * Note: We haven't moved all the "act on new configuration" logic
1263 * here yet. Some is still in do_hup() and other places.
1265 static int
1266 options_act(or_options_t *old_options)
1268 config_line_t *cl;
1269 or_options_t *options = get_options();
1270 int running_tor = options->command == CMD_RUN_TOR;
1271 char *msg;
1273 if (running_tor && !have_lockfile()) {
1274 if (try_locking(options, 1) < 0)
1275 return -1;
1278 if (consider_adding_dir_authorities(options, old_options) < 0)
1279 return -1;
1281 if (options->Bridges) {
1282 clear_bridge_list();
1283 for (cl = options->Bridges; cl; cl = cl->next) {
1284 if (parse_bridge_line(cl->value, 0)<0) {
1285 log_warn(LD_BUG,
1286 "Previously validated Bridge line could not be added!");
1287 return -1;
1292 if (running_tor && rend_config_services(options, 0)<0) {
1293 log_warn(LD_BUG,
1294 "Previously validated hidden services line could not be added!");
1295 return -1;
1298 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1299 log_warn(LD_BUG, "Previously validated client authorization for "
1300 "hidden services could not be added!");
1301 return -1;
1304 /* Load state */
1305 if (! global_state && running_tor) {
1306 if (or_state_load())
1307 return -1;
1308 rep_hist_load_mtbf_data(time(NULL));
1311 /* Bail out at this point if we're not going to be a client or server:
1312 * we want to not fork, and to log stuff to stderr. */
1313 if (!running_tor)
1314 return 0;
1316 /* Finish backgrounding the process */
1317 if (running_tor && options->RunAsDaemon) {
1318 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1319 finish_daemon(options->DataDirectory);
1322 /* Write our PID to the PID file. If we do not have write permissions we
1323 * will log a warning */
1324 if (running_tor && options->PidFile)
1325 write_pidfile(options->PidFile);
1327 /* Register addressmap directives */
1328 config_register_addressmaps(options);
1329 parse_virtual_addr_network(options->VirtualAddrNetwork, 0, &msg);
1331 /* Update address policies. */
1332 if (policies_parse_from_options(options) < 0) {
1333 /* This should be impossible, but let's be sure. */
1334 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1335 return -1;
1338 if (init_cookie_authentication(options->CookieAuthentication) < 0) {
1339 log_warn(LD_CONFIG,"Error creating cookie authentication file.");
1340 return -1;
1343 /* reload keys as needed for rendezvous services. */
1344 if (rend_service_load_keys()<0) {
1345 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1346 return -1;
1349 /* Set up accounting */
1350 if (accounting_parse_options(options, 0)<0) {
1351 log_warn(LD_CONFIG,"Error in accounting options");
1352 return -1;
1354 if (accounting_is_enabled(options))
1355 configure_accounting(time(NULL));
1357 /* Check for transitions that need action. */
1358 if (old_options) {
1359 if (options->UseEntryGuards && !old_options->UseEntryGuards) {
1360 log_info(LD_CIRC,
1361 "Switching to entry guards; abandoning previous circuits");
1362 circuit_mark_all_unused_circs();
1363 circuit_expire_all_dirty_circs();
1366 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
1367 log_info(LD_GENERAL, "Bridge status changed. Forgetting GeoIP stats.");
1368 geoip_remove_old_clients(time(NULL)+(2*60*60));
1371 if (options_transition_affects_workers(old_options, options)) {
1372 log_info(LD_GENERAL,
1373 "Worker-related options changed. Rotating workers.");
1374 if (server_mode(options) && !server_mode(old_options)) {
1375 if (init_keys() < 0) {
1376 log_warn(LD_BUG,"Error initializing keys; exiting");
1377 return -1;
1379 ip_address_changed(0);
1380 if (has_completed_circuit || !any_predicted_circuits(time(NULL)))
1381 inform_testing_reachability();
1383 cpuworkers_rotate();
1384 if (dns_reset())
1385 return -1;
1386 } else {
1387 if (dns_reset())
1388 return -1;
1391 if (options->V3AuthoritativeDir && !old_options->V3AuthoritativeDir)
1392 init_keys();
1395 /* Maybe load geoip file */
1396 if (options->GeoIPFile &&
1397 ((!old_options || !opt_streq(old_options->GeoIPFile, options->GeoIPFile))
1398 || !geoip_is_loaded())) {
1399 /* XXXX Don't use this "<default>" junk; make our filename options
1400 * understand prefixes somehow. -NM */
1401 /* XXXX021 Reload GeoIPFile on SIGHUP. -NM */
1402 char *actual_fname = tor_strdup(options->GeoIPFile);
1403 #ifdef WIN32
1404 if (!strcmp(actual_fname, "<default>")) {
1405 const char *conf_root = get_windows_conf_root();
1406 size_t len = strlen(conf_root)+16;
1407 tor_free(actual_fname);
1408 actual_fname = tor_malloc(len+1);
1409 tor_snprintf(actual_fname, len, "%s\\geoip", conf_root);
1411 #endif
1412 geoip_load_file(actual_fname, options);
1413 tor_free(actual_fname);
1415 #ifdef ENABLE_GEOIP_STATS
1416 log_warn(LD_CONFIG, "We are configured to measure GeoIP statistics, but "
1417 "the way these statistics are measured has changed "
1418 "significantly in later versions of Tor. The results may not be "
1419 "as expected if you are used to later versions. Be sure you "
1420 "know what you are doing.");
1421 #endif
1422 /* Check if we need to parse and add the EntryNodes config option. */
1423 if (options->EntryNodes &&
1424 (!old_options ||
1425 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
1426 entry_nodes_should_be_added();
1428 /* Since our options changed, we might need to regenerate and upload our
1429 * server descriptor.
1431 if (!old_options ||
1432 options_transition_affects_descriptor(old_options, options))
1433 mark_my_descriptor_dirty();
1435 /* We may need to reschedule some directory stuff if our status changed. */
1436 if (old_options) {
1437 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1438 dirvote_recalculate_timing(options, time(NULL));
1439 if (!bool_eq(directory_fetches_dir_info_early(options),
1440 directory_fetches_dir_info_early(old_options)) ||
1441 !bool_eq(directory_fetches_dir_info_later(options),
1442 directory_fetches_dir_info_later(old_options))) {
1443 /* Make sure update_router_have_min_dir_info gets called. */
1444 router_dir_info_changed();
1445 /* We might need to download a new consensus status later or sooner than
1446 * we had expected. */
1447 update_consensus_networkstatus_fetch_time(time(NULL));
1451 /* Load the webpage we're going to serve every time someone asks for '/' on
1452 our DirPort. */
1453 tor_free(global_dirfrontpagecontents);
1454 if (options->DirPortFrontPage) {
1455 global_dirfrontpagecontents =
1456 read_file_to_str(options->DirPortFrontPage, 0, NULL);
1457 if (!global_dirfrontpagecontents) {
1458 log_warn(LD_CONFIG,
1459 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1460 options->DirPortFrontPage);
1464 return 0;
1468 * Functions to parse config options
1471 /** If <b>option</b> is an official abbreviation for a longer option,
1472 * return the longer option. Otherwise return <b>option</b>.
1473 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1474 * apply abbreviations that work for the config file and the command line.
1475 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1476 static const char *
1477 expand_abbrev(config_format_t *fmt, const char *option, int command_line,
1478 int warn_obsolete)
1480 int i;
1481 if (! fmt->abbrevs)
1482 return option;
1483 for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
1484 /* Abbreviations are case insensitive. */
1485 if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
1486 (command_line || !fmt->abbrevs[i].commandline_only)) {
1487 if (warn_obsolete && fmt->abbrevs[i].warn) {
1488 log_warn(LD_CONFIG,
1489 "The configuration option '%s' is deprecated; "
1490 "use '%s' instead.",
1491 fmt->abbrevs[i].abbreviated,
1492 fmt->abbrevs[i].full);
1494 return fmt->abbrevs[i].full;
1497 return option;
1500 /** Helper: Read a list of configuration options from the command line.
1501 * If successful, put them in *<b>result</b> and return 0, and return
1502 * -1 and leave *<b>result</b> alone. */
1503 static int
1504 config_get_commandlines(int argc, char **argv, config_line_t **result)
1506 config_line_t *front = NULL;
1507 config_line_t **new = &front;
1508 char *s;
1509 int i = 1;
1511 while (i < argc) {
1512 if (!strcmp(argv[i],"-f") ||
1513 !strcmp(argv[i],"--hash-password")) {
1514 i += 2; /* command-line option with argument. ignore them. */
1515 continue;
1516 } else if (!strcmp(argv[i],"--list-fingerprint") ||
1517 !strcmp(argv[i],"--verify-config") ||
1518 !strcmp(argv[i],"--ignore-missing-torrc") ||
1519 !strcmp(argv[i],"--quiet") ||
1520 !strcmp(argv[i],"--hush")) {
1521 i += 1; /* command-line option. ignore it. */
1522 continue;
1523 } else if (!strcmp(argv[i],"--nt-service") ||
1524 !strcmp(argv[i],"-nt-service")) {
1525 i += 1;
1526 continue;
1529 if (i == argc-1) {
1530 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1531 argv[i]);
1532 config_free_lines(front);
1533 return -1;
1536 *new = tor_malloc_zero(sizeof(config_line_t));
1537 s = argv[i];
1539 while (*s == '-')
1540 s++;
1542 (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1, 1));
1543 (*new)->value = tor_strdup(argv[i+1]);
1544 (*new)->next = NULL;
1545 log(LOG_DEBUG, LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
1546 (*new)->key, (*new)->value);
1548 new = &((*new)->next);
1549 i += 2;
1551 *result = front;
1552 return 0;
1555 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1556 * append it to *<b>lst</b>. */
1557 static void
1558 config_line_append(config_line_t **lst,
1559 const char *key,
1560 const char *val)
1562 config_line_t *newline;
1564 newline = tor_malloc(sizeof(config_line_t));
1565 newline->key = tor_strdup(key);
1566 newline->value = tor_strdup(val);
1567 newline->next = NULL;
1568 while (*lst)
1569 lst = &((*lst)->next);
1571 (*lst) = newline;
1574 /** Helper: parse the config string and strdup into key/value
1575 * strings. Set *result to the list, or NULL if parsing the string
1576 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1577 * misformatted lines. */
1579 config_get_lines(const char *string, config_line_t **result)
1581 config_line_t *list = NULL, **next;
1582 char *k, *v;
1584 next = &list;
1585 do {
1586 k = v = NULL;
1587 string = parse_config_line_from_str(string, &k, &v);
1588 if (!string) {
1589 config_free_lines(list);
1590 tor_free(k);
1591 tor_free(v);
1592 return -1;
1594 if (k && v) {
1595 /* This list can get long, so we keep a pointer to the end of it
1596 * rather than using config_line_append over and over and getting
1597 * n^2 performance. */
1598 *next = tor_malloc(sizeof(config_line_t));
1599 (*next)->key = k;
1600 (*next)->value = v;
1601 (*next)->next = NULL;
1602 next = &((*next)->next);
1603 } else {
1604 tor_free(k);
1605 tor_free(v);
1607 } while (*string);
1609 *result = list;
1610 return 0;
1614 * Free all the configuration lines on the linked list <b>front</b>.
1616 void
1617 config_free_lines(config_line_t *front)
1619 config_line_t *tmp;
1621 while (front) {
1622 tmp = front;
1623 front = tmp->next;
1625 tor_free(tmp->key);
1626 tor_free(tmp->value);
1627 tor_free(tmp);
1631 /** Return the description for a given configuration variable, or NULL if no
1632 * description exists. */
1633 static const char *
1634 config_find_description(config_format_t *fmt, const char *name)
1636 int i;
1637 for (i=0; fmt->descriptions[i].name; ++i) {
1638 if (!strcasecmp(name, fmt->descriptions[i].name))
1639 return fmt->descriptions[i].description;
1641 return NULL;
1644 /** If <b>key</b> is a configuration option, return the corresponding
1645 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1646 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1648 static config_var_t *
1649 config_find_option(config_format_t *fmt, const char *key)
1651 int i;
1652 size_t keylen = strlen(key);
1653 if (!keylen)
1654 return NULL; /* if they say "--" on the command line, it's not an option */
1655 /* First, check for an exact (case-insensitive) match */
1656 for (i=0; fmt->vars[i].name; ++i) {
1657 if (!strcasecmp(key, fmt->vars[i].name)) {
1658 return &fmt->vars[i];
1661 /* If none, check for an abbreviated match */
1662 for (i=0; fmt->vars[i].name; ++i) {
1663 if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
1664 log_warn(LD_CONFIG, "The abbreviation '%s' is deprecated. "
1665 "Please use '%s' instead",
1666 key, fmt->vars[i].name);
1667 return &fmt->vars[i];
1670 /* Okay, unrecognized option */
1671 return NULL;
1675 * Functions to assign config options.
1678 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1679 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1681 * Called from config_assign_line() and option_reset().
1683 static int
1684 config_assign_value(config_format_t *fmt, or_options_t *options,
1685 config_line_t *c, char **msg)
1687 int i, r, ok;
1688 char buf[1024];
1689 config_var_t *var;
1690 void *lvalue;
1692 CHECK(fmt, options);
1694 var = config_find_option(fmt, c->key);
1695 tor_assert(var);
1697 lvalue = STRUCT_VAR_P(options, var->var_offset);
1699 switch (var->type) {
1701 case CONFIG_TYPE_UINT:
1702 i = (int)tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
1703 if (!ok) {
1704 r = tor_snprintf(buf, sizeof(buf),
1705 "Int keyword '%s %s' is malformed or out of bounds.",
1706 c->key, c->value);
1707 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1708 return -1;
1710 *(int *)lvalue = i;
1711 break;
1713 case CONFIG_TYPE_INTERVAL: {
1714 i = config_parse_interval(c->value, &ok);
1715 if (!ok) {
1716 r = tor_snprintf(buf, sizeof(buf),
1717 "Interval '%s %s' is malformed or out of bounds.",
1718 c->key, c->value);
1719 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1720 return -1;
1722 *(int *)lvalue = i;
1723 break;
1726 case CONFIG_TYPE_MEMUNIT: {
1727 uint64_t u64 = config_parse_memunit(c->value, &ok);
1728 if (!ok) {
1729 r = tor_snprintf(buf, sizeof(buf),
1730 "Value '%s %s' is malformed or out of bounds.",
1731 c->key, c->value);
1732 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1733 return -1;
1735 *(uint64_t *)lvalue = u64;
1736 break;
1739 case CONFIG_TYPE_BOOL:
1740 i = (int)tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
1741 if (!ok) {
1742 r = tor_snprintf(buf, sizeof(buf),
1743 "Boolean '%s %s' expects 0 or 1.",
1744 c->key, c->value);
1745 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1746 return -1;
1748 *(int *)lvalue = i;
1749 break;
1751 case CONFIG_TYPE_STRING:
1752 case CONFIG_TYPE_FILENAME:
1753 tor_free(*(char **)lvalue);
1754 *(char **)lvalue = tor_strdup(c->value);
1755 break;
1757 case CONFIG_TYPE_DOUBLE:
1758 *(double *)lvalue = atof(c->value);
1759 break;
1761 case CONFIG_TYPE_ISOTIME:
1762 if (parse_iso_time(c->value, (time_t *)lvalue)) {
1763 r = tor_snprintf(buf, sizeof(buf),
1764 "Invalid time '%s' for keyword '%s'", c->value, c->key);
1765 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1766 return -1;
1768 break;
1770 case CONFIG_TYPE_ROUTERSET:
1771 if (*(routerset_t**)lvalue) {
1772 routerset_free(*(routerset_t**)lvalue);
1774 *(routerset_t**)lvalue = routerset_new();
1775 if (routerset_parse(*(routerset_t**)lvalue, c->value, c->key)<0) {
1776 tor_snprintf(buf, sizeof(buf), "Invalid exit list '%s' for option '%s'",
1777 c->value, c->key);
1778 *msg = tor_strdup(buf);
1779 return -1;
1781 break;
1783 case CONFIG_TYPE_CSV:
1784 if (*(smartlist_t**)lvalue) {
1785 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
1786 smartlist_clear(*(smartlist_t**)lvalue);
1787 } else {
1788 *(smartlist_t**)lvalue = smartlist_create();
1791 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
1792 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1793 break;
1795 case CONFIG_TYPE_LINELIST:
1796 case CONFIG_TYPE_LINELIST_S:
1797 config_line_append((config_line_t**)lvalue, c->key, c->value);
1798 break;
1799 case CONFIG_TYPE_OBSOLETE:
1800 log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
1801 break;
1802 case CONFIG_TYPE_LINELIST_V:
1803 r = tor_snprintf(buf, sizeof(buf),
1804 "You may not provide a value for virtual option '%s'", c->key);
1805 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1806 return -1;
1807 default:
1808 tor_assert(0);
1809 break;
1811 return 0;
1814 /** If <b>c</b> is a syntactically valid configuration line, update
1815 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1816 * key, -2 for bad value.
1818 * If <b>clear_first</b> is set, clear the value first. Then if
1819 * <b>use_defaults</b> is set, set the value to the default.
1821 * Called from config_assign().
1823 static int
1824 config_assign_line(config_format_t *fmt, or_options_t *options,
1825 config_line_t *c, int use_defaults,
1826 int clear_first, char **msg)
1828 config_var_t *var;
1830 CHECK(fmt, options);
1832 var = config_find_option(fmt, c->key);
1833 if (!var) {
1834 if (fmt->extra) {
1835 void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
1836 log_info(LD_CONFIG,
1837 "Found unrecognized option '%s'; saving it.", c->key);
1838 config_line_append((config_line_t**)lvalue, c->key, c->value);
1839 return 0;
1840 } else {
1841 char buf[1024];
1842 int tmp = tor_snprintf(buf, sizeof(buf),
1843 "Unknown option '%s'. Failing.", c->key);
1844 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1845 return -1;
1848 /* Put keyword into canonical case. */
1849 if (strcmp(var->name, c->key)) {
1850 tor_free(c->key);
1851 c->key = tor_strdup(var->name);
1854 if (!strlen(c->value)) {
1855 /* reset or clear it, then return */
1856 if (!clear_first) {
1857 if (var->type == CONFIG_TYPE_LINELIST ||
1858 var->type == CONFIG_TYPE_LINELIST_S) {
1859 /* We got an empty linelist from the torrc or command line.
1860 As a special case, call this an error. Warn and ignore. */
1861 log_warn(LD_CONFIG,
1862 "Linelist option '%s' has no value. Skipping.", c->key);
1863 } else { /* not already cleared */
1864 option_reset(fmt, options, var, use_defaults);
1867 return 0;
1870 if (config_assign_value(fmt, options, c, msg) < 0)
1871 return -2;
1872 return 0;
1875 /** Restore the option named <b>key</b> in options to its default value.
1876 * Called from config_assign(). */
1877 static void
1878 config_reset_line(config_format_t *fmt, or_options_t *options,
1879 const char *key, int use_defaults)
1881 config_var_t *var;
1883 CHECK(fmt, options);
1885 var = config_find_option(fmt, key);
1886 if (!var)
1887 return; /* give error on next pass. */
1889 option_reset(fmt, options, var, use_defaults);
1892 /** Return true iff key is a valid configuration option. */
1894 option_is_recognized(const char *key)
1896 config_var_t *var = config_find_option(&options_format, key);
1897 return (var != NULL);
1900 /** Return the canonical name of a configuration option, or NULL
1901 * if no such option exists. */
1902 const char *
1903 option_get_canonical_name(const char *key)
1905 config_var_t *var = config_find_option(&options_format, key);
1906 return var ? var->name : NULL;
1909 /** Return a canonical list of the options assigned for key.
1911 config_line_t *
1912 option_get_assignment(or_options_t *options, const char *key)
1914 return get_assigned_option(&options_format, options, key, 1);
1917 /** Return true iff value needs to be quoted and escaped to be used in
1918 * a configuration file. */
1919 static int
1920 config_value_needs_escape(const char *value)
1922 if (*value == '\"')
1923 return 1;
1924 while (*value) {
1925 switch (*value)
1927 case '\r':
1928 case '\n':
1929 case '#':
1930 /* Note: quotes and backspaces need special handling when we are using
1931 * quotes, not otherwise, so they don't trigger escaping on their
1932 * own. */
1933 return 1;
1934 default:
1935 if (!TOR_ISPRINT(*value))
1936 return 1;
1938 ++value;
1940 return 0;
1943 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1944 static config_line_t *
1945 config_lines_dup(const config_line_t *inp)
1947 config_line_t *result = NULL;
1948 config_line_t **next_out = &result;
1949 while (inp) {
1950 *next_out = tor_malloc(sizeof(config_line_t));
1951 (*next_out)->key = tor_strdup(inp->key);
1952 (*next_out)->value = tor_strdup(inp->value);
1953 inp = inp->next;
1954 next_out = &((*next_out)->next);
1956 (*next_out) = NULL;
1957 return result;
1960 /** Return newly allocated line or lines corresponding to <b>key</b> in the
1961 * configuration <b>options</b>. If <b>escape_val</b> is true and a
1962 * value needs to be quoted before it's put in a config file, quote and
1963 * escape that value. Return NULL if no such key exists. */
1964 static config_line_t *
1965 get_assigned_option(config_format_t *fmt, void *options,
1966 const char *key, int escape_val)
1968 config_var_t *var;
1969 const void *value;
1970 char buf[32];
1971 config_line_t *result;
1972 tor_assert(options && key);
1974 CHECK(fmt, options);
1976 var = config_find_option(fmt, key);
1977 if (!var) {
1978 log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
1979 return NULL;
1981 value = STRUCT_VAR_P(options, var->var_offset);
1983 result = tor_malloc_zero(sizeof(config_line_t));
1984 result->key = tor_strdup(var->name);
1985 switch (var->type)
1987 case CONFIG_TYPE_STRING:
1988 case CONFIG_TYPE_FILENAME:
1989 if (*(char**)value) {
1990 result->value = tor_strdup(*(char**)value);
1991 } else {
1992 tor_free(result->key);
1993 tor_free(result);
1994 return NULL;
1996 break;
1997 case CONFIG_TYPE_ISOTIME:
1998 if (*(time_t*)value) {
1999 result->value = tor_malloc(ISO_TIME_LEN+1);
2000 format_iso_time(result->value, *(time_t*)value);
2001 } else {
2002 tor_free(result->key);
2003 tor_free(result);
2005 escape_val = 0; /* Can't need escape. */
2006 break;
2007 case CONFIG_TYPE_INTERVAL:
2008 case CONFIG_TYPE_UINT:
2009 /* This means every or_options_t uint or bool element
2010 * needs to be an int. Not, say, a uint16_t or char. */
2011 tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
2012 result->value = tor_strdup(buf);
2013 escape_val = 0; /* Can't need escape. */
2014 break;
2015 case CONFIG_TYPE_MEMUNIT:
2016 tor_snprintf(buf, sizeof(buf), U64_FORMAT,
2017 U64_PRINTF_ARG(*(uint64_t*)value));
2018 result->value = tor_strdup(buf);
2019 escape_val = 0; /* Can't need escape. */
2020 break;
2021 case CONFIG_TYPE_DOUBLE:
2022 tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
2023 result->value = tor_strdup(buf);
2024 escape_val = 0; /* Can't need escape. */
2025 break;
2026 case CONFIG_TYPE_BOOL:
2027 result->value = tor_strdup(*(int*)value ? "1" : "0");
2028 escape_val = 0; /* Can't need escape. */
2029 break;
2030 case CONFIG_TYPE_ROUTERSET:
2031 result->value = routerset_to_string(*(routerset_t**)value);
2032 break;
2033 case CONFIG_TYPE_CSV:
2034 if (*(smartlist_t**)value)
2035 result->value =
2036 smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
2037 else
2038 result->value = tor_strdup("");
2039 break;
2040 case CONFIG_TYPE_OBSOLETE:
2041 log_fn(LOG_PROTOCOL_WARN, LD_CONFIG,
2042 "You asked me for the value of an obsolete config option '%s'.",
2043 key);
2044 tor_free(result->key);
2045 tor_free(result);
2046 return NULL;
2047 case CONFIG_TYPE_LINELIST_S:
2048 log_warn(LD_CONFIG,
2049 "Can't return context-sensitive '%s' on its own", key);
2050 tor_free(result->key);
2051 tor_free(result);
2052 return NULL;
2053 case CONFIG_TYPE_LINELIST:
2054 case CONFIG_TYPE_LINELIST_V:
2055 tor_free(result->key);
2056 tor_free(result);
2057 result = config_lines_dup(*(const config_line_t**)value);
2058 break;
2059 default:
2060 tor_free(result->key);
2061 tor_free(result);
2062 log_warn(LD_BUG,"Unknown type %d for known key '%s'",
2063 var->type, key);
2064 return NULL;
2067 if (escape_val) {
2068 config_line_t *line;
2069 for (line = result; line; line = line->next) {
2070 if (line->value && config_value_needs_escape(line->value)) {
2071 char *newval = esc_for_log(line->value);
2072 tor_free(line->value);
2073 line->value = newval;
2078 return result;
2081 /** Iterate through the linked list of requested options <b>list</b>.
2082 * For each item, convert as appropriate and assign to <b>options</b>.
2083 * If an item is unrecognized, set *msg and return -1 immediately,
2084 * else return 0 for success.
2086 * If <b>clear_first</b>, interpret config options as replacing (not
2087 * extending) their previous values. If <b>clear_first</b> is set,
2088 * then <b>use_defaults</b> to decide if you set to defaults after
2089 * clearing, or make the value 0 or NULL.
2091 * Here are the use cases:
2092 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
2093 * if linelist, replaces current if csv.
2094 * 2. An empty AllowInvalid line in your torrc. Should clear it.
2095 * 3. "RESETCONF AllowInvalid" sets it to default.
2096 * 4. "SETCONF AllowInvalid" makes it NULL.
2097 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
2099 * Use_defaults Clear_first
2100 * 0 0 "append"
2101 * 1 0 undefined, don't use
2102 * 0 1 "set to null first"
2103 * 1 1 "set to defaults first"
2104 * Return 0 on success, -1 on bad key, -2 on bad value.
2106 * As an additional special case, if a LINELIST config option has
2107 * no value and clear_first is 0, then warn and ignore it.
2111 There are three call cases for config_assign() currently.
2113 Case one: Torrc entry
2114 options_init_from_torrc() calls config_assign(0, 0)
2115 calls config_assign_line(0, 0).
2116 if value is empty, calls option_reset(0) and returns.
2117 calls config_assign_value(), appends.
2119 Case two: setconf
2120 options_trial_assign() calls config_assign(0, 1)
2121 calls config_reset_line(0)
2122 calls option_reset(0)
2123 calls option_clear().
2124 calls config_assign_line(0, 1).
2125 if value is empty, returns.
2126 calls config_assign_value(), appends.
2128 Case three: resetconf
2129 options_trial_assign() calls config_assign(1, 1)
2130 calls config_reset_line(1)
2131 calls option_reset(1)
2132 calls option_clear().
2133 calls config_assign_value(default)
2134 calls config_assign_line(1, 1).
2135 returns.
2137 static int
2138 config_assign(config_format_t *fmt, void *options, config_line_t *list,
2139 int use_defaults, int clear_first, char **msg)
2141 config_line_t *p;
2143 CHECK(fmt, options);
2145 /* pass 1: normalize keys */
2146 for (p = list; p; p = p->next) {
2147 const char *full = expand_abbrev(fmt, p->key, 0, 1);
2148 if (strcmp(full,p->key)) {
2149 tor_free(p->key);
2150 p->key = tor_strdup(full);
2154 /* pass 2: if we're reading from a resetting source, clear all
2155 * mentioned config options, and maybe set to their defaults. */
2156 if (clear_first) {
2157 for (p = list; p; p = p->next)
2158 config_reset_line(fmt, options, p->key, use_defaults);
2161 /* pass 3: assign. */
2162 while (list) {
2163 int r;
2164 if ((r=config_assign_line(fmt, options, list, use_defaults,
2165 clear_first, msg)))
2166 return r;
2167 list = list->next;
2169 return 0;
2172 /** Try assigning <b>list</b> to the global options. You do this by duping
2173 * options, assigning list to the new one, then validating it. If it's
2174 * ok, then throw out the old one and stick with the new one. Else,
2175 * revert to old and return failure. Return SETOPT_OK on success, or
2176 * a setopt_err_t on failure.
2178 * If not success, point *<b>msg</b> to a newly allocated string describing
2179 * what went wrong.
2181 setopt_err_t
2182 options_trial_assign(config_line_t *list, int use_defaults,
2183 int clear_first, char **msg)
2185 int r;
2186 or_options_t *trial_options = options_dup(&options_format, get_options());
2188 if ((r=config_assign(&options_format, trial_options,
2189 list, use_defaults, clear_first, msg)) < 0) {
2190 config_free(&options_format, trial_options);
2191 return r;
2194 if (options_validate(get_options(), trial_options, 1, msg) < 0) {
2195 config_free(&options_format, trial_options);
2196 return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2199 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2200 config_free(&options_format, trial_options);
2201 return SETOPT_ERR_TRANSITION;
2204 if (set_options(trial_options, msg)<0) {
2205 config_free(&options_format, trial_options);
2206 return SETOPT_ERR_SETTING;
2209 /* we liked it. put it in place. */
2210 return SETOPT_OK;
2213 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2214 * Called from option_reset() and config_free(). */
2215 static void
2216 option_clear(config_format_t *fmt, or_options_t *options, config_var_t *var)
2218 void *lvalue = STRUCT_VAR_P(options, var->var_offset);
2219 (void)fmt; /* unused */
2220 switch (var->type) {
2221 case CONFIG_TYPE_STRING:
2222 case CONFIG_TYPE_FILENAME:
2223 tor_free(*(char**)lvalue);
2224 break;
2225 case CONFIG_TYPE_DOUBLE:
2226 *(double*)lvalue = 0.0;
2227 break;
2228 case CONFIG_TYPE_ISOTIME:
2229 *(time_t*)lvalue = 0;
2230 break;
2231 case CONFIG_TYPE_INTERVAL:
2232 case CONFIG_TYPE_UINT:
2233 case CONFIG_TYPE_BOOL:
2234 *(int*)lvalue = 0;
2235 break;
2236 case CONFIG_TYPE_MEMUNIT:
2237 *(uint64_t*)lvalue = 0;
2238 break;
2239 case CONFIG_TYPE_ROUTERSET:
2240 if (*(routerset_t**)lvalue) {
2241 routerset_free(*(routerset_t**)lvalue);
2242 *(routerset_t**)lvalue = NULL;
2244 break;
2245 case CONFIG_TYPE_CSV:
2246 if (*(smartlist_t**)lvalue) {
2247 SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
2248 smartlist_free(*(smartlist_t **)lvalue);
2249 *(smartlist_t **)lvalue = NULL;
2251 break;
2252 case CONFIG_TYPE_LINELIST:
2253 case CONFIG_TYPE_LINELIST_S:
2254 config_free_lines(*(config_line_t **)lvalue);
2255 *(config_line_t **)lvalue = NULL;
2256 break;
2257 case CONFIG_TYPE_LINELIST_V:
2258 /* handled by linelist_s. */
2259 break;
2260 case CONFIG_TYPE_OBSOLETE:
2261 break;
2265 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2266 * <b>use_defaults</b>, set it to its default value.
2267 * Called by config_init() and option_reset_line() and option_assign_line(). */
2268 static void
2269 option_reset(config_format_t *fmt, or_options_t *options,
2270 config_var_t *var, int use_defaults)
2272 config_line_t *c;
2273 char *msg = NULL;
2274 CHECK(fmt, options);
2275 option_clear(fmt, options, var); /* clear it first */
2276 if (!use_defaults)
2277 return; /* all done */
2278 if (var->initvalue) {
2279 c = tor_malloc_zero(sizeof(config_line_t));
2280 c->key = tor_strdup(var->name);
2281 c->value = tor_strdup(var->initvalue);
2282 if (config_assign_value(fmt, options, c, &msg) < 0) {
2283 log_warn(LD_BUG, "Failed to assign default: %s", msg);
2284 tor_free(msg); /* if this happens it's a bug */
2286 config_free_lines(c);
2290 /** Print a usage message for tor. */
2291 static void
2292 print_usage(void)
2294 printf(
2295 "Copyright (c) 2001-2004, Roger Dingledine\n"
2296 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2297 "Copyright (c) 2007-2010, The Tor Project, Inc.\n\n"
2298 "tor -f <torrc> [args]\n"
2299 "See man page for options, or https://www.torproject.org/ for "
2300 "documentation.\n");
2303 /** Print all non-obsolete torrc options. */
2304 static void
2305 list_torrc_options(void)
2307 int i;
2308 smartlist_t *lines = smartlist_create();
2309 for (i = 0; _option_vars[i].name; ++i) {
2310 config_var_t *var = &_option_vars[i];
2311 const char *desc;
2312 if (var->type == CONFIG_TYPE_OBSOLETE ||
2313 var->type == CONFIG_TYPE_LINELIST_V)
2314 continue;
2315 desc = config_find_description(&options_format, var->name);
2316 printf("%s\n", var->name);
2317 if (desc) {
2318 wrap_string(lines, desc, 76, " ", " ");
2319 SMARTLIST_FOREACH(lines, char *, cp, {
2320 printf("%s", cp);
2321 tor_free(cp);
2323 smartlist_clear(lines);
2326 smartlist_free(lines);
2329 /** Last value actually set by resolve_my_address. */
2330 static uint32_t last_resolved_addr = 0;
2332 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2333 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2334 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2335 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2336 * public IP address.
2339 resolve_my_address(int warn_severity, or_options_t *options,
2340 uint32_t *addr_out, char **hostname_out)
2342 struct in_addr in;
2343 uint32_t addr;
2344 char hostname[256];
2345 int explicit_ip=1;
2346 int explicit_hostname=1;
2347 int from_interface=0;
2348 char tmpbuf[INET_NTOA_BUF_LEN];
2349 const char *address = options->Address;
2350 int notice_severity = warn_severity <= LOG_NOTICE ?
2351 LOG_NOTICE : warn_severity;
2353 tor_assert(addr_out);
2355 if (address && *address) {
2356 strlcpy(hostname, address, sizeof(hostname));
2357 } else { /* then we need to guess our address */
2358 explicit_ip = 0; /* it's implicit */
2359 explicit_hostname = 0; /* it's implicit */
2361 if (gethostname(hostname, sizeof(hostname)) < 0) {
2362 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2363 return -1;
2365 log_debug(LD_CONFIG,"Guessed local host name as '%s'",hostname);
2368 /* now we know hostname. resolve it and keep only the IP address */
2370 if (tor_inet_aton(hostname, &in) == 0) {
2371 /* then we have to resolve it */
2372 explicit_ip = 0;
2373 if (tor_lookup_hostname(hostname, &addr)) {
2374 uint32_t interface_ip;
2376 if (explicit_hostname) {
2377 log_fn(warn_severity, LD_CONFIG,
2378 "Could not resolve local Address '%s'. Failing.", hostname);
2379 return -1;
2381 log_fn(notice_severity, LD_CONFIG,
2382 "Could not resolve guessed local hostname '%s'. "
2383 "Trying something else.", hostname);
2384 if (get_interface_address(warn_severity, &interface_ip)) {
2385 log_fn(warn_severity, LD_CONFIG,
2386 "Could not get local interface IP address. Failing.");
2387 return -1;
2389 from_interface = 1;
2390 in.s_addr = htonl(interface_ip);
2391 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2392 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2393 "local interface. Using that.", tmpbuf);
2394 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2395 } else {
2396 in.s_addr = htonl(addr);
2398 if (!explicit_hostname &&
2399 is_internal_IP(ntohl(in.s_addr), 0)) {
2400 uint32_t interface_ip;
2402 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2403 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2404 "resolves to a private IP address (%s). Trying something "
2405 "else.", hostname, tmpbuf);
2407 if (get_interface_address(warn_severity, &interface_ip)) {
2408 log_fn(warn_severity, LD_CONFIG,
2409 "Could not get local interface IP address. Too bad.");
2410 } else if (is_internal_IP(interface_ip, 0)) {
2411 struct in_addr in2;
2412 in2.s_addr = htonl(interface_ip);
2413 tor_inet_ntoa(&in2,tmpbuf,sizeof(tmpbuf));
2414 log_fn(notice_severity, LD_CONFIG,
2415 "Interface IP address '%s' is a private address too. "
2416 "Ignoring.", tmpbuf);
2417 } else {
2418 from_interface = 1;
2419 in.s_addr = htonl(interface_ip);
2420 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2421 log_fn(notice_severity, LD_CONFIG,
2422 "Learned IP address '%s' for local interface."
2423 " Using that.", tmpbuf);
2424 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2430 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2431 if (is_internal_IP(ntohl(in.s_addr), 0)) {
2432 /* make sure we're ok with publishing an internal IP */
2433 if (!options->DirServers && !options->AlternateDirAuthority) {
2434 /* if they are using the default dirservers, disallow internal IPs
2435 * always. */
2436 log_fn(warn_severity, LD_CONFIG,
2437 "Address '%s' resolves to private IP address '%s'. "
2438 "Tor servers that use the default DirServers must have public "
2439 "IP addresses.", hostname, tmpbuf);
2440 return -1;
2442 if (!explicit_ip) {
2443 /* even if they've set their own dirservers, require an explicit IP if
2444 * they're using an internal address. */
2445 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2446 "IP address '%s'. Please set the Address config option to be "
2447 "the IP address you want to use.", hostname, tmpbuf);
2448 return -1;
2452 log_debug(LD_CONFIG, "Resolved Address to '%s'.", tmpbuf);
2453 *addr_out = ntohl(in.s_addr);
2454 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2455 /* Leave this as a notice, regardless of the requested severity,
2456 * at least until dynamic IP address support becomes bulletproof. */
2457 log_notice(LD_NET,
2458 "Your IP address seems to have changed to %s. Updating.",
2459 tmpbuf);
2460 ip_address_changed(0);
2462 if (last_resolved_addr != *addr_out) {
2463 const char *method;
2464 const char *h = hostname;
2465 if (explicit_ip) {
2466 method = "CONFIGURED";
2467 h = NULL;
2468 } else if (explicit_hostname) {
2469 method = "RESOLVED";
2470 } else if (from_interface) {
2471 method = "INTERFACE";
2472 h = NULL;
2473 } else {
2474 method = "GETHOSTNAME";
2476 control_event_server_status(LOG_NOTICE,
2477 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2478 tmpbuf, method, h?"HOSTNAME=":"", h);
2480 last_resolved_addr = *addr_out;
2481 if (hostname_out)
2482 *hostname_out = tor_strdup(hostname);
2483 return 0;
2486 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2487 * on a private network.
2490 is_local_addr(const tor_addr_t *addr)
2492 if (tor_addr_is_internal(addr, 0))
2493 return 1;
2494 /* Check whether ip is on the same /24 as we are. */
2495 if (get_options()->EnforceDistinctSubnets == 0)
2496 return 0;
2497 if (tor_addr_family(addr) == AF_INET) {
2498 /*XXXX022 IP6 what corresponds to an /24? */
2499 uint32_t ip = tor_addr_to_ipv4h(addr);
2501 /* It's possible that this next check will hit before the first time
2502 * resolve_my_address actually succeeds. (For clients, it is likely that
2503 * resolve_my_address will never be called at all). In those cases,
2504 * last_resolved_addr will be 0, and so checking to see whether ip is on
2505 * the same /24 as last_resolved_addr will be the same as checking whether
2506 * it was on net 0, which is already done by is_internal_IP.
2508 if ((last_resolved_addr & (uint32_t)0xffffff00ul)
2509 == (ip & (uint32_t)0xffffff00ul))
2510 return 1;
2512 return 0;
2515 /** Called when we don't have a nickname set. Try to guess a good nickname
2516 * based on the hostname, and return it in a newly allocated string. If we
2517 * can't, return NULL and let the caller warn if it wants to. */
2518 static char *
2519 get_default_nickname(void)
2521 static const char * const bad_default_nicknames[] = {
2522 "localhost",
2523 NULL,
2525 char localhostname[256];
2526 char *cp, *out, *outp;
2527 int i;
2529 if (gethostname(localhostname, sizeof(localhostname)) < 0)
2530 return NULL;
2532 /* Put it in lowercase; stop at the first dot. */
2533 if ((cp = strchr(localhostname, '.')))
2534 *cp = '\0';
2535 tor_strlower(localhostname);
2537 /* Strip invalid characters. */
2538 cp = localhostname;
2539 out = outp = tor_malloc(strlen(localhostname) + 1);
2540 while (*cp) {
2541 if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
2542 *outp++ = *cp++;
2543 else
2544 cp++;
2546 *outp = '\0';
2548 /* Enforce length. */
2549 if (strlen(out) > MAX_NICKNAME_LEN)
2550 out[MAX_NICKNAME_LEN]='\0';
2552 /* Check for dumb names. */
2553 for (i = 0; bad_default_nicknames[i]; ++i) {
2554 if (!strcmp(out, bad_default_nicknames[i])) {
2555 tor_free(out);
2556 return NULL;
2560 return out;
2563 /** Release storage held by <b>options</b>. */
2564 static void
2565 config_free(config_format_t *fmt, void *options)
2567 int i;
2569 tor_assert(options);
2571 for (i=0; fmt->vars[i].name; ++i)
2572 option_clear(fmt, options, &(fmt->vars[i]));
2573 if (fmt->extra) {
2574 config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
2575 config_free_lines(*linep);
2576 *linep = NULL;
2578 tor_free(options);
2581 /** Return true iff a and b contain identical keys and values in identical
2582 * order. */
2583 static int
2584 config_lines_eq(config_line_t *a, config_line_t *b)
2586 while (a && b) {
2587 if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
2588 return 0;
2589 a = a->next;
2590 b = b->next;
2592 if (a || b)
2593 return 0;
2594 return 1;
2597 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2598 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2600 static int
2601 option_is_same(config_format_t *fmt,
2602 or_options_t *o1, or_options_t *o2, const char *name)
2604 config_line_t *c1, *c2;
2605 int r = 1;
2606 CHECK(fmt, o1);
2607 CHECK(fmt, o2);
2609 c1 = get_assigned_option(fmt, o1, name, 0);
2610 c2 = get_assigned_option(fmt, o2, name, 0);
2611 r = config_lines_eq(c1, c2);
2612 config_free_lines(c1);
2613 config_free_lines(c2);
2614 return r;
2617 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2618 static or_options_t *
2619 options_dup(config_format_t *fmt, or_options_t *old)
2621 or_options_t *newopts;
2622 int i;
2623 config_line_t *line;
2625 newopts = config_alloc(fmt);
2626 for (i=0; fmt->vars[i].name; ++i) {
2627 if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2628 continue;
2629 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
2630 continue;
2631 line = get_assigned_option(fmt, old, fmt->vars[i].name, 0);
2632 if (line) {
2633 char *msg = NULL;
2634 if (config_assign(fmt, newopts, line, 0, 0, &msg) < 0) {
2635 log_err(LD_BUG, "Config_get_assigned_option() generated "
2636 "something we couldn't config_assign(): %s", msg);
2637 tor_free(msg);
2638 tor_assert(0);
2641 config_free_lines(line);
2643 return newopts;
2646 /** Return a new empty or_options_t. Used for testing. */
2647 or_options_t *
2648 options_new(void)
2650 return config_alloc(&options_format);
2653 /** Set <b>options</b> to hold reasonable defaults for most options.
2654 * Each option defaults to zero. */
2655 void
2656 options_init(or_options_t *options)
2658 config_init(&options_format, options);
2661 /* Check if the port number given in <b>port_option</b> in combination with
2662 * the specified port in <b>listen_options</b> will result in Tor actually
2663 * opening a low port (meaning a port lower than 1024). Return 1 if
2664 * it is, or 0 if it isn't or the concept of a low port isn't applicable for
2665 * the platform we're on. */
2666 static int
2667 is_listening_on_low_port(uint16_t port_option,
2668 const config_line_t *listen_options)
2670 #ifdef MS_WINDOWS
2671 return 0; /* No port is too low for windows. */
2672 #else
2673 const config_line_t *l;
2674 uint16_t p;
2675 if (port_option == 0)
2676 return 0; /* We're not listening */
2677 if (listen_options == NULL)
2678 return (port_option < 1024);
2680 for (l = listen_options; l; l = l->next) {
2681 parse_addr_port(LOG_WARN, l->value, NULL, NULL, &p);
2682 if (p<1024) {
2683 return 1;
2686 return 0;
2687 #endif
2690 /** Set all vars in the configuration object <b>options</b> to their default
2691 * values. */
2692 static void
2693 config_init(config_format_t *fmt, void *options)
2695 int i;
2696 config_var_t *var;
2697 CHECK(fmt, options);
2699 for (i=0; fmt->vars[i].name; ++i) {
2700 var = &fmt->vars[i];
2701 if (!var->initvalue)
2702 continue; /* defaults to NULL or 0 */
2703 option_reset(fmt, options, var, 1);
2707 /** Allocate and return a new string holding the written-out values of the vars
2708 * in 'options'. If 'minimal', do not write out any default-valued vars.
2709 * Else, if comment_defaults, write default values as comments.
2711 static char *
2712 config_dump(config_format_t *fmt, void *options, int minimal,
2713 int comment_defaults)
2715 smartlist_t *elements;
2716 or_options_t *defaults;
2717 config_line_t *line, *assigned;
2718 char *result;
2719 int i;
2720 const char *desc;
2721 char *msg = NULL;
2723 defaults = config_alloc(fmt);
2724 config_init(fmt, defaults);
2726 /* XXX use a 1 here so we don't add a new log line while dumping */
2727 if (fmt->validate_fn(NULL,defaults, 1, &msg) < 0) {
2728 log_err(LD_BUG, "Failed to validate default config.");
2729 tor_free(msg);
2730 tor_assert(0);
2733 elements = smartlist_create();
2734 for (i=0; fmt->vars[i].name; ++i) {
2735 int comment_option = 0;
2736 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
2737 fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2738 continue;
2739 /* Don't save 'hidden' control variables. */
2740 if (!strcmpstart(fmt->vars[i].name, "__"))
2741 continue;
2742 if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
2743 continue;
2744 else if (comment_defaults &&
2745 option_is_same(fmt, options, defaults, fmt->vars[i].name))
2746 comment_option = 1;
2748 desc = config_find_description(fmt, fmt->vars[i].name);
2749 line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name, 1);
2751 if (line && desc) {
2752 /* Only dump the description if there's something to describe. */
2753 wrap_string(elements, desc, 78, "# ", "# ");
2756 for (; line; line = line->next) {
2757 size_t len = strlen(line->key) + strlen(line->value) + 5;
2758 char *tmp;
2759 tmp = tor_malloc(len);
2760 if (tor_snprintf(tmp, len, "%s%s %s\n",
2761 comment_option ? "# " : "",
2762 line->key, line->value)<0) {
2763 log_err(LD_BUG,"Internal error writing option value");
2764 tor_assert(0);
2766 smartlist_add(elements, tmp);
2768 config_free_lines(assigned);
2771 if (fmt->extra) {
2772 line = *(config_line_t**)STRUCT_VAR_P(options, fmt->extra->var_offset);
2773 for (; line; line = line->next) {
2774 size_t len = strlen(line->key) + strlen(line->value) + 3;
2775 char *tmp;
2776 tmp = tor_malloc(len);
2777 if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
2778 log_err(LD_BUG,"Internal error writing option value");
2779 tor_assert(0);
2781 smartlist_add(elements, tmp);
2785 result = smartlist_join_strings(elements, "", 0, NULL);
2786 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2787 smartlist_free(elements);
2788 config_free(fmt, defaults);
2789 return result;
2792 /** Return a string containing a possible configuration file that would give
2793 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2794 * include options that are the same as Tor's defaults.
2796 static char *
2797 options_dump(or_options_t *options, int minimal)
2799 return config_dump(&options_format, options, minimal, 0);
2802 /** Return 0 if every element of sl is a string holding a decimal
2803 * representation of a port number, or if sl is NULL.
2804 * Otherwise set *msg and return -1. */
2805 static int
2806 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2808 int i;
2809 char buf[1024];
2810 tor_assert(name);
2812 if (!sl)
2813 return 0;
2815 SMARTLIST_FOREACH(sl, const char *, cp,
2817 i = atoi(cp);
2818 if (i < 1 || i > 65535) {
2819 int r = tor_snprintf(buf, sizeof(buf),
2820 "Port '%s' out of range in %s", cp, name);
2821 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2822 return -1;
2825 return 0;
2828 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2829 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2830 * Else return 0.
2832 static int
2833 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2835 int r;
2836 char buf[1024];
2837 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2838 /* This handles an understandable special case where somebody says "2gb"
2839 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2840 --*value;
2842 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2843 r = tor_snprintf(buf, sizeof(buf), "%s ("U64_FORMAT") must be at most %d",
2844 desc, U64_PRINTF_ARG(*value),
2845 ROUTER_MAX_DECLARED_BANDWIDTH);
2846 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2847 return -1;
2849 return 0;
2852 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2853 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2854 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2855 * Treat "0" as "".
2856 * Return 0 on success or -1 if not a recognized authority type (in which
2857 * case the value of _PublishServerDescriptor is undefined). */
2858 static int
2859 compute_publishserverdescriptor(or_options_t *options)
2861 smartlist_t *list = options->PublishServerDescriptor;
2862 authority_type_t *auth = &options->_PublishServerDescriptor;
2863 *auth = NO_AUTHORITY;
2864 if (!list) /* empty list, answer is none */
2865 return 0;
2866 SMARTLIST_FOREACH(list, const char *, string, {
2867 if (!strcasecmp(string, "v1"))
2868 *auth |= V1_AUTHORITY;
2869 else if (!strcmp(string, "1"))
2870 if (options->BridgeRelay)
2871 *auth |= BRIDGE_AUTHORITY;
2872 else
2873 *auth |= V2_AUTHORITY | V3_AUTHORITY;
2874 else if (!strcasecmp(string, "v2"))
2875 *auth |= V2_AUTHORITY;
2876 else if (!strcasecmp(string, "v3"))
2877 *auth |= V3_AUTHORITY;
2878 else if (!strcasecmp(string, "bridge"))
2879 *auth |= BRIDGE_AUTHORITY;
2880 else if (!strcasecmp(string, "hidserv"))
2881 *auth |= HIDSERV_AUTHORITY;
2882 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2883 /* no authority */;
2884 else
2885 return -1;
2887 return 0;
2890 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2891 * services can overload the directory system. */
2892 #define MIN_REND_POST_PERIOD (10*60)
2894 /** Highest allowable value for RendPostPeriod. */
2895 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2897 /** Lowest allowable value for CircuitBuildTimeout; values too low will
2898 * increase network load because of failing connections being retried, and
2899 * might prevent users from connecting to the network at all. */
2900 #define MIN_CIRCUIT_BUILD_TIMEOUT 30
2902 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2903 * will generate too many circuits and potentially overload the network. */
2904 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2906 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2907 * permissible transition from <b>old_options</b>. Else return -1.
2908 * Should have no side effects, except for normalizing the contents of
2909 * <b>options</b>.
2911 * On error, tor_strdup an error explanation into *<b>msg</b>.
2913 * XXX
2914 * If <b>from_setconf</b>, we were called by the controller, and our
2915 * Log line should stay empty. If it's 0, then give us a default log
2916 * if there are no logs defined.
2918 static int
2919 options_validate(or_options_t *old_options, or_options_t *options,
2920 int from_setconf, char **msg)
2922 int i, r;
2923 config_line_t *cl;
2924 const char *uname = get_uname();
2925 char buf[1024];
2926 #define REJECT(arg) \
2927 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2928 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2930 tor_assert(msg);
2931 *msg = NULL;
2933 if (options->ORPort < 0 || options->ORPort > 65535)
2934 REJECT("ORPort option out of bounds.");
2936 if (server_mode(options) &&
2937 (!strcmpstart(uname, "Windows 95") ||
2938 !strcmpstart(uname, "Windows 98") ||
2939 !strcmpstart(uname, "Windows Me"))) {
2940 log(LOG_WARN, LD_CONFIG, "Tor is running as a server, but you are "
2941 "running %s; this probably won't work. See "
2942 "http://wiki.noreply.org/noreply/TheOnionRouter/TorFAQ#ServerOS "
2943 "for details.", uname);
2946 if (options->ORPort == 0 && options->ORListenAddress != NULL)
2947 REJECT("ORPort must be defined if ORListenAddress is defined.");
2949 if (options->DirPort == 0 && options->DirListenAddress != NULL)
2950 REJECT("DirPort must be defined if DirListenAddress is defined.");
2952 if (options->DNSPort == 0 && options->DNSListenAddress != NULL)
2953 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
2955 if (options->ControlPort == 0 && options->ControlListenAddress != NULL)
2956 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
2958 if (options->TransPort == 0 && options->TransListenAddress != NULL)
2959 REJECT("TransPort must be defined if TransListenAddress is defined.");
2961 if (options->NatdPort == 0 && options->NatdListenAddress != NULL)
2962 REJECT("NatdPort must be defined if NatdListenAddress is defined.");
2964 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
2965 * configuration does this. */
2967 for (i = 0; i < 3; ++i) {
2968 int is_socks = i==0;
2969 int is_trans = i==1;
2970 config_line_t *line, *opt, *old;
2971 const char *tp;
2972 if (is_socks) {
2973 opt = options->SocksListenAddress;
2974 old = old_options ? old_options->SocksListenAddress : NULL;
2975 tp = "SOCKS proxy";
2976 } else if (is_trans) {
2977 opt = options->TransListenAddress;
2978 old = old_options ? old_options->TransListenAddress : NULL;
2979 tp = "transparent proxy";
2980 } else {
2981 opt = options->NatdListenAddress;
2982 old = old_options ? old_options->NatdListenAddress : NULL;
2983 tp = "natd proxy";
2986 for (line = opt; line; line = line->next) {
2987 char *address = NULL;
2988 uint16_t port;
2989 uint32_t addr;
2990 if (parse_addr_port(LOG_WARN, line->value, &address, &addr, &port)<0)
2991 continue; /* We'll warn about this later. */
2992 if (!is_internal_IP(addr, 1) &&
2993 (!old_options || !config_lines_eq(old, opt))) {
2994 log_warn(LD_CONFIG,
2995 "You specified a public address '%s' for a %s. Other "
2996 "people on the Internet might find your computer and use it as "
2997 "an open %s. Please don't allow this unless you have "
2998 "a good reason.", address, tp, tp);
3000 tor_free(address);
3004 if (validate_data_directory(options)<0)
3005 REJECT("Invalid DataDirectory");
3007 if (options->Nickname == NULL) {
3008 if (server_mode(options)) {
3009 if (!(options->Nickname = get_default_nickname())) {
3010 log_notice(LD_CONFIG, "Couldn't pick a nickname based on "
3011 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME);
3012 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
3013 } else {
3014 log_notice(LD_CONFIG, "Choosing default nickname '%s'",
3015 options->Nickname);
3018 } else {
3019 if (!is_legal_nickname(options->Nickname)) {
3020 r = tor_snprintf(buf, sizeof(buf),
3021 "Nickname '%s' is wrong length or contains illegal characters.",
3022 options->Nickname);
3023 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3024 return -1;
3028 if (server_mode(options) && !options->ContactInfo)
3029 log(LOG_NOTICE, LD_CONFIG, "Your ContactInfo config option is not set. "
3030 "Please consider setting it, so we can contact you if your server is "
3031 "misconfigured or something else goes wrong.");
3033 /* Special case on first boot if no Log options are given. */
3034 if (!options->Logs && !options->RunAsDaemon && !from_setconf)
3035 config_line_append(&options->Logs, "Log", "notice stdout");
3037 if (options_init_logs(options, 1)<0) /* Validate the log(s) */
3038 REJECT("Failed to validate Log options. See logs for details.");
3040 if (options->NoPublish) {
3041 log(LOG_WARN, LD_CONFIG,
3042 "NoPublish is obsolete. Use PublishServerDescriptor instead.");
3043 SMARTLIST_FOREACH(options->PublishServerDescriptor, char *, s,
3044 tor_free(s));
3045 smartlist_clear(options->PublishServerDescriptor);
3048 if (authdir_mode(options)) {
3049 /* confirm that our address isn't broken, so we can complain now */
3050 uint32_t tmp;
3051 if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
3052 REJECT("Failed to resolve/guess local address. See logs for details.");
3055 #ifndef MS_WINDOWS
3056 if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
3057 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
3058 #endif
3060 if (options->SocksPort < 0 || options->SocksPort > 65535)
3061 REJECT("SocksPort option out of bounds.");
3063 if (options->DNSPort < 0 || options->DNSPort > 65535)
3064 REJECT("DNSPort option out of bounds.");
3066 if (options->TransPort < 0 || options->TransPort > 65535)
3067 REJECT("TransPort option out of bounds.");
3069 if (options->NatdPort < 0 || options->NatdPort > 65535)
3070 REJECT("NatdPort option out of bounds.");
3072 if (options->SocksPort == 0 && options->TransPort == 0 &&
3073 options->NatdPort == 0 && options->ORPort == 0 &&
3074 options->DNSPort == 0 && !options->RendConfigLines)
3075 log(LOG_WARN, LD_CONFIG,
3076 "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
3077 "undefined, and there aren't any hidden services configured. "
3078 "Tor will still run, but probably won't do anything.");
3080 if (options->ControlPort < 0 || options->ControlPort > 65535)
3081 REJECT("ControlPort option out of bounds.");
3083 if (options->DirPort < 0 || options->DirPort > 65535)
3084 REJECT("DirPort option out of bounds.");
3086 #ifndef USE_TRANSPARENT
3087 if (options->TransPort || options->TransListenAddress)
3088 REJECT("TransPort and TransListenAddress are disabled in this build.");
3089 #endif
3091 if (options->AccountingMax &&
3092 (is_listening_on_low_port(options->ORPort, options->ORListenAddress) ||
3093 is_listening_on_low_port(options->DirPort, options->DirListenAddress)))
3095 log(LOG_WARN, LD_CONFIG,
3096 "You have set AccountingMax to use hibernation. You have also "
3097 "chosen a low DirPort or OrPort. This combination can make Tor stop "
3098 "working when it tries to re-attach the port after a period of "
3099 "hibernation. Please choose a different port or turn off "
3100 "hibernation unless you know this combination will work on your "
3101 "platform.");
3104 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3105 options->_ExcludeExitNodesUnion = routerset_new();
3106 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeExitNodes);
3107 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeNodes);
3110 if (options->StrictExitNodes &&
3111 (!options->ExitNodes) &&
3112 (!old_options ||
3113 (old_options->StrictExitNodes != options->StrictExitNodes) ||
3114 (!routerset_equal(old_options->ExitNodes,options->ExitNodes))))
3115 COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
3117 if (options->StrictEntryNodes &&
3118 (!options->EntryNodes) &&
3119 (!old_options ||
3120 (old_options->StrictEntryNodes != options->StrictEntryNodes) ||
3121 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
3122 COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
3124 if (options->EntryNodes && !routerset_is_list(options->EntryNodes)) {
3125 /* XXXX fix this; see entry_guards_prepend_from_config(). */
3126 REJECT("IPs or countries are not yet supported in EntryNodes.");
3129 if (options->AuthoritativeDir) {
3130 if (!options->ContactInfo && !options->TestingTorNetwork)
3131 REJECT("Authoritative directory servers must set ContactInfo");
3132 if (options->V1AuthoritativeDir && !options->RecommendedVersions)
3133 REJECT("V1 authoritative dir servers must set RecommendedVersions.");
3134 if (!options->RecommendedClientVersions)
3135 options->RecommendedClientVersions =
3136 config_lines_dup(options->RecommendedVersions);
3137 if (!options->RecommendedServerVersions)
3138 options->RecommendedServerVersions =
3139 config_lines_dup(options->RecommendedVersions);
3140 if (options->VersioningAuthoritativeDir &&
3141 (!options->RecommendedClientVersions ||
3142 !options->RecommendedServerVersions))
3143 REJECT("Versioning authoritative dir servers must set "
3144 "Recommended*Versions.");
3145 if (options->UseEntryGuards) {
3146 log_info(LD_CONFIG, "Authoritative directory servers can't set "
3147 "UseEntryGuards. Disabling.");
3148 options->UseEntryGuards = 0;
3150 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
3151 log_info(LD_CONFIG, "Authoritative directories always try to download "
3152 "extra-info documents. Setting DownloadExtraInfo.");
3153 options->DownloadExtraInfo = 1;
3155 if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
3156 options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
3157 options->V3AuthoritativeDir))
3158 REJECT("AuthoritativeDir is set, but none of "
3159 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
3162 if (options->AuthoritativeDir && !options->DirPort)
3163 REJECT("Running as authoritative directory, but no DirPort set.");
3165 if (options->AuthoritativeDir && !options->ORPort)
3166 REJECT("Running as authoritative directory, but no ORPort set.");
3168 if (options->AuthoritativeDir && options->ClientOnly)
3169 REJECT("Running as authoritative directory, but ClientOnly also set.");
3171 if (options->HSAuthorityRecordStats && !options->HSAuthoritativeDir)
3172 REJECT("HSAuthorityRecordStats is set but we're not running as "
3173 "a hidden service authority.");
3175 if (options->ConnLimit <= 0) {
3176 r = tor_snprintf(buf, sizeof(buf),
3177 "ConnLimit must be greater than 0, but was set to %d",
3178 options->ConnLimit);
3179 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3180 return -1;
3183 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3184 return -1;
3186 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3187 return -1;
3189 if (validate_ports_csv(options->RejectPlaintextPorts,
3190 "RejectPlaintextPorts", msg) < 0)
3191 return -1;
3193 if (validate_ports_csv(options->WarnPlaintextPorts,
3194 "WarnPlaintextPorts", msg) < 0)
3195 return -1;
3197 if (options->FascistFirewall && !options->ReachableAddresses) {
3198 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3199 /* We already have firewall ports set, so migrate them to
3200 * ReachableAddresses, which will set ReachableORAddresses and
3201 * ReachableDirAddresses if they aren't set explicitly. */
3202 smartlist_t *instead = smartlist_create();
3203 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3204 new_line->key = tor_strdup("ReachableAddresses");
3205 /* If we're configured with the old format, we need to prepend some
3206 * open ports. */
3207 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3209 int p = atoi(portno);
3210 char *s;
3211 if (p<0) continue;
3212 s = tor_malloc(16);
3213 tor_snprintf(s, 16, "*:%d", p);
3214 smartlist_add(instead, s);
3216 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3217 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3218 log(LOG_NOTICE, LD_CONFIG,
3219 "Converting FascistFirewall and FirewallPorts "
3220 "config options to new format: \"ReachableAddresses %s\"",
3221 new_line->value);
3222 options->ReachableAddresses = new_line;
3223 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3224 smartlist_free(instead);
3225 } else {
3226 /* We do not have FirewallPorts set, so add 80 to
3227 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3228 if (!options->ReachableDirAddresses) {
3229 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3230 new_line->key = tor_strdup("ReachableDirAddresses");
3231 new_line->value = tor_strdup("*:80");
3232 options->ReachableDirAddresses = new_line;
3233 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3234 "to new format: \"ReachableDirAddresses *:80\"");
3236 if (!options->ReachableORAddresses) {
3237 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3238 new_line->key = tor_strdup("ReachableORAddresses");
3239 new_line->value = tor_strdup("*:443");
3240 options->ReachableORAddresses = new_line;
3241 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3242 "to new format: \"ReachableORAddresses *:443\"");
3247 for (i=0; i<3; i++) {
3248 config_line_t **linep =
3249 (i==0) ? &options->ReachableAddresses :
3250 (i==1) ? &options->ReachableORAddresses :
3251 &options->ReachableDirAddresses;
3252 if (!*linep)
3253 continue;
3254 /* We need to end with a reject *:*, not an implicit accept *:* */
3255 for (;;) {
3256 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
3257 break;
3258 linep = &((*linep)->next);
3259 if (!*linep) {
3260 *linep = tor_malloc_zero(sizeof(config_line_t));
3261 (*linep)->key = tor_strdup(
3262 (i==0) ? "ReachableAddresses" :
3263 (i==1) ? "ReachableORAddresses" :
3264 "ReachableDirAddresses");
3265 (*linep)->value = tor_strdup("reject *:*");
3266 break;
3271 if ((options->ReachableAddresses ||
3272 options->ReachableORAddresses ||
3273 options->ReachableDirAddresses) &&
3274 server_mode(options))
3275 REJECT("Servers must be able to freely connect to the rest "
3276 "of the Internet, so they must not set Reachable*Addresses "
3277 "or FascistFirewall.");
3279 if (options->UseBridges &&
3280 server_mode(options))
3281 REJECT("Servers must be able to freely connect to the rest "
3282 "of the Internet, so they must not set UseBridges.");
3284 options->_AllowInvalid = 0;
3285 if (options->AllowInvalidNodes) {
3286 SMARTLIST_FOREACH(options->AllowInvalidNodes, const char *, cp, {
3287 if (!strcasecmp(cp, "entry"))
3288 options->_AllowInvalid |= ALLOW_INVALID_ENTRY;
3289 else if (!strcasecmp(cp, "exit"))
3290 options->_AllowInvalid |= ALLOW_INVALID_EXIT;
3291 else if (!strcasecmp(cp, "middle"))
3292 options->_AllowInvalid |= ALLOW_INVALID_MIDDLE;
3293 else if (!strcasecmp(cp, "introduction"))
3294 options->_AllowInvalid |= ALLOW_INVALID_INTRODUCTION;
3295 else if (!strcasecmp(cp, "rendezvous"))
3296 options->_AllowInvalid |= ALLOW_INVALID_RENDEZVOUS;
3297 else {
3298 r = tor_snprintf(buf, sizeof(buf),
3299 "Unrecognized value '%s' in AllowInvalidNodes", cp);
3300 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3301 return -1;
3306 if (compute_publishserverdescriptor(options) < 0) {
3307 r = tor_snprintf(buf, sizeof(buf),
3308 "Unrecognized value in PublishServerDescriptor");
3309 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3310 return -1;
3313 if ((options->BridgeRelay
3314 || options->_PublishServerDescriptor & BRIDGE_AUTHORITY)
3315 && (options->_PublishServerDescriptor
3316 & (V1_AUTHORITY|V2_AUTHORITY|V3_AUTHORITY))) {
3317 REJECT("Bridges are not supposed to publish router descriptors to the "
3318 "directory authorities. Please correct your "
3319 "PublishServerDescriptor line.");
3322 if (options->MinUptimeHidServDirectoryV2 < 0) {
3323 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3324 "least 0 seconds. Changing to 0.");
3325 options->MinUptimeHidServDirectoryV2 = 0;
3328 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
3329 log(LOG_WARN,LD_CONFIG,"RendPostPeriod option is too short; "
3330 "raising to %d seconds.", MIN_REND_POST_PERIOD);
3331 options->RendPostPeriod = MIN_REND_POST_PERIOD;
3334 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3335 log(LOG_WARN, LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3336 MAX_DIR_PERIOD);
3337 options->RendPostPeriod = MAX_DIR_PERIOD;
3340 if (options->CircuitBuildTimeout < MIN_CIRCUIT_BUILD_TIMEOUT) {
3341 log(LOG_WARN, LD_CONFIG, "CircuitBuildTimeout option is too short; "
3342 "raising to %d seconds.", MIN_CIRCUIT_BUILD_TIMEOUT);
3343 options->CircuitBuildTimeout = MIN_CIRCUIT_BUILD_TIMEOUT;
3346 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3347 log(LOG_WARN, LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3348 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3349 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3352 if (options->KeepalivePeriod < 1)
3353 REJECT("KeepalivePeriod option must be positive.");
3355 if (ensure_bandwidth_cap(&options->BandwidthRate,
3356 "BandwidthRate", msg) < 0)
3357 return -1;
3358 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3359 "BandwidthBurst", msg) < 0)
3360 return -1;
3361 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3362 "MaxAdvertisedBandwidth", msg) < 0)
3363 return -1;
3364 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3365 "RelayBandwidthRate", msg) < 0)
3366 return -1;
3367 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3368 "RelayBandwidthBurst", msg) < 0)
3369 return -1;
3371 if (server_mode(options)) {
3372 if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3373 r = tor_snprintf(buf, sizeof(buf),
3374 "BandwidthRate is set to %d bytes/second. "
3375 "For servers, it must be at least %d.",
3376 (int)options->BandwidthRate,
3377 ROUTER_REQUIRED_MIN_BANDWIDTH);
3378 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3379 return -1;
3380 } else if (options->MaxAdvertisedBandwidth <
3381 ROUTER_REQUIRED_MIN_BANDWIDTH/2) {
3382 r = tor_snprintf(buf, sizeof(buf),
3383 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3384 "For servers, it must be at least %d.",
3385 (int)options->MaxAdvertisedBandwidth,
3386 ROUTER_REQUIRED_MIN_BANDWIDTH/2);
3387 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3388 return -1;
3390 if (options->RelayBandwidthRate &&
3391 options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3392 r = tor_snprintf(buf, sizeof(buf),
3393 "RelayBandwidthRate is set to %d bytes/second. "
3394 "For servers, it must be at least %d.",
3395 (int)options->RelayBandwidthRate,
3396 ROUTER_REQUIRED_MIN_BANDWIDTH);
3397 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3398 return -1;
3402 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3403 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3405 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3406 REJECT("RelayBandwidthBurst must be at least equal "
3407 "to RelayBandwidthRate.");
3409 if (options->BandwidthRate > options->BandwidthBurst)
3410 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3412 /* if they set relaybandwidth* really high but left bandwidth*
3413 * at the default, raise the defaults. */
3414 if (options->RelayBandwidthRate > options->BandwidthRate)
3415 options->BandwidthRate = options->RelayBandwidthRate;
3416 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3417 options->BandwidthBurst = options->RelayBandwidthBurst;
3419 if (accounting_parse_options(options, 1)<0)
3420 REJECT("Failed to parse accounting options. See logs for details.");
3422 if (options->HttpProxy) { /* parse it now */
3423 if (parse_addr_port(LOG_WARN, options->HttpProxy, NULL,
3424 &options->HttpProxyAddr, &options->HttpProxyPort) < 0)
3425 REJECT("HttpProxy failed to parse or resolve. Please fix.");
3426 if (options->HttpProxyPort == 0) { /* give it a default */
3427 options->HttpProxyPort = 80;
3431 if (options->HttpProxyAuthenticator) {
3432 if (strlen(options->HttpProxyAuthenticator) >= 48)
3433 REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
3436 if (options->HttpsProxy) { /* parse it now */
3437 if (parse_addr_port(LOG_WARN, options->HttpsProxy, NULL,
3438 &options->HttpsProxyAddr, &options->HttpsProxyPort) <0)
3439 REJECT("HttpsProxy failed to parse or resolve. Please fix.");
3440 if (options->HttpsProxyPort == 0) { /* give it a default */
3441 options->HttpsProxyPort = 443;
3445 if (options->HttpsProxyAuthenticator) {
3446 if (strlen(options->HttpsProxyAuthenticator) >= 48)
3447 REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
3450 if (options->HashedControlPassword) {
3451 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3452 if (!sl) {
3453 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3454 } else {
3455 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3456 smartlist_free(sl);
3460 if (options->HashedControlSessionPassword) {
3461 smartlist_t *sl = decode_hashed_passwords(
3462 options->HashedControlSessionPassword);
3463 if (!sl) {
3464 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3465 } else {
3466 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3467 smartlist_free(sl);
3471 if (options->ControlListenAddress) {
3472 int all_are_local = 1;
3473 config_line_t *ln;
3474 for (ln = options->ControlListenAddress; ln; ln = ln->next) {
3475 if (strcmpstart(ln->value, "127."))
3476 all_are_local = 0;
3478 if (!all_are_local) {
3479 if (!options->HashedControlPassword &&
3480 !options->HashedControlSessionPassword &&
3481 !options->CookieAuthentication) {
3482 log_warn(LD_CONFIG,
3483 "You have a ControlListenAddress set to accept "
3484 "unauthenticated connections from a non-local address. "
3485 "This means that programs not running on your computer "
3486 "can reconfigure your Tor, without even having to guess a "
3487 "password. That's so bad that I'm closing your ControlPort "
3488 "for you. If you need to control your Tor remotely, try "
3489 "enabling authentication and using a tool like stunnel or "
3490 "ssh to encrypt remote access.");
3491 options->ControlPort = 0;
3492 } else {
3493 log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
3494 "connections from a non-local address. This means that "
3495 "programs not running on your computer can reconfigure your "
3496 "Tor. That's pretty bad, since the controller "
3497 "protocol isn't encrypted! Maybe you should just listen on "
3498 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
3499 "remote connections to your control port.");
3504 if (options->ControlPort && !options->HashedControlPassword &&
3505 !options->HashedControlSessionPassword &&
3506 !options->CookieAuthentication) {
3507 log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
3508 "has been configured. This means that any program on your "
3509 "computer can reconfigure your Tor. That's bad! You should "
3510 "upgrade your Tor controller as soon as possible.");
3513 if (options->UseEntryGuards && ! options->NumEntryGuards)
3514 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3516 if (check_nickname_list(options->MyFamily, "MyFamily", msg))
3517 return -1;
3518 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3519 if (check_nickname_list(cl->value, "NodeFamily", msg))
3520 return -1;
3523 if (validate_addr_policies(options, msg) < 0)
3524 return -1;
3526 if (validate_dir_authorities(options, old_options) < 0)
3527 REJECT("Directory authority line did not parse. See logs for details.");
3529 if (options->UseBridges && !options->Bridges)
3530 REJECT("If you set UseBridges, you must specify at least one bridge.");
3531 if (options->UseBridges && !options->TunnelDirConns)
3532 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3533 if (options->Bridges) {
3534 for (cl = options->Bridges; cl; cl = cl->next) {
3535 if (parse_bridge_line(cl->value, 1)<0)
3536 REJECT("Bridge line did not parse. See logs for details.");
3540 if (options->ConstrainedSockets) {
3541 /* If the user wants to constrain socket buffer use, make sure the desired
3542 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3543 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3544 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3545 options->ConstrainedSockSize % 1024) {
3546 r = tor_snprintf(buf, sizeof(buf),
3547 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3548 "in 1024 byte increments.",
3549 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3550 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3551 return -1;
3553 if (options->DirPort) {
3554 /* Providing cached directory entries while system TCP buffers are scarce
3555 * will exacerbate the socket errors. Suggest that this be disabled. */
3556 COMPLAIN("You have requested constrained socket buffers while also "
3557 "serving directory entries via DirPort. It is strongly "
3558 "suggested that you disable serving directory requests when "
3559 "system TCP buffer resources are scarce.");
3563 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3564 options->V3AuthVotingInterval/2) {
3565 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3566 "V3AuthVotingInterval");
3568 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
3569 REJECT("V3AuthVoteDelay is way too low.");
3570 if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
3571 REJECT("V3AuthDistDelay is way too low.");
3573 if (options->V3AuthNIntervalsValid < 2)
3574 REJECT("V3AuthNIntervalsValid must be at least 2.");
3576 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3577 REJECT("V3AuthVotingInterval is insanely low.");
3578 } else if (options->V3AuthVotingInterval > 24*60*60) {
3579 REJECT("V3AuthVotingInterval is insanely high.");
3580 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3581 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3584 if (rend_config_services(options, 1) < 0)
3585 REJECT("Failed to configure rendezvous options. See logs for details.");
3587 /* Parse client-side authorization for hidden services. */
3588 if (rend_parse_service_authorization(options, 1) < 0)
3589 REJECT("Failed to configure client authorization for hidden services. "
3590 "See logs for details.");
3592 if (parse_virtual_addr_network(options->VirtualAddrNetwork, 1, NULL)<0)
3593 return -1;
3595 if (options->PreferTunneledDirConns && !options->TunnelDirConns)
3596 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3598 if (options->AutomapHostsSuffixes) {
3599 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
3601 size_t len = strlen(suf);
3602 if (len && suf[len-1] == '.')
3603 suf[len-1] = '\0';
3607 if (options->TestingTorNetwork && !options->DirServers) {
3608 REJECT("TestingTorNetwork may only be configured in combination with "
3609 "a non-default set of DirServers.");
3612 /*XXXX022 checking for defaults manually like this is a bit fragile.*/
3614 /* Keep changes to hard-coded values synchronous to man page and default
3615 * values table. */
3616 if (options->TestingV3AuthInitialVotingInterval != 30*60 &&
3617 !options->TestingTorNetwork) {
3618 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
3619 "Tor networks!");
3620 } else if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
3621 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3622 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
3623 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3624 "30 minutes.");
3627 if (options->TestingV3AuthInitialVoteDelay != 5*60 &&
3628 !options->TestingTorNetwork) {
3629 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
3630 "Tor networks!");
3631 } else if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
3632 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3635 if (options->TestingV3AuthInitialDistDelay != 5*60 &&
3636 !options->TestingTorNetwork) {
3637 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
3638 "Tor networks!");
3639 } else if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
3640 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3643 if (options->TestingV3AuthInitialVoteDelay +
3644 options->TestingV3AuthInitialDistDelay >=
3645 options->TestingV3AuthInitialVotingInterval/2) {
3646 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3647 "must be less than half TestingV3AuthInitialVotingInterval");
3650 if (options->TestingAuthDirTimeToLearnReachability != 30*60 &&
3651 !options->TestingTorNetwork) {
3652 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
3653 "testing Tor networks!");
3654 } else if (options->TestingAuthDirTimeToLearnReachability < 0) {
3655 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3656 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
3657 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3660 if (options->TestingEstimatedDescriptorPropagationTime != 10*60 &&
3661 !options->TestingTorNetwork) {
3662 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
3663 "testing Tor networks!");
3664 } else if (options->TestingEstimatedDescriptorPropagationTime < 0) {
3665 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3666 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
3667 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3670 if (options->TestingTorNetwork) {
3671 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
3672 "almost unusable in the public Tor network, and is "
3673 "therefore only advised if you are building a "
3674 "testing Tor network!");
3677 return 0;
3678 #undef REJECT
3679 #undef COMPLAIN
3682 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3683 * equal strings. */
3684 static int
3685 opt_streq(const char *s1, const char *s2)
3687 if (!s1 && !s2)
3688 return 1;
3689 else if (s1 && s2 && !strcmp(s1,s2))
3690 return 1;
3691 else
3692 return 0;
3695 /** Check if any of the previous options have changed but aren't allowed to. */
3696 static int
3697 options_transition_allowed(or_options_t *old, or_options_t *new_val,
3698 char **msg)
3700 if (!old)
3701 return 0;
3703 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3704 *msg = tor_strdup("PidFile is not allowed to change.");
3705 return -1;
3708 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3709 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3710 "is not allowed.");
3711 return -1;
3714 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
3715 char buf[1024];
3716 int r = tor_snprintf(buf, sizeof(buf),
3717 "While Tor is running, changing DataDirectory "
3718 "(\"%s\"->\"%s\") is not allowed.",
3719 old->DataDirectory, new_val->DataDirectory);
3720 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3721 return -1;
3724 if (!opt_streq(old->User, new_val->User)) {
3725 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
3726 return -1;
3729 if (!opt_streq(old->Group, new_val->Group)) {
3730 *msg = tor_strdup("While Tor is running, changing Group is not allowed.");
3731 return -1;
3734 if (old->HardwareAccel != new_val->HardwareAccel) {
3735 *msg = tor_strdup("While Tor is running, changing HardwareAccel is "
3736 "not allowed.");
3737 return -1;
3740 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
3741 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
3742 "is not allowed.");
3743 return -1;
3746 return 0;
3749 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3750 * will require us to rotate the CPU and DNS workers; else return 0. */
3751 static int
3752 options_transition_affects_workers(or_options_t *old_options,
3753 or_options_t *new_options)
3755 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3756 old_options->NumCpus != new_options->NumCpus ||
3757 old_options->ORPort != new_options->ORPort ||
3758 old_options->ServerDNSSearchDomains !=
3759 new_options->ServerDNSSearchDomains ||
3760 old_options->SafeLogging != new_options->SafeLogging ||
3761 old_options->ClientOnly != new_options->ClientOnly ||
3762 !config_lines_eq(old_options->Logs, new_options->Logs))
3763 return 1;
3765 /* Check whether log options match. */
3767 /* Nothing that changed matters. */
3768 return 0;
3771 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3772 * will require us to generate a new descriptor; else return 0. */
3773 static int
3774 options_transition_affects_descriptor(or_options_t *old_options,
3775 or_options_t *new_options)
3777 /* XXX We can be smarter here. If your DirPort isn't being
3778 * published and you just turned it off, no need to republish. Etc. */
3779 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3780 !opt_streq(old_options->Nickname,new_options->Nickname) ||
3781 !opt_streq(old_options->Address,new_options->Address) ||
3782 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
3783 old_options->ExitPolicyRejectPrivate !=
3784 new_options->ExitPolicyRejectPrivate ||
3785 old_options->ORPort != new_options->ORPort ||
3786 old_options->DirPort != new_options->DirPort ||
3787 old_options->ClientOnly != new_options->ClientOnly ||
3788 old_options->NoPublish != new_options->NoPublish ||
3789 old_options->_PublishServerDescriptor !=
3790 new_options->_PublishServerDescriptor ||
3791 get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
3792 get_effective_bwburst(old_options) !=
3793 get_effective_bwburst(new_options) ||
3794 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
3795 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
3796 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
3797 old_options->AccountingMax != new_options->AccountingMax)
3798 return 1;
3800 return 0;
3803 #ifdef MS_WINDOWS
3804 /** Return the directory on windows where we expect to find our application
3805 * data. */
3806 static char *
3807 get_windows_conf_root(void)
3809 static int is_set = 0;
3810 static char path[MAX_PATH+1];
3812 LPITEMIDLIST idl;
3813 IMalloc *m;
3814 HRESULT result;
3816 if (is_set)
3817 return path;
3819 /* Find X:\documents and settings\username\application data\ .
3820 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3822 #ifdef ENABLE_LOCAL_APPDATA
3823 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
3824 #else
3825 #define APPDATA_PATH CSIDL_APPDATA
3826 #endif
3827 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
3828 GetCurrentDirectory(MAX_PATH, path);
3829 is_set = 1;
3830 log_warn(LD_CONFIG,
3831 "I couldn't find your application data folder: are you "
3832 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3833 path);
3834 return path;
3836 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3837 result = SHGetPathFromIDList(idl, path);
3838 /* Now we need to free the */
3839 SHGetMalloc(&m);
3840 if (m) {
3841 m->lpVtbl->Free(m, idl);
3842 m->lpVtbl->Release(m);
3844 if (!SUCCEEDED(result)) {
3845 return NULL;
3847 strlcat(path,"\\tor",MAX_PATH);
3848 is_set = 1;
3849 return path;
3851 #endif
3853 /** Return the default location for our torrc file. */
3854 static const char *
3855 get_default_conf_file(void)
3857 #ifdef MS_WINDOWS
3858 static char path[MAX_PATH+1];
3859 strlcpy(path, get_windows_conf_root(), MAX_PATH);
3860 strlcat(path,"\\torrc",MAX_PATH);
3861 return path;
3862 #else
3863 return (CONFDIR "/torrc");
3864 #endif
3867 /** Verify whether lst is a string containing valid-looking comma-separated
3868 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3870 static int
3871 check_nickname_list(const char *lst, const char *name, char **msg)
3873 int r = 0;
3874 smartlist_t *sl;
3876 if (!lst)
3877 return 0;
3878 sl = smartlist_create();
3880 smartlist_split_string(sl, lst, ",",
3881 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
3883 SMARTLIST_FOREACH(sl, const char *, s,
3885 if (!is_legal_nickname_or_hexdigest(s)) {
3886 char buf[1024];
3887 int tmp = tor_snprintf(buf, sizeof(buf),
3888 "Invalid nickname '%s' in %s line", s, name);
3889 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
3890 r = -1;
3891 break;
3894 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
3895 smartlist_free(sl);
3896 return r;
3899 /** Learn config file name from command line arguments, or use the default */
3900 static char *
3901 find_torrc_filename(int argc, char **argv,
3902 int *using_default_torrc, int *ignore_missing_torrc)
3904 char *fname=NULL;
3905 int i;
3907 for (i = 1; i < argc; ++i) {
3908 if (i < argc-1 && !strcmp(argv[i],"-f")) {
3909 if (fname) {
3910 log(LOG_WARN, LD_CONFIG, "Duplicate -f options on command line.");
3911 tor_free(fname);
3913 #ifdef MS_WINDOWS
3914 /* XXX one day we might want to extend expand_filename to work
3915 * under Windows as well. */
3916 fname = tor_strdup(argv[i+1]);
3917 #else
3918 fname = expand_filename(argv[i+1]);
3919 #endif
3920 *using_default_torrc = 0;
3921 ++i;
3922 } else if (!strcmp(argv[i],"--ignore-missing-torrc")) {
3923 *ignore_missing_torrc = 1;
3927 if (*using_default_torrc) {
3928 /* didn't find one, try CONFDIR */
3929 const char *dflt = get_default_conf_file();
3930 if (dflt && file_status(dflt) == FN_FILE) {
3931 fname = tor_strdup(dflt);
3932 } else {
3933 #ifndef MS_WINDOWS
3934 char *fn;
3935 fn = expand_filename("~/.torrc");
3936 if (fn && file_status(fn) == FN_FILE) {
3937 fname = fn;
3938 } else {
3939 tor_free(fn);
3940 fname = tor_strdup(dflt);
3942 #else
3943 fname = tor_strdup(dflt);
3944 #endif
3947 return fname;
3950 /** Load torrc from disk, setting torrc_fname if successful */
3951 static char *
3952 load_torrc_from_disk(int argc, char **argv)
3954 char *fname=NULL;
3955 char *cf = NULL;
3956 int using_default_torrc = 1;
3957 int ignore_missing_torrc = 0;
3959 fname = find_torrc_filename(argc, argv,
3960 &using_default_torrc, &ignore_missing_torrc);
3961 tor_assert(fname);
3962 log(LOG_DEBUG, LD_CONFIG, "Opening config file \"%s\"", fname);
3964 tor_free(torrc_fname);
3965 torrc_fname = fname;
3967 /* Open config file */
3968 if (file_status(fname) != FN_FILE ||
3969 !(cf = read_file_to_str(fname,0,NULL))) {
3970 if (using_default_torrc == 1 || ignore_missing_torrc ) {
3971 log(LOG_NOTICE, LD_CONFIG, "Configuration file \"%s\" not present, "
3972 "using reasonable defaults.", fname);
3973 tor_free(fname); /* sets fname to NULL */
3974 torrc_fname = NULL;
3975 cf = tor_strdup("");
3976 } else {
3977 log(LOG_WARN, LD_CONFIG,
3978 "Unable to open configuration file \"%s\".", fname);
3979 goto err;
3983 return cf;
3984 err:
3985 tor_free(fname);
3986 torrc_fname = NULL;
3987 return NULL;
3990 /** Read a configuration file into <b>options</b>, finding the configuration
3991 * file location based on the command line. After loading the file
3992 * call options_init_from_string() to load the config.
3993 * Return 0 if success, -1 if failure. */
3995 options_init_from_torrc(int argc, char **argv)
3997 char *cf=NULL;
3998 int i, retval, command;
3999 static char **backup_argv;
4000 static int backup_argc;
4001 char *command_arg = NULL;
4002 char *errmsg=NULL;
4004 if (argv) { /* first time we're called. save command line args */
4005 backup_argv = argv;
4006 backup_argc = argc;
4007 } else { /* we're reloading. need to clean up old options first. */
4008 argv = backup_argv;
4009 argc = backup_argc;
4011 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
4012 print_usage();
4013 exit(0);
4015 if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
4016 /* For documenting validating whether we've documented everything. */
4017 list_torrc_options();
4018 exit(0);
4021 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
4022 printf("Tor version %s.\n",get_version());
4023 exit(0);
4026 /* Go through command-line variables */
4027 if (!global_cmdline_options) {
4028 /* Or we could redo the list every time we pass this place.
4029 * It does not really matter */
4030 if (config_get_commandlines(argc, argv, &global_cmdline_options) < 0) {
4031 goto err;
4035 command = CMD_RUN_TOR;
4036 for (i = 1; i < argc; ++i) {
4037 if (!strcmp(argv[i],"--list-fingerprint")) {
4038 command = CMD_LIST_FINGERPRINT;
4039 } else if (!strcmp(argv[i],"--hash-password")) {
4040 command = CMD_HASH_PASSWORD;
4041 command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
4042 ++i;
4043 } else if (!strcmp(argv[i],"--verify-config")) {
4044 command = CMD_VERIFY_CONFIG;
4048 if (command == CMD_HASH_PASSWORD) {
4049 cf = tor_strdup("");
4050 } else {
4051 cf = load_torrc_from_disk(argc, argv);
4052 if (!cf)
4053 goto err;
4056 retval = options_init_from_string(cf, command, command_arg, &errmsg);
4057 tor_free(cf);
4058 if (retval < 0)
4059 goto err;
4061 return 0;
4063 err:
4064 if (errmsg) {
4065 log(LOG_WARN,LD_CONFIG,"%s", errmsg);
4066 tor_free(errmsg);
4068 return -1;
4071 /** Load the options from the configuration in <b>cf</b>, validate
4072 * them for consistency and take actions based on them.
4074 * Return 0 if success, negative on error:
4075 * * -1 for general errors.
4076 * * -2 for failure to parse/validate,
4077 * * -3 for transition not allowed
4078 * * -4 for error while setting the new options
4080 setopt_err_t
4081 options_init_from_string(const char *cf,
4082 int command, const char *command_arg,
4083 char **msg)
4085 or_options_t *oldoptions, *newoptions;
4086 config_line_t *cl;
4087 int retval;
4088 setopt_err_t err = SETOPT_ERR_MISC;
4089 tor_assert(msg);
4091 oldoptions = global_options; /* get_options unfortunately asserts if
4092 this is the first time we run*/
4094 newoptions = tor_malloc_zero(sizeof(or_options_t));
4095 newoptions->_magic = OR_OPTIONS_MAGIC;
4096 options_init(newoptions);
4097 newoptions->command = command;
4098 newoptions->command_arg = command_arg;
4100 /* get config lines, assign them */
4101 retval = config_get_lines(cf, &cl);
4102 if (retval < 0) {
4103 err = SETOPT_ERR_PARSE;
4104 goto err;
4106 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4107 config_free_lines(cl);
4108 if (retval < 0) {
4109 err = SETOPT_ERR_PARSE;
4110 goto err;
4113 /* Go through command-line variables too */
4114 retval = config_assign(&options_format, newoptions,
4115 global_cmdline_options, 0, 0, msg);
4116 if (retval < 0) {
4117 err = SETOPT_ERR_PARSE;
4118 goto err;
4121 /* If this is a testing network configuration, change defaults
4122 * for a list of dependent config options, re-initialize newoptions
4123 * with the new defaults, and assign all options to it second time. */
4124 if (newoptions->TestingTorNetwork) {
4125 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4126 * this? We could, for example, make the parsing algorithm do two passes
4127 * over the configuration. If it finds any "suite" options like
4128 * TestingTorNetwork, it could change the defaults before its second pass.
4129 * Not urgent so long as this seems to work, but at any sign of trouble,
4130 * let's clean it up. -NM */
4132 /* Change defaults. */
4133 int i;
4134 for (i = 0; testing_tor_network_defaults[i].name; ++i) {
4135 config_var_t *new_var = &testing_tor_network_defaults[i];
4136 config_var_t *old_var =
4137 config_find_option(&options_format, new_var->name);
4138 tor_assert(new_var);
4139 tor_assert(old_var);
4140 old_var->initvalue = new_var->initvalue;
4143 /* Clear newoptions and re-initialize them with new defaults. */
4144 config_free(&options_format, newoptions);
4145 newoptions = tor_malloc_zero(sizeof(or_options_t));
4146 newoptions->_magic = OR_OPTIONS_MAGIC;
4147 options_init(newoptions);
4148 newoptions->command = command;
4149 newoptions->command_arg = command_arg;
4151 /* Assign all options a second time. */
4152 retval = config_get_lines(cf, &cl);
4153 if (retval < 0) {
4154 err = SETOPT_ERR_PARSE;
4155 goto err;
4157 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4158 config_free_lines(cl);
4159 if (retval < 0) {
4160 err = SETOPT_ERR_PARSE;
4161 goto err;
4163 retval = config_assign(&options_format, newoptions,
4164 global_cmdline_options, 0, 0, msg);
4165 if (retval < 0) {
4166 err = SETOPT_ERR_PARSE;
4167 goto err;
4171 /* Validate newoptions */
4172 if (options_validate(oldoptions, newoptions, 0, msg) < 0) {
4173 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
4174 goto err;
4177 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
4178 err = SETOPT_ERR_TRANSITION;
4179 goto err;
4182 if (set_options(newoptions, msg)) {
4183 err = SETOPT_ERR_SETTING;
4184 goto err; /* frees and replaces old options */
4187 return SETOPT_OK;
4189 err:
4190 config_free(&options_format, newoptions);
4191 if (*msg) {
4192 int len = (int)strlen(*msg)+256;
4193 char *newmsg = tor_malloc(len);
4195 tor_snprintf(newmsg, len, "Failed to parse/validate config: %s", *msg);
4196 tor_free(*msg);
4197 *msg = newmsg;
4199 return err;
4202 /** Return the location for our configuration file.
4204 const char *
4205 get_torrc_fname(void)
4207 if (torrc_fname)
4208 return torrc_fname;
4209 else
4210 return get_default_conf_file();
4213 /** Adjust the address map based on the MapAddress elements in the
4214 * configuration <b>options</b>
4216 static void
4217 config_register_addressmaps(or_options_t *options)
4219 smartlist_t *elts;
4220 config_line_t *opt;
4221 char *from, *to;
4223 addressmap_clear_configured();
4224 elts = smartlist_create();
4225 for (opt = options->AddressMap; opt; opt = opt->next) {
4226 smartlist_split_string(elts, opt->value, NULL,
4227 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4228 if (smartlist_len(elts) >= 2) {
4229 from = smartlist_get(elts,0);
4230 to = smartlist_get(elts,1);
4231 if (address_is_invalid_destination(to, 1)) {
4232 log_warn(LD_CONFIG,
4233 "Skipping invalid argument '%s' to MapAddress", to);
4234 } else {
4235 addressmap_register(from, tor_strdup(to), 0, ADDRMAPSRC_TORRC);
4236 if (smartlist_len(elts)>2) {
4237 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
4240 } else {
4241 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
4242 opt->value);
4244 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4245 smartlist_clear(elts);
4247 smartlist_free(elts);
4251 * Initialize the logs based on the configuration file.
4253 static int
4254 options_init_logs(or_options_t *options, int validate_only)
4256 config_line_t *opt;
4257 int ok;
4258 smartlist_t *elts;
4259 int daemon =
4260 #ifdef MS_WINDOWS
4262 #else
4263 options->RunAsDaemon;
4264 #endif
4266 ok = 1;
4267 elts = smartlist_create();
4269 for (opt = options->Logs; opt; opt = opt->next) {
4270 log_severity_list_t *severity;
4271 const char *cfg = opt->value;
4272 severity = tor_malloc_zero(sizeof(log_severity_list_t));
4273 if (parse_log_severity_config(&cfg, severity) < 0) {
4274 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
4275 opt->value);
4276 ok = 0; goto cleanup;
4279 smartlist_split_string(elts, cfg, NULL,
4280 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4282 if (smartlist_len(elts) == 0)
4283 smartlist_add(elts, tor_strdup("stdout"));
4285 if (smartlist_len(elts) == 1 &&
4286 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
4287 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
4288 int err = smartlist_len(elts) &&
4289 !strcasecmp(smartlist_get(elts,0), "stderr");
4290 if (!validate_only) {
4291 if (daemon) {
4292 log_warn(LD_CONFIG,
4293 "Can't log to %s with RunAsDaemon set; skipping stdout",
4294 err?"stderr":"stdout");
4295 } else {
4296 add_stream_log(severity, err?"<stderr>":"<stdout>",
4297 fileno(err?stderr:stdout));
4300 goto cleanup;
4302 if (smartlist_len(elts) == 1 &&
4303 !strcasecmp(smartlist_get(elts,0), "syslog")) {
4304 #ifdef HAVE_SYSLOG_H
4305 if (!validate_only) {
4306 add_syslog_log(severity);
4308 #else
4309 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
4310 #endif
4311 goto cleanup;
4314 if (smartlist_len(elts) == 2 &&
4315 !strcasecmp(smartlist_get(elts,0), "file")) {
4316 if (!validate_only) {
4317 if (add_file_log(severity, smartlist_get(elts, 1)) < 0) {
4318 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
4319 opt->value, strerror(errno));
4320 ok = 0;
4323 goto cleanup;
4326 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
4327 opt->value);
4328 ok = 0; goto cleanup;
4330 cleanup:
4331 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4332 smartlist_clear(elts);
4333 tor_free(severity);
4335 smartlist_free(elts);
4337 return ok?0:-1;
4340 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4341 * if the line is well-formed, and -1 if it isn't. If
4342 * <b>validate_only</b> is 0, and the line is well-formed, then add
4343 * the bridge described in the line to our internal bridge list. */
4344 static int
4345 parse_bridge_line(const char *line, int validate_only)
4347 smartlist_t *items = NULL;
4348 int r;
4349 char *addrport=NULL, *fingerprint=NULL;
4350 tor_addr_t addr;
4351 uint16_t port = 0;
4352 char digest[DIGEST_LEN];
4354 items = smartlist_create();
4355 smartlist_split_string(items, line, NULL,
4356 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4357 if (smartlist_len(items) < 1) {
4358 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
4359 goto err;
4361 addrport = smartlist_get(items, 0);
4362 smartlist_del_keeporder(items, 0);
4363 if (tor_addr_port_parse(addrport, &addr, &port)<0) {
4364 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
4365 goto err;
4367 if (!port) {
4368 log_info(LD_CONFIG,
4369 "Bridge address '%s' has no port; using default port 443.",
4370 addrport);
4371 port = 443;
4374 if (smartlist_len(items)) {
4375 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4376 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4377 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
4378 goto err;
4380 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4381 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
4382 goto err;
4386 if (!validate_only) {
4387 log_debug(LD_DIR, "Bridge at %s:%d (%s)", fmt_addr(&addr),
4388 (int)port,
4389 fingerprint ? fingerprint : "no key listed");
4390 bridge_add_from_config(&addr, port, fingerprint ? digest : NULL);
4393 r = 0;
4394 goto done;
4396 err:
4397 r = -1;
4399 done:
4400 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4401 smartlist_free(items);
4402 tor_free(addrport);
4403 tor_free(fingerprint);
4404 return r;
4407 /** Read the contents of a DirServer line from <b>line</b>. If
4408 * <b>validate_only</b> is 0, and the line is well-formed, and it
4409 * shares any bits with <b>required_type</b> or <b>required_type</b>
4410 * is 0, then add the dirserver described in the line (minus whatever
4411 * bits it's missing) as a valid authority. Return 0 on success,
4412 * or -1 if the line isn't well-formed or if we can't add it. */
4413 static int
4414 parse_dir_server_line(const char *line, authority_type_t required_type,
4415 int validate_only)
4417 smartlist_t *items = NULL;
4418 int r;
4419 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
4420 uint16_t dir_port = 0, or_port = 0;
4421 char digest[DIGEST_LEN];
4422 char v3_digest[DIGEST_LEN];
4423 authority_type_t type = V2_AUTHORITY;
4424 int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
4426 items = smartlist_create();
4427 smartlist_split_string(items, line, NULL,
4428 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4429 if (smartlist_len(items) < 1) {
4430 log_warn(LD_CONFIG, "No arguments on DirServer line.");
4431 goto err;
4434 if (is_legal_nickname(smartlist_get(items, 0))) {
4435 nickname = smartlist_get(items, 0);
4436 smartlist_del_keeporder(items, 0);
4439 while (smartlist_len(items)) {
4440 char *flag = smartlist_get(items, 0);
4441 if (TOR_ISDIGIT(flag[0]))
4442 break;
4443 if (!strcasecmp(flag, "v1")) {
4444 type |= (V1_AUTHORITY | HIDSERV_AUTHORITY);
4445 } else if (!strcasecmp(flag, "hs")) {
4446 type |= HIDSERV_AUTHORITY;
4447 } else if (!strcasecmp(flag, "no-hs")) {
4448 is_not_hidserv_authority = 1;
4449 } else if (!strcasecmp(flag, "bridge")) {
4450 type |= BRIDGE_AUTHORITY;
4451 } else if (!strcasecmp(flag, "no-v2")) {
4452 is_not_v2_authority = 1;
4453 } else if (!strcasecmpstart(flag, "orport=")) {
4454 int ok;
4455 char *portstring = flag + strlen("orport=");
4456 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
4457 if (!ok)
4458 log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
4459 portstring);
4460 } else if (!strcasecmpstart(flag, "v3ident=")) {
4461 char *idstr = flag + strlen("v3ident=");
4462 if (strlen(idstr) != HEX_DIGEST_LEN ||
4463 base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
4464 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirServer line",
4465 flag);
4466 } else {
4467 type |= V3_AUTHORITY;
4469 } else {
4470 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
4471 flag);
4473 tor_free(flag);
4474 smartlist_del_keeporder(items, 0);
4476 if (is_not_hidserv_authority)
4477 type &= ~HIDSERV_AUTHORITY;
4478 if (is_not_v2_authority)
4479 type &= ~V2_AUTHORITY;
4481 if (smartlist_len(items) < 2) {
4482 log_warn(LD_CONFIG, "Too few arguments to DirServer line.");
4483 goto err;
4485 addrport = smartlist_get(items, 0);
4486 smartlist_del_keeporder(items, 0);
4487 if (parse_addr_port(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
4488 log_warn(LD_CONFIG, "Error parsing DirServer address '%s'", addrport);
4489 goto err;
4491 if (!dir_port) {
4492 log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
4493 goto err;
4496 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4497 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4498 log_warn(LD_CONFIG, "Key digest for DirServer is wrong length %d.",
4499 (int)strlen(fingerprint));
4500 goto err;
4502 if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4503 /* a known bad fingerprint. refuse to use it. We can remove this
4504 * clause once Tor 0.1.2.17 is obsolete. */
4505 log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
4506 "torrc file (%s), or reinstall Tor and use the default torrc.",
4507 get_torrc_fname());
4508 goto err;
4510 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4511 log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
4512 goto err;
4515 if (!validate_only && (!required_type || required_type & type)) {
4516 if (required_type)
4517 type &= required_type; /* pare down what we think of them as an
4518 * authority for. */
4519 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
4520 address, (int)dir_port, (char*)smartlist_get(items,0));
4521 if (!add_trusted_dir_server(nickname, address, dir_port, or_port,
4522 digest, v3_digest, type))
4523 goto err;
4526 r = 0;
4527 goto done;
4529 err:
4530 r = -1;
4532 done:
4533 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4534 smartlist_free(items);
4535 tor_free(addrport);
4536 tor_free(address);
4537 tor_free(nickname);
4538 tor_free(fingerprint);
4539 return r;
4542 /** Adjust the value of options->DataDirectory, or fill it in if it's
4543 * absent. Return 0 on success, -1 on failure. */
4544 static int
4545 normalize_data_directory(or_options_t *options)
4547 #ifdef MS_WINDOWS
4548 char *p;
4549 if (options->DataDirectory)
4550 return 0; /* all set */
4551 p = tor_malloc(MAX_PATH);
4552 strlcpy(p,get_windows_conf_root(),MAX_PATH);
4553 options->DataDirectory = p;
4554 return 0;
4555 #else
4556 const char *d = options->DataDirectory;
4557 if (!d)
4558 d = "~/.tor";
4560 if (strncmp(d,"~/",2) == 0) {
4561 char *fn = expand_filename(d);
4562 if (!fn) {
4563 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
4564 return -1;
4566 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
4567 /* If our homedir is /, we probably don't want to use it. */
4568 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4569 * want. */
4570 log_warn(LD_CONFIG,
4571 "Default DataDirectory is \"~/.tor\". This expands to "
4572 "\"%s\", which is probably not what you want. Using "
4573 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
4574 tor_free(fn);
4575 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
4577 tor_free(options->DataDirectory);
4578 options->DataDirectory = fn;
4580 return 0;
4581 #endif
4584 /** Check and normalize the value of options->DataDirectory; return 0 if it
4585 * sane, -1 otherwise. */
4586 static int
4587 validate_data_directory(or_options_t *options)
4589 if (normalize_data_directory(options) < 0)
4590 return -1;
4591 tor_assert(options->DataDirectory);
4592 if (strlen(options->DataDirectory) > (512-128)) {
4593 log_warn(LD_CONFIG, "DataDirectory is too long.");
4594 return -1;
4596 return 0;
4599 /** This string must remain the same forevermore. It is how we
4600 * recognize that the torrc file doesn't need to be backed up. */
4601 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4602 "if you edit it, comments will not be preserved"
4603 /** This string can change; it tries to give the reader an idea
4604 * that editing this file by hand is not a good plan. */
4605 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4606 "to torrc.orig.1 or similar, and Tor will ignore it"
4608 /** Save a configuration file for the configuration in <b>options</b>
4609 * into the file <b>fname</b>. If the file already exists, and
4610 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4611 * replace it. Return 0 on success, -1 on failure. */
4612 static int
4613 write_configuration_file(const char *fname, or_options_t *options)
4615 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4616 int rename_old = 0, r;
4617 size_t len;
4619 tor_assert(fname);
4621 switch (file_status(fname)) {
4622 case FN_FILE:
4623 old_val = read_file_to_str(fname, 0, NULL);
4624 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4625 rename_old = 1;
4627 tor_free(old_val);
4628 break;
4629 case FN_NOENT:
4630 break;
4631 case FN_ERROR:
4632 case FN_DIR:
4633 default:
4634 log_warn(LD_CONFIG,
4635 "Config file \"%s\" is not a file? Failing.", fname);
4636 return -1;
4639 if (!(new_conf = options_dump(options, 1))) {
4640 log_warn(LD_BUG, "Couldn't get configuration string");
4641 goto err;
4644 len = strlen(new_conf)+256;
4645 new_val = tor_malloc(len);
4646 tor_snprintf(new_val, len, "%s\n%s\n\n%s",
4647 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4649 if (rename_old) {
4650 int i = 1;
4651 size_t fn_tmp_len = strlen(fname)+32;
4652 char *fn_tmp;
4653 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4654 fn_tmp = tor_malloc(fn_tmp_len);
4655 while (1) {
4656 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4657 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4658 tor_free(fn_tmp);
4659 goto err;
4661 if (file_status(fn_tmp) == FN_NOENT)
4662 break;
4663 ++i;
4665 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4666 if (rename(fname, fn_tmp) < 0) {
4667 log_warn(LD_FS,
4668 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4669 fname, fn_tmp, strerror(errno));
4670 tor_free(fn_tmp);
4671 goto err;
4673 tor_free(fn_tmp);
4676 if (write_str_to_file(fname, new_val, 0) < 0)
4677 goto err;
4679 r = 0;
4680 goto done;
4681 err:
4682 r = -1;
4683 done:
4684 tor_free(new_val);
4685 tor_free(new_conf);
4686 return r;
4690 * Save the current configuration file value to disk. Return 0 on
4691 * success, -1 on failure.
4694 options_save_current(void)
4696 if (torrc_fname) {
4697 /* This fails if we can't write to our configuration file.
4699 * If we try falling back to datadirectory or something, we have a better
4700 * chance of saving the configuration, but a better chance of doing
4701 * something the user never expected. Let's just warn instead. */
4702 return write_configuration_file(torrc_fname, get_options());
4704 return write_configuration_file(get_default_conf_file(), get_options());
4707 /** Mapping from a unit name to a multiplier for converting that unit into a
4708 * base unit. */
4709 struct unit_table_t {
4710 const char *unit;
4711 uint64_t multiplier;
4714 /** Table to map the names of memory units to the number of bytes they
4715 * contain. */
4716 static struct unit_table_t memory_units[] = {
4717 { "", 1 },
4718 { "b", 1<< 0 },
4719 { "byte", 1<< 0 },
4720 { "bytes", 1<< 0 },
4721 { "kb", 1<<10 },
4722 { "kbyte", 1<<10 },
4723 { "kbytes", 1<<10 },
4724 { "kilobyte", 1<<10 },
4725 { "kilobytes", 1<<10 },
4726 { "m", 1<<20 },
4727 { "mb", 1<<20 },
4728 { "mbyte", 1<<20 },
4729 { "mbytes", 1<<20 },
4730 { "megabyte", 1<<20 },
4731 { "megabytes", 1<<20 },
4732 { "gb", 1<<30 },
4733 { "gbyte", 1<<30 },
4734 { "gbytes", 1<<30 },
4735 { "gigabyte", 1<<30 },
4736 { "gigabytes", 1<<30 },
4737 { "tb", U64_LITERAL(1)<<40 },
4738 { "terabyte", U64_LITERAL(1)<<40 },
4739 { "terabytes", U64_LITERAL(1)<<40 },
4740 { NULL, 0 },
4743 /** Table to map the names of time units to the number of seconds they
4744 * contain. */
4745 static struct unit_table_t time_units[] = {
4746 { "", 1 },
4747 { "second", 1 },
4748 { "seconds", 1 },
4749 { "minute", 60 },
4750 { "minutes", 60 },
4751 { "hour", 60*60 },
4752 { "hours", 60*60 },
4753 { "day", 24*60*60 },
4754 { "days", 24*60*60 },
4755 { "week", 7*24*60*60 },
4756 { "weeks", 7*24*60*60 },
4757 { NULL, 0 },
4760 /** Parse a string <b>val</b> containing a number, zero or more
4761 * spaces, and an optional unit string. If the unit appears in the
4762 * table <b>u</b>, then multiply the number by the unit multiplier.
4763 * On success, set *<b>ok</b> to 1 and return this product.
4764 * Otherwise, set *<b>ok</b> to 0.
4766 static uint64_t
4767 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4769 uint64_t v;
4770 char *cp;
4772 tor_assert(ok);
4774 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4775 if (!*ok)
4776 return 0;
4777 if (!cp) {
4778 *ok = 1;
4779 return v;
4781 while (TOR_ISSPACE(*cp))
4782 ++cp;
4783 for ( ;u->unit;++u) {
4784 if (!strcasecmp(u->unit, cp)) {
4785 v *= u->multiplier;
4786 *ok = 1;
4787 return v;
4790 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4791 *ok = 0;
4792 return 0;
4795 /** Parse a string in the format "number unit", where unit is a unit of
4796 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4797 * and return the number of bytes specified. Otherwise, set
4798 * *<b>ok</b> to false and return 0. */
4799 static uint64_t
4800 config_parse_memunit(const char *s, int *ok)
4802 return config_parse_units(s, memory_units, ok);
4805 /** Parse a string in the format "number unit", where unit is a unit of time.
4806 * On success, set *<b>ok</b> to true and return the number of seconds in
4807 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4809 static int
4810 config_parse_interval(const char *s, int *ok)
4812 uint64_t r;
4813 r = config_parse_units(s, time_units, ok);
4814 if (!ok)
4815 return -1;
4816 if (r > INT_MAX) {
4817 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4818 *ok = 0;
4819 return -1;
4821 return (int)r;
4824 /* This is what passes for version detection on OSX. We set
4825 * MACOSX_KQUEUE_IS_BROKEN to true iff we're on a version of OSX before
4826 * 10.4.0 (aka 1040). */
4827 #ifdef __APPLE__
4828 #ifdef __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__
4829 #define MACOSX_KQUEUE_IS_BROKEN \
4830 (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1040)
4831 #else
4832 #define MACOSX_KQUEUE_IS_BROKEN 0
4833 #endif
4834 #endif
4837 * Initialize the libevent library.
4839 static void
4840 init_libevent(void)
4842 configure_libevent_logging();
4843 /* If the kernel complains that some method (say, epoll) doesn't
4844 * exist, we don't care about it, since libevent will cope.
4846 suppress_libevent_log_msg("Function not implemented");
4847 #ifdef __APPLE__
4848 if (MACOSX_KQUEUE_IS_BROKEN ||
4849 decode_libevent_version(event_get_version(), NULL) < LE_11B) {
4850 setenv("EVENT_NOKQUEUE","1",1);
4852 #endif
4854 /* In libevent versions before 2.0, it's hard to keep binary compatibility
4855 * between upgrades, and unpleasant to detect when the version we compiled
4856 * against is unlike the version we have linked against. Here's how. */
4857 #if defined(_EVENT_VERSION) && defined(HAVE_EVENT_GET_VERSION)
4858 /* We have a header-file version and a function-call version. Easy. */
4859 if (strcmp(_EVENT_VERSION, event_get_version())) {
4860 int compat1 = -1, compat2 = -1;
4861 int verybad, prettybad ;
4862 decode_libevent_version(_EVENT_VERSION, &compat1);
4863 decode_libevent_version(event_get_version(), &compat2);
4864 verybad = compat1 != compat2;
4865 prettybad = (compat1 == -1 || compat2 == -1) && compat1 != compat2;
4867 log(verybad ? LOG_WARN : (prettybad ? LOG_NOTICE : LOG_INFO),
4868 LD_GENERAL, "We were compiled with headers from version %s "
4869 "of Libevent, but we're using a Libevent library that says it's "
4870 "version %s.", _EVENT_VERSION, event_get_version());
4871 if (verybad)
4872 log_warn(LD_GENERAL, "This will almost certainly make Tor crash.");
4873 else if (prettybad)
4874 log_notice(LD_GENERAL, "If Tor crashes, this might be why.");
4875 else
4876 log_info(LD_GENERAL, "I think these versions are binary-compatible.");
4878 #elif defined(HAVE_EVENT_GET_VERSION)
4879 /* event_get_version but no _EVENT_VERSION. We might be in 1.4.0-beta or
4880 earlier, where that's normal. To see whether we were compiled with an
4881 earlier version, let's see whether the struct event defines MIN_HEAP_IDX.
4883 #ifdef HAVE_STRUCT_EVENT_MIN_HEAP_IDX
4884 /* The header files are 1.4.0-beta or later. If the version is not
4885 * 1.4.0-beta, we are incompatible. */
4887 if (strcmp(event_get_version(), "1.4.0-beta")) {
4888 log_warn(LD_GENERAL, "It's a little hard to tell, but you seem to have "
4889 "Libevent 1.4.0-beta header files, whereas you have linked "
4890 "against Libevent %s. This will probably make Tor crash.",
4891 event_get_version());
4894 #else
4895 /* Our headers are 1.3e or earlier. If the library version is not 1.4.x or
4896 later, we're probably fine. */
4898 const char *v = event_get_version();
4899 if ((v[0] == '1' && v[2] == '.' && v[3] > '3') || v[0] > '1') {
4900 log_warn(LD_GENERAL, "It's a little hard to tell, but you seem to have "
4901 "Libevent header file from 1.3e or earlier, whereas you have "
4902 "linked against Libevent %s. This will probably make Tor "
4903 "crash.", event_get_version());
4906 #endif
4908 #elif defined(_EVENT_VERSION)
4909 #warn "_EVENT_VERSION is defined but not get_event_version(): Libevent is odd."
4910 #else
4911 /* Your libevent is ancient. */
4912 #endif
4914 event_init();
4915 suppress_libevent_log_msg(NULL);
4916 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4917 /* Making this a NOTICE for now so we can link bugs to a libevent versions
4918 * or methods better. */
4919 log(LOG_NOTICE, LD_GENERAL,
4920 "Initialized libevent version %s using method %s. Good.",
4921 event_get_version(), event_get_method());
4922 check_libevent_version(event_get_method(), get_options()->ORPort != 0);
4923 #else
4924 log(LOG_NOTICE, LD_GENERAL,
4925 "Initialized old libevent (version 1.0b or earlier).");
4926 log(LOG_WARN, LD_GENERAL,
4927 "You have a *VERY* old version of libevent. It is likely to be buggy; "
4928 "please build Tor with a more recent version.");
4929 #endif
4932 /** Table mapping return value of event_get_version() to le_version_t. */
4933 static const struct {
4934 const char *name; le_version_t version; int bincompat;
4935 } le_version_table[] = {
4936 /* earlier versions don't have get_version. */
4937 { "1.0c", LE_10C, 1},
4938 { "1.0d", LE_10D, 1},
4939 { "1.0e", LE_10E, 1},
4940 { "1.1", LE_11, 1 },
4941 { "1.1a", LE_11A, 1 },
4942 { "1.1b", LE_11B, 1 },
4943 { "1.2", LE_12, 1 },
4944 { "1.2a", LE_12A, 1 },
4945 { "1.3", LE_13, 1 },
4946 { "1.3a", LE_13A, 1 },
4947 { "1.3b", LE_13B, 1 },
4948 { "1.3c", LE_13C, 1 },
4949 { "1.3d", LE_13D, 1 },
4950 { "1.3e", LE_13E, 1 },
4951 { "1.4.0-beta", LE_140, 2 },
4952 { "1.4.1-beta", LE_141, 2 },
4953 { "1.4.2-rc", LE_142, 2 },
4954 { "1.4.3-stable", LE_143, 2 },
4955 { "1.4.4-stable", LE_144, 2 },
4956 { "1.4.5-stable", LE_145, 2 },
4957 { "1.4.6-stable", LE_146, 2 },
4958 { "1.4.7-stable", LE_147, 2 },
4959 { "1.4.8-stable", LE_148, 2 },
4960 { "1.4.99-trunk", LE_1499, 3 },
4961 { NULL, LE_OTHER, 0 }
4964 /** Return the le_version_t for the current version of libevent. If the
4965 * version is very new, return LE_OTHER. If the version is so old that it
4966 * doesn't support event_get_version(), return LE_OLD. */
4967 static le_version_t
4968 decode_libevent_version(const char *v, int *bincompat_out)
4970 int i;
4971 for (i=0; le_version_table[i].name; ++i) {
4972 if (!strcmp(le_version_table[i].name, v)) {
4973 if (bincompat_out)
4974 *bincompat_out = le_version_table[i].bincompat;
4975 return le_version_table[i].version;
4978 if (v[0] != '1' && bincompat_out)
4979 *bincompat_out = 100;
4980 else if (!strcmpstart(v, "1.4") && bincompat_out)
4981 *bincompat_out = 2;
4982 return LE_OTHER;
4985 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4987 * Compare the given libevent method and version to a list of versions
4988 * which are known not to work. Warn the user as appropriate.
4990 static void
4991 check_libevent_version(const char *m, int server)
4993 int buggy = 0, iffy = 0, slow = 0, thread_unsafe = 0;
4994 le_version_t version;
4995 const char *v = event_get_version();
4996 const char *badness = NULL;
4997 const char *sad_os = "";
4999 version = decode_libevent_version(v, NULL);
5001 /* XXX Would it be worthwhile disabling the methods that we know
5002 * are buggy, rather than just warning about them and then proceeding
5003 * to use them? If so, we should probably not wrap this whole thing
5004 * in HAVE_EVENT_GET_VERSION and HAVE_EVENT_GET_METHOD. -RD */
5005 /* XXXX The problem is that it's not trivial to get libevent to change it's
5006 * method once it's initialized, and it's not trivial to tell what method it
5007 * will use without initializing it. I guess we could preemptively disable
5008 * buggy libevent modes based on the version _before_ initializing it,
5009 * though, but then there's no good way (afaict) to warn "I would have used
5010 * kqueue, but instead I'm using select." -NM */
5011 if (!strcmp(m, "kqueue")) {
5012 if (version < LE_11B)
5013 buggy = 1;
5014 } else if (!strcmp(m, "epoll")) {
5015 if (version < LE_11)
5016 iffy = 1;
5017 } else if (!strcmp(m, "poll")) {
5018 if (version < LE_10E)
5019 buggy = 1;
5020 else if (version < LE_11)
5021 slow = 1;
5022 } else if (!strcmp(m, "select")) {
5023 if (version < LE_11)
5024 slow = 1;
5025 } else if (!strcmp(m, "win32")) {
5026 if (version < LE_11B)
5027 buggy = 1;
5030 /* Libevent versions before 1.3b do very badly on operating systems with
5031 * user-space threading implementations. */
5032 #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
5033 if (server && version < LE_13B) {
5034 thread_unsafe = 1;
5035 sad_os = "BSD variants";
5037 #elif defined(__APPLE__) || defined(__darwin__)
5038 if (server && version < LE_13B) {
5039 thread_unsafe = 1;
5040 sad_os = "Mac OS X";
5042 #endif
5044 if (thread_unsafe) {
5045 log(LOG_WARN, LD_GENERAL,
5046 "Libevent version %s often crashes when running a Tor server with %s. "
5047 "Please use the latest version of libevent (1.3b or later)",v,sad_os);
5048 badness = "BROKEN";
5049 } else if (buggy) {
5050 log(LOG_WARN, LD_GENERAL,
5051 "There are serious bugs in using %s with libevent %s. "
5052 "Please use the latest version of libevent.", m, v);
5053 badness = "BROKEN";
5054 } else if (iffy) {
5055 log(LOG_WARN, LD_GENERAL,
5056 "There are minor bugs in using %s with libevent %s. "
5057 "You may want to use the latest version of libevent.", m, v);
5058 badness = "BUGGY";
5059 } else if (slow && server) {
5060 log(LOG_WARN, LD_GENERAL,
5061 "libevent %s can be very slow with %s. "
5062 "When running a server, please use the latest version of libevent.",
5063 v,m);
5064 badness = "SLOW";
5066 if (badness) {
5067 control_event_general_status(LOG_WARN,
5068 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
5069 v, m, badness);
5073 #endif
5075 /** Return the persistent state struct for this Tor. */
5076 or_state_t *
5077 get_or_state(void)
5079 tor_assert(global_state);
5080 return global_state;
5083 /** Return a newly allocated string holding a filename relative to the data
5084 * directory. If <b>sub1</b> is present, it is the first path component after
5085 * the data directory. If <b>sub2</b> is also present, it is the second path
5086 * component after the data directory. If <b>suffix</b> is present, it
5087 * is appended to the filename.
5089 * Examples:
5090 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
5091 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
5092 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
5093 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
5095 * Note: Consider using the get_datadir_fname* macros in or.h.
5097 char *
5098 options_get_datadir_fname2_suffix(or_options_t *options,
5099 const char *sub1, const char *sub2,
5100 const char *suffix)
5102 char *fname = NULL;
5103 size_t len;
5104 tor_assert(options);
5105 tor_assert(options->DataDirectory);
5106 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
5107 len = strlen(options->DataDirectory);
5108 if (sub1) {
5109 len += strlen(sub1)+1;
5110 if (sub2)
5111 len += strlen(sub2)+1;
5113 if (suffix)
5114 len += strlen(suffix);
5115 len++;
5116 fname = tor_malloc(len);
5117 if (sub1) {
5118 if (sub2) {
5119 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
5120 options->DataDirectory, sub1, sub2);
5121 } else {
5122 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
5123 options->DataDirectory, sub1);
5125 } else {
5126 strlcpy(fname, options->DataDirectory, len);
5128 if (suffix)
5129 strlcat(fname, suffix, len);
5130 return fname;
5133 /** Return 0 if every setting in <b>state</b> is reasonable, and a
5134 * permissible transition from <b>old_state</b>. Else warn and return -1.
5135 * Should have no side effects, except for normalizing the contents of
5136 * <b>state</b>.
5138 /* XXX from_setconf is here because of bug 238 */
5139 static int
5140 or_state_validate(or_state_t *old_state, or_state_t *state,
5141 int from_setconf, char **msg)
5143 /* We don't use these; only options do. Still, we need to match that
5144 * signature. */
5145 (void) from_setconf;
5146 (void) old_state;
5148 if (entry_guards_parse_state(state, 0, msg)<0)
5149 return -1;
5151 return 0;
5154 /** Replace the current persistent state with <b>new_state</b> */
5155 static void
5156 or_state_set(or_state_t *new_state)
5158 char *err = NULL;
5159 tor_assert(new_state);
5160 if (global_state)
5161 config_free(&state_format, global_state);
5162 global_state = new_state;
5163 if (entry_guards_parse_state(global_state, 1, &err)<0) {
5164 log_warn(LD_GENERAL,"%s",err);
5165 tor_free(err);
5167 if (rep_hist_load_state(global_state, &err)<0) {
5168 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
5169 tor_free(err);
5173 /** Reload the persistent state from disk, generating a new state as needed.
5174 * Return 0 on success, less than 0 on failure.
5176 static int
5177 or_state_load(void)
5179 or_state_t *new_state = NULL;
5180 char *contents = NULL, *fname;
5181 char *errmsg = NULL;
5182 int r = -1, badstate = 0;
5184 fname = get_datadir_fname("state");
5185 switch (file_status(fname)) {
5186 case FN_FILE:
5187 if (!(contents = read_file_to_str(fname, 0, NULL))) {
5188 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
5189 goto done;
5191 break;
5192 case FN_NOENT:
5193 break;
5194 case FN_ERROR:
5195 case FN_DIR:
5196 default:
5197 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
5198 goto done;
5200 new_state = tor_malloc_zero(sizeof(or_state_t));
5201 new_state->_magic = OR_STATE_MAGIC;
5202 config_init(&state_format, new_state);
5203 if (contents) {
5204 config_line_t *lines=NULL;
5205 int assign_retval;
5206 if (config_get_lines(contents, &lines)<0)
5207 goto done;
5208 assign_retval = config_assign(&state_format, new_state,
5209 lines, 0, 0, &errmsg);
5210 config_free_lines(lines);
5211 if (assign_retval<0)
5212 badstate = 1;
5213 if (errmsg) {
5214 log_warn(LD_GENERAL, "%s", errmsg);
5215 tor_free(errmsg);
5219 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
5220 badstate = 1;
5222 if (errmsg) {
5223 log_warn(LD_GENERAL, "%s", errmsg);
5224 tor_free(errmsg);
5227 if (badstate && !contents) {
5228 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
5229 " This is a bug in Tor.");
5230 goto done;
5231 } else if (badstate && contents) {
5232 int i;
5233 file_status_t status;
5234 size_t len = strlen(fname)+16;
5235 char *fname2 = tor_malloc(len);
5236 for (i = 0; i < 100; ++i) {
5237 tor_snprintf(fname2, len, "%s.%d", fname, i);
5238 status = file_status(fname2);
5239 if (status == FN_NOENT)
5240 break;
5242 if (i == 100) {
5243 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
5244 "state files to move aside. Discarding the old state file.",
5245 fname);
5246 unlink(fname);
5247 } else {
5248 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
5249 "to \"%s\". This could be a bug in Tor; please tell "
5250 "the developers.", fname, fname2);
5251 if (rename(fname, fname2) < 0) {
5252 log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
5253 "OS gave an error of %s", strerror(errno));
5256 tor_free(fname2);
5257 tor_free(contents);
5258 config_free(&state_format, new_state);
5260 new_state = tor_malloc_zero(sizeof(or_state_t));
5261 new_state->_magic = OR_STATE_MAGIC;
5262 config_init(&state_format, new_state);
5263 } else if (contents) {
5264 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
5265 } else {
5266 log_info(LD_GENERAL, "Initialized state");
5268 or_state_set(new_state);
5269 new_state = NULL;
5270 if (!contents) {
5271 global_state->next_write = 0;
5272 or_state_save(time(NULL));
5274 r = 0;
5276 done:
5277 tor_free(fname);
5278 tor_free(contents);
5279 if (new_state)
5280 config_free(&state_format, new_state);
5282 return r;
5285 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
5287 or_state_save(time_t now)
5289 char *state, *contents;
5290 char tbuf[ISO_TIME_LEN+1];
5291 size_t len;
5292 char *fname;
5294 tor_assert(global_state);
5296 if (global_state->next_write > now)
5297 return 0;
5299 /* Call everything else that might dirty the state even more, in order
5300 * to avoid redundant writes. */
5301 entry_guards_update_state(global_state);
5302 rep_hist_update_state(global_state);
5303 if (accounting_is_enabled(get_options()))
5304 accounting_run_housekeeping(now);
5306 global_state->LastWritten = time(NULL);
5307 tor_free(global_state->TorVersion);
5308 len = strlen(get_version())+8;
5309 global_state->TorVersion = tor_malloc(len);
5310 tor_snprintf(global_state->TorVersion, len, "Tor %s", get_version());
5312 state = config_dump(&state_format, global_state, 1, 0);
5313 len = strlen(state)+256;
5314 contents = tor_malloc(len);
5315 format_local_iso_time(tbuf, time(NULL));
5316 tor_snprintf(contents, len,
5317 "# Tor state file last generated on %s local time\n"
5318 "# Other times below are in GMT\n"
5319 "# You *do not* need to edit this file.\n\n%s",
5320 tbuf, state);
5321 tor_free(state);
5322 fname = get_datadir_fname("state");
5323 if (write_str_to_file(fname, contents, 0)<0) {
5324 log_warn(LD_FS, "Unable to write state to file \"%s\"", fname);
5325 tor_free(fname);
5326 tor_free(contents);
5327 return -1;
5329 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
5330 tor_free(fname);
5331 tor_free(contents);
5333 global_state->next_write = TIME_MAX;
5334 return 0;
5337 /** Given a file name check to see whether the file exists but has not been
5338 * modified for a very long time. If so, remove it. */
5339 void
5340 remove_file_if_very_old(const char *fname, time_t now)
5342 #define VERY_OLD_FILE_AGE (28*24*60*60)
5343 struct stat st;
5345 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
5346 char buf[ISO_TIME_LEN+1];
5347 format_local_iso_time(buf, st.st_mtime);
5348 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
5349 "Removing it.", fname, buf);
5350 unlink(fname);
5354 /** Helper to implement GETINFO functions about configuration variables (not
5355 * their values). Given a "config/names" question, set *<b>answer</b> to a
5356 * new string describing the supported configuration variables and their
5357 * types. */
5359 getinfo_helper_config(control_connection_t *conn,
5360 const char *question, char **answer)
5362 (void) conn;
5363 if (!strcmp(question, "config/names")) {
5364 smartlist_t *sl = smartlist_create();
5365 int i;
5366 for (i = 0; _option_vars[i].name; ++i) {
5367 config_var_t *var = &_option_vars[i];
5368 const char *type, *desc;
5369 char *line;
5370 size_t len;
5371 desc = config_find_description(&options_format, var->name);
5372 switch (var->type) {
5373 case CONFIG_TYPE_STRING: type = "String"; break;
5374 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
5375 case CONFIG_TYPE_UINT: type = "Integer"; break;
5376 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
5377 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
5378 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
5379 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
5380 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
5381 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
5382 case CONFIG_TYPE_CSV: type = "CommaList"; break;
5383 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
5384 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
5385 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
5386 default:
5387 case CONFIG_TYPE_OBSOLETE:
5388 type = NULL; break;
5390 if (!type)
5391 continue;
5392 len = strlen(var->name)+strlen(type)+16;
5393 if (desc)
5394 len += strlen(desc);
5395 line = tor_malloc(len);
5396 if (desc)
5397 tor_snprintf(line, len, "%s %s %s\n",var->name,type,desc);
5398 else
5399 tor_snprintf(line, len, "%s %s\n",var->name,type);
5400 smartlist_add(sl, line);
5402 *answer = smartlist_join_strings(sl, "", 0, NULL);
5403 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
5404 smartlist_free(sl);
5406 return 0;