Set up urras as the seventh v3 directory authority.
[tor/rransom.git] / src / or / config.c
blob84146c1063ed080c76e79e3534621082c2927e86
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-2009, 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 v1 orport=9001 v3ident=E2A2AF570166665D738736D0DD58169CC61D8A8B "
907 "128.31.0.34:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441",
908 "moria2 v1 orport=9002 128.31.0.34:9032 "
909 "719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF",
910 "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
911 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
912 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
913 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
914 "Tonga orport=443 bridge no-v2 82.94.251.206:80 "
915 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
916 "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
917 "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
918 "gabelmoo orport=443 no-v2 "
919 "v3ident=81349FC1F2DBA2C2C11B45CB9706637D480AB913 "
920 "80.190.246.100:80 6833 3D07 61BC F397 A587 A0C0 B963 E4A9 E99E C4D3",
921 "dannenberg orport=443 no-v2 "
922 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
923 "213.73.91.31:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
924 "urras orport=80 no-v2 v3ident=80550987E1D626E3EBA5E5E75A458DE0626D088C "
925 "208.83.223.34:443 0AD3 FA88 4D18 F89E EA2D 89C0 1937 9E0E 7FD9 4417",
926 NULL
928 for (i=0; dirservers[i]; i++) {
929 if (parse_dir_server_line(dirservers[i], type, 0)<0) {
930 log_err(LD_BUG, "Couldn't parse internal dirserver line %s",
931 dirservers[i]);
936 /** Look at all the config options for using alternate directory
937 * authorities, and make sure none of them are broken. Also, warn the
938 * user if we changed any dangerous ones.
940 static int
941 validate_dir_authorities(or_options_t *options, or_options_t *old_options)
943 config_line_t *cl;
945 if (options->DirServers &&
946 (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
947 options->AlternateHSAuthority)) {
948 log_warn(LD_CONFIG,
949 "You cannot set both DirServers and Alternate*Authority.");
950 return -1;
953 /* do we want to complain to the user about being partitionable? */
954 if ((options->DirServers &&
955 (!old_options ||
956 !config_lines_eq(options->DirServers, old_options->DirServers))) ||
957 (options->AlternateDirAuthority &&
958 (!old_options ||
959 !config_lines_eq(options->AlternateDirAuthority,
960 old_options->AlternateDirAuthority)))) {
961 log_warn(LD_CONFIG,
962 "You have used DirServer or AlternateDirAuthority to "
963 "specify alternate directory authorities in "
964 "your configuration. This is potentially dangerous: it can "
965 "make you look different from all other Tor users, and hurt "
966 "your anonymity. Even if you've specified the same "
967 "authorities as Tor uses by default, the defaults could "
968 "change in the future. Be sure you know what you're doing.");
971 /* Now go through the four ways you can configure an alternate
972 * set of directory authorities, and make sure none are broken. */
973 for (cl = options->DirServers; cl; cl = cl->next)
974 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
975 return -1;
976 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
977 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
978 return -1;
979 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
980 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
981 return -1;
982 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
983 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
984 return -1;
985 return 0;
988 /** Look at all the config options and assign new dir authorities
989 * as appropriate.
991 static int
992 consider_adding_dir_authorities(or_options_t *options,
993 or_options_t *old_options)
995 config_line_t *cl;
996 int need_to_update =
997 !smartlist_len(router_get_trusted_dir_servers()) || !old_options ||
998 !config_lines_eq(options->DirServers, old_options->DirServers) ||
999 !config_lines_eq(options->AlternateBridgeAuthority,
1000 old_options->AlternateBridgeAuthority) ||
1001 !config_lines_eq(options->AlternateDirAuthority,
1002 old_options->AlternateDirAuthority) ||
1003 !config_lines_eq(options->AlternateHSAuthority,
1004 old_options->AlternateHSAuthority);
1006 if (!need_to_update)
1007 return 0; /* all done */
1009 /* Start from a clean slate. */
1010 clear_trusted_dir_servers();
1012 if (!options->DirServers) {
1013 /* then we may want some of the defaults */
1014 authority_type_t type = NO_AUTHORITY;
1015 if (!options->AlternateBridgeAuthority)
1016 type |= BRIDGE_AUTHORITY;
1017 if (!options->AlternateDirAuthority)
1018 type |= V1_AUTHORITY | V2_AUTHORITY | V3_AUTHORITY;
1019 if (!options->AlternateHSAuthority)
1020 type |= HIDSERV_AUTHORITY;
1021 add_default_trusted_dir_authorities(type);
1024 for (cl = options->DirServers; cl; cl = cl->next)
1025 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1026 return -1;
1027 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1028 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1029 return -1;
1030 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1031 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1032 return -1;
1033 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
1034 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1035 return -1;
1036 return 0;
1039 /** Fetch the active option list, and take actions based on it. All of the
1040 * things we do should survive being done repeatedly. If present,
1041 * <b>old_options</b> contains the previous value of the options.
1043 * Return 0 if all goes well, return -1 if things went badly.
1045 static int
1046 options_act_reversible(or_options_t *old_options, char **msg)
1048 smartlist_t *new_listeners = smartlist_create();
1049 smartlist_t *replaced_listeners = smartlist_create();
1050 static int libevent_initialized = 0;
1051 or_options_t *options = get_options();
1052 int running_tor = options->command == CMD_RUN_TOR;
1053 int set_conn_limit = 0;
1054 int r = -1;
1055 int logs_marked = 0;
1057 /* Daemonize _first_, since we only want to open most of this stuff in
1058 * the subprocess. Libevent bases can't be reliably inherited across
1059 * processes. */
1060 if (running_tor && options->RunAsDaemon) {
1061 /* No need to roll back, since you can't change the value. */
1062 start_daemon();
1065 #ifndef HAVE_SYS_UN_H
1066 if (options->ControlSocket) {
1067 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported"
1068 " on this OS/with this build.");
1069 goto rollback;
1071 #endif
1073 if (running_tor) {
1074 /* We need to set the connection limit before we can open the listeners. */
1075 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1076 &options->_ConnLimit) < 0) {
1077 *msg = tor_strdup("Problem with ConnLimit value. See logs for details.");
1078 goto rollback;
1080 set_conn_limit = 1;
1082 /* Set up libevent. (We need to do this before we can register the
1083 * listeners as listeners.) */
1084 if (running_tor && !libevent_initialized) {
1085 init_libevent();
1086 libevent_initialized = 1;
1089 /* Launch the listeners. (We do this before we setuid, so we can bind to
1090 * ports under 1024.) */
1091 if (retry_all_listeners(replaced_listeners, new_listeners) < 0) {
1092 *msg = tor_strdup("Failed to bind one of the listener ports.");
1093 goto rollback;
1097 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1098 /* Open /dev/pf before dropping privileges. */
1099 if (options->TransPort) {
1100 if (get_pf_socket() < 0) {
1101 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1102 goto rollback;
1105 #endif
1107 /* Setuid/setgid as appropriate */
1108 if (options->User) {
1109 if (switch_id(options->User) != 0) {
1110 /* No need to roll back, since you can't change the value. */
1111 *msg = tor_strdup("Problem with User value. See logs for details.");
1112 goto done;
1116 /* Ensure data directory is private; create if possible. */
1117 if (check_private_dir(options->DataDirectory,
1118 running_tor ? CPD_CREATE : CPD_CHECK)<0) {
1119 char buf[1024];
1120 int tmp = tor_snprintf(buf, sizeof(buf),
1121 "Couldn't access/create private data directory \"%s\"",
1122 options->DataDirectory);
1123 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1124 goto done;
1125 /* No need to roll back, since you can't change the value. */
1128 if (directory_caches_v2_dir_info(options)) {
1129 size_t len = strlen(options->DataDirectory)+32;
1130 char *fn = tor_malloc(len);
1131 tor_snprintf(fn, len, "%s"PATH_SEPARATOR"cached-status",
1132 options->DataDirectory);
1133 if (check_private_dir(fn, running_tor ? CPD_CREATE : CPD_CHECK) < 0) {
1134 char buf[1024];
1135 int tmp = tor_snprintf(buf, sizeof(buf),
1136 "Couldn't access/create private data directory \"%s\"", fn);
1137 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1138 tor_free(fn);
1139 goto done;
1141 tor_free(fn);
1144 /* Bail out at this point if we're not going to be a client or server:
1145 * we don't run Tor itself. */
1146 if (!running_tor)
1147 goto commit;
1149 mark_logs_temp(); /* Close current logs once new logs are open. */
1150 logs_marked = 1;
1151 if (options_init_logs(options, 0)<0) { /* Configure the log(s) */
1152 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1153 goto rollback;
1156 commit:
1157 r = 0;
1158 if (logs_marked) {
1159 log_severity_list_t *severity =
1160 tor_malloc_zero(sizeof(log_severity_list_t));
1161 close_temp_logs();
1162 add_callback_log(severity, control_event_logmsg);
1163 control_adjust_event_log_severity();
1164 tor_free(severity);
1166 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1168 log_notice(LD_NET, "Closing old %s on %s:%d",
1169 conn_type_to_string(conn->type), conn->address, conn->port);
1170 connection_close_immediate(conn);
1171 connection_mark_for_close(conn);
1173 goto done;
1175 rollback:
1176 r = -1;
1177 tor_assert(*msg);
1179 if (logs_marked) {
1180 rollback_log_changes();
1181 control_adjust_event_log_severity();
1184 if (set_conn_limit && old_options)
1185 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1186 &options->_ConnLimit);
1188 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1190 log_notice(LD_NET, "Closing partially-constructed listener %s on %s:%d",
1191 conn_type_to_string(conn->type), conn->address, conn->port);
1192 connection_close_immediate(conn);
1193 connection_mark_for_close(conn);
1196 done:
1197 smartlist_free(new_listeners);
1198 smartlist_free(replaced_listeners);
1199 return r;
1202 /** If we need to have a GEOIP ip-to-country map to run with our configured
1203 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1205 options_need_geoip_info(or_options_t *options, const char **reason_out)
1207 int bridge_usage =
1208 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1209 int routerset_usage =
1210 routerset_needs_geoip(options->EntryNodes) ||
1211 routerset_needs_geoip(options->ExitNodes) ||
1212 routerset_needs_geoip(options->ExcludeExitNodes) ||
1213 routerset_needs_geoip(options->ExcludeNodes);
1215 if (routerset_usage && reason_out) {
1216 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1217 "countries, and we need GEOIP information to figure out which ones they "
1218 "are.";
1219 } else if (bridge_usage && reason_out) {
1220 *reason_out = "We've been configured to see which countries can access "
1221 "us as a bridge, and we need GEOIP information to tell which countries "
1222 "clients are in.";
1224 return bridge_usage || routerset_usage;
1227 /** Return the bandwidthrate that we are going to report to the authorities
1228 * based on the config options. */
1229 uint32_t
1230 get_effective_bwrate(or_options_t *options)
1232 uint64_t bw = options->BandwidthRate;
1233 if (bw > options->MaxAdvertisedBandwidth)
1234 bw = options->MaxAdvertisedBandwidth;
1235 if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1236 bw = options->RelayBandwidthRate;
1238 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1239 return (uint32_t)bw;
1242 /** Return the bandwidthburst that we are going to report to the authorities
1243 * based on the config options. */
1244 uint32_t
1245 get_effective_bwburst(or_options_t *options)
1247 uint64_t bw = options->BandwidthBurst;
1248 if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1249 bw = options->RelayBandwidthBurst;
1250 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1251 return (uint32_t)bw;
1254 /** Fetch the active option list, and take actions based on it. All of the
1255 * things we do should survive being done repeatedly. If present,
1256 * <b>old_options</b> contains the previous value of the options.
1258 * Return 0 if all goes well, return -1 if it's time to die.
1260 * Note: We haven't moved all the "act on new configuration" logic
1261 * here yet. Some is still in do_hup() and other places.
1263 static int
1264 options_act(or_options_t *old_options)
1266 config_line_t *cl;
1267 or_options_t *options = get_options();
1268 int running_tor = options->command == CMD_RUN_TOR;
1269 char *msg;
1271 if (running_tor && !have_lockfile()) {
1272 if (try_locking(options, 1) < 0)
1273 return -1;
1276 if (consider_adding_dir_authorities(options, old_options) < 0)
1277 return -1;
1279 if (options->Bridges) {
1280 clear_bridge_list();
1281 for (cl = options->Bridges; cl; cl = cl->next) {
1282 if (parse_bridge_line(cl->value, 0)<0) {
1283 log_warn(LD_BUG,
1284 "Previously validated Bridge line could not be added!");
1285 return -1;
1290 if (running_tor && rend_config_services(options, 0)<0) {
1291 log_warn(LD_BUG,
1292 "Previously validated hidden services line could not be added!");
1293 return -1;
1296 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1297 log_warn(LD_BUG, "Previously validated client authorization for "
1298 "hidden services could not be added!");
1299 return -1;
1302 /* Load state */
1303 if (! global_state && running_tor) {
1304 if (or_state_load())
1305 return -1;
1306 rep_hist_load_mtbf_data(time(NULL));
1309 /* Bail out at this point if we're not going to be a client or server:
1310 * we want to not fork, and to log stuff to stderr. */
1311 if (!running_tor)
1312 return 0;
1314 /* Finish backgrounding the process */
1315 if (running_tor && options->RunAsDaemon) {
1316 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1317 finish_daemon(options->DataDirectory);
1320 /* Write our PID to the PID file. If we do not have write permissions we
1321 * will log a warning */
1322 if (running_tor && options->PidFile)
1323 write_pidfile(options->PidFile);
1325 /* Register addressmap directives */
1326 config_register_addressmaps(options);
1327 parse_virtual_addr_network(options->VirtualAddrNetwork, 0, &msg);
1329 /* Update address policies. */
1330 if (policies_parse_from_options(options) < 0) {
1331 /* This should be impossible, but let's be sure. */
1332 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1333 return -1;
1336 if (init_cookie_authentication(options->CookieAuthentication) < 0) {
1337 log_warn(LD_CONFIG,"Error creating cookie authentication file.");
1338 return -1;
1341 /* reload keys as needed for rendezvous services. */
1342 if (rend_service_load_keys()<0) {
1343 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1344 return -1;
1347 /* Set up accounting */
1348 if (accounting_parse_options(options, 0)<0) {
1349 log_warn(LD_CONFIG,"Error in accounting options");
1350 return -1;
1352 if (accounting_is_enabled(options))
1353 configure_accounting(time(NULL));
1355 /* Check for transitions that need action. */
1356 if (old_options) {
1357 if (options->UseEntryGuards && !old_options->UseEntryGuards) {
1358 log_info(LD_CIRC,
1359 "Switching to entry guards; abandoning previous circuits");
1360 circuit_mark_all_unused_circs();
1361 circuit_expire_all_dirty_circs();
1364 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
1365 log_info(LD_GENERAL, "Bridge status changed. Forgetting GeoIP stats.");
1366 geoip_remove_old_clients(time(NULL)+(2*60*60));
1369 if (options_transition_affects_workers(old_options, options)) {
1370 log_info(LD_GENERAL,
1371 "Worker-related options changed. Rotating workers.");
1372 if (server_mode(options) && !server_mode(old_options)) {
1373 if (init_keys() < 0) {
1374 log_warn(LD_BUG,"Error initializing keys; exiting");
1375 return -1;
1377 ip_address_changed(0);
1378 if (has_completed_circuit || !any_predicted_circuits(time(NULL)))
1379 inform_testing_reachability();
1381 cpuworkers_rotate();
1382 if (dns_reset())
1383 return -1;
1384 } else {
1385 if (dns_reset())
1386 return -1;
1389 if (options->V3AuthoritativeDir && !old_options->V3AuthoritativeDir)
1390 init_keys();
1393 /* Maybe load geoip file */
1394 if (options->GeoIPFile &&
1395 ((!old_options || !opt_streq(old_options->GeoIPFile, options->GeoIPFile))
1396 || !geoip_is_loaded())) {
1397 /* XXXX Don't use this "<default>" junk; make our filename options
1398 * understand prefixes somehow. -NM */
1399 /* XXXX021 Reload GeoIPFile on SIGHUP. -NM */
1400 char *actual_fname = tor_strdup(options->GeoIPFile);
1401 #ifdef WIN32
1402 if (!strcmp(actual_fname, "<default>")) {
1403 const char *conf_root = get_windows_conf_root();
1404 size_t len = strlen(conf_root)+16;
1405 tor_free(actual_fname);
1406 actual_fname = tor_malloc(len+1);
1407 tor_snprintf(actual_fname, len, "%s\\geoip", conf_root);
1409 #endif
1410 geoip_load_file(actual_fname, options);
1411 tor_free(actual_fname);
1413 #ifdef ENABLE_GEOIP_STATS
1414 log_warn(LD_CONFIG, "We are configured to measure GeoIP statistics, but "
1415 "the way these statistics are measured has changed "
1416 "significantly in later versions of Tor. The results may not be "
1417 "as expected if you are used to later versions. Be sure you "
1418 "know what you are doing.");
1419 #endif
1420 /* Check if we need to parse and add the EntryNodes config option. */
1421 if (options->EntryNodes &&
1422 (!old_options ||
1423 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
1424 entry_nodes_should_be_added();
1426 /* Since our options changed, we might need to regenerate and upload our
1427 * server descriptor.
1429 if (!old_options ||
1430 options_transition_affects_descriptor(old_options, options))
1431 mark_my_descriptor_dirty();
1433 /* We may need to reschedule some directory stuff if our status changed. */
1434 if (old_options) {
1435 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1436 dirvote_recalculate_timing(options, time(NULL));
1437 if (!bool_eq(directory_fetches_dir_info_early(options),
1438 directory_fetches_dir_info_early(old_options)) ||
1439 !bool_eq(directory_fetches_dir_info_later(options),
1440 directory_fetches_dir_info_later(old_options))) {
1441 /* Make sure update_router_have_min_dir_info gets called. */
1442 router_dir_info_changed();
1443 /* We might need to download a new consensus status later or sooner than
1444 * we had expected. */
1445 update_consensus_networkstatus_fetch_time(time(NULL));
1449 /* Load the webpage we're going to serve every time someone asks for '/' on
1450 our DirPort. */
1451 tor_free(global_dirfrontpagecontents);
1452 if (options->DirPortFrontPage) {
1453 global_dirfrontpagecontents =
1454 read_file_to_str(options->DirPortFrontPage, 0, NULL);
1455 if (!global_dirfrontpagecontents) {
1456 log_warn(LD_CONFIG,
1457 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1458 options->DirPortFrontPage);
1462 return 0;
1466 * Functions to parse config options
1469 /** If <b>option</b> is an official abbreviation for a longer option,
1470 * return the longer option. Otherwise return <b>option</b>.
1471 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1472 * apply abbreviations that work for the config file and the command line.
1473 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1474 static const char *
1475 expand_abbrev(config_format_t *fmt, const char *option, int command_line,
1476 int warn_obsolete)
1478 int i;
1479 if (! fmt->abbrevs)
1480 return option;
1481 for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
1482 /* Abbreviations are case insensitive. */
1483 if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
1484 (command_line || !fmt->abbrevs[i].commandline_only)) {
1485 if (warn_obsolete && fmt->abbrevs[i].warn) {
1486 log_warn(LD_CONFIG,
1487 "The configuration option '%s' is deprecated; "
1488 "use '%s' instead.",
1489 fmt->abbrevs[i].abbreviated,
1490 fmt->abbrevs[i].full);
1492 return fmt->abbrevs[i].full;
1495 return option;
1498 /** Helper: Read a list of configuration options from the command line.
1499 * If successful, put them in *<b>result</b> and return 0, and return
1500 * -1 and leave *<b>result</b> alone. */
1501 static int
1502 config_get_commandlines(int argc, char **argv, config_line_t **result)
1504 config_line_t *front = NULL;
1505 config_line_t **new = &front;
1506 char *s;
1507 int i = 1;
1509 while (i < argc) {
1510 if (!strcmp(argv[i],"-f") ||
1511 !strcmp(argv[i],"--hash-password")) {
1512 i += 2; /* command-line option with argument. ignore them. */
1513 continue;
1514 } else if (!strcmp(argv[i],"--list-fingerprint") ||
1515 !strcmp(argv[i],"--verify-config") ||
1516 !strcmp(argv[i],"--ignore-missing-torrc") ||
1517 !strcmp(argv[i],"--quiet") ||
1518 !strcmp(argv[i],"--hush")) {
1519 i += 1; /* command-line option. ignore it. */
1520 continue;
1521 } else if (!strcmp(argv[i],"--nt-service") ||
1522 !strcmp(argv[i],"-nt-service")) {
1523 i += 1;
1524 continue;
1527 if (i == argc-1) {
1528 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1529 argv[i]);
1530 config_free_lines(front);
1531 return -1;
1534 *new = tor_malloc_zero(sizeof(config_line_t));
1535 s = argv[i];
1537 while (*s == '-')
1538 s++;
1540 (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1, 1));
1541 (*new)->value = tor_strdup(argv[i+1]);
1542 (*new)->next = NULL;
1543 log(LOG_DEBUG, LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
1544 (*new)->key, (*new)->value);
1546 new = &((*new)->next);
1547 i += 2;
1549 *result = front;
1550 return 0;
1553 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1554 * append it to *<b>lst</b>. */
1555 static void
1556 config_line_append(config_line_t **lst,
1557 const char *key,
1558 const char *val)
1560 config_line_t *newline;
1562 newline = tor_malloc(sizeof(config_line_t));
1563 newline->key = tor_strdup(key);
1564 newline->value = tor_strdup(val);
1565 newline->next = NULL;
1566 while (*lst)
1567 lst = &((*lst)->next);
1569 (*lst) = newline;
1572 /** Helper: parse the config string and strdup into key/value
1573 * strings. Set *result to the list, or NULL if parsing the string
1574 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1575 * misformatted lines. */
1577 config_get_lines(const char *string, config_line_t **result)
1579 config_line_t *list = NULL, **next;
1580 char *k, *v;
1582 next = &list;
1583 do {
1584 k = v = NULL;
1585 string = parse_config_line_from_str(string, &k, &v);
1586 if (!string) {
1587 config_free_lines(list);
1588 tor_free(k);
1589 tor_free(v);
1590 return -1;
1592 if (k && v) {
1593 /* This list can get long, so we keep a pointer to the end of it
1594 * rather than using config_line_append over and over and getting
1595 * n^2 performance. */
1596 *next = tor_malloc(sizeof(config_line_t));
1597 (*next)->key = k;
1598 (*next)->value = v;
1599 (*next)->next = NULL;
1600 next = &((*next)->next);
1601 } else {
1602 tor_free(k);
1603 tor_free(v);
1605 } while (*string);
1607 *result = list;
1608 return 0;
1612 * Free all the configuration lines on the linked list <b>front</b>.
1614 void
1615 config_free_lines(config_line_t *front)
1617 config_line_t *tmp;
1619 while (front) {
1620 tmp = front;
1621 front = tmp->next;
1623 tor_free(tmp->key);
1624 tor_free(tmp->value);
1625 tor_free(tmp);
1629 /** Return the description for a given configuration variable, or NULL if no
1630 * description exists. */
1631 static const char *
1632 config_find_description(config_format_t *fmt, const char *name)
1634 int i;
1635 for (i=0; fmt->descriptions[i].name; ++i) {
1636 if (!strcasecmp(name, fmt->descriptions[i].name))
1637 return fmt->descriptions[i].description;
1639 return NULL;
1642 /** If <b>key</b> is a configuration option, return the corresponding
1643 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1644 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1646 static config_var_t *
1647 config_find_option(config_format_t *fmt, const char *key)
1649 int i;
1650 size_t keylen = strlen(key);
1651 if (!keylen)
1652 return NULL; /* if they say "--" on the command line, it's not an option */
1653 /* First, check for an exact (case-insensitive) match */
1654 for (i=0; fmt->vars[i].name; ++i) {
1655 if (!strcasecmp(key, fmt->vars[i].name)) {
1656 return &fmt->vars[i];
1659 /* If none, check for an abbreviated match */
1660 for (i=0; fmt->vars[i].name; ++i) {
1661 if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
1662 log_warn(LD_CONFIG, "The abbreviation '%s' is deprecated. "
1663 "Please use '%s' instead",
1664 key, fmt->vars[i].name);
1665 return &fmt->vars[i];
1668 /* Okay, unrecognized option */
1669 return NULL;
1673 * Functions to assign config options.
1676 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1677 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1679 * Called from config_assign_line() and option_reset().
1681 static int
1682 config_assign_value(config_format_t *fmt, or_options_t *options,
1683 config_line_t *c, char **msg)
1685 int i, r, ok;
1686 char buf[1024];
1687 config_var_t *var;
1688 void *lvalue;
1690 CHECK(fmt, options);
1692 var = config_find_option(fmt, c->key);
1693 tor_assert(var);
1695 lvalue = STRUCT_VAR_P(options, var->var_offset);
1697 switch (var->type) {
1699 case CONFIG_TYPE_UINT:
1700 i = (int)tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
1701 if (!ok) {
1702 r = tor_snprintf(buf, sizeof(buf),
1703 "Int keyword '%s %s' is malformed or out of bounds.",
1704 c->key, c->value);
1705 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1706 return -1;
1708 *(int *)lvalue = i;
1709 break;
1711 case CONFIG_TYPE_INTERVAL: {
1712 i = config_parse_interval(c->value, &ok);
1713 if (!ok) {
1714 r = tor_snprintf(buf, sizeof(buf),
1715 "Interval '%s %s' is malformed or out of bounds.",
1716 c->key, c->value);
1717 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1718 return -1;
1720 *(int *)lvalue = i;
1721 break;
1724 case CONFIG_TYPE_MEMUNIT: {
1725 uint64_t u64 = config_parse_memunit(c->value, &ok);
1726 if (!ok) {
1727 r = tor_snprintf(buf, sizeof(buf),
1728 "Value '%s %s' is malformed or out of bounds.",
1729 c->key, c->value);
1730 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1731 return -1;
1733 *(uint64_t *)lvalue = u64;
1734 break;
1737 case CONFIG_TYPE_BOOL:
1738 i = (int)tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
1739 if (!ok) {
1740 r = tor_snprintf(buf, sizeof(buf),
1741 "Boolean '%s %s' expects 0 or 1.",
1742 c->key, c->value);
1743 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1744 return -1;
1746 *(int *)lvalue = i;
1747 break;
1749 case CONFIG_TYPE_STRING:
1750 case CONFIG_TYPE_FILENAME:
1751 tor_free(*(char **)lvalue);
1752 *(char **)lvalue = tor_strdup(c->value);
1753 break;
1755 case CONFIG_TYPE_DOUBLE:
1756 *(double *)lvalue = atof(c->value);
1757 break;
1759 case CONFIG_TYPE_ISOTIME:
1760 if (parse_iso_time(c->value, (time_t *)lvalue)) {
1761 r = tor_snprintf(buf, sizeof(buf),
1762 "Invalid time '%s' for keyword '%s'", c->value, c->key);
1763 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1764 return -1;
1766 break;
1768 case CONFIG_TYPE_ROUTERSET:
1769 if (*(routerset_t**)lvalue) {
1770 routerset_free(*(routerset_t**)lvalue);
1772 *(routerset_t**)lvalue = routerset_new();
1773 if (routerset_parse(*(routerset_t**)lvalue, c->value, c->key)<0) {
1774 tor_snprintf(buf, sizeof(buf), "Invalid exit list '%s' for option '%s'",
1775 c->value, c->key);
1776 *msg = tor_strdup(buf);
1777 return -1;
1779 break;
1781 case CONFIG_TYPE_CSV:
1782 if (*(smartlist_t**)lvalue) {
1783 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
1784 smartlist_clear(*(smartlist_t**)lvalue);
1785 } else {
1786 *(smartlist_t**)lvalue = smartlist_create();
1789 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
1790 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1791 break;
1793 case CONFIG_TYPE_LINELIST:
1794 case CONFIG_TYPE_LINELIST_S:
1795 config_line_append((config_line_t**)lvalue, c->key, c->value);
1796 break;
1797 case CONFIG_TYPE_OBSOLETE:
1798 log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
1799 break;
1800 case CONFIG_TYPE_LINELIST_V:
1801 r = tor_snprintf(buf, sizeof(buf),
1802 "You may not provide a value for virtual option '%s'", c->key);
1803 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1804 return -1;
1805 default:
1806 tor_assert(0);
1807 break;
1809 return 0;
1812 /** If <b>c</b> is a syntactically valid configuration line, update
1813 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1814 * key, -2 for bad value.
1816 * If <b>clear_first</b> is set, clear the value first. Then if
1817 * <b>use_defaults</b> is set, set the value to the default.
1819 * Called from config_assign().
1821 static int
1822 config_assign_line(config_format_t *fmt, or_options_t *options,
1823 config_line_t *c, int use_defaults,
1824 int clear_first, char **msg)
1826 config_var_t *var;
1828 CHECK(fmt, options);
1830 var = config_find_option(fmt, c->key);
1831 if (!var) {
1832 if (fmt->extra) {
1833 void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
1834 log_info(LD_CONFIG,
1835 "Found unrecognized option '%s'; saving it.", c->key);
1836 config_line_append((config_line_t**)lvalue, c->key, c->value);
1837 return 0;
1838 } else {
1839 char buf[1024];
1840 int tmp = tor_snprintf(buf, sizeof(buf),
1841 "Unknown option '%s'. Failing.", c->key);
1842 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1843 return -1;
1846 /* Put keyword into canonical case. */
1847 if (strcmp(var->name, c->key)) {
1848 tor_free(c->key);
1849 c->key = tor_strdup(var->name);
1852 if (!strlen(c->value)) {
1853 /* reset or clear it, then return */
1854 if (!clear_first) {
1855 if (var->type == CONFIG_TYPE_LINELIST ||
1856 var->type == CONFIG_TYPE_LINELIST_S) {
1857 /* We got an empty linelist from the torrc or command line.
1858 As a special case, call this an error. Warn and ignore. */
1859 log_warn(LD_CONFIG,
1860 "Linelist option '%s' has no value. Skipping.", c->key);
1861 } else { /* not already cleared */
1862 option_reset(fmt, options, var, use_defaults);
1865 return 0;
1868 if (config_assign_value(fmt, options, c, msg) < 0)
1869 return -2;
1870 return 0;
1873 /** Restore the option named <b>key</b> in options to its default value.
1874 * Called from config_assign(). */
1875 static void
1876 config_reset_line(config_format_t *fmt, or_options_t *options,
1877 const char *key, int use_defaults)
1879 config_var_t *var;
1881 CHECK(fmt, options);
1883 var = config_find_option(fmt, key);
1884 if (!var)
1885 return; /* give error on next pass. */
1887 option_reset(fmt, options, var, use_defaults);
1890 /** Return true iff key is a valid configuration option. */
1892 option_is_recognized(const char *key)
1894 config_var_t *var = config_find_option(&options_format, key);
1895 return (var != NULL);
1898 /** Return the canonical name of a configuration option, or NULL
1899 * if no such option exists. */
1900 const char *
1901 option_get_canonical_name(const char *key)
1903 config_var_t *var = config_find_option(&options_format, key);
1904 return var ? var->name : NULL;
1907 /** Return a canonical list of the options assigned for key.
1909 config_line_t *
1910 option_get_assignment(or_options_t *options, const char *key)
1912 return get_assigned_option(&options_format, options, key, 1);
1915 /** Return true iff value needs to be quoted and escaped to be used in
1916 * a configuration file. */
1917 static int
1918 config_value_needs_escape(const char *value)
1920 if (*value == '\"')
1921 return 1;
1922 while (*value) {
1923 switch (*value)
1925 case '\r':
1926 case '\n':
1927 case '#':
1928 /* Note: quotes and backspaces need special handling when we are using
1929 * quotes, not otherwise, so they don't trigger escaping on their
1930 * own. */
1931 return 1;
1932 default:
1933 if (!TOR_ISPRINT(*value))
1934 return 1;
1936 ++value;
1938 return 0;
1941 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1942 static config_line_t *
1943 config_lines_dup(const config_line_t *inp)
1945 config_line_t *result = NULL;
1946 config_line_t **next_out = &result;
1947 while (inp) {
1948 *next_out = tor_malloc(sizeof(config_line_t));
1949 (*next_out)->key = tor_strdup(inp->key);
1950 (*next_out)->value = tor_strdup(inp->value);
1951 inp = inp->next;
1952 next_out = &((*next_out)->next);
1954 (*next_out) = NULL;
1955 return result;
1958 /** Return newly allocated line or lines corresponding to <b>key</b> in the
1959 * configuration <b>options</b>. If <b>escape_val</b> is true and a
1960 * value needs to be quoted before it's put in a config file, quote and
1961 * escape that value. Return NULL if no such key exists. */
1962 static config_line_t *
1963 get_assigned_option(config_format_t *fmt, void *options,
1964 const char *key, int escape_val)
1966 config_var_t *var;
1967 const void *value;
1968 char buf[32];
1969 config_line_t *result;
1970 tor_assert(options && key);
1972 CHECK(fmt, options);
1974 var = config_find_option(fmt, key);
1975 if (!var) {
1976 log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
1977 return NULL;
1979 value = STRUCT_VAR_P(options, var->var_offset);
1981 result = tor_malloc_zero(sizeof(config_line_t));
1982 result->key = tor_strdup(var->name);
1983 switch (var->type)
1985 case CONFIG_TYPE_STRING:
1986 case CONFIG_TYPE_FILENAME:
1987 if (*(char**)value) {
1988 result->value = tor_strdup(*(char**)value);
1989 } else {
1990 tor_free(result->key);
1991 tor_free(result);
1992 return NULL;
1994 break;
1995 case CONFIG_TYPE_ISOTIME:
1996 if (*(time_t*)value) {
1997 result->value = tor_malloc(ISO_TIME_LEN+1);
1998 format_iso_time(result->value, *(time_t*)value);
1999 } else {
2000 tor_free(result->key);
2001 tor_free(result);
2003 escape_val = 0; /* Can't need escape. */
2004 break;
2005 case CONFIG_TYPE_INTERVAL:
2006 case CONFIG_TYPE_UINT:
2007 /* This means every or_options_t uint or bool element
2008 * needs to be an int. Not, say, a uint16_t or char. */
2009 tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
2010 result->value = tor_strdup(buf);
2011 escape_val = 0; /* Can't need escape. */
2012 break;
2013 case CONFIG_TYPE_MEMUNIT:
2014 tor_snprintf(buf, sizeof(buf), U64_FORMAT,
2015 U64_PRINTF_ARG(*(uint64_t*)value));
2016 result->value = tor_strdup(buf);
2017 escape_val = 0; /* Can't need escape. */
2018 break;
2019 case CONFIG_TYPE_DOUBLE:
2020 tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
2021 result->value = tor_strdup(buf);
2022 escape_val = 0; /* Can't need escape. */
2023 break;
2024 case CONFIG_TYPE_BOOL:
2025 result->value = tor_strdup(*(int*)value ? "1" : "0");
2026 escape_val = 0; /* Can't need escape. */
2027 break;
2028 case CONFIG_TYPE_ROUTERSET:
2029 result->value = routerset_to_string(*(routerset_t**)value);
2030 break;
2031 case CONFIG_TYPE_CSV:
2032 if (*(smartlist_t**)value)
2033 result->value =
2034 smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
2035 else
2036 result->value = tor_strdup("");
2037 break;
2038 case CONFIG_TYPE_OBSOLETE:
2039 log_fn(LOG_PROTOCOL_WARN, LD_CONFIG,
2040 "You asked me for the value of an obsolete config option '%s'.",
2041 key);
2042 tor_free(result->key);
2043 tor_free(result);
2044 return NULL;
2045 case CONFIG_TYPE_LINELIST_S:
2046 log_warn(LD_CONFIG,
2047 "Can't return context-sensitive '%s' on its own", key);
2048 tor_free(result->key);
2049 tor_free(result);
2050 return NULL;
2051 case CONFIG_TYPE_LINELIST:
2052 case CONFIG_TYPE_LINELIST_V:
2053 tor_free(result->key);
2054 tor_free(result);
2055 result = config_lines_dup(*(const config_line_t**)value);
2056 break;
2057 default:
2058 tor_free(result->key);
2059 tor_free(result);
2060 log_warn(LD_BUG,"Unknown type %d for known key '%s'",
2061 var->type, key);
2062 return NULL;
2065 if (escape_val) {
2066 config_line_t *line;
2067 for (line = result; line; line = line->next) {
2068 if (line->value && config_value_needs_escape(line->value)) {
2069 char *newval = esc_for_log(line->value);
2070 tor_free(line->value);
2071 line->value = newval;
2076 return result;
2079 /** Iterate through the linked list of requested options <b>list</b>.
2080 * For each item, convert as appropriate and assign to <b>options</b>.
2081 * If an item is unrecognized, set *msg and return -1 immediately,
2082 * else return 0 for success.
2084 * If <b>clear_first</b>, interpret config options as replacing (not
2085 * extending) their previous values. If <b>clear_first</b> is set,
2086 * then <b>use_defaults</b> to decide if you set to defaults after
2087 * clearing, or make the value 0 or NULL.
2089 * Here are the use cases:
2090 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
2091 * if linelist, replaces current if csv.
2092 * 2. An empty AllowInvalid line in your torrc. Should clear it.
2093 * 3. "RESETCONF AllowInvalid" sets it to default.
2094 * 4. "SETCONF AllowInvalid" makes it NULL.
2095 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
2097 * Use_defaults Clear_first
2098 * 0 0 "append"
2099 * 1 0 undefined, don't use
2100 * 0 1 "set to null first"
2101 * 1 1 "set to defaults first"
2102 * Return 0 on success, -1 on bad key, -2 on bad value.
2104 * As an additional special case, if a LINELIST config option has
2105 * no value and clear_first is 0, then warn and ignore it.
2109 There are three call cases for config_assign() currently.
2111 Case one: Torrc entry
2112 options_init_from_torrc() calls config_assign(0, 0)
2113 calls config_assign_line(0, 0).
2114 if value is empty, calls option_reset(0) and returns.
2115 calls config_assign_value(), appends.
2117 Case two: setconf
2118 options_trial_assign() calls config_assign(0, 1)
2119 calls config_reset_line(0)
2120 calls option_reset(0)
2121 calls option_clear().
2122 calls config_assign_line(0, 1).
2123 if value is empty, returns.
2124 calls config_assign_value(), appends.
2126 Case three: resetconf
2127 options_trial_assign() calls config_assign(1, 1)
2128 calls config_reset_line(1)
2129 calls option_reset(1)
2130 calls option_clear().
2131 calls config_assign_value(default)
2132 calls config_assign_line(1, 1).
2133 returns.
2135 static int
2136 config_assign(config_format_t *fmt, void *options, config_line_t *list,
2137 int use_defaults, int clear_first, char **msg)
2139 config_line_t *p;
2141 CHECK(fmt, options);
2143 /* pass 1: normalize keys */
2144 for (p = list; p; p = p->next) {
2145 const char *full = expand_abbrev(fmt, p->key, 0, 1);
2146 if (strcmp(full,p->key)) {
2147 tor_free(p->key);
2148 p->key = tor_strdup(full);
2152 /* pass 2: if we're reading from a resetting source, clear all
2153 * mentioned config options, and maybe set to their defaults. */
2154 if (clear_first) {
2155 for (p = list; p; p = p->next)
2156 config_reset_line(fmt, options, p->key, use_defaults);
2159 /* pass 3: assign. */
2160 while (list) {
2161 int r;
2162 if ((r=config_assign_line(fmt, options, list, use_defaults,
2163 clear_first, msg)))
2164 return r;
2165 list = list->next;
2167 return 0;
2170 /** Try assigning <b>list</b> to the global options. You do this by duping
2171 * options, assigning list to the new one, then validating it. If it's
2172 * ok, then throw out the old one and stick with the new one. Else,
2173 * revert to old and return failure. Return SETOPT_OK on success, or
2174 * a setopt_err_t on failure.
2176 * If not success, point *<b>msg</b> to a newly allocated string describing
2177 * what went wrong.
2179 setopt_err_t
2180 options_trial_assign(config_line_t *list, int use_defaults,
2181 int clear_first, char **msg)
2183 int r;
2184 or_options_t *trial_options = options_dup(&options_format, get_options());
2186 if ((r=config_assign(&options_format, trial_options,
2187 list, use_defaults, clear_first, msg)) < 0) {
2188 config_free(&options_format, trial_options);
2189 return r;
2192 if (options_validate(get_options(), trial_options, 1, msg) < 0) {
2193 config_free(&options_format, trial_options);
2194 return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2197 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2198 config_free(&options_format, trial_options);
2199 return SETOPT_ERR_TRANSITION;
2202 if (set_options(trial_options, msg)<0) {
2203 config_free(&options_format, trial_options);
2204 return SETOPT_ERR_SETTING;
2207 /* we liked it. put it in place. */
2208 return SETOPT_OK;
2211 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2212 * Called from option_reset() and config_free(). */
2213 static void
2214 option_clear(config_format_t *fmt, or_options_t *options, config_var_t *var)
2216 void *lvalue = STRUCT_VAR_P(options, var->var_offset);
2217 (void)fmt; /* unused */
2218 switch (var->type) {
2219 case CONFIG_TYPE_STRING:
2220 case CONFIG_TYPE_FILENAME:
2221 tor_free(*(char**)lvalue);
2222 break;
2223 case CONFIG_TYPE_DOUBLE:
2224 *(double*)lvalue = 0.0;
2225 break;
2226 case CONFIG_TYPE_ISOTIME:
2227 *(time_t*)lvalue = 0;
2228 case CONFIG_TYPE_INTERVAL:
2229 case CONFIG_TYPE_UINT:
2230 case CONFIG_TYPE_BOOL:
2231 *(int*)lvalue = 0;
2232 break;
2233 case CONFIG_TYPE_MEMUNIT:
2234 *(uint64_t*)lvalue = 0;
2235 break;
2236 case CONFIG_TYPE_ROUTERSET:
2237 if (*(routerset_t**)lvalue) {
2238 routerset_free(*(routerset_t**)lvalue);
2239 *(routerset_t**)lvalue = NULL;
2241 case CONFIG_TYPE_CSV:
2242 if (*(smartlist_t**)lvalue) {
2243 SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
2244 smartlist_free(*(smartlist_t **)lvalue);
2245 *(smartlist_t **)lvalue = NULL;
2247 break;
2248 case CONFIG_TYPE_LINELIST:
2249 case CONFIG_TYPE_LINELIST_S:
2250 config_free_lines(*(config_line_t **)lvalue);
2251 *(config_line_t **)lvalue = NULL;
2252 break;
2253 case CONFIG_TYPE_LINELIST_V:
2254 /* handled by linelist_s. */
2255 break;
2256 case CONFIG_TYPE_OBSOLETE:
2257 break;
2261 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2262 * <b>use_defaults</b>, set it to its default value.
2263 * Called by config_init() and option_reset_line() and option_assign_line(). */
2264 static void
2265 option_reset(config_format_t *fmt, or_options_t *options,
2266 config_var_t *var, int use_defaults)
2268 config_line_t *c;
2269 char *msg = NULL;
2270 CHECK(fmt, options);
2271 option_clear(fmt, options, var); /* clear it first */
2272 if (!use_defaults)
2273 return; /* all done */
2274 if (var->initvalue) {
2275 c = tor_malloc_zero(sizeof(config_line_t));
2276 c->key = tor_strdup(var->name);
2277 c->value = tor_strdup(var->initvalue);
2278 if (config_assign_value(fmt, options, c, &msg) < 0) {
2279 log_warn(LD_BUG, "Failed to assign default: %s", msg);
2280 tor_free(msg); /* if this happens it's a bug */
2282 config_free_lines(c);
2286 /** Print a usage message for tor. */
2287 static void
2288 print_usage(void)
2290 printf(
2291 "Copyright (c) 2001-2004, Roger Dingledine\n"
2292 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2293 "Copyright (c) 2007-2009, The Tor Project, Inc.\n\n"
2294 "tor -f <torrc> [args]\n"
2295 "See man page for options, or https://www.torproject.org/ for "
2296 "documentation.\n");
2299 /** Print all non-obsolete torrc options. */
2300 static void
2301 list_torrc_options(void)
2303 int i;
2304 smartlist_t *lines = smartlist_create();
2305 for (i = 0; _option_vars[i].name; ++i) {
2306 config_var_t *var = &_option_vars[i];
2307 const char *desc;
2308 if (var->type == CONFIG_TYPE_OBSOLETE ||
2309 var->type == CONFIG_TYPE_LINELIST_V)
2310 continue;
2311 desc = config_find_description(&options_format, var->name);
2312 printf("%s\n", var->name);
2313 if (desc) {
2314 wrap_string(lines, desc, 76, " ", " ");
2315 SMARTLIST_FOREACH(lines, char *, cp, {
2316 printf("%s", cp);
2317 tor_free(cp);
2319 smartlist_clear(lines);
2322 smartlist_free(lines);
2325 /** Last value actually set by resolve_my_address. */
2326 static uint32_t last_resolved_addr = 0;
2328 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2329 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2330 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2331 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2332 * public IP address.
2335 resolve_my_address(int warn_severity, or_options_t *options,
2336 uint32_t *addr_out, char **hostname_out)
2338 struct in_addr in;
2339 struct hostent *rent;
2340 char hostname[256];
2341 int explicit_ip=1;
2342 int explicit_hostname=1;
2343 int from_interface=0;
2344 char tmpbuf[INET_NTOA_BUF_LEN];
2345 const char *address = options->Address;
2346 int notice_severity = warn_severity <= LOG_NOTICE ?
2347 LOG_NOTICE : warn_severity;
2349 tor_assert(addr_out);
2351 if (address && *address) {
2352 strlcpy(hostname, address, sizeof(hostname));
2353 } else { /* then we need to guess our address */
2354 explicit_ip = 0; /* it's implicit */
2355 explicit_hostname = 0; /* it's implicit */
2357 if (gethostname(hostname, sizeof(hostname)) < 0) {
2358 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2359 return -1;
2361 log_debug(LD_CONFIG,"Guessed local host name as '%s'",hostname);
2364 /* now we know hostname. resolve it and keep only the IP address */
2366 if (tor_inet_aton(hostname, &in) == 0) {
2367 /* then we have to resolve it */
2368 explicit_ip = 0;
2369 rent = (struct hostent *)gethostbyname(hostname);
2370 if (!rent) {
2371 uint32_t interface_ip;
2373 if (explicit_hostname) {
2374 log_fn(warn_severity, LD_CONFIG,
2375 "Could not resolve local Address '%s'. Failing.", hostname);
2376 return -1;
2378 log_fn(notice_severity, LD_CONFIG,
2379 "Could not resolve guessed local hostname '%s'. "
2380 "Trying something else.", hostname);
2381 if (get_interface_address(warn_severity, &interface_ip)) {
2382 log_fn(warn_severity, LD_CONFIG,
2383 "Could not get local interface IP address. Failing.");
2384 return -1;
2386 from_interface = 1;
2387 in.s_addr = htonl(interface_ip);
2388 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2389 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2390 "local interface. Using that.", tmpbuf);
2391 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2392 } else {
2393 tor_assert(rent->h_length == 4);
2394 memcpy(&in.s_addr, rent->h_addr, rent->h_length);
2396 if (!explicit_hostname &&
2397 is_internal_IP(ntohl(in.s_addr), 0)) {
2398 uint32_t interface_ip;
2400 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2401 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2402 "resolves to a private IP address (%s). Trying something "
2403 "else.", hostname, tmpbuf);
2405 if (get_interface_address(warn_severity, &interface_ip)) {
2406 log_fn(warn_severity, LD_CONFIG,
2407 "Could not get local interface IP address. Too bad.");
2408 } else if (is_internal_IP(interface_ip, 0)) {
2409 struct in_addr in2;
2410 in2.s_addr = htonl(interface_ip);
2411 tor_inet_ntoa(&in2,tmpbuf,sizeof(tmpbuf));
2412 log_fn(notice_severity, LD_CONFIG,
2413 "Interface IP address '%s' is a private address too. "
2414 "Ignoring.", tmpbuf);
2415 } else {
2416 from_interface = 1;
2417 in.s_addr = htonl(interface_ip);
2418 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2419 log_fn(notice_severity, LD_CONFIG,
2420 "Learned IP address '%s' for local interface."
2421 " Using that.", tmpbuf);
2422 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2428 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2429 if (is_internal_IP(ntohl(in.s_addr), 0) &&
2430 options->_PublishServerDescriptor) {
2431 /* make sure we're ok with publishing an internal IP */
2432 if (!options->DirServers && !options->AlternateDirAuthority) {
2433 /* if they are using the default dirservers, disallow internal IPs
2434 * always. */
2435 log_fn(warn_severity, LD_CONFIG,
2436 "Address '%s' resolves to private IP address '%s'. "
2437 "Tor servers that use the default DirServers must have public "
2438 "IP addresses.", hostname, tmpbuf);
2439 return -1;
2441 if (!explicit_ip) {
2442 /* even if they've set their own dirservers, require an explicit IP if
2443 * they're using an internal address. */
2444 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2445 "IP address '%s'. Please set the Address config option to be "
2446 "the IP address you want to use.", hostname, tmpbuf);
2447 return -1;
2451 log_debug(LD_CONFIG, "Resolved Address to '%s'.", tmpbuf);
2452 *addr_out = ntohl(in.s_addr);
2453 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2454 /* Leave this as a notice, regardless of the requested severity,
2455 * at least until dynamic IP address support becomes bulletproof. */
2456 log_notice(LD_NET,
2457 "Your IP address seems to have changed to %s. Updating.",
2458 tmpbuf);
2459 ip_address_changed(0);
2461 if (last_resolved_addr != *addr_out) {
2462 const char *method;
2463 const char *h = hostname;
2464 if (explicit_ip) {
2465 method = "CONFIGURED";
2466 h = NULL;
2467 } else if (explicit_hostname) {
2468 method = "RESOLVED";
2469 } else if (from_interface) {
2470 method = "INTERFACE";
2471 h = NULL;
2472 } else {
2473 method = "GETHOSTNAME";
2475 control_event_server_status(LOG_NOTICE,
2476 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2477 tmpbuf, method, h?"HOSTNAME=":"", h);
2479 last_resolved_addr = *addr_out;
2480 if (hostname_out)
2481 *hostname_out = tor_strdup(hostname);
2482 return 0;
2485 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2486 * on a private network.
2489 is_local_addr(const tor_addr_t *addr)
2491 if (tor_addr_is_internal(addr, 0))
2492 return 1;
2493 /* Check whether ip is on the same /24 as we are. */
2494 if (get_options()->EnforceDistinctSubnets == 0)
2495 return 0;
2496 if (tor_addr_family(addr) == AF_INET) {
2497 /*XXXX022 IP6 what corresponds to an /24? */
2498 uint32_t ip = tor_addr_to_ipv4h(addr);
2500 /* It's possible that this next check will hit before the first time
2501 * resolve_my_address actually succeeds. (For clients, it is likely that
2502 * resolve_my_address will never be called at all). In those cases,
2503 * last_resolved_addr will be 0, and so checking to see whether ip is on
2504 * the same /24 as last_resolved_addr will be the same as checking whether
2505 * it was on net 0, which is already done by is_internal_IP.
2507 if ((last_resolved_addr & 0xffffff00ul) == (ip & 0xffffff00ul))
2508 return 1;
2510 return 0;
2513 /** Called when we don't have a nickname set. Try to guess a good nickname
2514 * based on the hostname, and return it in a newly allocated string. If we
2515 * can't, return NULL and let the caller warn if it wants to. */
2516 static char *
2517 get_default_nickname(void)
2519 static const char * const bad_default_nicknames[] = {
2520 "localhost",
2521 NULL,
2523 char localhostname[256];
2524 char *cp, *out, *outp;
2525 int i;
2527 if (gethostname(localhostname, sizeof(localhostname)) < 0)
2528 return NULL;
2530 /* Put it in lowercase; stop at the first dot. */
2531 if ((cp = strchr(localhostname, '.')))
2532 *cp = '\0';
2533 tor_strlower(localhostname);
2535 /* Strip invalid characters. */
2536 cp = localhostname;
2537 out = outp = tor_malloc(strlen(localhostname) + 1);
2538 while (*cp) {
2539 if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
2540 *outp++ = *cp++;
2541 else
2542 cp++;
2544 *outp = '\0';
2546 /* Enforce length. */
2547 if (strlen(out) > MAX_NICKNAME_LEN)
2548 out[MAX_NICKNAME_LEN]='\0';
2550 /* Check for dumb names. */
2551 for (i = 0; bad_default_nicknames[i]; ++i) {
2552 if (!strcmp(out, bad_default_nicknames[i])) {
2553 tor_free(out);
2554 return NULL;
2558 return out;
2561 /** Release storage held by <b>options</b>. */
2562 static void
2563 config_free(config_format_t *fmt, void *options)
2565 int i;
2567 tor_assert(options);
2569 for (i=0; fmt->vars[i].name; ++i)
2570 option_clear(fmt, options, &(fmt->vars[i]));
2571 if (fmt->extra) {
2572 config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
2573 config_free_lines(*linep);
2574 *linep = NULL;
2576 tor_free(options);
2579 /** Return true iff a and b contain identical keys and values in identical
2580 * order. */
2581 static int
2582 config_lines_eq(config_line_t *a, config_line_t *b)
2584 while (a && b) {
2585 if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
2586 return 0;
2587 a = a->next;
2588 b = b->next;
2590 if (a || b)
2591 return 0;
2592 return 1;
2595 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2596 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2598 static int
2599 option_is_same(config_format_t *fmt,
2600 or_options_t *o1, or_options_t *o2, const char *name)
2602 config_line_t *c1, *c2;
2603 int r = 1;
2604 CHECK(fmt, o1);
2605 CHECK(fmt, o2);
2607 c1 = get_assigned_option(fmt, o1, name, 0);
2608 c2 = get_assigned_option(fmt, o2, name, 0);
2609 r = config_lines_eq(c1, c2);
2610 config_free_lines(c1);
2611 config_free_lines(c2);
2612 return r;
2615 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2616 static or_options_t *
2617 options_dup(config_format_t *fmt, or_options_t *old)
2619 or_options_t *newopts;
2620 int i;
2621 config_line_t *line;
2623 newopts = config_alloc(fmt);
2624 for (i=0; fmt->vars[i].name; ++i) {
2625 if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2626 continue;
2627 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
2628 continue;
2629 line = get_assigned_option(fmt, old, fmt->vars[i].name, 0);
2630 if (line) {
2631 char *msg = NULL;
2632 if (config_assign(fmt, newopts, line, 0, 0, &msg) < 0) {
2633 log_err(LD_BUG, "Config_get_assigned_option() generated "
2634 "something we couldn't config_assign(): %s", msg);
2635 tor_free(msg);
2636 tor_assert(0);
2639 config_free_lines(line);
2641 return newopts;
2644 /** Return a new empty or_options_t. Used for testing. */
2645 or_options_t *
2646 options_new(void)
2648 return config_alloc(&options_format);
2651 /** Set <b>options</b> to hold reasonable defaults for most options.
2652 * Each option defaults to zero. */
2653 void
2654 options_init(or_options_t *options)
2656 config_init(&options_format, options);
2659 /* Check if the port number given in <b>port_option</b> in combination with
2660 * the specified port in <b>listen_options</b> will result in Tor actually
2661 * opening a low port (meaning a port lower than 1024). Return 1 if
2662 * it is, or 0 if it isn't or the concept of a low port isn't applicable for
2663 * the platform we're on. */
2664 static int
2665 is_listening_on_low_port(uint16_t port_option,
2666 const config_line_t *listen_options)
2668 #ifdef MS_WINDOWS
2669 return 0; /* No port is too low for windows. */
2670 #else
2671 const config_line_t *l;
2672 uint16_t p;
2673 if (port_option == 0)
2674 return 0; /* We're not listening */
2675 if (listen_options == NULL)
2676 return (port_option < 1024);
2678 for (l = listen_options; l; l = l->next) {
2679 parse_addr_port(LOG_WARN, l->value, NULL, NULL, &p);
2680 if (p<1024) {
2681 return 1;
2684 return 0;
2685 #endif
2688 /** Set all vars in the configuration object <b>options</b> to their default
2689 * values. */
2690 static void
2691 config_init(config_format_t *fmt, void *options)
2693 int i;
2694 config_var_t *var;
2695 CHECK(fmt, options);
2697 for (i=0; fmt->vars[i].name; ++i) {
2698 var = &fmt->vars[i];
2699 if (!var->initvalue)
2700 continue; /* defaults to NULL or 0 */
2701 option_reset(fmt, options, var, 1);
2705 /** Allocate and return a new string holding the written-out values of the vars
2706 * in 'options'. If 'minimal', do not write out any default-valued vars.
2707 * Else, if comment_defaults, write default values as comments.
2709 static char *
2710 config_dump(config_format_t *fmt, void *options, int minimal,
2711 int comment_defaults)
2713 smartlist_t *elements;
2714 or_options_t *defaults;
2715 config_line_t *line, *assigned;
2716 char *result;
2717 int i;
2718 const char *desc;
2719 char *msg = NULL;
2721 defaults = config_alloc(fmt);
2722 config_init(fmt, defaults);
2724 /* XXX use a 1 here so we don't add a new log line while dumping */
2725 if (fmt->validate_fn(NULL,defaults, 1, &msg) < 0) {
2726 log_err(LD_BUG, "Failed to validate default config.");
2727 tor_free(msg);
2728 tor_assert(0);
2731 elements = smartlist_create();
2732 for (i=0; fmt->vars[i].name; ++i) {
2733 int comment_option = 0;
2734 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
2735 fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2736 continue;
2737 /* Don't save 'hidden' control variables. */
2738 if (!strcmpstart(fmt->vars[i].name, "__"))
2739 continue;
2740 if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
2741 continue;
2742 else if (comment_defaults &&
2743 option_is_same(fmt, options, defaults, fmt->vars[i].name))
2744 comment_option = 1;
2746 desc = config_find_description(fmt, fmt->vars[i].name);
2747 line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name, 1);
2749 if (line && desc) {
2750 /* Only dump the description if there's something to describe. */
2751 wrap_string(elements, desc, 78, "# ", "# ");
2754 for (; line; line = line->next) {
2755 size_t len = strlen(line->key) + strlen(line->value) + 5;
2756 char *tmp;
2757 tmp = tor_malloc(len);
2758 if (tor_snprintf(tmp, len, "%s%s %s\n",
2759 comment_option ? "# " : "",
2760 line->key, line->value)<0) {
2761 log_err(LD_BUG,"Internal error writing option value");
2762 tor_assert(0);
2764 smartlist_add(elements, tmp);
2766 config_free_lines(assigned);
2769 if (fmt->extra) {
2770 line = *(config_line_t**)STRUCT_VAR_P(options, fmt->extra->var_offset);
2771 for (; line; line = line->next) {
2772 size_t len = strlen(line->key) + strlen(line->value) + 3;
2773 char *tmp;
2774 tmp = tor_malloc(len);
2775 if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
2776 log_err(LD_BUG,"Internal error writing option value");
2777 tor_assert(0);
2779 smartlist_add(elements, tmp);
2783 result = smartlist_join_strings(elements, "", 0, NULL);
2784 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2785 smartlist_free(elements);
2786 config_free(fmt, defaults);
2787 return result;
2790 /** Return a string containing a possible configuration file that would give
2791 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2792 * include options that are the same as Tor's defaults.
2794 static char *
2795 options_dump(or_options_t *options, int minimal)
2797 return config_dump(&options_format, options, minimal, 0);
2800 /** Return 0 if every element of sl is a string holding a decimal
2801 * representation of a port number, or if sl is NULL.
2802 * Otherwise set *msg and return -1. */
2803 static int
2804 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2806 int i;
2807 char buf[1024];
2808 tor_assert(name);
2810 if (!sl)
2811 return 0;
2813 SMARTLIST_FOREACH(sl, const char *, cp,
2815 i = atoi(cp);
2816 if (i < 1 || i > 65535) {
2817 int r = tor_snprintf(buf, sizeof(buf),
2818 "Port '%s' out of range in %s", cp, name);
2819 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2820 return -1;
2823 return 0;
2826 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2827 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2828 * Else return 0.
2830 static int
2831 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2833 int r;
2834 char buf[1024];
2835 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2836 /* This handles an understandable special case where somebody says "2gb"
2837 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2838 --*value;
2840 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2841 r = tor_snprintf(buf, sizeof(buf), "%s ("U64_FORMAT") must be at most %d",
2842 desc, U64_PRINTF_ARG(*value),
2843 ROUTER_MAX_DECLARED_BANDWIDTH);
2844 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2845 return -1;
2847 return 0;
2850 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2851 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2852 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2853 * Treat "0" as "".
2854 * Return 0 on success or -1 if not a recognized authority type (in which
2855 * case the value of _PublishServerDescriptor is undefined). */
2856 static int
2857 compute_publishserverdescriptor(or_options_t *options)
2859 smartlist_t *list = options->PublishServerDescriptor;
2860 authority_type_t *auth = &options->_PublishServerDescriptor;
2861 *auth = NO_AUTHORITY;
2862 if (!list) /* empty list, answer is none */
2863 return 0;
2864 SMARTLIST_FOREACH(list, const char *, string, {
2865 if (!strcasecmp(string, "v1"))
2866 *auth |= V1_AUTHORITY;
2867 else if (!strcmp(string, "1"))
2868 if (options->BridgeRelay)
2869 *auth |= BRIDGE_AUTHORITY;
2870 else
2871 *auth |= V2_AUTHORITY | V3_AUTHORITY;
2872 else if (!strcasecmp(string, "v2"))
2873 *auth |= V2_AUTHORITY;
2874 else if (!strcasecmp(string, "v3"))
2875 *auth |= V3_AUTHORITY;
2876 else if (!strcasecmp(string, "bridge"))
2877 *auth |= BRIDGE_AUTHORITY;
2878 else if (!strcasecmp(string, "hidserv"))
2879 *auth |= HIDSERV_AUTHORITY;
2880 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2881 /* no authority */;
2882 else
2883 return -1;
2885 return 0;
2888 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2889 * services can overload the directory system. */
2890 #define MIN_REND_POST_PERIOD (10*60)
2892 /** Highest allowable value for RendPostPeriod. */
2893 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2895 /** Lowest allowable value for CircuitBuildTimeout; values too low will
2896 * increase network load because of failing connections being retried, and
2897 * might prevent users from connecting to the network at all. */
2898 #define MIN_CIRCUIT_BUILD_TIMEOUT 30
2900 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2901 * will generate too many circuits and potentially overload the network. */
2902 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2904 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2905 * permissible transition from <b>old_options</b>. Else return -1.
2906 * Should have no side effects, except for normalizing the contents of
2907 * <b>options</b>.
2909 * On error, tor_strdup an error explanation into *<b>msg</b>.
2911 * XXX
2912 * If <b>from_setconf</b>, we were called by the controller, and our
2913 * Log line should stay empty. If it's 0, then give us a default log
2914 * if there are no logs defined.
2916 static int
2917 options_validate(or_options_t *old_options, or_options_t *options,
2918 int from_setconf, char **msg)
2920 int i, r;
2921 config_line_t *cl;
2922 const char *uname = get_uname();
2923 char buf[1024];
2924 #define REJECT(arg) \
2925 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2926 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2928 tor_assert(msg);
2929 *msg = NULL;
2931 if (options->ORPort < 0 || options->ORPort > 65535)
2932 REJECT("ORPort option out of bounds.");
2934 if (server_mode(options) &&
2935 (!strcmpstart(uname, "Windows 95") ||
2936 !strcmpstart(uname, "Windows 98") ||
2937 !strcmpstart(uname, "Windows Me"))) {
2938 log(LOG_WARN, LD_CONFIG, "Tor is running as a server, but you are "
2939 "running %s; this probably won't work. See "
2940 "http://wiki.noreply.org/noreply/TheOnionRouter/TorFAQ#ServerOS "
2941 "for details.", uname);
2944 if (options->ORPort == 0 && options->ORListenAddress != NULL)
2945 REJECT("ORPort must be defined if ORListenAddress is defined.");
2947 if (options->DirPort == 0 && options->DirListenAddress != NULL)
2948 REJECT("DirPort must be defined if DirListenAddress is defined.");
2950 if (options->DNSPort == 0 && options->DNSListenAddress != NULL)
2951 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
2953 if (options->ControlPort == 0 && options->ControlListenAddress != NULL)
2954 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
2956 if (options->TransPort == 0 && options->TransListenAddress != NULL)
2957 REJECT("TransPort must be defined if TransListenAddress is defined.");
2959 if (options->NatdPort == 0 && options->NatdListenAddress != NULL)
2960 REJECT("NatdPort must be defined if NatdListenAddress is defined.");
2962 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
2963 * configuration does this. */
2965 for (i = 0; i < 3; ++i) {
2966 int is_socks = i==0;
2967 int is_trans = i==1;
2968 config_line_t *line, *opt, *old;
2969 const char *tp;
2970 if (is_socks) {
2971 opt = options->SocksListenAddress;
2972 old = old_options ? old_options->SocksListenAddress : NULL;
2973 tp = "SOCKS proxy";
2974 } else if (is_trans) {
2975 opt = options->TransListenAddress;
2976 old = old_options ? old_options->TransListenAddress : NULL;
2977 tp = "transparent proxy";
2978 } else {
2979 opt = options->NatdListenAddress;
2980 old = old_options ? old_options->NatdListenAddress : NULL;
2981 tp = "natd proxy";
2984 for (line = opt; line; line = line->next) {
2985 char *address = NULL;
2986 uint16_t port;
2987 uint32_t addr;
2988 if (parse_addr_port(LOG_WARN, line->value, &address, &addr, &port)<0)
2989 continue; /* We'll warn about this later. */
2990 if (!is_internal_IP(addr, 1) &&
2991 (!old_options || !config_lines_eq(old, opt))) {
2992 log_warn(LD_CONFIG,
2993 "You specified a public address '%s' for a %s. Other "
2994 "people on the Internet might find your computer and use it as "
2995 "an open %s. Please don't allow this unless you have "
2996 "a good reason.", address, tp, tp);
2998 tor_free(address);
3002 if (validate_data_directory(options)<0)
3003 REJECT("Invalid DataDirectory");
3005 if (options->Nickname == NULL) {
3006 if (server_mode(options)) {
3007 if (!(options->Nickname = get_default_nickname())) {
3008 log_notice(LD_CONFIG, "Couldn't pick a nickname based on "
3009 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME);
3010 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
3011 } else {
3012 log_notice(LD_CONFIG, "Choosing default nickname '%s'",
3013 options->Nickname);
3016 } else {
3017 if (!is_legal_nickname(options->Nickname)) {
3018 r = tor_snprintf(buf, sizeof(buf),
3019 "Nickname '%s' is wrong length or contains illegal characters.",
3020 options->Nickname);
3021 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3022 return -1;
3026 if (server_mode(options) && !options->ContactInfo)
3027 log(LOG_NOTICE, LD_CONFIG, "Your ContactInfo config option is not set. "
3028 "Please consider setting it, so we can contact you if your server is "
3029 "misconfigured or something else goes wrong.");
3031 /* Special case on first boot if no Log options are given. */
3032 if (!options->Logs && !options->RunAsDaemon && !from_setconf)
3033 config_line_append(&options->Logs, "Log", "notice stdout");
3035 if (options_init_logs(options, 1)<0) /* Validate the log(s) */
3036 REJECT("Failed to validate Log options. See logs for details.");
3038 if (options->NoPublish) {
3039 log(LOG_WARN, LD_CONFIG,
3040 "NoPublish is obsolete. Use PublishServerDescriptor instead.");
3041 SMARTLIST_FOREACH(options->PublishServerDescriptor, char *, s,
3042 tor_free(s));
3043 smartlist_clear(options->PublishServerDescriptor);
3046 if (authdir_mode(options)) {
3047 /* confirm that our address isn't broken, so we can complain now */
3048 uint32_t tmp;
3049 if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
3050 REJECT("Failed to resolve/guess local address. See logs for details.");
3053 #ifndef MS_WINDOWS
3054 if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
3055 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
3056 #endif
3058 if (options->SocksPort < 0 || options->SocksPort > 65535)
3059 REJECT("SocksPort option out of bounds.");
3061 if (options->DNSPort < 0 || options->DNSPort > 65535)
3062 REJECT("DNSPort option out of bounds.");
3064 if (options->TransPort < 0 || options->TransPort > 65535)
3065 REJECT("TransPort option out of bounds.");
3067 if (options->NatdPort < 0 || options->NatdPort > 65535)
3068 REJECT("NatdPort option out of bounds.");
3070 if (options->SocksPort == 0 && options->TransPort == 0 &&
3071 options->NatdPort == 0 && options->ORPort == 0 &&
3072 options->DNSPort == 0 && !options->RendConfigLines)
3073 log(LOG_WARN, LD_CONFIG,
3074 "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
3075 "undefined, and there aren't any hidden services configured. "
3076 "Tor will still run, but probably won't do anything.");
3078 if (options->ControlPort < 0 || options->ControlPort > 65535)
3079 REJECT("ControlPort option out of bounds.");
3081 if (options->DirPort < 0 || options->DirPort > 65535)
3082 REJECT("DirPort option out of bounds.");
3084 #ifndef USE_TRANSPARENT
3085 if (options->TransPort || options->TransListenAddress)
3086 REJECT("TransPort and TransListenAddress are disabled in this build.");
3087 #endif
3089 if (options->AccountingMax &&
3090 (is_listening_on_low_port(options->ORPort, options->ORListenAddress) ||
3091 is_listening_on_low_port(options->DirPort, options->DirListenAddress)))
3093 log(LOG_WARN, LD_CONFIG,
3094 "You have set AccountingMax to use hibernation. You have also "
3095 "chosen a low DirPort or OrPort. This combination can make Tor stop "
3096 "working when it tries to re-attach the port after a period of "
3097 "hibernation. Please choose a different port or turn off "
3098 "hibernation unless you know this combination will work on your "
3099 "platform.");
3102 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3103 options->_ExcludeExitNodesUnion = routerset_new();
3104 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeExitNodes);
3105 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeNodes);
3108 if (options->StrictExitNodes &&
3109 (!options->ExitNodes) &&
3110 (!old_options ||
3111 (old_options->StrictExitNodes != options->StrictExitNodes) ||
3112 (!routerset_equal(old_options->ExitNodes,options->ExitNodes))))
3113 COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
3115 if (options->StrictEntryNodes &&
3116 (!options->EntryNodes) &&
3117 (!old_options ||
3118 (old_options->StrictEntryNodes != options->StrictEntryNodes) ||
3119 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
3120 COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
3122 if (options->EntryNodes && !routerset_is_list(options->EntryNodes)) {
3123 /* XXXX fix this; see entry_guards_prepend_from_config(). */
3124 REJECT("IPs or countries are not yet supported in EntryNodes.");
3127 if (options->AuthoritativeDir) {
3128 if (!options->ContactInfo && !options->TestingTorNetwork)
3129 REJECT("Authoritative directory servers must set ContactInfo");
3130 if (options->V1AuthoritativeDir && !options->RecommendedVersions)
3131 REJECT("V1 authoritative dir servers must set RecommendedVersions.");
3132 if (!options->RecommendedClientVersions)
3133 options->RecommendedClientVersions =
3134 config_lines_dup(options->RecommendedVersions);
3135 if (!options->RecommendedServerVersions)
3136 options->RecommendedServerVersions =
3137 config_lines_dup(options->RecommendedVersions);
3138 if (options->VersioningAuthoritativeDir &&
3139 (!options->RecommendedClientVersions ||
3140 !options->RecommendedServerVersions))
3141 REJECT("Versioning authoritative dir servers must set "
3142 "Recommended*Versions.");
3143 if (options->UseEntryGuards) {
3144 log_info(LD_CONFIG, "Authoritative directory servers can't set "
3145 "UseEntryGuards. Disabling.");
3146 options->UseEntryGuards = 0;
3148 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
3149 log_info(LD_CONFIG, "Authoritative directories always try to download "
3150 "extra-info documents. Setting DownloadExtraInfo.");
3151 options->DownloadExtraInfo = 1;
3153 if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
3154 options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
3155 options->V3AuthoritativeDir))
3156 REJECT("AuthoritativeDir is set, but none of "
3157 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
3160 if (options->AuthoritativeDir && !options->DirPort)
3161 REJECT("Running as authoritative directory, but no DirPort set.");
3163 if (options->AuthoritativeDir && !options->ORPort)
3164 REJECT("Running as authoritative directory, but no ORPort set.");
3166 if (options->AuthoritativeDir && options->ClientOnly)
3167 REJECT("Running as authoritative directory, but ClientOnly also set.");
3169 if (options->HSAuthorityRecordStats && !options->HSAuthoritativeDir)
3170 REJECT("HSAuthorityRecordStats is set but we're not running as "
3171 "a hidden service authority.");
3173 if (options->ConnLimit <= 0) {
3174 r = tor_snprintf(buf, sizeof(buf),
3175 "ConnLimit must be greater than 0, but was set to %d",
3176 options->ConnLimit);
3177 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3178 return -1;
3181 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3182 return -1;
3184 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3185 return -1;
3187 if (validate_ports_csv(options->RejectPlaintextPorts,
3188 "RejectPlaintextPorts", msg) < 0)
3189 return -1;
3191 if (validate_ports_csv(options->WarnPlaintextPorts,
3192 "WarnPlaintextPorts", msg) < 0)
3193 return -1;
3195 if (options->FascistFirewall && !options->ReachableAddresses) {
3196 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3197 /* We already have firewall ports set, so migrate them to
3198 * ReachableAddresses, which will set ReachableORAddresses and
3199 * ReachableDirAddresses if they aren't set explicitly. */
3200 smartlist_t *instead = smartlist_create();
3201 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3202 new_line->key = tor_strdup("ReachableAddresses");
3203 /* If we're configured with the old format, we need to prepend some
3204 * open ports. */
3205 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3207 int p = atoi(portno);
3208 char *s;
3209 if (p<0) continue;
3210 s = tor_malloc(16);
3211 tor_snprintf(s, 16, "*:%d", p);
3212 smartlist_add(instead, s);
3214 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3215 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3216 log(LOG_NOTICE, LD_CONFIG,
3217 "Converting FascistFirewall and FirewallPorts "
3218 "config options to new format: \"ReachableAddresses %s\"",
3219 new_line->value);
3220 options->ReachableAddresses = new_line;
3221 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3222 smartlist_free(instead);
3223 } else {
3224 /* We do not have FirewallPorts set, so add 80 to
3225 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3226 if (!options->ReachableDirAddresses) {
3227 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3228 new_line->key = tor_strdup("ReachableDirAddresses");
3229 new_line->value = tor_strdup("*:80");
3230 options->ReachableDirAddresses = new_line;
3231 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3232 "to new format: \"ReachableDirAddresses *:80\"");
3234 if (!options->ReachableORAddresses) {
3235 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3236 new_line->key = tor_strdup("ReachableORAddresses");
3237 new_line->value = tor_strdup("*:443");
3238 options->ReachableORAddresses = new_line;
3239 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3240 "to new format: \"ReachableORAddresses *:443\"");
3245 for (i=0; i<3; i++) {
3246 config_line_t **linep =
3247 (i==0) ? &options->ReachableAddresses :
3248 (i==1) ? &options->ReachableORAddresses :
3249 &options->ReachableDirAddresses;
3250 if (!*linep)
3251 continue;
3252 /* We need to end with a reject *:*, not an implicit accept *:* */
3253 for (;;) {
3254 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
3255 break;
3256 linep = &((*linep)->next);
3257 if (!*linep) {
3258 *linep = tor_malloc_zero(sizeof(config_line_t));
3259 (*linep)->key = tor_strdup(
3260 (i==0) ? "ReachableAddresses" :
3261 (i==1) ? "ReachableORAddresses" :
3262 "ReachableDirAddresses");
3263 (*linep)->value = tor_strdup("reject *:*");
3264 break;
3269 if ((options->ReachableAddresses ||
3270 options->ReachableORAddresses ||
3271 options->ReachableDirAddresses) &&
3272 server_mode(options))
3273 REJECT("Servers must be able to freely connect to the rest "
3274 "of the Internet, so they must not set Reachable*Addresses "
3275 "or FascistFirewall.");
3277 if (options->UseBridges &&
3278 server_mode(options))
3279 REJECT("Servers must be able to freely connect to the rest "
3280 "of the Internet, so they must not set UseBridges.");
3282 options->_AllowInvalid = 0;
3283 if (options->AllowInvalidNodes) {
3284 SMARTLIST_FOREACH(options->AllowInvalidNodes, const char *, cp, {
3285 if (!strcasecmp(cp, "entry"))
3286 options->_AllowInvalid |= ALLOW_INVALID_ENTRY;
3287 else if (!strcasecmp(cp, "exit"))
3288 options->_AllowInvalid |= ALLOW_INVALID_EXIT;
3289 else if (!strcasecmp(cp, "middle"))
3290 options->_AllowInvalid |= ALLOW_INVALID_MIDDLE;
3291 else if (!strcasecmp(cp, "introduction"))
3292 options->_AllowInvalid |= ALLOW_INVALID_INTRODUCTION;
3293 else if (!strcasecmp(cp, "rendezvous"))
3294 options->_AllowInvalid |= ALLOW_INVALID_RENDEZVOUS;
3295 else {
3296 r = tor_snprintf(buf, sizeof(buf),
3297 "Unrecognized value '%s' in AllowInvalidNodes", cp);
3298 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3299 return -1;
3304 if (compute_publishserverdescriptor(options) < 0) {
3305 r = tor_snprintf(buf, sizeof(buf),
3306 "Unrecognized value in PublishServerDescriptor");
3307 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3308 return -1;
3311 if ((options->BridgeRelay
3312 || options->_PublishServerDescriptor & BRIDGE_AUTHORITY)
3313 && (options->_PublishServerDescriptor
3314 & (V1_AUTHORITY|V2_AUTHORITY|V3_AUTHORITY))) {
3315 REJECT("Bridges are not supposed to publish router descriptors to the "
3316 "directory authorities. Please correct your "
3317 "PublishServerDescriptor line.");
3320 if (options->MinUptimeHidServDirectoryV2 < 0) {
3321 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3322 "least 0 seconds. Changing to 0.");
3323 options->MinUptimeHidServDirectoryV2 = 0;
3326 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
3327 log(LOG_WARN,LD_CONFIG,"RendPostPeriod option is too short; "
3328 "raising to %d seconds.", MIN_REND_POST_PERIOD);
3329 options->RendPostPeriod = MIN_REND_POST_PERIOD;
3332 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3333 log(LOG_WARN, LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3334 MAX_DIR_PERIOD);
3335 options->RendPostPeriod = MAX_DIR_PERIOD;
3338 if (options->CircuitBuildTimeout < MIN_CIRCUIT_BUILD_TIMEOUT) {
3339 log(LOG_WARN, LD_CONFIG, "CircuitBuildTimeout option is too short; "
3340 "raising to %d seconds.", MIN_CIRCUIT_BUILD_TIMEOUT);
3341 options->CircuitBuildTimeout = MIN_CIRCUIT_BUILD_TIMEOUT;
3344 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3345 log(LOG_WARN, LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3346 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3347 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3350 if (options->KeepalivePeriod < 1)
3351 REJECT("KeepalivePeriod option must be positive.");
3353 if (ensure_bandwidth_cap(&options->BandwidthRate,
3354 "BandwidthRate", msg) < 0)
3355 return -1;
3356 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3357 "BandwidthBurst", msg) < 0)
3358 return -1;
3359 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3360 "MaxAdvertisedBandwidth", msg) < 0)
3361 return -1;
3362 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3363 "RelayBandwidthRate", msg) < 0)
3364 return -1;
3365 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3366 "RelayBandwidthBurst", msg) < 0)
3367 return -1;
3369 if (server_mode(options)) {
3370 if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3371 r = tor_snprintf(buf, sizeof(buf),
3372 "BandwidthRate is set to %d bytes/second. "
3373 "For servers, it must be at least %d.",
3374 (int)options->BandwidthRate,
3375 ROUTER_REQUIRED_MIN_BANDWIDTH);
3376 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3377 return -1;
3378 } else if (options->MaxAdvertisedBandwidth <
3379 ROUTER_REQUIRED_MIN_BANDWIDTH/2) {
3380 r = tor_snprintf(buf, sizeof(buf),
3381 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3382 "For servers, it must be at least %d.",
3383 (int)options->MaxAdvertisedBandwidth,
3384 ROUTER_REQUIRED_MIN_BANDWIDTH/2);
3385 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3386 return -1;
3388 if (options->RelayBandwidthRate &&
3389 options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3390 r = tor_snprintf(buf, sizeof(buf),
3391 "RelayBandwidthRate is set to %d bytes/second. "
3392 "For servers, it must be at least %d.",
3393 (int)options->RelayBandwidthRate,
3394 ROUTER_REQUIRED_MIN_BANDWIDTH);
3395 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3396 return -1;
3400 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3401 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3403 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3404 REJECT("RelayBandwidthBurst must be at least equal "
3405 "to RelayBandwidthRate.");
3407 if (options->BandwidthRate > options->BandwidthBurst)
3408 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3410 /* if they set relaybandwidth* really high but left bandwidth*
3411 * at the default, raise the defaults. */
3412 if (options->RelayBandwidthRate > options->BandwidthRate)
3413 options->BandwidthRate = options->RelayBandwidthRate;
3414 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3415 options->BandwidthBurst = options->RelayBandwidthBurst;
3417 if (accounting_parse_options(options, 1)<0)
3418 REJECT("Failed to parse accounting options. See logs for details.");
3420 if (options->HttpProxy) { /* parse it now */
3421 if (parse_addr_port(LOG_WARN, options->HttpProxy, NULL,
3422 &options->HttpProxyAddr, &options->HttpProxyPort) < 0)
3423 REJECT("HttpProxy failed to parse or resolve. Please fix.");
3424 if (options->HttpProxyPort == 0) { /* give it a default */
3425 options->HttpProxyPort = 80;
3429 if (options->HttpProxyAuthenticator) {
3430 if (strlen(options->HttpProxyAuthenticator) >= 48)
3431 REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
3434 if (options->HttpsProxy) { /* parse it now */
3435 if (parse_addr_port(LOG_WARN, options->HttpsProxy, NULL,
3436 &options->HttpsProxyAddr, &options->HttpsProxyPort) <0)
3437 REJECT("HttpsProxy failed to parse or resolve. Please fix.");
3438 if (options->HttpsProxyPort == 0) { /* give it a default */
3439 options->HttpsProxyPort = 443;
3443 if (options->HttpsProxyAuthenticator) {
3444 if (strlen(options->HttpsProxyAuthenticator) >= 48)
3445 REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
3448 if (options->HashedControlPassword) {
3449 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3450 if (!sl) {
3451 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3452 } else {
3453 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3454 smartlist_free(sl);
3458 if (options->HashedControlSessionPassword) {
3459 smartlist_t *sl = decode_hashed_passwords(
3460 options->HashedControlSessionPassword);
3461 if (!sl) {
3462 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3463 } else {
3464 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3465 smartlist_free(sl);
3469 if (options->ControlListenAddress) {
3470 int all_are_local = 1;
3471 config_line_t *ln;
3472 for (ln = options->ControlListenAddress; ln; ln = ln->next) {
3473 if (strcmpstart(ln->value, "127."))
3474 all_are_local = 0;
3476 if (!all_are_local) {
3477 if (!options->HashedControlPassword &&
3478 !options->HashedControlSessionPassword &&
3479 !options->CookieAuthentication) {
3480 log_warn(LD_CONFIG,
3481 "You have a ControlListenAddress set to accept "
3482 "unauthenticated connections from a non-local address. "
3483 "This means that programs not running on your computer "
3484 "can reconfigure your Tor, without even having to guess a "
3485 "password. That's so bad that I'm closing your ControlPort "
3486 "for you. If you need to control your Tor remotely, try "
3487 "enabling authentication and using a tool like stunnel or "
3488 "ssh to encrypt remote access.");
3489 options->ControlPort = 0;
3490 } else {
3491 log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
3492 "connections from a non-local address. This means that "
3493 "programs not running on your computer can reconfigure your "
3494 "Tor. That's pretty bad, since the controller "
3495 "protocol isn't encrypted! Maybe you should just listen on "
3496 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
3497 "remote connections to your control port.");
3502 if (options->ControlPort && !options->HashedControlPassword &&
3503 !options->HashedControlSessionPassword &&
3504 !options->CookieAuthentication) {
3505 log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
3506 "has been configured. This means that any program on your "
3507 "computer can reconfigure your Tor. That's bad! You should "
3508 "upgrade your Tor controller as soon as possible.");
3511 if (options->UseEntryGuards && ! options->NumEntryGuards)
3512 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3514 if (check_nickname_list(options->MyFamily, "MyFamily", msg))
3515 return -1;
3516 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3517 if (check_nickname_list(cl->value, "NodeFamily", msg))
3518 return -1;
3521 if (validate_addr_policies(options, msg) < 0)
3522 return -1;
3524 if (validate_dir_authorities(options, old_options) < 0)
3525 REJECT("Directory authority line did not parse. See logs for details.");
3527 if (options->UseBridges && !options->Bridges)
3528 REJECT("If you set UseBridges, you must specify at least one bridge.");
3529 if (options->UseBridges && !options->TunnelDirConns)
3530 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3531 if (options->Bridges) {
3532 for (cl = options->Bridges; cl; cl = cl->next) {
3533 if (parse_bridge_line(cl->value, 1)<0)
3534 REJECT("Bridge line did not parse. See logs for details.");
3538 if (options->ConstrainedSockets) {
3539 /* If the user wants to constrain socket buffer use, make sure the desired
3540 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3541 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3542 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3543 options->ConstrainedSockSize % 1024) {
3544 r = tor_snprintf(buf, sizeof(buf),
3545 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3546 "in 1024 byte increments.",
3547 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3548 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3549 return -1;
3551 if (options->DirPort) {
3552 /* Providing cached directory entries while system TCP buffers are scarce
3553 * will exacerbate the socket errors. Suggest that this be disabled. */
3554 COMPLAIN("You have requested constrained socket buffers while also "
3555 "serving directory entries via DirPort. It is strongly "
3556 "suggested that you disable serving directory requests when "
3557 "system TCP buffer resources are scarce.");
3561 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3562 options->V3AuthVotingInterval/2) {
3563 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3564 "V3AuthVotingInterval");
3566 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
3567 REJECT("V3AuthVoteDelay is way too low.");
3568 if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
3569 REJECT("V3AuthDistDelay is way too low.");
3571 if (options->V3AuthNIntervalsValid < 2)
3572 REJECT("V3AuthNIntervalsValid must be at least 2.");
3574 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3575 REJECT("V3AuthVotingInterval is insanely low.");
3576 } else if (options->V3AuthVotingInterval > 24*60*60) {
3577 REJECT("V3AuthVotingInterval is insanely high.");
3578 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3579 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3582 if (rend_config_services(options, 1) < 0)
3583 REJECT("Failed to configure rendezvous options. See logs for details.");
3585 /* Parse client-side authorization for hidden services. */
3586 if (rend_parse_service_authorization(options, 1) < 0)
3587 REJECT("Failed to configure client authorization for hidden services. "
3588 "See logs for details.");
3590 if (parse_virtual_addr_network(options->VirtualAddrNetwork, 1, NULL)<0)
3591 return -1;
3593 if (options->PreferTunneledDirConns && !options->TunnelDirConns)
3594 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3596 if (options->AutomapHostsSuffixes) {
3597 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
3599 size_t len = strlen(suf);
3600 if (len && suf[len-1] == '.')
3601 suf[len-1] = '\0';
3605 if (options->TestingTorNetwork && !options->DirServers) {
3606 REJECT("TestingTorNetwork may only be configured in combination with "
3607 "a non-default set of DirServers.");
3610 /*XXXX022 checking for defaults manually like this is a bit fragile.*/
3612 /* Keep changes to hard-coded values synchronous to man page and default
3613 * values table. */
3614 if (options->TestingV3AuthInitialVotingInterval != 30*60 &&
3615 !options->TestingTorNetwork) {
3616 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
3617 "Tor networks!");
3618 } else if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
3619 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3620 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
3621 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3622 "30 minutes.");
3625 if (options->TestingV3AuthInitialVoteDelay != 5*60 &&
3626 !options->TestingTorNetwork) {
3627 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
3628 "Tor networks!");
3629 } else if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
3630 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3633 if (options->TestingV3AuthInitialDistDelay != 5*60 &&
3634 !options->TestingTorNetwork) {
3635 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
3636 "Tor networks!");
3637 } else if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
3638 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3641 if (options->TestingV3AuthInitialVoteDelay +
3642 options->TestingV3AuthInitialDistDelay >=
3643 options->TestingV3AuthInitialVotingInterval/2) {
3644 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3645 "must be less than half TestingV3AuthInitialVotingInterval");
3648 if (options->TestingAuthDirTimeToLearnReachability != 30*60 &&
3649 !options->TestingTorNetwork) {
3650 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
3651 "testing Tor networks!");
3652 } else if (options->TestingAuthDirTimeToLearnReachability < 0) {
3653 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3654 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
3655 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3658 if (options->TestingEstimatedDescriptorPropagationTime != 10*60 &&
3659 !options->TestingTorNetwork) {
3660 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
3661 "testing Tor networks!");
3662 } else if (options->TestingEstimatedDescriptorPropagationTime < 0) {
3663 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3664 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
3665 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3668 if (options->TestingTorNetwork) {
3669 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
3670 "almost unusable in the public Tor network, and is "
3671 "therefore only advised if you are building a "
3672 "testing Tor network!");
3675 return 0;
3676 #undef REJECT
3677 #undef COMPLAIN
3680 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3681 * equal strings. */
3682 static int
3683 opt_streq(const char *s1, const char *s2)
3685 if (!s1 && !s2)
3686 return 1;
3687 else if (s1 && s2 && !strcmp(s1,s2))
3688 return 1;
3689 else
3690 return 0;
3693 /** Check if any of the previous options have changed but aren't allowed to. */
3694 static int
3695 options_transition_allowed(or_options_t *old, or_options_t *new_val,
3696 char **msg)
3698 if (!old)
3699 return 0;
3701 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3702 *msg = tor_strdup("PidFile is not allowed to change.");
3703 return -1;
3706 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3707 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3708 "is not allowed.");
3709 return -1;
3712 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
3713 char buf[1024];
3714 int r = tor_snprintf(buf, sizeof(buf),
3715 "While Tor is running, changing DataDirectory "
3716 "(\"%s\"->\"%s\") is not allowed.",
3717 old->DataDirectory, new_val->DataDirectory);
3718 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3719 return -1;
3722 if (!opt_streq(old->User, new_val->User)) {
3723 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
3724 return -1;
3727 if (!opt_streq(old->Group, new_val->Group)) {
3728 *msg = tor_strdup("While Tor is running, changing Group is not allowed.");
3729 return -1;
3732 if (old->HardwareAccel != new_val->HardwareAccel) {
3733 *msg = tor_strdup("While Tor is running, changing HardwareAccel is "
3734 "not allowed.");
3735 return -1;
3738 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
3739 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
3740 "is not allowed.");
3741 return -1;
3744 return 0;
3747 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3748 * will require us to rotate the CPU and DNS workers; else return 0. */
3749 static int
3750 options_transition_affects_workers(or_options_t *old_options,
3751 or_options_t *new_options)
3753 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3754 old_options->NumCpus != new_options->NumCpus ||
3755 old_options->ORPort != new_options->ORPort ||
3756 old_options->ServerDNSSearchDomains !=
3757 new_options->ServerDNSSearchDomains ||
3758 old_options->SafeLogging != new_options->SafeLogging ||
3759 old_options->ClientOnly != new_options->ClientOnly ||
3760 !config_lines_eq(old_options->Logs, new_options->Logs))
3761 return 1;
3763 /* Check whether log options match. */
3765 /* Nothing that changed matters. */
3766 return 0;
3769 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3770 * will require us to generate a new descriptor; else return 0. */
3771 static int
3772 options_transition_affects_descriptor(or_options_t *old_options,
3773 or_options_t *new_options)
3775 /* XXX We can be smarter here. If your DirPort isn't being
3776 * published and you just turned it off, no need to republish. Etc. */
3777 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3778 !opt_streq(old_options->Nickname,new_options->Nickname) ||
3779 !opt_streq(old_options->Address,new_options->Address) ||
3780 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
3781 old_options->ExitPolicyRejectPrivate !=
3782 new_options->ExitPolicyRejectPrivate ||
3783 old_options->ORPort != new_options->ORPort ||
3784 old_options->DirPort != new_options->DirPort ||
3785 old_options->ClientOnly != new_options->ClientOnly ||
3786 old_options->NoPublish != new_options->NoPublish ||
3787 old_options->_PublishServerDescriptor !=
3788 new_options->_PublishServerDescriptor ||
3789 get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
3790 get_effective_bwburst(old_options) !=
3791 get_effective_bwburst(new_options) ||
3792 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
3793 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
3794 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
3795 old_options->AccountingMax != new_options->AccountingMax)
3796 return 1;
3798 return 0;
3801 #ifdef MS_WINDOWS
3802 /** Return the directory on windows where we expect to find our application
3803 * data. */
3804 static char *
3805 get_windows_conf_root(void)
3807 static int is_set = 0;
3808 static char path[MAX_PATH+1];
3810 LPITEMIDLIST idl;
3811 IMalloc *m;
3812 HRESULT result;
3814 if (is_set)
3815 return path;
3817 /* Find X:\documents and settings\username\application data\ .
3818 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3820 #ifdef ENABLE_LOCAL_APPDATA
3821 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
3822 #else
3823 #define APPDATA_PATH CSIDL_APPDATA
3824 #endif
3825 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
3826 GetCurrentDirectory(MAX_PATH, path);
3827 is_set = 1;
3828 log_warn(LD_CONFIG,
3829 "I couldn't find your application data folder: are you "
3830 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3831 path);
3832 return path;
3834 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3835 result = SHGetPathFromIDList(idl, path);
3836 /* Now we need to free the */
3837 SHGetMalloc(&m);
3838 if (m) {
3839 m->lpVtbl->Free(m, idl);
3840 m->lpVtbl->Release(m);
3842 if (!SUCCEEDED(result)) {
3843 return NULL;
3845 strlcat(path,"\\tor",MAX_PATH);
3846 is_set = 1;
3847 return path;
3849 #endif
3851 /** Return the default location for our torrc file. */
3852 static const char *
3853 get_default_conf_file(void)
3855 #ifdef MS_WINDOWS
3856 static char path[MAX_PATH+1];
3857 strlcpy(path, get_windows_conf_root(), MAX_PATH);
3858 strlcat(path,"\\torrc",MAX_PATH);
3859 return path;
3860 #else
3861 return (CONFDIR "/torrc");
3862 #endif
3865 /** Verify whether lst is a string containing valid-looking comma-separated
3866 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3868 static int
3869 check_nickname_list(const char *lst, const char *name, char **msg)
3871 int r = 0;
3872 smartlist_t *sl;
3874 if (!lst)
3875 return 0;
3876 sl = smartlist_create();
3878 smartlist_split_string(sl, lst, ",",
3879 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
3881 SMARTLIST_FOREACH(sl, const char *, s,
3883 if (!is_legal_nickname_or_hexdigest(s)) {
3884 char buf[1024];
3885 int tmp = tor_snprintf(buf, sizeof(buf),
3886 "Invalid nickname '%s' in %s line", s, name);
3887 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
3888 r = -1;
3889 break;
3892 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
3893 smartlist_free(sl);
3894 return r;
3897 /** Learn config file name from command line arguments, or use the default */
3898 static char *
3899 find_torrc_filename(int argc, char **argv,
3900 int *using_default_torrc, int *ignore_missing_torrc)
3902 char *fname=NULL;
3903 int i;
3905 for (i = 1; i < argc; ++i) {
3906 if (i < argc-1 && !strcmp(argv[i],"-f")) {
3907 if (fname) {
3908 log(LOG_WARN, LD_CONFIG, "Duplicate -f options on command line.");
3909 tor_free(fname);
3911 #ifdef MS_WINDOWS
3912 /* XXX one day we might want to extend expand_filename to work
3913 * under Windows as well. */
3914 fname = tor_strdup(argv[i+1]);
3915 #else
3916 fname = expand_filename(argv[i+1]);
3917 #endif
3918 *using_default_torrc = 0;
3919 ++i;
3920 } else if (!strcmp(argv[i],"--ignore-missing-torrc")) {
3921 *ignore_missing_torrc = 1;
3925 if (*using_default_torrc) {
3926 /* didn't find one, try CONFDIR */
3927 const char *dflt = get_default_conf_file();
3928 if (dflt && file_status(dflt) == FN_FILE) {
3929 fname = tor_strdup(dflt);
3930 } else {
3931 #ifndef MS_WINDOWS
3932 char *fn;
3933 fn = expand_filename("~/.torrc");
3934 if (fn && file_status(fn) == FN_FILE) {
3935 fname = fn;
3936 } else {
3937 tor_free(fn);
3938 fname = tor_strdup(dflt);
3940 #else
3941 fname = tor_strdup(dflt);
3942 #endif
3945 return fname;
3948 /** Load torrc from disk, setting torrc_fname if successful */
3949 static char *
3950 load_torrc_from_disk(int argc, char **argv)
3952 char *fname=NULL;
3953 char *cf = NULL;
3954 int using_default_torrc = 1;
3955 int ignore_missing_torrc = 0;
3957 fname = find_torrc_filename(argc, argv,
3958 &using_default_torrc, &ignore_missing_torrc);
3959 tor_assert(fname);
3960 log(LOG_DEBUG, LD_CONFIG, "Opening config file \"%s\"", fname);
3962 tor_free(torrc_fname);
3963 torrc_fname = fname;
3965 /* Open config file */
3966 if (file_status(fname) != FN_FILE ||
3967 !(cf = read_file_to_str(fname,0,NULL))) {
3968 if (using_default_torrc == 1 || ignore_missing_torrc ) {
3969 log(LOG_NOTICE, LD_CONFIG, "Configuration file \"%s\" not present, "
3970 "using reasonable defaults.", fname);
3971 tor_free(fname); /* sets fname to NULL */
3972 torrc_fname = NULL;
3973 cf = tor_strdup("");
3974 } else {
3975 log(LOG_WARN, LD_CONFIG,
3976 "Unable to open configuration file \"%s\".", fname);
3977 goto err;
3981 return cf;
3982 err:
3983 tor_free(fname);
3984 torrc_fname = NULL;
3985 return NULL;
3988 /** Read a configuration file into <b>options</b>, finding the configuration
3989 * file location based on the command line. After loading the file
3990 * call options_init_from_string() to load the config.
3991 * Return 0 if success, -1 if failure. */
3993 options_init_from_torrc(int argc, char **argv)
3995 char *cf=NULL;
3996 int i, retval, command;
3997 static char **backup_argv;
3998 static int backup_argc;
3999 char *command_arg = NULL;
4000 char *errmsg=NULL;
4002 if (argv) { /* first time we're called. save command line args */
4003 backup_argv = argv;
4004 backup_argc = argc;
4005 } else { /* we're reloading. need to clean up old options first. */
4006 argv = backup_argv;
4007 argc = backup_argc;
4009 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
4010 print_usage();
4011 exit(0);
4013 if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
4014 /* For documenting validating whether we've documented everything. */
4015 list_torrc_options();
4016 exit(0);
4019 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
4020 printf("Tor version %s.\n",get_version());
4021 exit(0);
4024 /* Go through command-line variables */
4025 if (!global_cmdline_options) {
4026 /* Or we could redo the list every time we pass this place.
4027 * It does not really matter */
4028 if (config_get_commandlines(argc, argv, &global_cmdline_options) < 0) {
4029 goto err;
4033 command = CMD_RUN_TOR;
4034 for (i = 1; i < argc; ++i) {
4035 if (!strcmp(argv[i],"--list-fingerprint")) {
4036 command = CMD_LIST_FINGERPRINT;
4037 } else if (!strcmp(argv[i],"--hash-password")) {
4038 command = CMD_HASH_PASSWORD;
4039 command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
4040 ++i;
4041 } else if (!strcmp(argv[i],"--verify-config")) {
4042 command = CMD_VERIFY_CONFIG;
4046 if (command == CMD_HASH_PASSWORD) {
4047 cf = tor_strdup("");
4048 } else {
4049 cf = load_torrc_from_disk(argc, argv);
4050 if (!cf)
4051 goto err;
4054 retval = options_init_from_string(cf, command, command_arg, &errmsg);
4055 tor_free(cf);
4056 if (retval < 0)
4057 goto err;
4059 return 0;
4061 err:
4062 if (errmsg) {
4063 log(LOG_WARN,LD_CONFIG,"%s", errmsg);
4064 tor_free(errmsg);
4066 return -1;
4069 /** Load the options from the configuration in <b>cf</b>, validate
4070 * them for consistency and take actions based on them.
4072 * Return 0 if success, negative on error:
4073 * * -1 for general errors.
4074 * * -2 for failure to parse/validate,
4075 * * -3 for transition not allowed
4076 * * -4 for error while setting the new options
4078 setopt_err_t
4079 options_init_from_string(const char *cf,
4080 int command, const char *command_arg,
4081 char **msg)
4083 or_options_t *oldoptions, *newoptions;
4084 config_line_t *cl;
4085 int retval;
4086 setopt_err_t err = SETOPT_ERR_MISC;
4087 tor_assert(msg);
4089 oldoptions = global_options; /* get_options unfortunately asserts if
4090 this is the first time we run*/
4092 newoptions = tor_malloc_zero(sizeof(or_options_t));
4093 newoptions->_magic = OR_OPTIONS_MAGIC;
4094 options_init(newoptions);
4095 newoptions->command = command;
4096 newoptions->command_arg = command_arg;
4098 /* get config lines, assign them */
4099 retval = config_get_lines(cf, &cl);
4100 if (retval < 0) {
4101 err = SETOPT_ERR_PARSE;
4102 goto err;
4104 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4105 config_free_lines(cl);
4106 if (retval < 0) {
4107 err = SETOPT_ERR_PARSE;
4108 goto err;
4111 /* Go through command-line variables too */
4112 retval = config_assign(&options_format, newoptions,
4113 global_cmdline_options, 0, 0, msg);
4114 if (retval < 0) {
4115 err = SETOPT_ERR_PARSE;
4116 goto err;
4119 /* If this is a testing network configuration, change defaults
4120 * for a list of dependent config options, re-initialize newoptions
4121 * with the new defaults, and assign all options to it second time. */
4122 if (newoptions->TestingTorNetwork) {
4123 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4124 * this? We could, for example, make the parsing algorithm do two passes
4125 * over the configuration. If it finds any "suite" options like
4126 * TestingTorNetwork, it could change the defaults before its second pass.
4127 * Not urgent so long as this seems to work, but at any sign of trouble,
4128 * let's clean it up. -NM */
4130 /* Change defaults. */
4131 int i;
4132 for (i = 0; testing_tor_network_defaults[i].name; ++i) {
4133 config_var_t *new_var = &testing_tor_network_defaults[i];
4134 config_var_t *old_var =
4135 config_find_option(&options_format, new_var->name);
4136 tor_assert(new_var);
4137 tor_assert(old_var);
4138 old_var->initvalue = new_var->initvalue;
4141 /* Clear newoptions and re-initialize them with new defaults. */
4142 config_free(&options_format, newoptions);
4143 newoptions = tor_malloc_zero(sizeof(or_options_t));
4144 newoptions->_magic = OR_OPTIONS_MAGIC;
4145 options_init(newoptions);
4146 newoptions->command = command;
4147 newoptions->command_arg = command_arg;
4149 /* Assign all options a second time. */
4150 retval = config_get_lines(cf, &cl);
4151 if (retval < 0) {
4152 err = SETOPT_ERR_PARSE;
4153 goto err;
4155 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4156 config_free_lines(cl);
4157 if (retval < 0) {
4158 err = SETOPT_ERR_PARSE;
4159 goto err;
4161 retval = config_assign(&options_format, newoptions,
4162 global_cmdline_options, 0, 0, msg);
4163 if (retval < 0) {
4164 err = SETOPT_ERR_PARSE;
4165 goto err;
4169 /* Validate newoptions */
4170 if (options_validate(oldoptions, newoptions, 0, msg) < 0) {
4171 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
4172 goto err;
4175 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
4176 err = SETOPT_ERR_TRANSITION;
4177 goto err;
4180 if (set_options(newoptions, msg)) {
4181 err = SETOPT_ERR_SETTING;
4182 goto err; /* frees and replaces old options */
4185 return SETOPT_OK;
4187 err:
4188 config_free(&options_format, newoptions);
4189 if (*msg) {
4190 int len = strlen(*msg)+256;
4191 char *newmsg = tor_malloc(len);
4193 tor_snprintf(newmsg, len, "Failed to parse/validate config: %s", *msg);
4194 tor_free(*msg);
4195 *msg = newmsg;
4197 return err;
4200 /** Return the location for our configuration file.
4202 const char *
4203 get_torrc_fname(void)
4205 if (torrc_fname)
4206 return torrc_fname;
4207 else
4208 return get_default_conf_file();
4211 /** Adjust the address map based on the MapAddress elements in the
4212 * configuration <b>options</b>
4214 static void
4215 config_register_addressmaps(or_options_t *options)
4217 smartlist_t *elts;
4218 config_line_t *opt;
4219 char *from, *to;
4221 addressmap_clear_configured();
4222 elts = smartlist_create();
4223 for (opt = options->AddressMap; opt; opt = opt->next) {
4224 smartlist_split_string(elts, opt->value, NULL,
4225 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4226 if (smartlist_len(elts) >= 2) {
4227 from = smartlist_get(elts,0);
4228 to = smartlist_get(elts,1);
4229 if (address_is_invalid_destination(to, 1)) {
4230 log_warn(LD_CONFIG,
4231 "Skipping invalid argument '%s' to MapAddress", to);
4232 } else {
4233 addressmap_register(from, tor_strdup(to), 0, ADDRMAPSRC_TORRC);
4234 if (smartlist_len(elts)>2) {
4235 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
4238 } else {
4239 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
4240 opt->value);
4242 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4243 smartlist_clear(elts);
4245 smartlist_free(elts);
4249 * Initialize the logs based on the configuration file.
4251 static int
4252 options_init_logs(or_options_t *options, int validate_only)
4254 config_line_t *opt;
4255 int ok;
4256 smartlist_t *elts;
4257 int daemon =
4258 #ifdef MS_WINDOWS
4260 #else
4261 options->RunAsDaemon;
4262 #endif
4264 ok = 1;
4265 elts = smartlist_create();
4267 for (opt = options->Logs; opt; opt = opt->next) {
4268 log_severity_list_t *severity;
4269 const char *cfg = opt->value;
4270 severity = tor_malloc_zero(sizeof(log_severity_list_t));
4271 if (parse_log_severity_config(&cfg, severity) < 0) {
4272 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
4273 opt->value);
4274 ok = 0; goto cleanup;
4277 smartlist_split_string(elts, cfg, NULL,
4278 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4280 if (smartlist_len(elts) == 0)
4281 smartlist_add(elts, tor_strdup("stdout"));
4283 if (smartlist_len(elts) == 1 &&
4284 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
4285 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
4286 int err = smartlist_len(elts) &&
4287 !strcasecmp(smartlist_get(elts,0), "stderr");
4288 if (!validate_only) {
4289 if (daemon) {
4290 log_warn(LD_CONFIG,
4291 "Can't log to %s with RunAsDaemon set; skipping stdout",
4292 err?"stderr":"stdout");
4293 } else {
4294 add_stream_log(severity, err?"<stderr>":"<stdout>",
4295 fileno(err?stderr:stdout));
4298 goto cleanup;
4300 if (smartlist_len(elts) == 1 &&
4301 !strcasecmp(smartlist_get(elts,0), "syslog")) {
4302 #ifdef HAVE_SYSLOG_H
4303 if (!validate_only) {
4304 add_syslog_log(severity);
4306 #else
4307 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
4308 #endif
4309 goto cleanup;
4312 if (smartlist_len(elts) == 2 &&
4313 !strcasecmp(smartlist_get(elts,0), "file")) {
4314 if (!validate_only) {
4315 if (add_file_log(severity, smartlist_get(elts, 1)) < 0) {
4316 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
4317 opt->value, strerror(errno));
4318 ok = 0;
4321 goto cleanup;
4324 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
4325 opt->value);
4326 ok = 0; goto cleanup;
4328 cleanup:
4329 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4330 smartlist_clear(elts);
4331 tor_free(severity);
4333 smartlist_free(elts);
4335 return ok?0:-1;
4338 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4339 * if the line is well-formed, and -1 if it isn't. If
4340 * <b>validate_only</b> is 0, and the line is well-formed, then add
4341 * the bridge described in the line to our internal bridge list. */
4342 static int
4343 parse_bridge_line(const char *line, int validate_only)
4345 smartlist_t *items = NULL;
4346 int r;
4347 char *addrport=NULL, *fingerprint=NULL;
4348 tor_addr_t addr;
4349 uint16_t port = 0;
4350 char digest[DIGEST_LEN];
4352 items = smartlist_create();
4353 smartlist_split_string(items, line, NULL,
4354 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4355 if (smartlist_len(items) < 1) {
4356 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
4357 goto err;
4359 addrport = smartlist_get(items, 0);
4360 smartlist_del_keeporder(items, 0);
4361 if (tor_addr_port_parse(addrport, &addr, &port)<0) {
4362 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
4363 goto err;
4365 if (!port) {
4366 log_info(LD_CONFIG,
4367 "Bridge address '%s' has no port; using default port 443.",
4368 addrport);
4369 port = 443;
4372 if (smartlist_len(items)) {
4373 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4374 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4375 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
4376 goto err;
4378 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4379 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
4380 goto err;
4384 if (!validate_only) {
4385 log_debug(LD_DIR, "Bridge at %s:%d (%s)", fmt_addr(&addr),
4386 (int)port,
4387 fingerprint ? fingerprint : "no key listed");
4388 bridge_add_from_config(&addr, port, fingerprint ? digest : NULL);
4391 r = 0;
4392 goto done;
4394 err:
4395 r = -1;
4397 done:
4398 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4399 smartlist_free(items);
4400 tor_free(addrport);
4401 tor_free(fingerprint);
4402 return r;
4405 /** Read the contents of a DirServer line from <b>line</b>. If
4406 * <b>validate_only</b> is 0, and the line is well-formed, and it
4407 * shares any bits with <b>required_type</b> or <b>required_type</b>
4408 * is 0, then add the dirserver described in the line (minus whatever
4409 * bits it's missing) as a valid authority. Return 0 on success,
4410 * or -1 if the line isn't well-formed or if we can't add it. */
4411 static int
4412 parse_dir_server_line(const char *line, authority_type_t required_type,
4413 int validate_only)
4415 smartlist_t *items = NULL;
4416 int r;
4417 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
4418 uint16_t dir_port = 0, or_port = 0;
4419 char digest[DIGEST_LEN];
4420 char v3_digest[DIGEST_LEN];
4421 authority_type_t type = V2_AUTHORITY;
4422 int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
4424 items = smartlist_create();
4425 smartlist_split_string(items, line, NULL,
4426 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4427 if (smartlist_len(items) < 1) {
4428 log_warn(LD_CONFIG, "No arguments on DirServer line.");
4429 goto err;
4432 if (is_legal_nickname(smartlist_get(items, 0))) {
4433 nickname = smartlist_get(items, 0);
4434 smartlist_del_keeporder(items, 0);
4437 while (smartlist_len(items)) {
4438 char *flag = smartlist_get(items, 0);
4439 if (TOR_ISDIGIT(flag[0]))
4440 break;
4441 if (!strcasecmp(flag, "v1")) {
4442 type |= (V1_AUTHORITY | HIDSERV_AUTHORITY);
4443 } else if (!strcasecmp(flag, "hs")) {
4444 type |= HIDSERV_AUTHORITY;
4445 } else if (!strcasecmp(flag, "no-hs")) {
4446 is_not_hidserv_authority = 1;
4447 } else if (!strcasecmp(flag, "bridge")) {
4448 type |= BRIDGE_AUTHORITY;
4449 } else if (!strcasecmp(flag, "no-v2")) {
4450 is_not_v2_authority = 1;
4451 } else if (!strcasecmpstart(flag, "orport=")) {
4452 int ok;
4453 char *portstring = flag + strlen("orport=");
4454 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
4455 if (!ok)
4456 log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
4457 portstring);
4458 } else if (!strcasecmpstart(flag, "v3ident=")) {
4459 char *idstr = flag + strlen("v3ident=");
4460 if (strlen(idstr) != HEX_DIGEST_LEN ||
4461 base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
4462 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirServer line",
4463 flag);
4464 } else {
4465 type |= V3_AUTHORITY;
4467 } else {
4468 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
4469 flag);
4471 tor_free(flag);
4472 smartlist_del_keeporder(items, 0);
4474 if (is_not_hidserv_authority)
4475 type &= ~HIDSERV_AUTHORITY;
4476 if (is_not_v2_authority)
4477 type &= ~V2_AUTHORITY;
4479 if (smartlist_len(items) < 2) {
4480 log_warn(LD_CONFIG, "Too few arguments to DirServer line.");
4481 goto err;
4483 addrport = smartlist_get(items, 0);
4484 smartlist_del_keeporder(items, 0);
4485 if (parse_addr_port(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
4486 log_warn(LD_CONFIG, "Error parsing DirServer address '%s'", addrport);
4487 goto err;
4489 if (!dir_port) {
4490 log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
4491 goto err;
4494 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4495 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4496 log_warn(LD_CONFIG, "Key digest for DirServer is wrong length %d.",
4497 (int)strlen(fingerprint));
4498 goto err;
4500 if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4501 /* a known bad fingerprint. refuse to use it. We can remove this
4502 * clause once Tor 0.1.2.17 is obsolete. */
4503 log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
4504 "torrc file (%s), or reinstall Tor and use the default torrc.",
4505 get_torrc_fname());
4506 goto err;
4508 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4509 log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
4510 goto err;
4513 if (!validate_only && (!required_type || required_type & type)) {
4514 if (required_type)
4515 type &= required_type; /* pare down what we think of them as an
4516 * authority for. */
4517 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
4518 address, (int)dir_port, (char*)smartlist_get(items,0));
4519 if (!add_trusted_dir_server(nickname, address, dir_port, or_port,
4520 digest, v3_digest, type))
4521 goto err;
4524 r = 0;
4525 goto done;
4527 err:
4528 r = -1;
4530 done:
4531 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4532 smartlist_free(items);
4533 tor_free(addrport);
4534 tor_free(address);
4535 tor_free(nickname);
4536 tor_free(fingerprint);
4537 return r;
4540 /** Adjust the value of options->DataDirectory, or fill it in if it's
4541 * absent. Return 0 on success, -1 on failure. */
4542 static int
4543 normalize_data_directory(or_options_t *options)
4545 #ifdef MS_WINDOWS
4546 char *p;
4547 if (options->DataDirectory)
4548 return 0; /* all set */
4549 p = tor_malloc(MAX_PATH);
4550 strlcpy(p,get_windows_conf_root(),MAX_PATH);
4551 options->DataDirectory = p;
4552 return 0;
4553 #else
4554 const char *d = options->DataDirectory;
4555 if (!d)
4556 d = "~/.tor";
4558 if (strncmp(d,"~/",2) == 0) {
4559 char *fn = expand_filename(d);
4560 if (!fn) {
4561 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
4562 return -1;
4564 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
4565 /* If our homedir is /, we probably don't want to use it. */
4566 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4567 * want. */
4568 log_warn(LD_CONFIG,
4569 "Default DataDirectory is \"~/.tor\". This expands to "
4570 "\"%s\", which is probably not what you want. Using "
4571 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
4572 tor_free(fn);
4573 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
4575 tor_free(options->DataDirectory);
4576 options->DataDirectory = fn;
4578 return 0;
4579 #endif
4582 /** Check and normalize the value of options->DataDirectory; return 0 if it
4583 * sane, -1 otherwise. */
4584 static int
4585 validate_data_directory(or_options_t *options)
4587 if (normalize_data_directory(options) < 0)
4588 return -1;
4589 tor_assert(options->DataDirectory);
4590 if (strlen(options->DataDirectory) > (512-128)) {
4591 log_warn(LD_CONFIG, "DataDirectory is too long.");
4592 return -1;
4594 return 0;
4597 /** This string must remain the same forevermore. It is how we
4598 * recognize that the torrc file doesn't need to be backed up. */
4599 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4600 "if you edit it, comments will not be preserved"
4601 /** This string can change; it tries to give the reader an idea
4602 * that editing this file by hand is not a good plan. */
4603 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4604 "to torrc.orig.1 or similar, and Tor will ignore it"
4606 /** Save a configuration file for the configuration in <b>options</b>
4607 * into the file <b>fname</b>. If the file already exists, and
4608 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4609 * replace it. Return 0 on success, -1 on failure. */
4610 static int
4611 write_configuration_file(const char *fname, or_options_t *options)
4613 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4614 int rename_old = 0, r;
4615 size_t len;
4617 tor_assert(fname);
4619 switch (file_status(fname)) {
4620 case FN_FILE:
4621 old_val = read_file_to_str(fname, 0, NULL);
4622 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4623 rename_old = 1;
4625 tor_free(old_val);
4626 break;
4627 case FN_NOENT:
4628 break;
4629 case FN_ERROR:
4630 case FN_DIR:
4631 default:
4632 log_warn(LD_CONFIG,
4633 "Config file \"%s\" is not a file? Failing.", fname);
4634 return -1;
4637 if (!(new_conf = options_dump(options, 1))) {
4638 log_warn(LD_BUG, "Couldn't get configuration string");
4639 goto err;
4642 len = strlen(new_conf)+256;
4643 new_val = tor_malloc(len);
4644 tor_snprintf(new_val, len, "%s\n%s\n\n%s",
4645 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4647 if (rename_old) {
4648 int i = 1;
4649 size_t fn_tmp_len = strlen(fname)+32;
4650 char *fn_tmp;
4651 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4652 fn_tmp = tor_malloc(fn_tmp_len);
4653 while (1) {
4654 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4655 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4656 tor_free(fn_tmp);
4657 goto err;
4659 if (file_status(fn_tmp) == FN_NOENT)
4660 break;
4661 ++i;
4663 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4664 if (rename(fname, fn_tmp) < 0) {
4665 log_warn(LD_FS,
4666 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4667 fname, fn_tmp, strerror(errno));
4668 tor_free(fn_tmp);
4669 goto err;
4671 tor_free(fn_tmp);
4674 if (write_str_to_file(fname, new_val, 0) < 0)
4675 goto err;
4677 r = 0;
4678 goto done;
4679 err:
4680 r = -1;
4681 done:
4682 tor_free(new_val);
4683 tor_free(new_conf);
4684 return r;
4688 * Save the current configuration file value to disk. Return 0 on
4689 * success, -1 on failure.
4692 options_save_current(void)
4694 if (torrc_fname) {
4695 /* This fails if we can't write to our configuration file.
4697 * If we try falling back to datadirectory or something, we have a better
4698 * chance of saving the configuration, but a better chance of doing
4699 * something the user never expected. Let's just warn instead. */
4700 return write_configuration_file(torrc_fname, get_options());
4702 return write_configuration_file(get_default_conf_file(), get_options());
4705 /** Mapping from a unit name to a multiplier for converting that unit into a
4706 * base unit. */
4707 struct unit_table_t {
4708 const char *unit;
4709 uint64_t multiplier;
4712 /** Table to map the names of memory units to the number of bytes they
4713 * contain. */
4714 static struct unit_table_t memory_units[] = {
4715 { "", 1 },
4716 { "b", 1<< 0 },
4717 { "byte", 1<< 0 },
4718 { "bytes", 1<< 0 },
4719 { "kb", 1<<10 },
4720 { "kbyte", 1<<10 },
4721 { "kbytes", 1<<10 },
4722 { "kilobyte", 1<<10 },
4723 { "kilobytes", 1<<10 },
4724 { "m", 1<<20 },
4725 { "mb", 1<<20 },
4726 { "mbyte", 1<<20 },
4727 { "mbytes", 1<<20 },
4728 { "megabyte", 1<<20 },
4729 { "megabytes", 1<<20 },
4730 { "gb", 1<<30 },
4731 { "gbyte", 1<<30 },
4732 { "gbytes", 1<<30 },
4733 { "gigabyte", 1<<30 },
4734 { "gigabytes", 1<<30 },
4735 { "tb", U64_LITERAL(1)<<40 },
4736 { "terabyte", U64_LITERAL(1)<<40 },
4737 { "terabytes", U64_LITERAL(1)<<40 },
4738 { NULL, 0 },
4741 /** Table to map the names of time units to the number of seconds they
4742 * contain. */
4743 static struct unit_table_t time_units[] = {
4744 { "", 1 },
4745 { "second", 1 },
4746 { "seconds", 1 },
4747 { "minute", 60 },
4748 { "minutes", 60 },
4749 { "hour", 60*60 },
4750 { "hours", 60*60 },
4751 { "day", 24*60*60 },
4752 { "days", 24*60*60 },
4753 { "week", 7*24*60*60 },
4754 { "weeks", 7*24*60*60 },
4755 { NULL, 0 },
4758 /** Parse a string <b>val</b> containing a number, zero or more
4759 * spaces, and an optional unit string. If the unit appears in the
4760 * table <b>u</b>, then multiply the number by the unit multiplier.
4761 * On success, set *<b>ok</b> to 1 and return this product.
4762 * Otherwise, set *<b>ok</b> to 0.
4764 static uint64_t
4765 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4767 uint64_t v;
4768 char *cp;
4770 tor_assert(ok);
4772 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4773 if (!*ok)
4774 return 0;
4775 if (!cp) {
4776 *ok = 1;
4777 return v;
4779 while (TOR_ISSPACE(*cp))
4780 ++cp;
4781 for ( ;u->unit;++u) {
4782 if (!strcasecmp(u->unit, cp)) {
4783 v *= u->multiplier;
4784 *ok = 1;
4785 return v;
4788 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4789 *ok = 0;
4790 return 0;
4793 /** Parse a string in the format "number unit", where unit is a unit of
4794 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4795 * and return the number of bytes specified. Otherwise, set
4796 * *<b>ok</b> to false and return 0. */
4797 static uint64_t
4798 config_parse_memunit(const char *s, int *ok)
4800 return config_parse_units(s, memory_units, ok);
4803 /** Parse a string in the format "number unit", where unit is a unit of time.
4804 * On success, set *<b>ok</b> to true and return the number of seconds in
4805 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4807 static int
4808 config_parse_interval(const char *s, int *ok)
4810 uint64_t r;
4811 r = config_parse_units(s, time_units, ok);
4812 if (!ok)
4813 return -1;
4814 if (r > INT_MAX) {
4815 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4816 *ok = 0;
4817 return -1;
4819 return (int)r;
4822 /* This is what passes for version detection on OSX. We set
4823 * MACOSX_KQUEUE_IS_BROKEN to true iff we're on a version of OSX before
4824 * 10.4.0 (aka 1040). */
4825 #ifdef __APPLE__
4826 #ifdef __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__
4827 #define MACOSX_KQUEUE_IS_BROKEN \
4828 (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1040)
4829 #else
4830 #define MACOSX_KQUEUE_IS_BROKEN 0
4831 #endif
4832 #endif
4835 * Initialize the libevent library.
4837 static void
4838 init_libevent(void)
4840 configure_libevent_logging();
4841 /* If the kernel complains that some method (say, epoll) doesn't
4842 * exist, we don't care about it, since libevent will cope.
4844 suppress_libevent_log_msg("Function not implemented");
4845 #ifdef __APPLE__
4846 if (MACOSX_KQUEUE_IS_BROKEN ||
4847 decode_libevent_version(event_get_version(), NULL) < LE_11B) {
4848 setenv("EVENT_NOKQUEUE","1",1);
4850 #endif
4852 /* In libevent versions before 2.0, it's hard to keep binary compatibility
4853 * between upgrades, and unpleasant to detect when the version we compiled
4854 * against is unlike the version we have linked against. Here's how. */
4855 #if defined(_EVENT_VERSION) && defined(HAVE_EVENT_GET_VERSION)
4856 /* We have a header-file version and a function-call version. Easy. */
4857 if (strcmp(_EVENT_VERSION, event_get_version())) {
4858 int compat1 = -1, compat2 = -1;
4859 int verybad, prettybad ;
4860 decode_libevent_version(_EVENT_VERSION, &compat1);
4861 decode_libevent_version(event_get_version(), &compat2);
4862 verybad = compat1 != compat2;
4863 prettybad = (compat1 == -1 || compat2 == -1) && compat1 != compat2;
4865 log(verybad ? LOG_WARN : (prettybad ? LOG_NOTICE : LOG_INFO),
4866 LD_GENERAL, "We were compiled with headers from version %s "
4867 "of Libevent, but we're using a Libevent library that says it's "
4868 "version %s.", _EVENT_VERSION, event_get_version());
4869 if (verybad)
4870 log_warn(LD_GENERAL, "This will almost certainly make Tor crash.");
4871 else if (prettybad)
4872 log_notice(LD_GENERAL, "If Tor crashes, this might be why.");
4873 else
4874 log_info(LD_GENERAL, "I think these versions are binary-compatible.");
4876 #elif defined(HAVE_EVENT_GET_VERSION)
4877 /* event_get_version but no _EVENT_VERSION. We might be in 1.4.0-beta or
4878 earlier, where that's normal. To see whether we were compiled with an
4879 earlier version, let's see whether the struct event defines MIN_HEAP_IDX.
4881 #ifdef HAVE_STRUCT_EVENT_MIN_HEAP_IDX
4882 /* The header files are 1.4.0-beta or later. If the version is not
4883 * 1.4.0-beta, we are incompatible. */
4885 if (strcmp(event_get_version(), "1.4.0-beta")) {
4886 log_warn(LD_GENERAL, "It's a little hard to tell, but you seem to have "
4887 "Libevent 1.4.0-beta header files, whereas you have linked "
4888 "against Libevent %s. This will probably make Tor crash.",
4889 event_get_version());
4892 #else
4893 /* Our headers are 1.3e or earlier. If the library version is not 1.4.x or
4894 later, we're probably fine. */
4896 const char *v = event_get_version();
4897 if ((v[0] == '1' && v[2] == '.' && v[3] > '3') || v[0] > '1') {
4898 log_warn(LD_GENERAL, "It's a little hard to tell, but you seem to have "
4899 "Libevent header file from 1.3e or earlier, whereas you have "
4900 "linked against Libevent %s. This will probably make Tor "
4901 "crash.", event_get_version());
4904 #endif
4906 #elif defined(_EVENT_VERSION)
4907 #warn "_EVENT_VERSION is defined but not get_event_version(): Libevent is odd."
4908 #else
4909 /* Your libevent is ancient. */
4910 #endif
4912 event_init();
4913 suppress_libevent_log_msg(NULL);
4914 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4915 /* Making this a NOTICE for now so we can link bugs to a libevent versions
4916 * or methods better. */
4917 log(LOG_NOTICE, LD_GENERAL,
4918 "Initialized libevent version %s using method %s. Good.",
4919 event_get_version(), event_get_method());
4920 check_libevent_version(event_get_method(), get_options()->ORPort != 0);
4921 #else
4922 log(LOG_NOTICE, LD_GENERAL,
4923 "Initialized old libevent (version 1.0b or earlier).");
4924 log(LOG_WARN, LD_GENERAL,
4925 "You have a *VERY* old version of libevent. It is likely to be buggy; "
4926 "please build Tor with a more recent version.");
4927 #endif
4930 /** Table mapping return value of event_get_version() to le_version_t. */
4931 static const struct {
4932 const char *name; le_version_t version; int bincompat;
4933 } le_version_table[] = {
4934 /* earlier versions don't have get_version. */
4935 { "1.0c", LE_10C, 1},
4936 { "1.0d", LE_10D, 1},
4937 { "1.0e", LE_10E, 1},
4938 { "1.1", LE_11, 1 },
4939 { "1.1a", LE_11A, 1 },
4940 { "1.1b", LE_11B, 1 },
4941 { "1.2", LE_12, 1 },
4942 { "1.2a", LE_12A, 1 },
4943 { "1.3", LE_13, 1 },
4944 { "1.3a", LE_13A, 1 },
4945 { "1.3b", LE_13B, 1 },
4946 { "1.3c", LE_13C, 1 },
4947 { "1.3d", LE_13D, 1 },
4948 { "1.3e", LE_13E, 1 },
4949 { "1.4.0-beta", LE_140, 2 },
4950 { "1.4.1-beta", LE_141, 2 },
4951 { "1.4.2-rc", LE_142, 2 },
4952 { "1.4.3-stable", LE_143, 2 },
4953 { "1.4.4-stable", LE_144, 2 },
4954 { "1.4.5-stable", LE_145, 2 },
4955 { "1.4.6-stable", LE_146, 2 },
4956 { "1.4.7-stable", LE_147, 2 },
4957 { "1.4.8-stable", LE_148, 2 },
4958 { "1.4.99-trunk", LE_1499, 3 },
4959 { NULL, LE_OTHER, 0 }
4962 /** Return the le_version_t for the current version of libevent. If the
4963 * version is very new, return LE_OTHER. If the version is so old that it
4964 * doesn't support event_get_version(), return LE_OLD. */
4965 static le_version_t
4966 decode_libevent_version(const char *v, int *bincompat_out)
4968 int i;
4969 for (i=0; le_version_table[i].name; ++i) {
4970 if (!strcmp(le_version_table[i].name, v)) {
4971 if (bincompat_out)
4972 *bincompat_out = le_version_table[i].bincompat;
4973 return le_version_table[i].version;
4976 if (v[0] != '1' && bincompat_out)
4977 *bincompat_out = 100;
4978 else if (!strcmpstart(v, "1.4") && bincompat_out)
4979 *bincompat_out = 2;
4980 return LE_OTHER;
4983 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4985 * Compare the given libevent method and version to a list of versions
4986 * which are known not to work. Warn the user as appropriate.
4988 static void
4989 check_libevent_version(const char *m, int server)
4991 int buggy = 0, iffy = 0, slow = 0, thread_unsafe = 0;
4992 le_version_t version;
4993 const char *v = event_get_version();
4994 const char *badness = NULL;
4995 const char *sad_os = "";
4997 version = decode_libevent_version(v, NULL);
4999 /* XXX Would it be worthwhile disabling the methods that we know
5000 * are buggy, rather than just warning about them and then proceeding
5001 * to use them? If so, we should probably not wrap this whole thing
5002 * in HAVE_EVENT_GET_VERSION and HAVE_EVENT_GET_METHOD. -RD */
5003 /* XXXX The problem is that it's not trivial to get libevent to change it's
5004 * method once it's initialized, and it's not trivial to tell what method it
5005 * will use without initializing it. I guess we could preemptively disable
5006 * buggy libevent modes based on the version _before_ initializing it,
5007 * though, but then there's no good way (afaict) to warn "I would have used
5008 * kqueue, but instead I'm using select." -NM */
5009 if (!strcmp(m, "kqueue")) {
5010 if (version < LE_11B)
5011 buggy = 1;
5012 } else if (!strcmp(m, "epoll")) {
5013 if (version < LE_11)
5014 iffy = 1;
5015 } else if (!strcmp(m, "poll")) {
5016 if (version < LE_10E)
5017 buggy = 1;
5018 else if (version < LE_11)
5019 slow = 1;
5020 } else if (!strcmp(m, "select")) {
5021 if (version < LE_11)
5022 slow = 1;
5023 } else if (!strcmp(m, "win32")) {
5024 if (version < LE_11B)
5025 buggy = 1;
5028 /* Libevent versions before 1.3b do very badly on operating systems with
5029 * user-space threading implementations. */
5030 #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
5031 if (server && version < LE_13B) {
5032 thread_unsafe = 1;
5033 sad_os = "BSD variants";
5035 #elif defined(__APPLE__) || defined(__darwin__)
5036 if (server && version < LE_13B) {
5037 thread_unsafe = 1;
5038 sad_os = "Mac OS X";
5040 #endif
5042 if (thread_unsafe) {
5043 log(LOG_WARN, LD_GENERAL,
5044 "Libevent version %s often crashes when running a Tor server with %s. "
5045 "Please use the latest version of libevent (1.3b or later)",v,sad_os);
5046 badness = "BROKEN";
5047 } else if (buggy) {
5048 log(LOG_WARN, LD_GENERAL,
5049 "There are serious bugs in using %s with libevent %s. "
5050 "Please use the latest version of libevent.", m, v);
5051 badness = "BROKEN";
5052 } else if (iffy) {
5053 log(LOG_WARN, LD_GENERAL,
5054 "There are minor bugs in using %s with libevent %s. "
5055 "You may want to use the latest version of libevent.", m, v);
5056 badness = "BUGGY";
5057 } else if (slow && server) {
5058 log(LOG_WARN, LD_GENERAL,
5059 "libevent %s can be very slow with %s. "
5060 "When running a server, please use the latest version of libevent.",
5061 v,m);
5062 badness = "SLOW";
5064 if (badness) {
5065 control_event_general_status(LOG_WARN,
5066 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
5067 v, m, badness);
5071 #endif
5073 /** Return the persistent state struct for this Tor. */
5074 or_state_t *
5075 get_or_state(void)
5077 tor_assert(global_state);
5078 return global_state;
5081 /** Return a newly allocated string holding a filename relative to the data
5082 * directory. If <b>sub1</b> is present, it is the first path component after
5083 * the data directory. If <b>sub2</b> is also present, it is the second path
5084 * component after the data directory. If <b>suffix</b> is present, it
5085 * is appended to the filename.
5087 * Examples:
5088 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
5089 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
5090 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
5091 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
5093 * Note: Consider using the get_datadir_fname* macros in or.h.
5095 char *
5096 options_get_datadir_fname2_suffix(or_options_t *options,
5097 const char *sub1, const char *sub2,
5098 const char *suffix)
5100 char *fname = NULL;
5101 size_t len;
5102 tor_assert(options);
5103 tor_assert(options->DataDirectory);
5104 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
5105 len = strlen(options->DataDirectory);
5106 if (sub1) {
5107 len += strlen(sub1)+1;
5108 if (sub2)
5109 len += strlen(sub2)+1;
5111 if (suffix)
5112 len += strlen(suffix);
5113 len++;
5114 fname = tor_malloc(len);
5115 if (sub1) {
5116 if (sub2) {
5117 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
5118 options->DataDirectory, sub1, sub2);
5119 } else {
5120 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
5121 options->DataDirectory, sub1);
5123 } else {
5124 strlcpy(fname, options->DataDirectory, len);
5126 if (suffix)
5127 strlcat(fname, suffix, len);
5128 return fname;
5131 /** Return 0 if every setting in <b>state</b> is reasonable, and a
5132 * permissible transition from <b>old_state</b>. Else warn and return -1.
5133 * Should have no side effects, except for normalizing the contents of
5134 * <b>state</b>.
5136 /* XXX from_setconf is here because of bug 238 */
5137 static int
5138 or_state_validate(or_state_t *old_state, or_state_t *state,
5139 int from_setconf, char **msg)
5141 /* We don't use these; only options do. Still, we need to match that
5142 * signature. */
5143 (void) from_setconf;
5144 (void) old_state;
5146 if (entry_guards_parse_state(state, 0, msg)<0)
5147 return -1;
5149 return 0;
5152 /** Replace the current persistent state with <b>new_state</b> */
5153 static void
5154 or_state_set(or_state_t *new_state)
5156 char *err = NULL;
5157 tor_assert(new_state);
5158 if (global_state)
5159 config_free(&state_format, global_state);
5160 global_state = new_state;
5161 if (entry_guards_parse_state(global_state, 1, &err)<0) {
5162 log_warn(LD_GENERAL,"%s",err);
5163 tor_free(err);
5165 if (rep_hist_load_state(global_state, &err)<0) {
5166 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
5167 tor_free(err);
5171 /** Reload the persistent state from disk, generating a new state as needed.
5172 * Return 0 on success, less than 0 on failure.
5174 static int
5175 or_state_load(void)
5177 or_state_t *new_state = NULL;
5178 char *contents = NULL, *fname;
5179 char *errmsg = NULL;
5180 int r = -1, badstate = 0;
5182 fname = get_datadir_fname("state");
5183 switch (file_status(fname)) {
5184 case FN_FILE:
5185 if (!(contents = read_file_to_str(fname, 0, NULL))) {
5186 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
5187 goto done;
5189 break;
5190 case FN_NOENT:
5191 break;
5192 case FN_ERROR:
5193 case FN_DIR:
5194 default:
5195 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
5196 goto done;
5198 new_state = tor_malloc_zero(sizeof(or_state_t));
5199 new_state->_magic = OR_STATE_MAGIC;
5200 config_init(&state_format, new_state);
5201 if (contents) {
5202 config_line_t *lines=NULL;
5203 int assign_retval;
5204 if (config_get_lines(contents, &lines)<0)
5205 goto done;
5206 assign_retval = config_assign(&state_format, new_state,
5207 lines, 0, 0, &errmsg);
5208 config_free_lines(lines);
5209 if (assign_retval<0)
5210 badstate = 1;
5211 if (errmsg) {
5212 log_warn(LD_GENERAL, "%s", errmsg);
5213 tor_free(errmsg);
5217 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
5218 badstate = 1;
5220 if (errmsg) {
5221 log_warn(LD_GENERAL, "%s", errmsg);
5222 tor_free(errmsg);
5225 if (badstate && !contents) {
5226 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
5227 " This is a bug in Tor.");
5228 goto done;
5229 } else if (badstate && contents) {
5230 int i;
5231 file_status_t status;
5232 size_t len = strlen(fname)+16;
5233 char *fname2 = tor_malloc(len);
5234 for (i = 0; i < 100; ++i) {
5235 tor_snprintf(fname2, len, "%s.%d", fname, i);
5236 status = file_status(fname2);
5237 if (status == FN_NOENT)
5238 break;
5240 if (i == 100) {
5241 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
5242 "state files to move aside. Discarding the old state file.",
5243 fname);
5244 unlink(fname);
5245 } else {
5246 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
5247 "to \"%s\". This could be a bug in Tor; please tell "
5248 "the developers.", fname, fname2);
5249 if (rename(fname, fname2) < 0) {
5250 log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
5251 "OS gave an error of %s", strerror(errno));
5254 tor_free(fname2);
5255 tor_free(contents);
5256 config_free(&state_format, new_state);
5258 new_state = tor_malloc_zero(sizeof(or_state_t));
5259 new_state->_magic = OR_STATE_MAGIC;
5260 config_init(&state_format, new_state);
5261 } else if (contents) {
5262 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
5263 } else {
5264 log_info(LD_GENERAL, "Initialized state");
5266 or_state_set(new_state);
5267 new_state = NULL;
5268 if (!contents) {
5269 global_state->next_write = 0;
5270 or_state_save(time(NULL));
5272 r = 0;
5274 done:
5275 tor_free(fname);
5276 tor_free(contents);
5277 if (new_state)
5278 config_free(&state_format, new_state);
5280 return r;
5283 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
5285 or_state_save(time_t now)
5287 char *state, *contents;
5288 char tbuf[ISO_TIME_LEN+1];
5289 size_t len;
5290 char *fname;
5292 tor_assert(global_state);
5294 if (global_state->next_write > now)
5295 return 0;
5297 /* Call everything else that might dirty the state even more, in order
5298 * to avoid redundant writes. */
5299 entry_guards_update_state(global_state);
5300 rep_hist_update_state(global_state);
5301 if (accounting_is_enabled(get_options()))
5302 accounting_run_housekeeping(now);
5304 global_state->LastWritten = time(NULL);
5305 tor_free(global_state->TorVersion);
5306 len = strlen(get_version())+8;
5307 global_state->TorVersion = tor_malloc(len);
5308 tor_snprintf(global_state->TorVersion, len, "Tor %s", get_version());
5310 state = config_dump(&state_format, global_state, 1, 0);
5311 len = strlen(state)+256;
5312 contents = tor_malloc(len);
5313 format_local_iso_time(tbuf, time(NULL));
5314 tor_snprintf(contents, len,
5315 "# Tor state file last generated on %s local time\n"
5316 "# Other times below are in GMT\n"
5317 "# You *do not* need to edit this file.\n\n%s",
5318 tbuf, state);
5319 tor_free(state);
5320 fname = get_datadir_fname("state");
5321 if (write_str_to_file(fname, contents, 0)<0) {
5322 log_warn(LD_FS, "Unable to write state to file \"%s\"", fname);
5323 tor_free(fname);
5324 tor_free(contents);
5325 return -1;
5327 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
5328 tor_free(fname);
5329 tor_free(contents);
5331 global_state->next_write = TIME_MAX;
5332 return 0;
5335 /** Given a file name check to see whether the file exists but has not been
5336 * modified for a very long time. If so, remove it. */
5337 void
5338 remove_file_if_very_old(const char *fname, time_t now)
5340 #define VERY_OLD_FILE_AGE (28*24*60*60)
5341 struct stat st;
5343 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
5344 char buf[ISO_TIME_LEN+1];
5345 format_local_iso_time(buf, st.st_mtime);
5346 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
5347 "Removing it.", fname, buf);
5348 unlink(fname);
5352 /** Helper to implement GETINFO functions about configuration variables (not
5353 * their values). Given a "config/names" question, set *<b>answer</b> to a
5354 * new string describing the supported configuration variables and their
5355 * types. */
5357 getinfo_helper_config(control_connection_t *conn,
5358 const char *question, char **answer)
5360 (void) conn;
5361 if (!strcmp(question, "config/names")) {
5362 smartlist_t *sl = smartlist_create();
5363 int i;
5364 for (i = 0; _option_vars[i].name; ++i) {
5365 config_var_t *var = &_option_vars[i];
5366 const char *type, *desc;
5367 char *line;
5368 size_t len;
5369 desc = config_find_description(&options_format, var->name);
5370 switch (var->type) {
5371 case CONFIG_TYPE_STRING: type = "String"; break;
5372 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
5373 case CONFIG_TYPE_UINT: type = "Integer"; break;
5374 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
5375 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
5376 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
5377 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
5378 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
5379 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
5380 case CONFIG_TYPE_CSV: type = "CommaList"; break;
5381 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
5382 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
5383 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
5384 default:
5385 case CONFIG_TYPE_OBSOLETE:
5386 type = NULL; break;
5388 if (!type)
5389 continue;
5390 len = strlen(var->name)+strlen(type)+16;
5391 if (desc)
5392 len += strlen(desc);
5393 line = tor_malloc(len);
5394 if (desc)
5395 tor_snprintf(line, len, "%s %s %s\n",var->name,type,desc);
5396 else
5397 tor_snprintf(line, len, "%s %s\n",var->name,type);
5398 smartlist_add(sl, line);
5400 *answer = smartlist_join_strings(sl, "", 0, NULL);
5401 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
5402 smartlist_free(sl);
5404 return 0;