Simplest fix to bug2402: do not include SVN versions
[tor/rransom.git] / src / or / config.c
blobc5d654078ef3acb5a75fbfb08e0730bfe00502b6
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-2011, 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 return VERSION;
833 /** Release additional memory allocated in options
835 static void
836 or_options_free(or_options_t *options)
838 if (options->_ExcludeExitNodesUnion)
839 routerset_free(options->_ExcludeExitNodesUnion);
840 config_free(&options_format, options);
843 /** Release all memory and resources held by global configuration structures.
845 void
846 config_free_all(void)
848 if (global_options) {
849 or_options_free(global_options);
850 global_options = NULL;
852 if (global_state) {
853 config_free(&state_format, global_state);
854 global_state = NULL;
856 if (global_cmdline_options) {
857 config_free_lines(global_cmdline_options);
858 global_cmdline_options = NULL;
860 tor_free(torrc_fname);
861 tor_free(_version);
862 tor_free(global_dirfrontpagecontents);
865 /** If options->SafeLogging is on, return a not very useful string,
866 * else return address.
868 const char *
869 safe_str(const char *address)
871 tor_assert(address);
872 if (get_options()->SafeLogging)
873 return "[scrubbed]";
874 else
875 return address;
878 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
879 * escaped(): don't use this outside the main thread, or twice in the same
880 * log statement. */
881 const char *
882 escaped_safe_str(const char *address)
884 if (get_options()->SafeLogging)
885 return "[scrubbed]";
886 else
887 return escaped(address);
890 /** Add the default directory authorities directly into the trusted dir list,
891 * but only add them insofar as they share bits with <b>type</b>. */
892 static void
893 add_default_trusted_dir_authorities(authority_type_t type)
895 int i;
896 const char *dirservers[] = {
897 "moria1 orport=9101 no-v2 "
898 "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
899 "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
900 "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
901 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
902 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
903 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
904 "Tonga orport=443 bridge no-v2 82.94.251.203:80 "
905 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
906 "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
907 "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
908 "gabelmoo orport=443 no-v2 "
909 "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
910 "212.112.245.170:80 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
911 "dannenberg orport=443 no-v2 "
912 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
913 "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
914 "urras orport=80 no-v2 v3ident=80550987E1D626E3EBA5E5E75A458DE0626D088C "
915 "208.83.223.34:443 0AD3 FA88 4D18 F89E EA2D 89C0 1937 9E0E 7FD9 4417",
916 "maatuska orport=80 no-v2 "
917 "v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
918 "213.115.239.118:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
919 NULL
921 for (i=0; dirservers[i]; i++) {
922 if (parse_dir_server_line(dirservers[i], type, 0)<0) {
923 log_err(LD_BUG, "Couldn't parse internal dirserver line %s",
924 dirservers[i]);
929 /** Look at all the config options for using alternate directory
930 * authorities, and make sure none of them are broken. Also, warn the
931 * user if we changed any dangerous ones.
933 static int
934 validate_dir_authorities(or_options_t *options, or_options_t *old_options)
936 config_line_t *cl;
938 if (options->DirServers &&
939 (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
940 options->AlternateHSAuthority)) {
941 log_warn(LD_CONFIG,
942 "You cannot set both DirServers and Alternate*Authority.");
943 return -1;
946 /* do we want to complain to the user about being partitionable? */
947 if ((options->DirServers &&
948 (!old_options ||
949 !config_lines_eq(options->DirServers, old_options->DirServers))) ||
950 (options->AlternateDirAuthority &&
951 (!old_options ||
952 !config_lines_eq(options->AlternateDirAuthority,
953 old_options->AlternateDirAuthority)))) {
954 log_warn(LD_CONFIG,
955 "You have used DirServer or AlternateDirAuthority to "
956 "specify alternate directory authorities in "
957 "your configuration. This is potentially dangerous: it can "
958 "make you look different from all other Tor users, and hurt "
959 "your anonymity. Even if you've specified the same "
960 "authorities as Tor uses by default, the defaults could "
961 "change in the future. Be sure you know what you're doing.");
964 /* Now go through the four ways you can configure an alternate
965 * set of directory authorities, and make sure none are broken. */
966 for (cl = options->DirServers; cl; cl = cl->next)
967 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
968 return -1;
969 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
970 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
971 return -1;
972 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
973 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
974 return -1;
975 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
976 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
977 return -1;
978 return 0;
981 /** Look at all the config options and assign new dir authorities
982 * as appropriate.
984 static int
985 consider_adding_dir_authorities(or_options_t *options,
986 or_options_t *old_options)
988 config_line_t *cl;
989 int need_to_update =
990 !smartlist_len(router_get_trusted_dir_servers()) || !old_options ||
991 !config_lines_eq(options->DirServers, old_options->DirServers) ||
992 !config_lines_eq(options->AlternateBridgeAuthority,
993 old_options->AlternateBridgeAuthority) ||
994 !config_lines_eq(options->AlternateDirAuthority,
995 old_options->AlternateDirAuthority) ||
996 !config_lines_eq(options->AlternateHSAuthority,
997 old_options->AlternateHSAuthority);
999 if (!need_to_update)
1000 return 0; /* all done */
1002 /* Start from a clean slate. */
1003 clear_trusted_dir_servers();
1005 if (!options->DirServers) {
1006 /* then we may want some of the defaults */
1007 authority_type_t type = NO_AUTHORITY;
1008 if (!options->AlternateBridgeAuthority)
1009 type |= BRIDGE_AUTHORITY;
1010 if (!options->AlternateDirAuthority)
1011 type |= V1_AUTHORITY | V2_AUTHORITY | V3_AUTHORITY;
1012 if (!options->AlternateHSAuthority)
1013 type |= HIDSERV_AUTHORITY;
1014 add_default_trusted_dir_authorities(type);
1017 for (cl = options->DirServers; cl; cl = cl->next)
1018 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1019 return -1;
1020 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1021 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1022 return -1;
1023 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1024 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1025 return -1;
1026 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
1027 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1028 return -1;
1029 return 0;
1032 /** Fetch the active option list, and take actions based on it. All of the
1033 * things we do should survive being done repeatedly. If present,
1034 * <b>old_options</b> contains the previous value of the options.
1036 * Return 0 if all goes well, return -1 if things went badly.
1038 static int
1039 options_act_reversible(or_options_t *old_options, char **msg)
1041 smartlist_t *new_listeners = smartlist_create();
1042 smartlist_t *replaced_listeners = smartlist_create();
1043 static int libevent_initialized = 0;
1044 or_options_t *options = get_options();
1045 int running_tor = options->command == CMD_RUN_TOR;
1046 int set_conn_limit = 0;
1047 int r = -1;
1048 int logs_marked = 0;
1050 /* Daemonize _first_, since we only want to open most of this stuff in
1051 * the subprocess. Libevent bases can't be reliably inherited across
1052 * processes. */
1053 if (running_tor && options->RunAsDaemon) {
1054 /* No need to roll back, since you can't change the value. */
1055 start_daemon();
1058 #ifndef HAVE_SYS_UN_H
1059 if (options->ControlSocket) {
1060 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported"
1061 " on this OS/with this build.");
1062 goto rollback;
1064 #endif
1066 if (running_tor) {
1067 /* We need to set the connection limit before we can open the listeners. */
1068 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1069 &options->_ConnLimit) < 0) {
1070 *msg = tor_strdup("Problem with ConnLimit value. See logs for details.");
1071 goto rollback;
1073 set_conn_limit = 1;
1075 /* Set up libevent. (We need to do this before we can register the
1076 * listeners as listeners.) */
1077 if (running_tor && !libevent_initialized) {
1078 init_libevent();
1079 libevent_initialized = 1;
1082 /* Launch the listeners. (We do this before we setuid, so we can bind to
1083 * ports under 1024.) */
1084 if (retry_all_listeners(replaced_listeners, new_listeners) < 0) {
1085 *msg = tor_strdup("Failed to bind one of the listener ports.");
1086 goto rollback;
1090 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1091 /* Open /dev/pf before dropping privileges. */
1092 if (options->TransPort) {
1093 if (get_pf_socket() < 0) {
1094 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1095 goto rollback;
1098 #endif
1100 /* Setuid/setgid as appropriate */
1101 if (options->User) {
1102 if (switch_id(options->User) != 0) {
1103 /* No need to roll back, since you can't change the value. */
1104 *msg = tor_strdup("Problem with User value. See logs for details.");
1105 goto done;
1109 /* Ensure data directory is private; create if possible. */
1110 if (check_private_dir(options->DataDirectory,
1111 running_tor ? CPD_CREATE : CPD_CHECK)<0) {
1112 char buf[1024];
1113 int tmp = tor_snprintf(buf, sizeof(buf),
1114 "Couldn't access/create private data directory \"%s\"",
1115 options->DataDirectory);
1116 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1117 goto done;
1118 /* No need to roll back, since you can't change the value. */
1121 if (directory_caches_v2_dir_info(options)) {
1122 size_t len = strlen(options->DataDirectory)+32;
1123 char *fn = tor_malloc(len);
1124 tor_snprintf(fn, len, "%s"PATH_SEPARATOR"cached-status",
1125 options->DataDirectory);
1126 if (check_private_dir(fn, running_tor ? CPD_CREATE : CPD_CHECK) < 0) {
1127 char buf[1024];
1128 int tmp = tor_snprintf(buf, sizeof(buf),
1129 "Couldn't access/create private data directory \"%s\"", fn);
1130 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1131 tor_free(fn);
1132 goto done;
1134 tor_free(fn);
1137 /* Bail out at this point if we're not going to be a client or server:
1138 * we don't run Tor itself. */
1139 if (!running_tor)
1140 goto commit;
1142 mark_logs_temp(); /* Close current logs once new logs are open. */
1143 logs_marked = 1;
1144 if (options_init_logs(options, 0)<0) { /* Configure the log(s) */
1145 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1146 goto rollback;
1149 commit:
1150 r = 0;
1151 if (logs_marked) {
1152 log_severity_list_t *severity =
1153 tor_malloc_zero(sizeof(log_severity_list_t));
1154 close_temp_logs();
1155 add_callback_log(severity, control_event_logmsg);
1156 control_adjust_event_log_severity();
1157 tor_free(severity);
1159 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1161 log_notice(LD_NET, "Closing old %s on %s:%d",
1162 conn_type_to_string(conn->type), conn->address, conn->port);
1163 connection_close_immediate(conn);
1164 connection_mark_for_close(conn);
1166 goto done;
1168 rollback:
1169 r = -1;
1170 tor_assert(*msg);
1172 if (logs_marked) {
1173 rollback_log_changes();
1174 control_adjust_event_log_severity();
1177 if (set_conn_limit && old_options)
1178 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1179 &options->_ConnLimit);
1181 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1183 log_notice(LD_NET, "Closing partially-constructed listener %s on %s:%d",
1184 conn_type_to_string(conn->type), conn->address, conn->port);
1185 connection_close_immediate(conn);
1186 connection_mark_for_close(conn);
1189 done:
1190 smartlist_free(new_listeners);
1191 smartlist_free(replaced_listeners);
1192 return r;
1195 /** If we need to have a GEOIP ip-to-country map to run with our configured
1196 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1198 options_need_geoip_info(or_options_t *options, const char **reason_out)
1200 int bridge_usage =
1201 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1202 int routerset_usage =
1203 routerset_needs_geoip(options->EntryNodes) ||
1204 routerset_needs_geoip(options->ExitNodes) ||
1205 routerset_needs_geoip(options->ExcludeExitNodes) ||
1206 routerset_needs_geoip(options->ExcludeNodes);
1208 if (routerset_usage && reason_out) {
1209 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1210 "countries, and we need GEOIP information to figure out which ones they "
1211 "are.";
1212 } else if (bridge_usage && reason_out) {
1213 *reason_out = "We've been configured to see which countries can access "
1214 "us as a bridge, and we need GEOIP information to tell which countries "
1215 "clients are in.";
1217 return bridge_usage || routerset_usage;
1220 /** Return the bandwidthrate that we are going to report to the authorities
1221 * based on the config options. */
1222 uint32_t
1223 get_effective_bwrate(or_options_t *options)
1225 uint64_t bw = options->BandwidthRate;
1226 if (bw > options->MaxAdvertisedBandwidth)
1227 bw = options->MaxAdvertisedBandwidth;
1228 if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1229 bw = options->RelayBandwidthRate;
1231 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1232 return (uint32_t)bw;
1235 /** Return the bandwidthburst that we are going to report to the authorities
1236 * based on the config options. */
1237 uint32_t
1238 get_effective_bwburst(or_options_t *options)
1240 uint64_t bw = options->BandwidthBurst;
1241 if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1242 bw = options->RelayBandwidthBurst;
1243 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1244 return (uint32_t)bw;
1247 /** Fetch the active option list, and take actions based on it. All of the
1248 * things we do should survive being done repeatedly. If present,
1249 * <b>old_options</b> contains the previous value of the options.
1251 * Return 0 if all goes well, return -1 if it's time to die.
1253 * Note: We haven't moved all the "act on new configuration" logic
1254 * here yet. Some is still in do_hup() and other places.
1256 static int
1257 options_act(or_options_t *old_options)
1259 config_line_t *cl;
1260 or_options_t *options = get_options();
1261 int running_tor = options->command == CMD_RUN_TOR;
1262 char *msg;
1264 if (running_tor && !have_lockfile()) {
1265 if (try_locking(options, 1) < 0)
1266 return -1;
1269 if (consider_adding_dir_authorities(options, old_options) < 0)
1270 return -1;
1272 if (options->Bridges) {
1273 clear_bridge_list();
1274 for (cl = options->Bridges; cl; cl = cl->next) {
1275 if (parse_bridge_line(cl->value, 0)<0) {
1276 log_warn(LD_BUG,
1277 "Previously validated Bridge line could not be added!");
1278 return -1;
1283 if (running_tor && rend_config_services(options, 0)<0) {
1284 log_warn(LD_BUG,
1285 "Previously validated hidden services line could not be added!");
1286 return -1;
1289 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1290 log_warn(LD_BUG, "Previously validated client authorization for "
1291 "hidden services could not be added!");
1292 return -1;
1295 /* Load state */
1296 if (! global_state && running_tor) {
1297 if (or_state_load())
1298 return -1;
1299 rep_hist_load_mtbf_data(time(NULL));
1302 /* Bail out at this point if we're not going to be a client or server:
1303 * we want to not fork, and to log stuff to stderr. */
1304 if (!running_tor)
1305 return 0;
1307 /* Finish backgrounding the process */
1308 if (running_tor && options->RunAsDaemon) {
1309 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1310 finish_daemon(options->DataDirectory);
1313 /* Write our PID to the PID file. If we do not have write permissions we
1314 * will log a warning */
1315 if (running_tor && options->PidFile)
1316 write_pidfile(options->PidFile);
1318 /* Register addressmap directives */
1319 config_register_addressmaps(options);
1320 parse_virtual_addr_network(options->VirtualAddrNetwork, 0, &msg);
1322 /* Update address policies. */
1323 if (policies_parse_from_options(options) < 0) {
1324 /* This should be impossible, but let's be sure. */
1325 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1326 return -1;
1329 if (init_cookie_authentication(options->CookieAuthentication) < 0) {
1330 log_warn(LD_CONFIG,"Error creating cookie authentication file.");
1331 return -1;
1334 /* reload keys as needed for rendezvous services. */
1335 if (rend_service_load_keys()<0) {
1336 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1337 return -1;
1340 /* Set up accounting */
1341 if (accounting_parse_options(options, 0)<0) {
1342 log_warn(LD_CONFIG,"Error in accounting options");
1343 return -1;
1345 if (accounting_is_enabled(options))
1346 configure_accounting(time(NULL));
1348 /* Check for transitions that need action. */
1349 if (old_options) {
1350 if (options->UseEntryGuards && !old_options->UseEntryGuards) {
1351 log_info(LD_CIRC,
1352 "Switching to entry guards; abandoning previous circuits");
1353 circuit_mark_all_unused_circs();
1354 circuit_expire_all_dirty_circs();
1357 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
1358 log_info(LD_GENERAL, "Bridge status changed. Forgetting GeoIP stats.");
1359 geoip_remove_old_clients(time(NULL)+(2*60*60));
1362 if (options_transition_affects_workers(old_options, options)) {
1363 log_info(LD_GENERAL,
1364 "Worker-related options changed. Rotating workers.");
1365 if (server_mode(options) && !server_mode(old_options)) {
1366 if (init_keys() < 0) {
1367 log_warn(LD_BUG,"Error initializing keys; exiting");
1368 return -1;
1370 ip_address_changed(0);
1371 if (has_completed_circuit || !any_predicted_circuits(time(NULL)))
1372 inform_testing_reachability();
1374 cpuworkers_rotate();
1375 if (dns_reset())
1376 return -1;
1377 } else {
1378 if (dns_reset())
1379 return -1;
1382 if (options->V3AuthoritativeDir && !old_options->V3AuthoritativeDir)
1383 init_keys();
1386 /* Maybe load geoip file */
1387 if (options->GeoIPFile &&
1388 ((!old_options || !opt_streq(old_options->GeoIPFile, options->GeoIPFile))
1389 || !geoip_is_loaded())) {
1390 /* XXXX Don't use this "<default>" junk; make our filename options
1391 * understand prefixes somehow. -NM */
1392 /* XXXX021 Reload GeoIPFile on SIGHUP. -NM */
1393 char *actual_fname = tor_strdup(options->GeoIPFile);
1394 #ifdef WIN32
1395 if (!strcmp(actual_fname, "<default>")) {
1396 const char *conf_root = get_windows_conf_root();
1397 size_t len = strlen(conf_root)+16;
1398 tor_free(actual_fname);
1399 actual_fname = tor_malloc(len+1);
1400 tor_snprintf(actual_fname, len, "%s\\geoip", conf_root);
1402 #endif
1403 geoip_load_file(actual_fname, options);
1404 tor_free(actual_fname);
1406 #ifdef ENABLE_GEOIP_STATS
1407 log_warn(LD_CONFIG, "We are configured to measure GeoIP statistics, but "
1408 "the way these statistics are measured has changed "
1409 "significantly in later versions of Tor. The results may not be "
1410 "as expected if you are used to later versions. Be sure you "
1411 "know what you are doing.");
1412 #endif
1413 /* Check if we need to parse and add the EntryNodes config option. */
1414 if (options->EntryNodes &&
1415 (!old_options ||
1416 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
1417 entry_nodes_should_be_added();
1419 /* Since our options changed, we might need to regenerate and upload our
1420 * server descriptor.
1422 if (!old_options ||
1423 options_transition_affects_descriptor(old_options, options))
1424 mark_my_descriptor_dirty();
1426 /* We may need to reschedule some directory stuff if our status changed. */
1427 if (old_options) {
1428 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1429 dirvote_recalculate_timing(options, time(NULL));
1430 if (!bool_eq(directory_fetches_dir_info_early(options),
1431 directory_fetches_dir_info_early(old_options)) ||
1432 !bool_eq(directory_fetches_dir_info_later(options),
1433 directory_fetches_dir_info_later(old_options))) {
1434 /* Make sure update_router_have_min_dir_info gets called. */
1435 router_dir_info_changed();
1436 /* We might need to download a new consensus status later or sooner than
1437 * we had expected. */
1438 update_consensus_networkstatus_fetch_time(time(NULL));
1442 /* Load the webpage we're going to serve every time someone asks for '/' on
1443 our DirPort. */
1444 tor_free(global_dirfrontpagecontents);
1445 if (options->DirPortFrontPage) {
1446 global_dirfrontpagecontents =
1447 read_file_to_str(options->DirPortFrontPage, 0, NULL);
1448 if (!global_dirfrontpagecontents) {
1449 log_warn(LD_CONFIG,
1450 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1451 options->DirPortFrontPage);
1455 return 0;
1459 * Functions to parse config options
1462 /** If <b>option</b> is an official abbreviation for a longer option,
1463 * return the longer option. Otherwise return <b>option</b>.
1464 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1465 * apply abbreviations that work for the config file and the command line.
1466 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1467 static const char *
1468 expand_abbrev(config_format_t *fmt, const char *option, int command_line,
1469 int warn_obsolete)
1471 int i;
1472 if (! fmt->abbrevs)
1473 return option;
1474 for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
1475 /* Abbreviations are case insensitive. */
1476 if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
1477 (command_line || !fmt->abbrevs[i].commandline_only)) {
1478 if (warn_obsolete && fmt->abbrevs[i].warn) {
1479 log_warn(LD_CONFIG,
1480 "The configuration option '%s' is deprecated; "
1481 "use '%s' instead.",
1482 fmt->abbrevs[i].abbreviated,
1483 fmt->abbrevs[i].full);
1485 return fmt->abbrevs[i].full;
1488 return option;
1491 /** Helper: Read a list of configuration options from the command line.
1492 * If successful, put them in *<b>result</b> and return 0, and return
1493 * -1 and leave *<b>result</b> alone. */
1494 static int
1495 config_get_commandlines(int argc, char **argv, config_line_t **result)
1497 config_line_t *front = NULL;
1498 config_line_t **new = &front;
1499 char *s;
1500 int i = 1;
1502 while (i < argc) {
1503 if (!strcmp(argv[i],"-f") ||
1504 !strcmp(argv[i],"--hash-password")) {
1505 i += 2; /* command-line option with argument. ignore them. */
1506 continue;
1507 } else if (!strcmp(argv[i],"--list-fingerprint") ||
1508 !strcmp(argv[i],"--verify-config") ||
1509 !strcmp(argv[i],"--ignore-missing-torrc") ||
1510 !strcmp(argv[i],"--quiet") ||
1511 !strcmp(argv[i],"--hush")) {
1512 i += 1; /* command-line option. ignore it. */
1513 continue;
1514 } else if (!strcmp(argv[i],"--nt-service") ||
1515 !strcmp(argv[i],"-nt-service")) {
1516 i += 1;
1517 continue;
1520 if (i == argc-1) {
1521 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1522 argv[i]);
1523 config_free_lines(front);
1524 return -1;
1527 *new = tor_malloc_zero(sizeof(config_line_t));
1528 s = argv[i];
1530 while (*s == '-')
1531 s++;
1533 (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1, 1));
1534 (*new)->value = tor_strdup(argv[i+1]);
1535 (*new)->next = NULL;
1536 log(LOG_DEBUG, LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
1537 (*new)->key, (*new)->value);
1539 new = &((*new)->next);
1540 i += 2;
1542 *result = front;
1543 return 0;
1546 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1547 * append it to *<b>lst</b>. */
1548 static void
1549 config_line_append(config_line_t **lst,
1550 const char *key,
1551 const char *val)
1553 config_line_t *newline;
1555 newline = tor_malloc(sizeof(config_line_t));
1556 newline->key = tor_strdup(key);
1557 newline->value = tor_strdup(val);
1558 newline->next = NULL;
1559 while (*lst)
1560 lst = &((*lst)->next);
1562 (*lst) = newline;
1565 /** Helper: parse the config string and strdup into key/value
1566 * strings. Set *result to the list, or NULL if parsing the string
1567 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1568 * misformatted lines. */
1570 config_get_lines(const char *string, config_line_t **result)
1572 config_line_t *list = NULL, **next;
1573 char *k, *v;
1575 next = &list;
1576 do {
1577 k = v = NULL;
1578 string = parse_config_line_from_str(string, &k, &v);
1579 if (!string) {
1580 config_free_lines(list);
1581 tor_free(k);
1582 tor_free(v);
1583 return -1;
1585 if (k && v) {
1586 /* This list can get long, so we keep a pointer to the end of it
1587 * rather than using config_line_append over and over and getting
1588 * n^2 performance. */
1589 *next = tor_malloc(sizeof(config_line_t));
1590 (*next)->key = k;
1591 (*next)->value = v;
1592 (*next)->next = NULL;
1593 next = &((*next)->next);
1594 } else {
1595 tor_free(k);
1596 tor_free(v);
1598 } while (*string);
1600 *result = list;
1601 return 0;
1605 * Free all the configuration lines on the linked list <b>front</b>.
1607 void
1608 config_free_lines(config_line_t *front)
1610 config_line_t *tmp;
1612 while (front) {
1613 tmp = front;
1614 front = tmp->next;
1616 tor_free(tmp->key);
1617 tor_free(tmp->value);
1618 tor_free(tmp);
1622 /** Return the description for a given configuration variable, or NULL if no
1623 * description exists. */
1624 static const char *
1625 config_find_description(config_format_t *fmt, const char *name)
1627 int i;
1628 for (i=0; fmt->descriptions[i].name; ++i) {
1629 if (!strcasecmp(name, fmt->descriptions[i].name))
1630 return fmt->descriptions[i].description;
1632 return NULL;
1635 /** If <b>key</b> is a configuration option, return the corresponding
1636 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1637 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1639 static config_var_t *
1640 config_find_option(config_format_t *fmt, const char *key)
1642 int i;
1643 size_t keylen = strlen(key);
1644 if (!keylen)
1645 return NULL; /* if they say "--" on the command line, it's not an option */
1646 /* First, check for an exact (case-insensitive) match */
1647 for (i=0; fmt->vars[i].name; ++i) {
1648 if (!strcasecmp(key, fmt->vars[i].name)) {
1649 return &fmt->vars[i];
1652 /* If none, check for an abbreviated match */
1653 for (i=0; fmt->vars[i].name; ++i) {
1654 if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
1655 log_warn(LD_CONFIG, "The abbreviation '%s' is deprecated. "
1656 "Please use '%s' instead",
1657 key, fmt->vars[i].name);
1658 return &fmt->vars[i];
1661 /* Okay, unrecognized option */
1662 return NULL;
1666 * Functions to assign config options.
1669 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1670 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1672 * Called from config_assign_line() and option_reset().
1674 static int
1675 config_assign_value(config_format_t *fmt, or_options_t *options,
1676 config_line_t *c, char **msg)
1678 int i, r, ok;
1679 char buf[1024];
1680 config_var_t *var;
1681 void *lvalue;
1683 CHECK(fmt, options);
1685 var = config_find_option(fmt, c->key);
1686 tor_assert(var);
1688 lvalue = STRUCT_VAR_P(options, var->var_offset);
1690 switch (var->type) {
1692 case CONFIG_TYPE_UINT:
1693 i = (int)tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
1694 if (!ok) {
1695 r = tor_snprintf(buf, sizeof(buf),
1696 "Int keyword '%s %s' is malformed or out of bounds.",
1697 c->key, c->value);
1698 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1699 return -1;
1701 *(int *)lvalue = i;
1702 break;
1704 case CONFIG_TYPE_INTERVAL: {
1705 i = config_parse_interval(c->value, &ok);
1706 if (!ok) {
1707 r = tor_snprintf(buf, sizeof(buf),
1708 "Interval '%s %s' is malformed or out of bounds.",
1709 c->key, c->value);
1710 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1711 return -1;
1713 *(int *)lvalue = i;
1714 break;
1717 case CONFIG_TYPE_MEMUNIT: {
1718 uint64_t u64 = config_parse_memunit(c->value, &ok);
1719 if (!ok) {
1720 r = tor_snprintf(buf, sizeof(buf),
1721 "Value '%s %s' is malformed or out of bounds.",
1722 c->key, c->value);
1723 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1724 return -1;
1726 *(uint64_t *)lvalue = u64;
1727 break;
1730 case CONFIG_TYPE_BOOL:
1731 i = (int)tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
1732 if (!ok) {
1733 r = tor_snprintf(buf, sizeof(buf),
1734 "Boolean '%s %s' expects 0 or 1.",
1735 c->key, c->value);
1736 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1737 return -1;
1739 *(int *)lvalue = i;
1740 break;
1742 case CONFIG_TYPE_STRING:
1743 case CONFIG_TYPE_FILENAME:
1744 tor_free(*(char **)lvalue);
1745 *(char **)lvalue = tor_strdup(c->value);
1746 break;
1748 case CONFIG_TYPE_DOUBLE:
1749 *(double *)lvalue = atof(c->value);
1750 break;
1752 case CONFIG_TYPE_ISOTIME:
1753 if (parse_iso_time(c->value, (time_t *)lvalue)) {
1754 r = tor_snprintf(buf, sizeof(buf),
1755 "Invalid time '%s' for keyword '%s'", c->value, c->key);
1756 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1757 return -1;
1759 break;
1761 case CONFIG_TYPE_ROUTERSET:
1762 if (*(routerset_t**)lvalue) {
1763 routerset_free(*(routerset_t**)lvalue);
1765 *(routerset_t**)lvalue = routerset_new();
1766 if (routerset_parse(*(routerset_t**)lvalue, c->value, c->key)<0) {
1767 tor_snprintf(buf, sizeof(buf), "Invalid exit list '%s' for option '%s'",
1768 c->value, c->key);
1769 *msg = tor_strdup(buf);
1770 return -1;
1772 break;
1774 case CONFIG_TYPE_CSV:
1775 if (*(smartlist_t**)lvalue) {
1776 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
1777 smartlist_clear(*(smartlist_t**)lvalue);
1778 } else {
1779 *(smartlist_t**)lvalue = smartlist_create();
1782 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
1783 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1784 break;
1786 case CONFIG_TYPE_LINELIST:
1787 case CONFIG_TYPE_LINELIST_S:
1788 config_line_append((config_line_t**)lvalue, c->key, c->value);
1789 break;
1790 case CONFIG_TYPE_OBSOLETE:
1791 log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
1792 break;
1793 case CONFIG_TYPE_LINELIST_V:
1794 r = tor_snprintf(buf, sizeof(buf),
1795 "You may not provide a value for virtual option '%s'", c->key);
1796 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1797 return -1;
1798 default:
1799 tor_assert(0);
1800 break;
1802 return 0;
1805 /** If <b>c</b> is a syntactically valid configuration line, update
1806 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1807 * key, -2 for bad value.
1809 * If <b>clear_first</b> is set, clear the value first. Then if
1810 * <b>use_defaults</b> is set, set the value to the default.
1812 * Called from config_assign().
1814 static int
1815 config_assign_line(config_format_t *fmt, or_options_t *options,
1816 config_line_t *c, int use_defaults,
1817 int clear_first, char **msg)
1819 config_var_t *var;
1821 CHECK(fmt, options);
1823 var = config_find_option(fmt, c->key);
1824 if (!var) {
1825 if (fmt->extra) {
1826 void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
1827 log_info(LD_CONFIG,
1828 "Found unrecognized option '%s'; saving it.", c->key);
1829 config_line_append((config_line_t**)lvalue, c->key, c->value);
1830 return 0;
1831 } else {
1832 char buf[1024];
1833 int tmp = tor_snprintf(buf, sizeof(buf),
1834 "Unknown option '%s'. Failing.", c->key);
1835 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1836 return -1;
1839 /* Put keyword into canonical case. */
1840 if (strcmp(var->name, c->key)) {
1841 tor_free(c->key);
1842 c->key = tor_strdup(var->name);
1845 if (!strlen(c->value)) {
1846 /* reset or clear it, then return */
1847 if (!clear_first) {
1848 if (var->type == CONFIG_TYPE_LINELIST ||
1849 var->type == CONFIG_TYPE_LINELIST_S) {
1850 /* We got an empty linelist from the torrc or command line.
1851 As a special case, call this an error. Warn and ignore. */
1852 log_warn(LD_CONFIG,
1853 "Linelist option '%s' has no value. Skipping.", c->key);
1854 } else { /* not already cleared */
1855 option_reset(fmt, options, var, use_defaults);
1858 return 0;
1861 if (config_assign_value(fmt, options, c, msg) < 0)
1862 return -2;
1863 return 0;
1866 /** Restore the option named <b>key</b> in options to its default value.
1867 * Called from config_assign(). */
1868 static void
1869 config_reset_line(config_format_t *fmt, or_options_t *options,
1870 const char *key, int use_defaults)
1872 config_var_t *var;
1874 CHECK(fmt, options);
1876 var = config_find_option(fmt, key);
1877 if (!var)
1878 return; /* give error on next pass. */
1880 option_reset(fmt, options, var, use_defaults);
1883 /** Return true iff key is a valid configuration option. */
1885 option_is_recognized(const char *key)
1887 config_var_t *var = config_find_option(&options_format, key);
1888 return (var != NULL);
1891 /** Return the canonical name of a configuration option, or NULL
1892 * if no such option exists. */
1893 const char *
1894 option_get_canonical_name(const char *key)
1896 config_var_t *var = config_find_option(&options_format, key);
1897 return var ? var->name : NULL;
1900 /** Return a canonical list of the options assigned for key.
1902 config_line_t *
1903 option_get_assignment(or_options_t *options, const char *key)
1905 return get_assigned_option(&options_format, options, key, 1);
1908 /** Return true iff value needs to be quoted and escaped to be used in
1909 * a configuration file. */
1910 static int
1911 config_value_needs_escape(const char *value)
1913 if (*value == '\"')
1914 return 1;
1915 while (*value) {
1916 switch (*value)
1918 case '\r':
1919 case '\n':
1920 case '#':
1921 /* Note: quotes and backspaces need special handling when we are using
1922 * quotes, not otherwise, so they don't trigger escaping on their
1923 * own. */
1924 return 1;
1925 default:
1926 if (!TOR_ISPRINT(*value))
1927 return 1;
1929 ++value;
1931 return 0;
1934 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1935 static config_line_t *
1936 config_lines_dup(const config_line_t *inp)
1938 config_line_t *result = NULL;
1939 config_line_t **next_out = &result;
1940 while (inp) {
1941 *next_out = tor_malloc(sizeof(config_line_t));
1942 (*next_out)->key = tor_strdup(inp->key);
1943 (*next_out)->value = tor_strdup(inp->value);
1944 inp = inp->next;
1945 next_out = &((*next_out)->next);
1947 (*next_out) = NULL;
1948 return result;
1951 /** Return newly allocated line or lines corresponding to <b>key</b> in the
1952 * configuration <b>options</b>. If <b>escape_val</b> is true and a
1953 * value needs to be quoted before it's put in a config file, quote and
1954 * escape that value. Return NULL if no such key exists. */
1955 static config_line_t *
1956 get_assigned_option(config_format_t *fmt, void *options,
1957 const char *key, int escape_val)
1959 config_var_t *var;
1960 const void *value;
1961 char buf[32];
1962 config_line_t *result;
1963 tor_assert(options && key);
1965 CHECK(fmt, options);
1967 var = config_find_option(fmt, key);
1968 if (!var) {
1969 log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
1970 return NULL;
1972 value = STRUCT_VAR_P(options, var->var_offset);
1974 result = tor_malloc_zero(sizeof(config_line_t));
1975 result->key = tor_strdup(var->name);
1976 switch (var->type)
1978 case CONFIG_TYPE_STRING:
1979 case CONFIG_TYPE_FILENAME:
1980 if (*(char**)value) {
1981 result->value = tor_strdup(*(char**)value);
1982 } else {
1983 tor_free(result->key);
1984 tor_free(result);
1985 return NULL;
1987 break;
1988 case CONFIG_TYPE_ISOTIME:
1989 if (*(time_t*)value) {
1990 result->value = tor_malloc(ISO_TIME_LEN+1);
1991 format_iso_time(result->value, *(time_t*)value);
1992 } else {
1993 tor_free(result->key);
1994 tor_free(result);
1996 escape_val = 0; /* Can't need escape. */
1997 break;
1998 case CONFIG_TYPE_INTERVAL:
1999 case CONFIG_TYPE_UINT:
2000 /* This means every or_options_t uint or bool element
2001 * needs to be an int. Not, say, a uint16_t or char. */
2002 tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
2003 result->value = tor_strdup(buf);
2004 escape_val = 0; /* Can't need escape. */
2005 break;
2006 case CONFIG_TYPE_MEMUNIT:
2007 tor_snprintf(buf, sizeof(buf), U64_FORMAT,
2008 U64_PRINTF_ARG(*(uint64_t*)value));
2009 result->value = tor_strdup(buf);
2010 escape_val = 0; /* Can't need escape. */
2011 break;
2012 case CONFIG_TYPE_DOUBLE:
2013 tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
2014 result->value = tor_strdup(buf);
2015 escape_val = 0; /* Can't need escape. */
2016 break;
2017 case CONFIG_TYPE_BOOL:
2018 result->value = tor_strdup(*(int*)value ? "1" : "0");
2019 escape_val = 0; /* Can't need escape. */
2020 break;
2021 case CONFIG_TYPE_ROUTERSET:
2022 result->value = routerset_to_string(*(routerset_t**)value);
2023 break;
2024 case CONFIG_TYPE_CSV:
2025 if (*(smartlist_t**)value)
2026 result->value =
2027 smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
2028 else
2029 result->value = tor_strdup("");
2030 break;
2031 case CONFIG_TYPE_OBSOLETE:
2032 log_fn(LOG_PROTOCOL_WARN, LD_CONFIG,
2033 "You asked me for the value of an obsolete config option '%s'.",
2034 key);
2035 tor_free(result->key);
2036 tor_free(result);
2037 return NULL;
2038 case CONFIG_TYPE_LINELIST_S:
2039 log_warn(LD_CONFIG,
2040 "Can't return context-sensitive '%s' on its own", key);
2041 tor_free(result->key);
2042 tor_free(result);
2043 return NULL;
2044 case CONFIG_TYPE_LINELIST:
2045 case CONFIG_TYPE_LINELIST_V:
2046 tor_free(result->key);
2047 tor_free(result);
2048 result = config_lines_dup(*(const config_line_t**)value);
2049 break;
2050 default:
2051 tor_free(result->key);
2052 tor_free(result);
2053 log_warn(LD_BUG,"Unknown type %d for known key '%s'",
2054 var->type, key);
2055 return NULL;
2058 if (escape_val) {
2059 config_line_t *line;
2060 for (line = result; line; line = line->next) {
2061 if (line->value && config_value_needs_escape(line->value)) {
2062 char *newval = esc_for_log(line->value);
2063 tor_free(line->value);
2064 line->value = newval;
2069 return result;
2072 /** Iterate through the linked list of requested options <b>list</b>.
2073 * For each item, convert as appropriate and assign to <b>options</b>.
2074 * If an item is unrecognized, set *msg and return -1 immediately,
2075 * else return 0 for success.
2077 * If <b>clear_first</b>, interpret config options as replacing (not
2078 * extending) their previous values. If <b>clear_first</b> is set,
2079 * then <b>use_defaults</b> to decide if you set to defaults after
2080 * clearing, or make the value 0 or NULL.
2082 * Here are the use cases:
2083 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
2084 * if linelist, replaces current if csv.
2085 * 2. An empty AllowInvalid line in your torrc. Should clear it.
2086 * 3. "RESETCONF AllowInvalid" sets it to default.
2087 * 4. "SETCONF AllowInvalid" makes it NULL.
2088 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
2090 * Use_defaults Clear_first
2091 * 0 0 "append"
2092 * 1 0 undefined, don't use
2093 * 0 1 "set to null first"
2094 * 1 1 "set to defaults first"
2095 * Return 0 on success, -1 on bad key, -2 on bad value.
2097 * As an additional special case, if a LINELIST config option has
2098 * no value and clear_first is 0, then warn and ignore it.
2102 There are three call cases for config_assign() currently.
2104 Case one: Torrc entry
2105 options_init_from_torrc() calls config_assign(0, 0)
2106 calls config_assign_line(0, 0).
2107 if value is empty, calls option_reset(0) and returns.
2108 calls config_assign_value(), appends.
2110 Case two: setconf
2111 options_trial_assign() calls config_assign(0, 1)
2112 calls config_reset_line(0)
2113 calls option_reset(0)
2114 calls option_clear().
2115 calls config_assign_line(0, 1).
2116 if value is empty, returns.
2117 calls config_assign_value(), appends.
2119 Case three: resetconf
2120 options_trial_assign() calls config_assign(1, 1)
2121 calls config_reset_line(1)
2122 calls option_reset(1)
2123 calls option_clear().
2124 calls config_assign_value(default)
2125 calls config_assign_line(1, 1).
2126 returns.
2128 static int
2129 config_assign(config_format_t *fmt, void *options, config_line_t *list,
2130 int use_defaults, int clear_first, char **msg)
2132 config_line_t *p;
2134 CHECK(fmt, options);
2136 /* pass 1: normalize keys */
2137 for (p = list; p; p = p->next) {
2138 const char *full = expand_abbrev(fmt, p->key, 0, 1);
2139 if (strcmp(full,p->key)) {
2140 tor_free(p->key);
2141 p->key = tor_strdup(full);
2145 /* pass 2: if we're reading from a resetting source, clear all
2146 * mentioned config options, and maybe set to their defaults. */
2147 if (clear_first) {
2148 for (p = list; p; p = p->next)
2149 config_reset_line(fmt, options, p->key, use_defaults);
2152 /* pass 3: assign. */
2153 while (list) {
2154 int r;
2155 if ((r=config_assign_line(fmt, options, list, use_defaults,
2156 clear_first, msg)))
2157 return r;
2158 list = list->next;
2160 return 0;
2163 /** Try assigning <b>list</b> to the global options. You do this by duping
2164 * options, assigning list to the new one, then validating it. If it's
2165 * ok, then throw out the old one and stick with the new one. Else,
2166 * revert to old and return failure. Return SETOPT_OK on success, or
2167 * a setopt_err_t on failure.
2169 * If not success, point *<b>msg</b> to a newly allocated string describing
2170 * what went wrong.
2172 setopt_err_t
2173 options_trial_assign(config_line_t *list, int use_defaults,
2174 int clear_first, char **msg)
2176 int r;
2177 or_options_t *trial_options = options_dup(&options_format, get_options());
2179 if ((r=config_assign(&options_format, trial_options,
2180 list, use_defaults, clear_first, msg)) < 0) {
2181 config_free(&options_format, trial_options);
2182 return r;
2185 if (options_validate(get_options(), trial_options, 1, msg) < 0) {
2186 config_free(&options_format, trial_options);
2187 return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2190 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2191 config_free(&options_format, trial_options);
2192 return SETOPT_ERR_TRANSITION;
2195 if (set_options(trial_options, msg)<0) {
2196 config_free(&options_format, trial_options);
2197 return SETOPT_ERR_SETTING;
2200 /* we liked it. put it in place. */
2201 return SETOPT_OK;
2204 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2205 * Called from option_reset() and config_free(). */
2206 static void
2207 option_clear(config_format_t *fmt, or_options_t *options, config_var_t *var)
2209 void *lvalue = STRUCT_VAR_P(options, var->var_offset);
2210 (void)fmt; /* unused */
2211 switch (var->type) {
2212 case CONFIG_TYPE_STRING:
2213 case CONFIG_TYPE_FILENAME:
2214 tor_free(*(char**)lvalue);
2215 break;
2216 case CONFIG_TYPE_DOUBLE:
2217 *(double*)lvalue = 0.0;
2218 break;
2219 case CONFIG_TYPE_ISOTIME:
2220 *(time_t*)lvalue = 0;
2221 break;
2222 case CONFIG_TYPE_INTERVAL:
2223 case CONFIG_TYPE_UINT:
2224 case CONFIG_TYPE_BOOL:
2225 *(int*)lvalue = 0;
2226 break;
2227 case CONFIG_TYPE_MEMUNIT:
2228 *(uint64_t*)lvalue = 0;
2229 break;
2230 case CONFIG_TYPE_ROUTERSET:
2231 if (*(routerset_t**)lvalue) {
2232 routerset_free(*(routerset_t**)lvalue);
2233 *(routerset_t**)lvalue = NULL;
2235 break;
2236 case CONFIG_TYPE_CSV:
2237 if (*(smartlist_t**)lvalue) {
2238 SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
2239 smartlist_free(*(smartlist_t **)lvalue);
2240 *(smartlist_t **)lvalue = NULL;
2242 break;
2243 case CONFIG_TYPE_LINELIST:
2244 case CONFIG_TYPE_LINELIST_S:
2245 config_free_lines(*(config_line_t **)lvalue);
2246 *(config_line_t **)lvalue = NULL;
2247 break;
2248 case CONFIG_TYPE_LINELIST_V:
2249 /* handled by linelist_s. */
2250 break;
2251 case CONFIG_TYPE_OBSOLETE:
2252 break;
2256 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2257 * <b>use_defaults</b>, set it to its default value.
2258 * Called by config_init() and option_reset_line() and option_assign_line(). */
2259 static void
2260 option_reset(config_format_t *fmt, or_options_t *options,
2261 config_var_t *var, int use_defaults)
2263 config_line_t *c;
2264 char *msg = NULL;
2265 CHECK(fmt, options);
2266 option_clear(fmt, options, var); /* clear it first */
2267 if (!use_defaults)
2268 return; /* all done */
2269 if (var->initvalue) {
2270 c = tor_malloc_zero(sizeof(config_line_t));
2271 c->key = tor_strdup(var->name);
2272 c->value = tor_strdup(var->initvalue);
2273 if (config_assign_value(fmt, options, c, &msg) < 0) {
2274 log_warn(LD_BUG, "Failed to assign default: %s", msg);
2275 tor_free(msg); /* if this happens it's a bug */
2277 config_free_lines(c);
2281 /** Print a usage message for tor. */
2282 static void
2283 print_usage(void)
2285 printf(
2286 "Copyright (c) 2001-2004, Roger Dingledine\n"
2287 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2288 "Copyright (c) 2007-2011, The Tor Project, Inc.\n\n"
2289 "tor -f <torrc> [args]\n"
2290 "See man page for options, or https://www.torproject.org/ for "
2291 "documentation.\n");
2294 /** Print all non-obsolete torrc options. */
2295 static void
2296 list_torrc_options(void)
2298 int i;
2299 smartlist_t *lines = smartlist_create();
2300 for (i = 0; _option_vars[i].name; ++i) {
2301 config_var_t *var = &_option_vars[i];
2302 const char *desc;
2303 if (var->type == CONFIG_TYPE_OBSOLETE ||
2304 var->type == CONFIG_TYPE_LINELIST_V)
2305 continue;
2306 desc = config_find_description(&options_format, var->name);
2307 printf("%s\n", var->name);
2308 if (desc) {
2309 wrap_string(lines, desc, 76, " ", " ");
2310 SMARTLIST_FOREACH(lines, char *, cp, {
2311 printf("%s", cp);
2312 tor_free(cp);
2314 smartlist_clear(lines);
2317 smartlist_free(lines);
2320 /** Last value actually set by resolve_my_address. */
2321 static uint32_t last_resolved_addr = 0;
2323 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2324 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2325 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2326 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2327 * public IP address.
2330 resolve_my_address(int warn_severity, or_options_t *options,
2331 uint32_t *addr_out, char **hostname_out)
2333 struct in_addr in;
2334 uint32_t addr;
2335 char hostname[256];
2336 int explicit_ip=1;
2337 int explicit_hostname=1;
2338 int from_interface=0;
2339 char tmpbuf[INET_NTOA_BUF_LEN];
2340 const char *address = options->Address;
2341 int notice_severity = warn_severity <= LOG_NOTICE ?
2342 LOG_NOTICE : warn_severity;
2344 tor_assert(addr_out);
2346 if (address && *address) {
2347 strlcpy(hostname, address, sizeof(hostname));
2348 } else { /* then we need to guess our address */
2349 explicit_ip = 0; /* it's implicit */
2350 explicit_hostname = 0; /* it's implicit */
2352 if (gethostname(hostname, sizeof(hostname)) < 0) {
2353 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2354 return -1;
2356 log_debug(LD_CONFIG,"Guessed local host name as '%s'",hostname);
2359 /* now we know hostname. resolve it and keep only the IP address */
2361 if (tor_inet_aton(hostname, &in) == 0) {
2362 /* then we have to resolve it */
2363 explicit_ip = 0;
2364 if (tor_lookup_hostname(hostname, &addr)) {
2365 uint32_t interface_ip;
2367 if (explicit_hostname) {
2368 log_fn(warn_severity, LD_CONFIG,
2369 "Could not resolve local Address '%s'. Failing.", hostname);
2370 return -1;
2372 log_fn(notice_severity, LD_CONFIG,
2373 "Could not resolve guessed local hostname '%s'. "
2374 "Trying something else.", hostname);
2375 if (get_interface_address(warn_severity, &interface_ip)) {
2376 log_fn(warn_severity, LD_CONFIG,
2377 "Could not get local interface IP address. Failing.");
2378 return -1;
2380 from_interface = 1;
2381 in.s_addr = htonl(interface_ip);
2382 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2383 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2384 "local interface. Using that.", tmpbuf);
2385 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2386 } else {
2387 in.s_addr = htonl(addr);
2389 if (!explicit_hostname &&
2390 is_internal_IP(ntohl(in.s_addr), 0)) {
2391 uint32_t interface_ip;
2393 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2394 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2395 "resolves to a private IP address (%s). Trying something "
2396 "else.", hostname, tmpbuf);
2398 if (get_interface_address(warn_severity, &interface_ip)) {
2399 log_fn(warn_severity, LD_CONFIG,
2400 "Could not get local interface IP address. Too bad.");
2401 } else if (is_internal_IP(interface_ip, 0)) {
2402 struct in_addr in2;
2403 in2.s_addr = htonl(interface_ip);
2404 tor_inet_ntoa(&in2,tmpbuf,sizeof(tmpbuf));
2405 log_fn(notice_severity, LD_CONFIG,
2406 "Interface IP address '%s' is a private address too. "
2407 "Ignoring.", tmpbuf);
2408 } else {
2409 from_interface = 1;
2410 in.s_addr = htonl(interface_ip);
2411 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2412 log_fn(notice_severity, LD_CONFIG,
2413 "Learned IP address '%s' for local interface."
2414 " Using that.", tmpbuf);
2415 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2421 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2422 if (is_internal_IP(ntohl(in.s_addr), 0)) {
2423 /* make sure we're ok with publishing an internal IP */
2424 if (!options->DirServers && !options->AlternateDirAuthority) {
2425 /* if they are using the default dirservers, disallow internal IPs
2426 * always. */
2427 log_fn(warn_severity, LD_CONFIG,
2428 "Address '%s' resolves to private IP address '%s'. "
2429 "Tor servers that use the default DirServers must have public "
2430 "IP addresses.", hostname, tmpbuf);
2431 return -1;
2433 if (!explicit_ip) {
2434 /* even if they've set their own dirservers, require an explicit IP if
2435 * they're using an internal address. */
2436 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2437 "IP address '%s'. Please set the Address config option to be "
2438 "the IP address you want to use.", hostname, tmpbuf);
2439 return -1;
2443 log_debug(LD_CONFIG, "Resolved Address to '%s'.", tmpbuf);
2444 *addr_out = ntohl(in.s_addr);
2445 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2446 /* Leave this as a notice, regardless of the requested severity,
2447 * at least until dynamic IP address support becomes bulletproof. */
2448 log_notice(LD_NET,
2449 "Your IP address seems to have changed to %s. Updating.",
2450 tmpbuf);
2451 ip_address_changed(0);
2453 if (last_resolved_addr != *addr_out) {
2454 const char *method;
2455 const char *h = hostname;
2456 if (explicit_ip) {
2457 method = "CONFIGURED";
2458 h = NULL;
2459 } else if (explicit_hostname) {
2460 method = "RESOLVED";
2461 } else if (from_interface) {
2462 method = "INTERFACE";
2463 h = NULL;
2464 } else {
2465 method = "GETHOSTNAME";
2467 control_event_server_status(LOG_NOTICE,
2468 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2469 tmpbuf, method, h?"HOSTNAME=":"", h);
2471 last_resolved_addr = *addr_out;
2472 if (hostname_out)
2473 *hostname_out = tor_strdup(hostname);
2474 return 0;
2477 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2478 * on a private network.
2481 is_local_addr(const tor_addr_t *addr)
2483 if (tor_addr_is_internal(addr, 0))
2484 return 1;
2485 /* Check whether ip is on the same /24 as we are. */
2486 if (get_options()->EnforceDistinctSubnets == 0)
2487 return 0;
2488 if (tor_addr_family(addr) == AF_INET) {
2489 /*XXXX022 IP6 what corresponds to an /24? */
2490 uint32_t ip = tor_addr_to_ipv4h(addr);
2492 /* It's possible that this next check will hit before the first time
2493 * resolve_my_address actually succeeds. (For clients, it is likely that
2494 * resolve_my_address will never be called at all). In those cases,
2495 * last_resolved_addr will be 0, and so checking to see whether ip is on
2496 * the same /24 as last_resolved_addr will be the same as checking whether
2497 * it was on net 0, which is already done by is_internal_IP.
2499 if ((last_resolved_addr & (uint32_t)0xffffff00ul)
2500 == (ip & (uint32_t)0xffffff00ul))
2501 return 1;
2503 return 0;
2506 /** Called when we don't have a nickname set. Try to guess a good nickname
2507 * based on the hostname, and return it in a newly allocated string. If we
2508 * can't, return NULL and let the caller warn if it wants to. */
2509 static char *
2510 get_default_nickname(void)
2512 static const char * const bad_default_nicknames[] = {
2513 "localhost",
2514 NULL,
2516 char localhostname[256];
2517 char *cp, *out, *outp;
2518 int i;
2520 if (gethostname(localhostname, sizeof(localhostname)) < 0)
2521 return NULL;
2523 /* Put it in lowercase; stop at the first dot. */
2524 if ((cp = strchr(localhostname, '.')))
2525 *cp = '\0';
2526 tor_strlower(localhostname);
2528 /* Strip invalid characters. */
2529 cp = localhostname;
2530 out = outp = tor_malloc(strlen(localhostname) + 1);
2531 while (*cp) {
2532 if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
2533 *outp++ = *cp++;
2534 else
2535 cp++;
2537 *outp = '\0';
2539 /* Enforce length. */
2540 if (strlen(out) > MAX_NICKNAME_LEN)
2541 out[MAX_NICKNAME_LEN]='\0';
2543 /* Check for dumb names. */
2544 for (i = 0; bad_default_nicknames[i]; ++i) {
2545 if (!strcmp(out, bad_default_nicknames[i])) {
2546 tor_free(out);
2547 return NULL;
2551 return out;
2554 /** Release storage held by <b>options</b>. */
2555 static void
2556 config_free(config_format_t *fmt, void *options)
2558 int i;
2560 tor_assert(options);
2562 for (i=0; fmt->vars[i].name; ++i)
2563 option_clear(fmt, options, &(fmt->vars[i]));
2564 if (fmt->extra) {
2565 config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
2566 config_free_lines(*linep);
2567 *linep = NULL;
2569 tor_free(options);
2572 /** Return true iff a and b contain identical keys and values in identical
2573 * order. */
2574 static int
2575 config_lines_eq(config_line_t *a, config_line_t *b)
2577 while (a && b) {
2578 if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
2579 return 0;
2580 a = a->next;
2581 b = b->next;
2583 if (a || b)
2584 return 0;
2585 return 1;
2588 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2589 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2591 static int
2592 option_is_same(config_format_t *fmt,
2593 or_options_t *o1, or_options_t *o2, const char *name)
2595 config_line_t *c1, *c2;
2596 int r = 1;
2597 CHECK(fmt, o1);
2598 CHECK(fmt, o2);
2600 c1 = get_assigned_option(fmt, o1, name, 0);
2601 c2 = get_assigned_option(fmt, o2, name, 0);
2602 r = config_lines_eq(c1, c2);
2603 config_free_lines(c1);
2604 config_free_lines(c2);
2605 return r;
2608 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2609 static or_options_t *
2610 options_dup(config_format_t *fmt, or_options_t *old)
2612 or_options_t *newopts;
2613 int i;
2614 config_line_t *line;
2616 newopts = config_alloc(fmt);
2617 for (i=0; fmt->vars[i].name; ++i) {
2618 if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2619 continue;
2620 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
2621 continue;
2622 line = get_assigned_option(fmt, old, fmt->vars[i].name, 0);
2623 if (line) {
2624 char *msg = NULL;
2625 if (config_assign(fmt, newopts, line, 0, 0, &msg) < 0) {
2626 log_err(LD_BUG, "Config_get_assigned_option() generated "
2627 "something we couldn't config_assign(): %s", msg);
2628 tor_free(msg);
2629 tor_assert(0);
2632 config_free_lines(line);
2634 return newopts;
2637 /** Return a new empty or_options_t. Used for testing. */
2638 or_options_t *
2639 options_new(void)
2641 return config_alloc(&options_format);
2644 /** Set <b>options</b> to hold reasonable defaults for most options.
2645 * Each option defaults to zero. */
2646 void
2647 options_init(or_options_t *options)
2649 config_init(&options_format, options);
2652 /* Check if the port number given in <b>port_option</b> in combination with
2653 * the specified port in <b>listen_options</b> will result in Tor actually
2654 * opening a low port (meaning a port lower than 1024). Return 1 if
2655 * it is, or 0 if it isn't or the concept of a low port isn't applicable for
2656 * the platform we're on. */
2657 static int
2658 is_listening_on_low_port(uint16_t port_option,
2659 const config_line_t *listen_options)
2661 #ifdef MS_WINDOWS
2662 return 0; /* No port is too low for windows. */
2663 #else
2664 const config_line_t *l;
2665 uint16_t p;
2666 if (port_option == 0)
2667 return 0; /* We're not listening */
2668 if (listen_options == NULL)
2669 return (port_option < 1024);
2671 for (l = listen_options; l; l = l->next) {
2672 parse_addr_port(LOG_WARN, l->value, NULL, NULL, &p);
2673 if (p<1024) {
2674 return 1;
2677 return 0;
2678 #endif
2681 /** Set all vars in the configuration object <b>options</b> to their default
2682 * values. */
2683 static void
2684 config_init(config_format_t *fmt, void *options)
2686 int i;
2687 config_var_t *var;
2688 CHECK(fmt, options);
2690 for (i=0; fmt->vars[i].name; ++i) {
2691 var = &fmt->vars[i];
2692 if (!var->initvalue)
2693 continue; /* defaults to NULL or 0 */
2694 option_reset(fmt, options, var, 1);
2698 /** Allocate and return a new string holding the written-out values of the vars
2699 * in 'options'. If 'minimal', do not write out any default-valued vars.
2700 * Else, if comment_defaults, write default values as comments.
2702 static char *
2703 config_dump(config_format_t *fmt, void *options, int minimal,
2704 int comment_defaults)
2706 smartlist_t *elements;
2707 or_options_t *defaults;
2708 config_line_t *line, *assigned;
2709 char *result;
2710 int i;
2711 const char *desc;
2712 char *msg = NULL;
2714 defaults = config_alloc(fmt);
2715 config_init(fmt, defaults);
2717 /* XXX use a 1 here so we don't add a new log line while dumping */
2718 if (fmt->validate_fn(NULL,defaults, 1, &msg) < 0) {
2719 log_err(LD_BUG, "Failed to validate default config.");
2720 tor_free(msg);
2721 tor_assert(0);
2724 elements = smartlist_create();
2725 for (i=0; fmt->vars[i].name; ++i) {
2726 int comment_option = 0;
2727 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
2728 fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2729 continue;
2730 /* Don't save 'hidden' control variables. */
2731 if (!strcmpstart(fmt->vars[i].name, "__"))
2732 continue;
2733 if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
2734 continue;
2735 else if (comment_defaults &&
2736 option_is_same(fmt, options, defaults, fmt->vars[i].name))
2737 comment_option = 1;
2739 desc = config_find_description(fmt, fmt->vars[i].name);
2740 line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name, 1);
2742 if (line && desc) {
2743 /* Only dump the description if there's something to describe. */
2744 wrap_string(elements, desc, 78, "# ", "# ");
2747 for (; line; line = line->next) {
2748 size_t len = strlen(line->key) + strlen(line->value) + 5;
2749 char *tmp;
2750 tmp = tor_malloc(len);
2751 if (tor_snprintf(tmp, len, "%s%s %s\n",
2752 comment_option ? "# " : "",
2753 line->key, line->value)<0) {
2754 log_err(LD_BUG,"Internal error writing option value");
2755 tor_assert(0);
2757 smartlist_add(elements, tmp);
2759 config_free_lines(assigned);
2762 if (fmt->extra) {
2763 line = *(config_line_t**)STRUCT_VAR_P(options, fmt->extra->var_offset);
2764 for (; line; line = line->next) {
2765 size_t len = strlen(line->key) + strlen(line->value) + 3;
2766 char *tmp;
2767 tmp = tor_malloc(len);
2768 if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
2769 log_err(LD_BUG,"Internal error writing option value");
2770 tor_assert(0);
2772 smartlist_add(elements, tmp);
2776 result = smartlist_join_strings(elements, "", 0, NULL);
2777 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2778 smartlist_free(elements);
2779 config_free(fmt, defaults);
2780 return result;
2783 /** Return a string containing a possible configuration file that would give
2784 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2785 * include options that are the same as Tor's defaults.
2787 static char *
2788 options_dump(or_options_t *options, int minimal)
2790 return config_dump(&options_format, options, minimal, 0);
2793 /** Return 0 if every element of sl is a string holding a decimal
2794 * representation of a port number, or if sl is NULL.
2795 * Otherwise set *msg and return -1. */
2796 static int
2797 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2799 int i;
2800 char buf[1024];
2801 tor_assert(name);
2803 if (!sl)
2804 return 0;
2806 SMARTLIST_FOREACH(sl, const char *, cp,
2808 i = atoi(cp);
2809 if (i < 1 || i > 65535) {
2810 int r = tor_snprintf(buf, sizeof(buf),
2811 "Port '%s' out of range in %s", cp, name);
2812 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2813 return -1;
2816 return 0;
2819 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2820 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2821 * Else return 0.
2823 static int
2824 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2826 int r;
2827 char buf[1024];
2828 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2829 /* This handles an understandable special case where somebody says "2gb"
2830 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2831 --*value;
2833 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2834 r = tor_snprintf(buf, sizeof(buf), "%s ("U64_FORMAT") must be at most %d",
2835 desc, U64_PRINTF_ARG(*value),
2836 ROUTER_MAX_DECLARED_BANDWIDTH);
2837 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2838 return -1;
2840 return 0;
2843 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2844 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2845 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2846 * Treat "0" as "".
2847 * Return 0 on success or -1 if not a recognized authority type (in which
2848 * case the value of _PublishServerDescriptor is undefined). */
2849 static int
2850 compute_publishserverdescriptor(or_options_t *options)
2852 smartlist_t *list = options->PublishServerDescriptor;
2853 authority_type_t *auth = &options->_PublishServerDescriptor;
2854 *auth = NO_AUTHORITY;
2855 if (!list) /* empty list, answer is none */
2856 return 0;
2857 SMARTLIST_FOREACH(list, const char *, string, {
2858 if (!strcasecmp(string, "v1"))
2859 *auth |= V1_AUTHORITY;
2860 else if (!strcmp(string, "1"))
2861 if (options->BridgeRelay)
2862 *auth |= BRIDGE_AUTHORITY;
2863 else
2864 *auth |= V2_AUTHORITY | V3_AUTHORITY;
2865 else if (!strcasecmp(string, "v2"))
2866 *auth |= V2_AUTHORITY;
2867 else if (!strcasecmp(string, "v3"))
2868 *auth |= V3_AUTHORITY;
2869 else if (!strcasecmp(string, "bridge"))
2870 *auth |= BRIDGE_AUTHORITY;
2871 else if (!strcasecmp(string, "hidserv"))
2872 *auth |= HIDSERV_AUTHORITY;
2873 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2874 /* no authority */;
2875 else
2876 return -1;
2878 return 0;
2881 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2882 * services can overload the directory system. */
2883 #define MIN_REND_POST_PERIOD (10*60)
2885 /** Highest allowable value for RendPostPeriod. */
2886 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2888 /** Lowest allowable value for CircuitBuildTimeout; values too low will
2889 * increase network load because of failing connections being retried, and
2890 * might prevent users from connecting to the network at all. */
2891 #define MIN_CIRCUIT_BUILD_TIMEOUT 30
2893 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2894 * will generate too many circuits and potentially overload the network. */
2895 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2897 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2898 * permissible transition from <b>old_options</b>. Else return -1.
2899 * Should have no side effects, except for normalizing the contents of
2900 * <b>options</b>.
2902 * On error, tor_strdup an error explanation into *<b>msg</b>.
2904 * XXX
2905 * If <b>from_setconf</b>, we were called by the controller, and our
2906 * Log line should stay empty. If it's 0, then give us a default log
2907 * if there are no logs defined.
2909 static int
2910 options_validate(or_options_t *old_options, or_options_t *options,
2911 int from_setconf, char **msg)
2913 int i, r;
2914 config_line_t *cl;
2915 const char *uname = get_uname();
2916 char buf[1024];
2917 #define REJECT(arg) \
2918 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2919 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2921 tor_assert(msg);
2922 *msg = NULL;
2924 if (options->ORPort < 0 || options->ORPort > 65535)
2925 REJECT("ORPort option out of bounds.");
2927 if (server_mode(options) &&
2928 (!strcmpstart(uname, "Windows 95") ||
2929 !strcmpstart(uname, "Windows 98") ||
2930 !strcmpstart(uname, "Windows Me"))) {
2931 log(LOG_WARN, LD_CONFIG, "Tor is running as a server, but you are "
2932 "running %s; this probably won't work. See "
2933 "http://wiki.noreply.org/noreply/TheOnionRouter/TorFAQ#ServerOS "
2934 "for details.", uname);
2937 if (options->ORPort == 0 && options->ORListenAddress != NULL)
2938 REJECT("ORPort must be defined if ORListenAddress is defined.");
2940 if (options->DirPort == 0 && options->DirListenAddress != NULL)
2941 REJECT("DirPort must be defined if DirListenAddress is defined.");
2943 if (options->DNSPort == 0 && options->DNSListenAddress != NULL)
2944 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
2946 if (options->ControlPort == 0 && options->ControlListenAddress != NULL)
2947 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
2949 if (options->TransPort == 0 && options->TransListenAddress != NULL)
2950 REJECT("TransPort must be defined if TransListenAddress is defined.");
2952 if (options->NatdPort == 0 && options->NatdListenAddress != NULL)
2953 REJECT("NatdPort must be defined if NatdListenAddress is defined.");
2955 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
2956 * configuration does this. */
2958 for (i = 0; i < 3; ++i) {
2959 int is_socks = i==0;
2960 int is_trans = i==1;
2961 config_line_t *line, *opt, *old;
2962 const char *tp;
2963 if (is_socks) {
2964 opt = options->SocksListenAddress;
2965 old = old_options ? old_options->SocksListenAddress : NULL;
2966 tp = "SOCKS proxy";
2967 } else if (is_trans) {
2968 opt = options->TransListenAddress;
2969 old = old_options ? old_options->TransListenAddress : NULL;
2970 tp = "transparent proxy";
2971 } else {
2972 opt = options->NatdListenAddress;
2973 old = old_options ? old_options->NatdListenAddress : NULL;
2974 tp = "natd proxy";
2977 for (line = opt; line; line = line->next) {
2978 char *address = NULL;
2979 uint16_t port;
2980 uint32_t addr;
2981 if (parse_addr_port(LOG_WARN, line->value, &address, &addr, &port)<0)
2982 continue; /* We'll warn about this later. */
2983 if (!is_internal_IP(addr, 1) &&
2984 (!old_options || !config_lines_eq(old, opt))) {
2985 log_warn(LD_CONFIG,
2986 "You specified a public address '%s' for a %s. Other "
2987 "people on the Internet might find your computer and use it as "
2988 "an open %s. Please don't allow this unless you have "
2989 "a good reason.", address, tp, tp);
2991 tor_free(address);
2995 if (validate_data_directory(options)<0)
2996 REJECT("Invalid DataDirectory");
2998 if (options->Nickname == NULL) {
2999 if (server_mode(options)) {
3000 if (!(options->Nickname = get_default_nickname())) {
3001 log_notice(LD_CONFIG, "Couldn't pick a nickname based on "
3002 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME);
3003 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
3004 } else {
3005 log_notice(LD_CONFIG, "Choosing default nickname '%s'",
3006 options->Nickname);
3009 } else {
3010 if (!is_legal_nickname(options->Nickname)) {
3011 r = tor_snprintf(buf, sizeof(buf),
3012 "Nickname '%s' is wrong length or contains illegal characters.",
3013 options->Nickname);
3014 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3015 return -1;
3019 if (server_mode(options) && !options->ContactInfo)
3020 log(LOG_NOTICE, LD_CONFIG, "Your ContactInfo config option is not set. "
3021 "Please consider setting it, so we can contact you if your server is "
3022 "misconfigured or something else goes wrong.");
3024 /* Special case on first boot if no Log options are given. */
3025 if (!options->Logs && !options->RunAsDaemon && !from_setconf)
3026 config_line_append(&options->Logs, "Log", "notice stdout");
3028 if (options_init_logs(options, 1)<0) /* Validate the log(s) */
3029 REJECT("Failed to validate Log options. See logs for details.");
3031 if (options->NoPublish) {
3032 log(LOG_WARN, LD_CONFIG,
3033 "NoPublish is obsolete. Use PublishServerDescriptor instead.");
3034 SMARTLIST_FOREACH(options->PublishServerDescriptor, char *, s,
3035 tor_free(s));
3036 smartlist_clear(options->PublishServerDescriptor);
3039 if (authdir_mode(options)) {
3040 /* confirm that our address isn't broken, so we can complain now */
3041 uint32_t tmp;
3042 if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
3043 REJECT("Failed to resolve/guess local address. See logs for details.");
3046 #ifndef MS_WINDOWS
3047 if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
3048 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
3049 #endif
3051 if (options->SocksPort < 0 || options->SocksPort > 65535)
3052 REJECT("SocksPort option out of bounds.");
3054 if (options->DNSPort < 0 || options->DNSPort > 65535)
3055 REJECT("DNSPort option out of bounds.");
3057 if (options->TransPort < 0 || options->TransPort > 65535)
3058 REJECT("TransPort option out of bounds.");
3060 if (options->NatdPort < 0 || options->NatdPort > 65535)
3061 REJECT("NatdPort option out of bounds.");
3063 if (options->SocksPort == 0 && options->TransPort == 0 &&
3064 options->NatdPort == 0 && options->ORPort == 0 &&
3065 options->DNSPort == 0 && !options->RendConfigLines)
3066 log(LOG_WARN, LD_CONFIG,
3067 "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
3068 "undefined, and there aren't any hidden services configured. "
3069 "Tor will still run, but probably won't do anything.");
3071 if (options->ControlPort < 0 || options->ControlPort > 65535)
3072 REJECT("ControlPort option out of bounds.");
3074 if (options->DirPort < 0 || options->DirPort > 65535)
3075 REJECT("DirPort option out of bounds.");
3077 #ifndef USE_TRANSPARENT
3078 if (options->TransPort || options->TransListenAddress)
3079 REJECT("TransPort and TransListenAddress are disabled in this build.");
3080 #endif
3082 if (options->AccountingMax &&
3083 (is_listening_on_low_port(options->ORPort, options->ORListenAddress) ||
3084 is_listening_on_low_port(options->DirPort, options->DirListenAddress)))
3086 log(LOG_WARN, LD_CONFIG,
3087 "You have set AccountingMax to use hibernation. You have also "
3088 "chosen a low DirPort or OrPort. This combination can make Tor stop "
3089 "working when it tries to re-attach the port after a period of "
3090 "hibernation. Please choose a different port or turn off "
3091 "hibernation unless you know this combination will work on your "
3092 "platform.");
3095 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3096 options->_ExcludeExitNodesUnion = routerset_new();
3097 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeExitNodes);
3098 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeNodes);
3101 if (options->StrictExitNodes &&
3102 (!options->ExitNodes) &&
3103 (!old_options ||
3104 (old_options->StrictExitNodes != options->StrictExitNodes) ||
3105 (!routerset_equal(old_options->ExitNodes,options->ExitNodes))))
3106 COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
3108 if (options->StrictEntryNodes &&
3109 (!options->EntryNodes) &&
3110 (!old_options ||
3111 (old_options->StrictEntryNodes != options->StrictEntryNodes) ||
3112 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
3113 COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
3115 if (options->EntryNodes && !routerset_is_list(options->EntryNodes)) {
3116 /* XXXX fix this; see entry_guards_prepend_from_config(). */
3117 REJECT("IPs or countries are not yet supported in EntryNodes.");
3120 if (options->AuthoritativeDir) {
3121 if (!options->ContactInfo && !options->TestingTorNetwork)
3122 REJECT("Authoritative directory servers must set ContactInfo");
3123 if (options->V1AuthoritativeDir && !options->RecommendedVersions)
3124 REJECT("V1 authoritative dir servers must set RecommendedVersions.");
3125 if (!options->RecommendedClientVersions)
3126 options->RecommendedClientVersions =
3127 config_lines_dup(options->RecommendedVersions);
3128 if (!options->RecommendedServerVersions)
3129 options->RecommendedServerVersions =
3130 config_lines_dup(options->RecommendedVersions);
3131 if (options->VersioningAuthoritativeDir &&
3132 (!options->RecommendedClientVersions ||
3133 !options->RecommendedServerVersions))
3134 REJECT("Versioning authoritative dir servers must set "
3135 "Recommended*Versions.");
3136 if (options->UseEntryGuards) {
3137 log_info(LD_CONFIG, "Authoritative directory servers can't set "
3138 "UseEntryGuards. Disabling.");
3139 options->UseEntryGuards = 0;
3141 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
3142 log_info(LD_CONFIG, "Authoritative directories always try to download "
3143 "extra-info documents. Setting DownloadExtraInfo.");
3144 options->DownloadExtraInfo = 1;
3146 if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
3147 options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
3148 options->V3AuthoritativeDir))
3149 REJECT("AuthoritativeDir is set, but none of "
3150 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
3153 if (options->AuthoritativeDir && !options->DirPort)
3154 REJECT("Running as authoritative directory, but no DirPort set.");
3156 if (options->AuthoritativeDir && !options->ORPort)
3157 REJECT("Running as authoritative directory, but no ORPort set.");
3159 if (options->AuthoritativeDir && options->ClientOnly)
3160 REJECT("Running as authoritative directory, but ClientOnly also set.");
3162 if (options->HSAuthorityRecordStats && !options->HSAuthoritativeDir)
3163 REJECT("HSAuthorityRecordStats is set but we're not running as "
3164 "a hidden service authority.");
3166 if (options->ConnLimit <= 0) {
3167 r = tor_snprintf(buf, sizeof(buf),
3168 "ConnLimit must be greater than 0, but was set to %d",
3169 options->ConnLimit);
3170 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3171 return -1;
3174 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3175 return -1;
3177 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3178 return -1;
3180 if (validate_ports_csv(options->RejectPlaintextPorts,
3181 "RejectPlaintextPorts", msg) < 0)
3182 return -1;
3184 if (validate_ports_csv(options->WarnPlaintextPorts,
3185 "WarnPlaintextPorts", msg) < 0)
3186 return -1;
3188 if (options->FascistFirewall && !options->ReachableAddresses) {
3189 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3190 /* We already have firewall ports set, so migrate them to
3191 * ReachableAddresses, which will set ReachableORAddresses and
3192 * ReachableDirAddresses if they aren't set explicitly. */
3193 smartlist_t *instead = smartlist_create();
3194 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3195 new_line->key = tor_strdup("ReachableAddresses");
3196 /* If we're configured with the old format, we need to prepend some
3197 * open ports. */
3198 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3200 int p = atoi(portno);
3201 char *s;
3202 if (p<0) continue;
3203 s = tor_malloc(16);
3204 tor_snprintf(s, 16, "*:%d", p);
3205 smartlist_add(instead, s);
3207 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3208 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3209 log(LOG_NOTICE, LD_CONFIG,
3210 "Converting FascistFirewall and FirewallPorts "
3211 "config options to new format: \"ReachableAddresses %s\"",
3212 new_line->value);
3213 options->ReachableAddresses = new_line;
3214 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3215 smartlist_free(instead);
3216 } else {
3217 /* We do not have FirewallPorts set, so add 80 to
3218 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3219 if (!options->ReachableDirAddresses) {
3220 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3221 new_line->key = tor_strdup("ReachableDirAddresses");
3222 new_line->value = tor_strdup("*:80");
3223 options->ReachableDirAddresses = new_line;
3224 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3225 "to new format: \"ReachableDirAddresses *:80\"");
3227 if (!options->ReachableORAddresses) {
3228 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3229 new_line->key = tor_strdup("ReachableORAddresses");
3230 new_line->value = tor_strdup("*:443");
3231 options->ReachableORAddresses = new_line;
3232 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3233 "to new format: \"ReachableORAddresses *:443\"");
3238 for (i=0; i<3; i++) {
3239 config_line_t **linep =
3240 (i==0) ? &options->ReachableAddresses :
3241 (i==1) ? &options->ReachableORAddresses :
3242 &options->ReachableDirAddresses;
3243 if (!*linep)
3244 continue;
3245 /* We need to end with a reject *:*, not an implicit accept *:* */
3246 for (;;) {
3247 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
3248 break;
3249 linep = &((*linep)->next);
3250 if (!*linep) {
3251 *linep = tor_malloc_zero(sizeof(config_line_t));
3252 (*linep)->key = tor_strdup(
3253 (i==0) ? "ReachableAddresses" :
3254 (i==1) ? "ReachableORAddresses" :
3255 "ReachableDirAddresses");
3256 (*linep)->value = tor_strdup("reject *:*");
3257 break;
3262 if ((options->ReachableAddresses ||
3263 options->ReachableORAddresses ||
3264 options->ReachableDirAddresses) &&
3265 server_mode(options))
3266 REJECT("Servers must be able to freely connect to the rest "
3267 "of the Internet, so they must not set Reachable*Addresses "
3268 "or FascistFirewall.");
3270 if (options->UseBridges &&
3271 server_mode(options))
3272 REJECT("Servers must be able to freely connect to the rest "
3273 "of the Internet, so they must not set UseBridges.");
3275 options->_AllowInvalid = 0;
3276 if (options->AllowInvalidNodes) {
3277 SMARTLIST_FOREACH(options->AllowInvalidNodes, const char *, cp, {
3278 if (!strcasecmp(cp, "entry"))
3279 options->_AllowInvalid |= ALLOW_INVALID_ENTRY;
3280 else if (!strcasecmp(cp, "exit"))
3281 options->_AllowInvalid |= ALLOW_INVALID_EXIT;
3282 else if (!strcasecmp(cp, "middle"))
3283 options->_AllowInvalid |= ALLOW_INVALID_MIDDLE;
3284 else if (!strcasecmp(cp, "introduction"))
3285 options->_AllowInvalid |= ALLOW_INVALID_INTRODUCTION;
3286 else if (!strcasecmp(cp, "rendezvous"))
3287 options->_AllowInvalid |= ALLOW_INVALID_RENDEZVOUS;
3288 else {
3289 r = tor_snprintf(buf, sizeof(buf),
3290 "Unrecognized value '%s' in AllowInvalidNodes", cp);
3291 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3292 return -1;
3297 if (compute_publishserverdescriptor(options) < 0) {
3298 r = tor_snprintf(buf, sizeof(buf),
3299 "Unrecognized value in PublishServerDescriptor");
3300 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3301 return -1;
3304 if ((options->BridgeRelay
3305 || options->_PublishServerDescriptor & BRIDGE_AUTHORITY)
3306 && (options->_PublishServerDescriptor
3307 & (V1_AUTHORITY|V2_AUTHORITY|V3_AUTHORITY))) {
3308 REJECT("Bridges are not supposed to publish router descriptors to the "
3309 "directory authorities. Please correct your "
3310 "PublishServerDescriptor line.");
3313 if (options->MinUptimeHidServDirectoryV2 < 0) {
3314 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3315 "least 0 seconds. Changing to 0.");
3316 options->MinUptimeHidServDirectoryV2 = 0;
3319 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
3320 log(LOG_WARN,LD_CONFIG,"RendPostPeriod option is too short; "
3321 "raising to %d seconds.", MIN_REND_POST_PERIOD);
3322 options->RendPostPeriod = MIN_REND_POST_PERIOD;
3325 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3326 log(LOG_WARN, LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3327 MAX_DIR_PERIOD);
3328 options->RendPostPeriod = MAX_DIR_PERIOD;
3331 if (options->CircuitBuildTimeout < MIN_CIRCUIT_BUILD_TIMEOUT) {
3332 log(LOG_WARN, LD_CONFIG, "CircuitBuildTimeout option is too short; "
3333 "raising to %d seconds.", MIN_CIRCUIT_BUILD_TIMEOUT);
3334 options->CircuitBuildTimeout = MIN_CIRCUIT_BUILD_TIMEOUT;
3337 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3338 log(LOG_WARN, LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3339 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3340 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3343 if (options->KeepalivePeriod < 1)
3344 REJECT("KeepalivePeriod option must be positive.");
3346 if (ensure_bandwidth_cap(&options->BandwidthRate,
3347 "BandwidthRate", msg) < 0)
3348 return -1;
3349 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3350 "BandwidthBurst", msg) < 0)
3351 return -1;
3352 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3353 "MaxAdvertisedBandwidth", msg) < 0)
3354 return -1;
3355 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3356 "RelayBandwidthRate", msg) < 0)
3357 return -1;
3358 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3359 "RelayBandwidthBurst", msg) < 0)
3360 return -1;
3362 if (server_mode(options)) {
3363 if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3364 r = tor_snprintf(buf, sizeof(buf),
3365 "BandwidthRate is set to %d bytes/second. "
3366 "For servers, it must be at least %d.",
3367 (int)options->BandwidthRate,
3368 ROUTER_REQUIRED_MIN_BANDWIDTH);
3369 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3370 return -1;
3371 } else if (options->MaxAdvertisedBandwidth <
3372 ROUTER_REQUIRED_MIN_BANDWIDTH/2) {
3373 r = tor_snprintf(buf, sizeof(buf),
3374 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3375 "For servers, it must be at least %d.",
3376 (int)options->MaxAdvertisedBandwidth,
3377 ROUTER_REQUIRED_MIN_BANDWIDTH/2);
3378 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3379 return -1;
3381 if (options->RelayBandwidthRate &&
3382 options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3383 r = tor_snprintf(buf, sizeof(buf),
3384 "RelayBandwidthRate is set to %d bytes/second. "
3385 "For servers, it must be at least %d.",
3386 (int)options->RelayBandwidthRate,
3387 ROUTER_REQUIRED_MIN_BANDWIDTH);
3388 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3389 return -1;
3393 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3394 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3396 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3397 REJECT("RelayBandwidthBurst must be at least equal "
3398 "to RelayBandwidthRate.");
3400 if (options->BandwidthRate > options->BandwidthBurst)
3401 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3403 /* if they set relaybandwidth* really high but left bandwidth*
3404 * at the default, raise the defaults. */
3405 if (options->RelayBandwidthRate > options->BandwidthRate)
3406 options->BandwidthRate = options->RelayBandwidthRate;
3407 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3408 options->BandwidthBurst = options->RelayBandwidthBurst;
3410 if (accounting_parse_options(options, 1)<0)
3411 REJECT("Failed to parse accounting options. See logs for details.");
3413 if (options->HttpProxy) { /* parse it now */
3414 if (parse_addr_port(LOG_WARN, options->HttpProxy, NULL,
3415 &options->HttpProxyAddr, &options->HttpProxyPort) < 0)
3416 REJECT("HttpProxy failed to parse or resolve. Please fix.");
3417 if (options->HttpProxyPort == 0) { /* give it a default */
3418 options->HttpProxyPort = 80;
3422 if (options->HttpProxyAuthenticator) {
3423 if (strlen(options->HttpProxyAuthenticator) >= 48)
3424 REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
3427 if (options->HttpsProxy) { /* parse it now */
3428 if (parse_addr_port(LOG_WARN, options->HttpsProxy, NULL,
3429 &options->HttpsProxyAddr, &options->HttpsProxyPort) <0)
3430 REJECT("HttpsProxy failed to parse or resolve. Please fix.");
3431 if (options->HttpsProxyPort == 0) { /* give it a default */
3432 options->HttpsProxyPort = 443;
3436 if (options->HttpsProxyAuthenticator) {
3437 if (strlen(options->HttpsProxyAuthenticator) >= 48)
3438 REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
3441 if (options->HashedControlPassword) {
3442 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3443 if (!sl) {
3444 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3445 } else {
3446 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3447 smartlist_free(sl);
3451 if (options->HashedControlSessionPassword) {
3452 smartlist_t *sl = decode_hashed_passwords(
3453 options->HashedControlSessionPassword);
3454 if (!sl) {
3455 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3456 } else {
3457 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3458 smartlist_free(sl);
3462 if (options->ControlListenAddress) {
3463 int all_are_local = 1;
3464 config_line_t *ln;
3465 for (ln = options->ControlListenAddress; ln; ln = ln->next) {
3466 if (strcmpstart(ln->value, "127."))
3467 all_are_local = 0;
3469 if (!all_are_local) {
3470 if (!options->HashedControlPassword &&
3471 !options->HashedControlSessionPassword &&
3472 !options->CookieAuthentication) {
3473 log_warn(LD_CONFIG,
3474 "You have a ControlListenAddress set to accept "
3475 "unauthenticated connections from a non-local address. "
3476 "This means that programs not running on your computer "
3477 "can reconfigure your Tor, without even having to guess a "
3478 "password. That's so bad that I'm closing your ControlPort "
3479 "for you. If you need to control your Tor remotely, try "
3480 "enabling authentication and using a tool like stunnel or "
3481 "ssh to encrypt remote access.");
3482 options->ControlPort = 0;
3483 } else {
3484 log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
3485 "connections from a non-local address. This means that "
3486 "programs not running on your computer can reconfigure your "
3487 "Tor. That's pretty bad, since the controller "
3488 "protocol isn't encrypted! Maybe you should just listen on "
3489 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
3490 "remote connections to your control port.");
3495 if (options->ControlPort && !options->HashedControlPassword &&
3496 !options->HashedControlSessionPassword &&
3497 !options->CookieAuthentication) {
3498 log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
3499 "has been configured. This means that any program on your "
3500 "computer can reconfigure your Tor. That's bad! You should "
3501 "upgrade your Tor controller as soon as possible.");
3504 if (options->UseEntryGuards && ! options->NumEntryGuards)
3505 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3507 if (check_nickname_list(options->MyFamily, "MyFamily", msg))
3508 return -1;
3509 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3510 if (check_nickname_list(cl->value, "NodeFamily", msg))
3511 return -1;
3514 if (validate_addr_policies(options, msg) < 0)
3515 return -1;
3517 if (validate_dir_authorities(options, old_options) < 0)
3518 REJECT("Directory authority line did not parse. See logs for details.");
3520 if (options->UseBridges && !options->Bridges)
3521 REJECT("If you set UseBridges, you must specify at least one bridge.");
3522 if (options->UseBridges && !options->TunnelDirConns)
3523 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3524 if (options->Bridges) {
3525 for (cl = options->Bridges; cl; cl = cl->next) {
3526 if (parse_bridge_line(cl->value, 1)<0)
3527 REJECT("Bridge line did not parse. See logs for details.");
3531 if (options->ConstrainedSockets) {
3532 /* If the user wants to constrain socket buffer use, make sure the desired
3533 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3534 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3535 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3536 options->ConstrainedSockSize % 1024) {
3537 r = tor_snprintf(buf, sizeof(buf),
3538 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3539 "in 1024 byte increments.",
3540 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3541 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3542 return -1;
3544 if (options->DirPort) {
3545 /* Providing cached directory entries while system TCP buffers are scarce
3546 * will exacerbate the socket errors. Suggest that this be disabled. */
3547 COMPLAIN("You have requested constrained socket buffers while also "
3548 "serving directory entries via DirPort. It is strongly "
3549 "suggested that you disable serving directory requests when "
3550 "system TCP buffer resources are scarce.");
3554 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3555 options->V3AuthVotingInterval/2) {
3556 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3557 "V3AuthVotingInterval");
3559 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
3560 REJECT("V3AuthVoteDelay is way too low.");
3561 if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
3562 REJECT("V3AuthDistDelay is way too low.");
3564 if (options->V3AuthNIntervalsValid < 2)
3565 REJECT("V3AuthNIntervalsValid must be at least 2.");
3567 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3568 REJECT("V3AuthVotingInterval is insanely low.");
3569 } else if (options->V3AuthVotingInterval > 24*60*60) {
3570 REJECT("V3AuthVotingInterval is insanely high.");
3571 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3572 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3575 if (rend_config_services(options, 1) < 0)
3576 REJECT("Failed to configure rendezvous options. See logs for details.");
3578 /* Parse client-side authorization for hidden services. */
3579 if (rend_parse_service_authorization(options, 1) < 0)
3580 REJECT("Failed to configure client authorization for hidden services. "
3581 "See logs for details.");
3583 if (parse_virtual_addr_network(options->VirtualAddrNetwork, 1, NULL)<0)
3584 return -1;
3586 if (options->PreferTunneledDirConns && !options->TunnelDirConns)
3587 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3589 if (options->AutomapHostsSuffixes) {
3590 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
3592 size_t len = strlen(suf);
3593 if (len && suf[len-1] == '.')
3594 suf[len-1] = '\0';
3598 if (options->TestingTorNetwork && !options->DirServers) {
3599 REJECT("TestingTorNetwork may only be configured in combination with "
3600 "a non-default set of DirServers.");
3603 /*XXXX022 checking for defaults manually like this is a bit fragile.*/
3605 /* Keep changes to hard-coded values synchronous to man page and default
3606 * values table. */
3607 if (options->TestingV3AuthInitialVotingInterval != 30*60 &&
3608 !options->TestingTorNetwork) {
3609 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
3610 "Tor networks!");
3611 } else if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
3612 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3613 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
3614 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3615 "30 minutes.");
3618 if (options->TestingV3AuthInitialVoteDelay != 5*60 &&
3619 !options->TestingTorNetwork) {
3620 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
3621 "Tor networks!");
3622 } else if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
3623 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3626 if (options->TestingV3AuthInitialDistDelay != 5*60 &&
3627 !options->TestingTorNetwork) {
3628 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
3629 "Tor networks!");
3630 } else if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
3631 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3634 if (options->TestingV3AuthInitialVoteDelay +
3635 options->TestingV3AuthInitialDistDelay >=
3636 options->TestingV3AuthInitialVotingInterval/2) {
3637 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3638 "must be less than half TestingV3AuthInitialVotingInterval");
3641 if (options->TestingAuthDirTimeToLearnReachability != 30*60 &&
3642 !options->TestingTorNetwork) {
3643 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
3644 "testing Tor networks!");
3645 } else if (options->TestingAuthDirTimeToLearnReachability < 0) {
3646 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3647 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
3648 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3651 if (options->TestingEstimatedDescriptorPropagationTime != 10*60 &&
3652 !options->TestingTorNetwork) {
3653 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
3654 "testing Tor networks!");
3655 } else if (options->TestingEstimatedDescriptorPropagationTime < 0) {
3656 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3657 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
3658 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3661 if (options->TestingTorNetwork) {
3662 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
3663 "almost unusable in the public Tor network, and is "
3664 "therefore only advised if you are building a "
3665 "testing Tor network!");
3668 return 0;
3669 #undef REJECT
3670 #undef COMPLAIN
3673 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3674 * equal strings. */
3675 static int
3676 opt_streq(const char *s1, const char *s2)
3678 if (!s1 && !s2)
3679 return 1;
3680 else if (s1 && s2 && !strcmp(s1,s2))
3681 return 1;
3682 else
3683 return 0;
3686 /** Check if any of the previous options have changed but aren't allowed to. */
3687 static int
3688 options_transition_allowed(or_options_t *old, or_options_t *new_val,
3689 char **msg)
3691 if (!old)
3692 return 0;
3694 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3695 *msg = tor_strdup("PidFile is not allowed to change.");
3696 return -1;
3699 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3700 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3701 "is not allowed.");
3702 return -1;
3705 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
3706 char buf[1024];
3707 int r = tor_snprintf(buf, sizeof(buf),
3708 "While Tor is running, changing DataDirectory "
3709 "(\"%s\"->\"%s\") is not allowed.",
3710 old->DataDirectory, new_val->DataDirectory);
3711 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3712 return -1;
3715 if (!opt_streq(old->User, new_val->User)) {
3716 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
3717 return -1;
3720 if (!opt_streq(old->Group, new_val->Group)) {
3721 *msg = tor_strdup("While Tor is running, changing Group is not allowed.");
3722 return -1;
3725 if (old->HardwareAccel != new_val->HardwareAccel) {
3726 *msg = tor_strdup("While Tor is running, changing HardwareAccel is "
3727 "not allowed.");
3728 return -1;
3731 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
3732 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
3733 "is not allowed.");
3734 return -1;
3737 return 0;
3740 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3741 * will require us to rotate the CPU and DNS workers; else return 0. */
3742 static int
3743 options_transition_affects_workers(or_options_t *old_options,
3744 or_options_t *new_options)
3746 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3747 old_options->NumCpus != new_options->NumCpus ||
3748 old_options->ORPort != new_options->ORPort ||
3749 old_options->ServerDNSSearchDomains !=
3750 new_options->ServerDNSSearchDomains ||
3751 old_options->SafeLogging != new_options->SafeLogging ||
3752 old_options->ClientOnly != new_options->ClientOnly ||
3753 !config_lines_eq(old_options->Logs, new_options->Logs))
3754 return 1;
3756 /* Check whether log options match. */
3758 /* Nothing that changed matters. */
3759 return 0;
3762 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3763 * will require us to generate a new descriptor; else return 0. */
3764 static int
3765 options_transition_affects_descriptor(or_options_t *old_options,
3766 or_options_t *new_options)
3768 /* XXX We can be smarter here. If your DirPort isn't being
3769 * published and you just turned it off, no need to republish. Etc. */
3770 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3771 !opt_streq(old_options->Nickname,new_options->Nickname) ||
3772 !opt_streq(old_options->Address,new_options->Address) ||
3773 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
3774 old_options->ExitPolicyRejectPrivate !=
3775 new_options->ExitPolicyRejectPrivate ||
3776 old_options->ORPort != new_options->ORPort ||
3777 old_options->DirPort != new_options->DirPort ||
3778 old_options->ClientOnly != new_options->ClientOnly ||
3779 old_options->NoPublish != new_options->NoPublish ||
3780 old_options->_PublishServerDescriptor !=
3781 new_options->_PublishServerDescriptor ||
3782 get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
3783 get_effective_bwburst(old_options) !=
3784 get_effective_bwburst(new_options) ||
3785 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
3786 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
3787 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
3788 old_options->AccountingMax != new_options->AccountingMax)
3789 return 1;
3791 return 0;
3794 #ifdef MS_WINDOWS
3795 /** Return the directory on windows where we expect to find our application
3796 * data. */
3797 static char *
3798 get_windows_conf_root(void)
3800 static int is_set = 0;
3801 static char path[MAX_PATH+1];
3803 LPITEMIDLIST idl;
3804 IMalloc *m;
3805 HRESULT result;
3807 if (is_set)
3808 return path;
3810 /* Find X:\documents and settings\username\application data\ .
3811 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3813 #ifdef ENABLE_LOCAL_APPDATA
3814 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
3815 #else
3816 #define APPDATA_PATH CSIDL_APPDATA
3817 #endif
3818 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
3819 GetCurrentDirectory(MAX_PATH, path);
3820 is_set = 1;
3821 log_warn(LD_CONFIG,
3822 "I couldn't find your application data folder: are you "
3823 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3824 path);
3825 return path;
3827 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3828 result = SHGetPathFromIDList(idl, path);
3829 /* Now we need to free the */
3830 SHGetMalloc(&m);
3831 if (m) {
3832 m->lpVtbl->Free(m, idl);
3833 m->lpVtbl->Release(m);
3835 if (!SUCCEEDED(result)) {
3836 return NULL;
3838 strlcat(path,"\\tor",MAX_PATH);
3839 is_set = 1;
3840 return path;
3842 #endif
3844 /** Return the default location for our torrc file. */
3845 static const char *
3846 get_default_conf_file(void)
3848 #ifdef MS_WINDOWS
3849 static char path[MAX_PATH+1];
3850 strlcpy(path, get_windows_conf_root(), MAX_PATH);
3851 strlcat(path,"\\torrc",MAX_PATH);
3852 return path;
3853 #else
3854 return (CONFDIR "/torrc");
3855 #endif
3858 /** Verify whether lst is a string containing valid-looking comma-separated
3859 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3861 static int
3862 check_nickname_list(const char *lst, const char *name, char **msg)
3864 int r = 0;
3865 smartlist_t *sl;
3867 if (!lst)
3868 return 0;
3869 sl = smartlist_create();
3871 smartlist_split_string(sl, lst, ",",
3872 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
3874 SMARTLIST_FOREACH(sl, const char *, s,
3876 if (!is_legal_nickname_or_hexdigest(s)) {
3877 char buf[1024];
3878 int tmp = tor_snprintf(buf, sizeof(buf),
3879 "Invalid nickname '%s' in %s line", s, name);
3880 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
3881 r = -1;
3882 break;
3885 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
3886 smartlist_free(sl);
3887 return r;
3890 /** Learn config file name from command line arguments, or use the default */
3891 static char *
3892 find_torrc_filename(int argc, char **argv,
3893 int *using_default_torrc, int *ignore_missing_torrc)
3895 char *fname=NULL;
3896 int i;
3898 for (i = 1; i < argc; ++i) {
3899 if (i < argc-1 && !strcmp(argv[i],"-f")) {
3900 if (fname) {
3901 log(LOG_WARN, LD_CONFIG, "Duplicate -f options on command line.");
3902 tor_free(fname);
3904 #ifdef MS_WINDOWS
3905 /* XXX one day we might want to extend expand_filename to work
3906 * under Windows as well. */
3907 fname = tor_strdup(argv[i+1]);
3908 #else
3909 fname = expand_filename(argv[i+1]);
3910 #endif
3911 *using_default_torrc = 0;
3912 ++i;
3913 } else if (!strcmp(argv[i],"--ignore-missing-torrc")) {
3914 *ignore_missing_torrc = 1;
3918 if (*using_default_torrc) {
3919 /* didn't find one, try CONFDIR */
3920 const char *dflt = get_default_conf_file();
3921 if (dflt && file_status(dflt) == FN_FILE) {
3922 fname = tor_strdup(dflt);
3923 } else {
3924 #ifndef MS_WINDOWS
3925 char *fn;
3926 fn = expand_filename("~/.torrc");
3927 if (fn && file_status(fn) == FN_FILE) {
3928 fname = fn;
3929 } else {
3930 tor_free(fn);
3931 fname = tor_strdup(dflt);
3933 #else
3934 fname = tor_strdup(dflt);
3935 #endif
3938 return fname;
3941 /** Load torrc from disk, setting torrc_fname if successful */
3942 static char *
3943 load_torrc_from_disk(int argc, char **argv)
3945 char *fname=NULL;
3946 char *cf = NULL;
3947 int using_default_torrc = 1;
3948 int ignore_missing_torrc = 0;
3950 fname = find_torrc_filename(argc, argv,
3951 &using_default_torrc, &ignore_missing_torrc);
3952 tor_assert(fname);
3953 log(LOG_DEBUG, LD_CONFIG, "Opening config file \"%s\"", fname);
3955 tor_free(torrc_fname);
3956 torrc_fname = fname;
3958 /* Open config file */
3959 if (file_status(fname) != FN_FILE ||
3960 !(cf = read_file_to_str(fname,0,NULL))) {
3961 if (using_default_torrc == 1 || ignore_missing_torrc ) {
3962 log(LOG_NOTICE, LD_CONFIG, "Configuration file \"%s\" not present, "
3963 "using reasonable defaults.", fname);
3964 tor_free(fname); /* sets fname to NULL */
3965 torrc_fname = NULL;
3966 cf = tor_strdup("");
3967 } else {
3968 log(LOG_WARN, LD_CONFIG,
3969 "Unable to open configuration file \"%s\".", fname);
3970 goto err;
3974 return cf;
3975 err:
3976 tor_free(fname);
3977 torrc_fname = NULL;
3978 return NULL;
3981 /** Read a configuration file into <b>options</b>, finding the configuration
3982 * file location based on the command line. After loading the file
3983 * call options_init_from_string() to load the config.
3984 * Return 0 if success, -1 if failure. */
3986 options_init_from_torrc(int argc, char **argv)
3988 char *cf=NULL;
3989 int i, retval, command;
3990 static char **backup_argv;
3991 static int backup_argc;
3992 char *command_arg = NULL;
3993 char *errmsg=NULL;
3995 if (argv) { /* first time we're called. save command line args */
3996 backup_argv = argv;
3997 backup_argc = argc;
3998 } else { /* we're reloading. need to clean up old options first. */
3999 argv = backup_argv;
4000 argc = backup_argc;
4002 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
4003 print_usage();
4004 exit(0);
4006 if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
4007 /* For documenting validating whether we've documented everything. */
4008 list_torrc_options();
4009 exit(0);
4012 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
4013 printf("Tor version %s.\n",get_version());
4014 exit(0);
4017 /* Go through command-line variables */
4018 if (!global_cmdline_options) {
4019 /* Or we could redo the list every time we pass this place.
4020 * It does not really matter */
4021 if (config_get_commandlines(argc, argv, &global_cmdline_options) < 0) {
4022 goto err;
4026 command = CMD_RUN_TOR;
4027 for (i = 1; i < argc; ++i) {
4028 if (!strcmp(argv[i],"--list-fingerprint")) {
4029 command = CMD_LIST_FINGERPRINT;
4030 } else if (!strcmp(argv[i],"--hash-password")) {
4031 command = CMD_HASH_PASSWORD;
4032 command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
4033 ++i;
4034 } else if (!strcmp(argv[i],"--verify-config")) {
4035 command = CMD_VERIFY_CONFIG;
4039 if (command == CMD_HASH_PASSWORD) {
4040 cf = tor_strdup("");
4041 } else {
4042 cf = load_torrc_from_disk(argc, argv);
4043 if (!cf)
4044 goto err;
4047 retval = options_init_from_string(cf, command, command_arg, &errmsg);
4048 tor_free(cf);
4049 if (retval < 0)
4050 goto err;
4052 return 0;
4054 err:
4055 if (errmsg) {
4056 log(LOG_WARN,LD_CONFIG,"%s", errmsg);
4057 tor_free(errmsg);
4059 return -1;
4062 /** Load the options from the configuration in <b>cf</b>, validate
4063 * them for consistency and take actions based on them.
4065 * Return 0 if success, negative on error:
4066 * * -1 for general errors.
4067 * * -2 for failure to parse/validate,
4068 * * -3 for transition not allowed
4069 * * -4 for error while setting the new options
4071 setopt_err_t
4072 options_init_from_string(const char *cf,
4073 int command, const char *command_arg,
4074 char **msg)
4076 or_options_t *oldoptions, *newoptions;
4077 config_line_t *cl;
4078 int retval;
4079 setopt_err_t err = SETOPT_ERR_MISC;
4080 tor_assert(msg);
4082 oldoptions = global_options; /* get_options unfortunately asserts if
4083 this is the first time we run*/
4085 newoptions = tor_malloc_zero(sizeof(or_options_t));
4086 newoptions->_magic = OR_OPTIONS_MAGIC;
4087 options_init(newoptions);
4088 newoptions->command = command;
4089 newoptions->command_arg = command_arg;
4091 /* get config lines, assign them */
4092 retval = config_get_lines(cf, &cl);
4093 if (retval < 0) {
4094 err = SETOPT_ERR_PARSE;
4095 goto err;
4097 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4098 config_free_lines(cl);
4099 if (retval < 0) {
4100 err = SETOPT_ERR_PARSE;
4101 goto err;
4104 /* Go through command-line variables too */
4105 retval = config_assign(&options_format, newoptions,
4106 global_cmdline_options, 0, 0, msg);
4107 if (retval < 0) {
4108 err = SETOPT_ERR_PARSE;
4109 goto err;
4112 /* If this is a testing network configuration, change defaults
4113 * for a list of dependent config options, re-initialize newoptions
4114 * with the new defaults, and assign all options to it second time. */
4115 if (newoptions->TestingTorNetwork) {
4116 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4117 * this? We could, for example, make the parsing algorithm do two passes
4118 * over the configuration. If it finds any "suite" options like
4119 * TestingTorNetwork, it could change the defaults before its second pass.
4120 * Not urgent so long as this seems to work, but at any sign of trouble,
4121 * let's clean it up. -NM */
4123 /* Change defaults. */
4124 int i;
4125 for (i = 0; testing_tor_network_defaults[i].name; ++i) {
4126 config_var_t *new_var = &testing_tor_network_defaults[i];
4127 config_var_t *old_var =
4128 config_find_option(&options_format, new_var->name);
4129 tor_assert(new_var);
4130 tor_assert(old_var);
4131 old_var->initvalue = new_var->initvalue;
4134 /* Clear newoptions and re-initialize them with new defaults. */
4135 config_free(&options_format, newoptions);
4136 newoptions = tor_malloc_zero(sizeof(or_options_t));
4137 newoptions->_magic = OR_OPTIONS_MAGIC;
4138 options_init(newoptions);
4139 newoptions->command = command;
4140 newoptions->command_arg = command_arg;
4142 /* Assign all options a second time. */
4143 retval = config_get_lines(cf, &cl);
4144 if (retval < 0) {
4145 err = SETOPT_ERR_PARSE;
4146 goto err;
4148 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4149 config_free_lines(cl);
4150 if (retval < 0) {
4151 err = SETOPT_ERR_PARSE;
4152 goto err;
4154 retval = config_assign(&options_format, newoptions,
4155 global_cmdline_options, 0, 0, msg);
4156 if (retval < 0) {
4157 err = SETOPT_ERR_PARSE;
4158 goto err;
4162 /* Validate newoptions */
4163 if (options_validate(oldoptions, newoptions, 0, msg) < 0) {
4164 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
4165 goto err;
4168 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
4169 err = SETOPT_ERR_TRANSITION;
4170 goto err;
4173 if (set_options(newoptions, msg)) {
4174 err = SETOPT_ERR_SETTING;
4175 goto err; /* frees and replaces old options */
4178 return SETOPT_OK;
4180 err:
4181 config_free(&options_format, newoptions);
4182 if (*msg) {
4183 int len = (int)strlen(*msg)+256;
4184 char *newmsg = tor_malloc(len);
4186 tor_snprintf(newmsg, len, "Failed to parse/validate config: %s", *msg);
4187 tor_free(*msg);
4188 *msg = newmsg;
4190 return err;
4193 /** Return the location for our configuration file.
4195 const char *
4196 get_torrc_fname(void)
4198 if (torrc_fname)
4199 return torrc_fname;
4200 else
4201 return get_default_conf_file();
4204 /** Adjust the address map based on the MapAddress elements in the
4205 * configuration <b>options</b>
4207 static void
4208 config_register_addressmaps(or_options_t *options)
4210 smartlist_t *elts;
4211 config_line_t *opt;
4212 char *from, *to;
4214 addressmap_clear_configured();
4215 elts = smartlist_create();
4216 for (opt = options->AddressMap; opt; opt = opt->next) {
4217 smartlist_split_string(elts, opt->value, NULL,
4218 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4219 if (smartlist_len(elts) >= 2) {
4220 from = smartlist_get(elts,0);
4221 to = smartlist_get(elts,1);
4222 if (address_is_invalid_destination(to, 1)) {
4223 log_warn(LD_CONFIG,
4224 "Skipping invalid argument '%s' to MapAddress", to);
4225 } else {
4226 addressmap_register(from, tor_strdup(to), 0, ADDRMAPSRC_TORRC);
4227 if (smartlist_len(elts)>2) {
4228 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
4231 } else {
4232 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
4233 opt->value);
4235 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4236 smartlist_clear(elts);
4238 smartlist_free(elts);
4242 * Initialize the logs based on the configuration file.
4244 static int
4245 options_init_logs(or_options_t *options, int validate_only)
4247 config_line_t *opt;
4248 int ok;
4249 smartlist_t *elts;
4250 int daemon =
4251 #ifdef MS_WINDOWS
4253 #else
4254 options->RunAsDaemon;
4255 #endif
4257 ok = 1;
4258 elts = smartlist_create();
4260 for (opt = options->Logs; opt; opt = opt->next) {
4261 log_severity_list_t *severity;
4262 const char *cfg = opt->value;
4263 severity = tor_malloc_zero(sizeof(log_severity_list_t));
4264 if (parse_log_severity_config(&cfg, severity) < 0) {
4265 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
4266 opt->value);
4267 ok = 0; goto cleanup;
4270 smartlist_split_string(elts, cfg, NULL,
4271 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4273 if (smartlist_len(elts) == 0)
4274 smartlist_add(elts, tor_strdup("stdout"));
4276 if (smartlist_len(elts) == 1 &&
4277 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
4278 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
4279 int err = smartlist_len(elts) &&
4280 !strcasecmp(smartlist_get(elts,0), "stderr");
4281 if (!validate_only) {
4282 if (daemon) {
4283 log_warn(LD_CONFIG,
4284 "Can't log to %s with RunAsDaemon set; skipping stdout",
4285 err?"stderr":"stdout");
4286 } else {
4287 add_stream_log(severity, err?"<stderr>":"<stdout>",
4288 fileno(err?stderr:stdout));
4291 goto cleanup;
4293 if (smartlist_len(elts) == 1 &&
4294 !strcasecmp(smartlist_get(elts,0), "syslog")) {
4295 #ifdef HAVE_SYSLOG_H
4296 if (!validate_only) {
4297 add_syslog_log(severity);
4299 #else
4300 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
4301 #endif
4302 goto cleanup;
4305 if (smartlist_len(elts) == 2 &&
4306 !strcasecmp(smartlist_get(elts,0), "file")) {
4307 if (!validate_only) {
4308 if (add_file_log(severity, smartlist_get(elts, 1)) < 0) {
4309 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
4310 opt->value, strerror(errno));
4311 ok = 0;
4314 goto cleanup;
4317 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
4318 opt->value);
4319 ok = 0; goto cleanup;
4321 cleanup:
4322 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4323 smartlist_clear(elts);
4324 tor_free(severity);
4326 smartlist_free(elts);
4328 return ok?0:-1;
4331 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4332 * if the line is well-formed, and -1 if it isn't. If
4333 * <b>validate_only</b> is 0, and the line is well-formed, then add
4334 * the bridge described in the line to our internal bridge list. */
4335 static int
4336 parse_bridge_line(const char *line, int validate_only)
4338 smartlist_t *items = NULL;
4339 int r;
4340 char *addrport=NULL, *fingerprint=NULL;
4341 tor_addr_t addr;
4342 uint16_t port = 0;
4343 char digest[DIGEST_LEN];
4345 items = smartlist_create();
4346 smartlist_split_string(items, line, NULL,
4347 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4348 if (smartlist_len(items) < 1) {
4349 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
4350 goto err;
4352 addrport = smartlist_get(items, 0);
4353 smartlist_del_keeporder(items, 0);
4354 if (tor_addr_port_parse(addrport, &addr, &port)<0) {
4355 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
4356 goto err;
4358 if (!port) {
4359 log_info(LD_CONFIG,
4360 "Bridge address '%s' has no port; using default port 443.",
4361 addrport);
4362 port = 443;
4365 if (smartlist_len(items)) {
4366 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4367 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4368 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
4369 goto err;
4371 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4372 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
4373 goto err;
4377 if (!validate_only) {
4378 log_debug(LD_DIR, "Bridge at %s:%d (%s)", fmt_addr(&addr),
4379 (int)port,
4380 fingerprint ? fingerprint : "no key listed");
4381 bridge_add_from_config(&addr, port, fingerprint ? digest : NULL);
4384 r = 0;
4385 goto done;
4387 err:
4388 r = -1;
4390 done:
4391 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4392 smartlist_free(items);
4393 tor_free(addrport);
4394 tor_free(fingerprint);
4395 return r;
4398 /** Read the contents of a DirServer line from <b>line</b>. If
4399 * <b>validate_only</b> is 0, and the line is well-formed, and it
4400 * shares any bits with <b>required_type</b> or <b>required_type</b>
4401 * is 0, then add the dirserver described in the line (minus whatever
4402 * bits it's missing) as a valid authority. Return 0 on success,
4403 * or -1 if the line isn't well-formed or if we can't add it. */
4404 static int
4405 parse_dir_server_line(const char *line, authority_type_t required_type,
4406 int validate_only)
4408 smartlist_t *items = NULL;
4409 int r;
4410 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
4411 uint16_t dir_port = 0, or_port = 0;
4412 char digest[DIGEST_LEN];
4413 char v3_digest[DIGEST_LEN];
4414 authority_type_t type = V2_AUTHORITY;
4415 int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
4417 items = smartlist_create();
4418 smartlist_split_string(items, line, NULL,
4419 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4420 if (smartlist_len(items) < 1) {
4421 log_warn(LD_CONFIG, "No arguments on DirServer line.");
4422 goto err;
4425 if (is_legal_nickname(smartlist_get(items, 0))) {
4426 nickname = smartlist_get(items, 0);
4427 smartlist_del_keeporder(items, 0);
4430 while (smartlist_len(items)) {
4431 char *flag = smartlist_get(items, 0);
4432 if (TOR_ISDIGIT(flag[0]))
4433 break;
4434 if (!strcasecmp(flag, "v1")) {
4435 type |= (V1_AUTHORITY | HIDSERV_AUTHORITY);
4436 } else if (!strcasecmp(flag, "hs")) {
4437 type |= HIDSERV_AUTHORITY;
4438 } else if (!strcasecmp(flag, "no-hs")) {
4439 is_not_hidserv_authority = 1;
4440 } else if (!strcasecmp(flag, "bridge")) {
4441 type |= BRIDGE_AUTHORITY;
4442 } else if (!strcasecmp(flag, "no-v2")) {
4443 is_not_v2_authority = 1;
4444 } else if (!strcasecmpstart(flag, "orport=")) {
4445 int ok;
4446 char *portstring = flag + strlen("orport=");
4447 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
4448 if (!ok)
4449 log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
4450 portstring);
4451 } else if (!strcasecmpstart(flag, "v3ident=")) {
4452 char *idstr = flag + strlen("v3ident=");
4453 if (strlen(idstr) != HEX_DIGEST_LEN ||
4454 base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
4455 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirServer line",
4456 flag);
4457 } else {
4458 type |= V3_AUTHORITY;
4460 } else {
4461 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
4462 flag);
4464 tor_free(flag);
4465 smartlist_del_keeporder(items, 0);
4467 if (is_not_hidserv_authority)
4468 type &= ~HIDSERV_AUTHORITY;
4469 if (is_not_v2_authority)
4470 type &= ~V2_AUTHORITY;
4472 if (smartlist_len(items) < 2) {
4473 log_warn(LD_CONFIG, "Too few arguments to DirServer line.");
4474 goto err;
4476 addrport = smartlist_get(items, 0);
4477 smartlist_del_keeporder(items, 0);
4478 if (parse_addr_port(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
4479 log_warn(LD_CONFIG, "Error parsing DirServer address '%s'", addrport);
4480 goto err;
4482 if (!dir_port) {
4483 log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
4484 goto err;
4487 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4488 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4489 log_warn(LD_CONFIG, "Key digest for DirServer is wrong length %d.",
4490 (int)strlen(fingerprint));
4491 goto err;
4493 if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4494 /* a known bad fingerprint. refuse to use it. We can remove this
4495 * clause once Tor 0.1.2.17 is obsolete. */
4496 log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
4497 "torrc file (%s), or reinstall Tor and use the default torrc.",
4498 get_torrc_fname());
4499 goto err;
4501 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4502 log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
4503 goto err;
4506 if (!validate_only && (!required_type || required_type & type)) {
4507 if (required_type)
4508 type &= required_type; /* pare down what we think of them as an
4509 * authority for. */
4510 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
4511 address, (int)dir_port, (char*)smartlist_get(items,0));
4512 if (!add_trusted_dir_server(nickname, address, dir_port, or_port,
4513 digest, v3_digest, type))
4514 goto err;
4517 r = 0;
4518 goto done;
4520 err:
4521 r = -1;
4523 done:
4524 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4525 smartlist_free(items);
4526 tor_free(addrport);
4527 tor_free(address);
4528 tor_free(nickname);
4529 tor_free(fingerprint);
4530 return r;
4533 /** Adjust the value of options->DataDirectory, or fill it in if it's
4534 * absent. Return 0 on success, -1 on failure. */
4535 static int
4536 normalize_data_directory(or_options_t *options)
4538 #ifdef MS_WINDOWS
4539 char *p;
4540 if (options->DataDirectory)
4541 return 0; /* all set */
4542 p = tor_malloc(MAX_PATH);
4543 strlcpy(p,get_windows_conf_root(),MAX_PATH);
4544 options->DataDirectory = p;
4545 return 0;
4546 #else
4547 const char *d = options->DataDirectory;
4548 if (!d)
4549 d = "~/.tor";
4551 if (strncmp(d,"~/",2) == 0) {
4552 char *fn = expand_filename(d);
4553 if (!fn) {
4554 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
4555 return -1;
4557 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
4558 /* If our homedir is /, we probably don't want to use it. */
4559 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4560 * want. */
4561 log_warn(LD_CONFIG,
4562 "Default DataDirectory is \"~/.tor\". This expands to "
4563 "\"%s\", which is probably not what you want. Using "
4564 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
4565 tor_free(fn);
4566 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
4568 tor_free(options->DataDirectory);
4569 options->DataDirectory = fn;
4571 return 0;
4572 #endif
4575 /** Check and normalize the value of options->DataDirectory; return 0 if it
4576 * sane, -1 otherwise. */
4577 static int
4578 validate_data_directory(or_options_t *options)
4580 if (normalize_data_directory(options) < 0)
4581 return -1;
4582 tor_assert(options->DataDirectory);
4583 if (strlen(options->DataDirectory) > (512-128)) {
4584 log_warn(LD_CONFIG, "DataDirectory is too long.");
4585 return -1;
4587 return 0;
4590 /** This string must remain the same forevermore. It is how we
4591 * recognize that the torrc file doesn't need to be backed up. */
4592 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4593 "if you edit it, comments will not be preserved"
4594 /** This string can change; it tries to give the reader an idea
4595 * that editing this file by hand is not a good plan. */
4596 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4597 "to torrc.orig.1 or similar, and Tor will ignore it"
4599 /** Save a configuration file for the configuration in <b>options</b>
4600 * into the file <b>fname</b>. If the file already exists, and
4601 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4602 * replace it. Return 0 on success, -1 on failure. */
4603 static int
4604 write_configuration_file(const char *fname, or_options_t *options)
4606 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4607 int rename_old = 0, r;
4608 size_t len;
4610 tor_assert(fname);
4612 switch (file_status(fname)) {
4613 case FN_FILE:
4614 old_val = read_file_to_str(fname, 0, NULL);
4615 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4616 rename_old = 1;
4618 tor_free(old_val);
4619 break;
4620 case FN_NOENT:
4621 break;
4622 case FN_ERROR:
4623 case FN_DIR:
4624 default:
4625 log_warn(LD_CONFIG,
4626 "Config file \"%s\" is not a file? Failing.", fname);
4627 return -1;
4630 if (!(new_conf = options_dump(options, 1))) {
4631 log_warn(LD_BUG, "Couldn't get configuration string");
4632 goto err;
4635 len = strlen(new_conf)+256;
4636 new_val = tor_malloc(len);
4637 tor_snprintf(new_val, len, "%s\n%s\n\n%s",
4638 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4640 if (rename_old) {
4641 int i = 1;
4642 size_t fn_tmp_len = strlen(fname)+32;
4643 char *fn_tmp;
4644 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4645 fn_tmp = tor_malloc(fn_tmp_len);
4646 while (1) {
4647 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4648 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4649 tor_free(fn_tmp);
4650 goto err;
4652 if (file_status(fn_tmp) == FN_NOENT)
4653 break;
4654 ++i;
4656 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4657 if (rename(fname, fn_tmp) < 0) {
4658 log_warn(LD_FS,
4659 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4660 fname, fn_tmp, strerror(errno));
4661 tor_free(fn_tmp);
4662 goto err;
4664 tor_free(fn_tmp);
4667 if (write_str_to_file(fname, new_val, 0) < 0)
4668 goto err;
4670 r = 0;
4671 goto done;
4672 err:
4673 r = -1;
4674 done:
4675 tor_free(new_val);
4676 tor_free(new_conf);
4677 return r;
4681 * Save the current configuration file value to disk. Return 0 on
4682 * success, -1 on failure.
4685 options_save_current(void)
4687 if (torrc_fname) {
4688 /* This fails if we can't write to our configuration file.
4690 * If we try falling back to datadirectory or something, we have a better
4691 * chance of saving the configuration, but a better chance of doing
4692 * something the user never expected. Let's just warn instead. */
4693 return write_configuration_file(torrc_fname, get_options());
4695 return write_configuration_file(get_default_conf_file(), get_options());
4698 /** Mapping from a unit name to a multiplier for converting that unit into a
4699 * base unit. */
4700 struct unit_table_t {
4701 const char *unit;
4702 uint64_t multiplier;
4705 /** Table to map the names of memory units to the number of bytes they
4706 * contain. */
4707 static struct unit_table_t memory_units[] = {
4708 { "", 1 },
4709 { "b", 1<< 0 },
4710 { "byte", 1<< 0 },
4711 { "bytes", 1<< 0 },
4712 { "kb", 1<<10 },
4713 { "kbyte", 1<<10 },
4714 { "kbytes", 1<<10 },
4715 { "kilobyte", 1<<10 },
4716 { "kilobytes", 1<<10 },
4717 { "m", 1<<20 },
4718 { "mb", 1<<20 },
4719 { "mbyte", 1<<20 },
4720 { "mbytes", 1<<20 },
4721 { "megabyte", 1<<20 },
4722 { "megabytes", 1<<20 },
4723 { "gb", 1<<30 },
4724 { "gbyte", 1<<30 },
4725 { "gbytes", 1<<30 },
4726 { "gigabyte", 1<<30 },
4727 { "gigabytes", 1<<30 },
4728 { "tb", U64_LITERAL(1)<<40 },
4729 { "terabyte", U64_LITERAL(1)<<40 },
4730 { "terabytes", U64_LITERAL(1)<<40 },
4731 { NULL, 0 },
4734 /** Table to map the names of time units to the number of seconds they
4735 * contain. */
4736 static struct unit_table_t time_units[] = {
4737 { "", 1 },
4738 { "second", 1 },
4739 { "seconds", 1 },
4740 { "minute", 60 },
4741 { "minutes", 60 },
4742 { "hour", 60*60 },
4743 { "hours", 60*60 },
4744 { "day", 24*60*60 },
4745 { "days", 24*60*60 },
4746 { "week", 7*24*60*60 },
4747 { "weeks", 7*24*60*60 },
4748 { NULL, 0 },
4751 /** Parse a string <b>val</b> containing a number, zero or more
4752 * spaces, and an optional unit string. If the unit appears in the
4753 * table <b>u</b>, then multiply the number by the unit multiplier.
4754 * On success, set *<b>ok</b> to 1 and return this product.
4755 * Otherwise, set *<b>ok</b> to 0.
4757 static uint64_t
4758 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4760 uint64_t v;
4761 char *cp;
4763 tor_assert(ok);
4765 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4766 if (!*ok)
4767 return 0;
4768 if (!cp) {
4769 *ok = 1;
4770 return v;
4772 while (TOR_ISSPACE(*cp))
4773 ++cp;
4774 for ( ;u->unit;++u) {
4775 if (!strcasecmp(u->unit, cp)) {
4776 v *= u->multiplier;
4777 *ok = 1;
4778 return v;
4781 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4782 *ok = 0;
4783 return 0;
4786 /** Parse a string in the format "number unit", where unit is a unit of
4787 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4788 * and return the number of bytes specified. Otherwise, set
4789 * *<b>ok</b> to false and return 0. */
4790 static uint64_t
4791 config_parse_memunit(const char *s, int *ok)
4793 return config_parse_units(s, memory_units, ok);
4796 /** Parse a string in the format "number unit", where unit is a unit of time.
4797 * On success, set *<b>ok</b> to true and return the number of seconds in
4798 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4800 static int
4801 config_parse_interval(const char *s, int *ok)
4803 uint64_t r;
4804 r = config_parse_units(s, time_units, ok);
4805 if (!ok)
4806 return -1;
4807 if (r > INT_MAX) {
4808 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4809 *ok = 0;
4810 return -1;
4812 return (int)r;
4815 /* This is what passes for version detection on OSX. We set
4816 * MACOSX_KQUEUE_IS_BROKEN to true iff we're on a version of OSX before
4817 * 10.4.0 (aka 1040). */
4818 #ifdef __APPLE__
4819 #ifdef __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__
4820 #define MACOSX_KQUEUE_IS_BROKEN \
4821 (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1040)
4822 #else
4823 #define MACOSX_KQUEUE_IS_BROKEN 0
4824 #endif
4825 #endif
4828 * Initialize the libevent library.
4830 static void
4831 init_libevent(void)
4833 configure_libevent_logging();
4834 /* If the kernel complains that some method (say, epoll) doesn't
4835 * exist, we don't care about it, since libevent will cope.
4837 suppress_libevent_log_msg("Function not implemented");
4838 #ifdef __APPLE__
4839 if (MACOSX_KQUEUE_IS_BROKEN ||
4840 decode_libevent_version(event_get_version(), NULL) < LE_11B) {
4841 setenv("EVENT_NOKQUEUE","1",1);
4843 #endif
4845 /* In libevent versions before 2.0, it's hard to keep binary compatibility
4846 * between upgrades, and unpleasant to detect when the version we compiled
4847 * against is unlike the version we have linked against. Here's how. */
4848 #if defined(_EVENT_VERSION) && defined(HAVE_EVENT_GET_VERSION)
4849 /* We have a header-file version and a function-call version. Easy. */
4850 if (strcmp(_EVENT_VERSION, event_get_version())) {
4851 int compat1 = -1, compat2 = -1;
4852 int verybad, prettybad ;
4853 decode_libevent_version(_EVENT_VERSION, &compat1);
4854 decode_libevent_version(event_get_version(), &compat2);
4855 verybad = compat1 != compat2;
4856 prettybad = (compat1 == -1 || compat2 == -1) && compat1 != compat2;
4858 log(verybad ? LOG_WARN : (prettybad ? LOG_NOTICE : LOG_INFO),
4859 LD_GENERAL, "We were compiled with headers from version %s "
4860 "of Libevent, but we're using a Libevent library that says it's "
4861 "version %s.", _EVENT_VERSION, event_get_version());
4862 if (verybad)
4863 log_warn(LD_GENERAL, "This will almost certainly make Tor crash.");
4864 else if (prettybad)
4865 log_notice(LD_GENERAL, "If Tor crashes, this might be why.");
4866 else
4867 log_info(LD_GENERAL, "I think these versions are binary-compatible.");
4869 #elif defined(HAVE_EVENT_GET_VERSION)
4870 /* event_get_version but no _EVENT_VERSION. We might be in 1.4.0-beta or
4871 earlier, where that's normal. To see whether we were compiled with an
4872 earlier version, let's see whether the struct event defines MIN_HEAP_IDX.
4874 #ifdef HAVE_STRUCT_EVENT_MIN_HEAP_IDX
4875 /* The header files are 1.4.0-beta or later. If the version is not
4876 * 1.4.0-beta, we are incompatible. */
4878 if (strcmp(event_get_version(), "1.4.0-beta")) {
4879 log_warn(LD_GENERAL, "It's a little hard to tell, but you seem to have "
4880 "Libevent 1.4.0-beta header files, whereas you have linked "
4881 "against Libevent %s. This will probably make Tor crash.",
4882 event_get_version());
4885 #else
4886 /* Our headers are 1.3e or earlier. If the library version is not 1.4.x or
4887 later, we're probably fine. */
4889 const char *v = event_get_version();
4890 if ((v[0] == '1' && v[2] == '.' && v[3] > '3') || v[0] > '1') {
4891 log_warn(LD_GENERAL, "It's a little hard to tell, but you seem to have "
4892 "Libevent header file from 1.3e or earlier, whereas you have "
4893 "linked against Libevent %s. This will probably make Tor "
4894 "crash.", event_get_version());
4897 #endif
4899 #elif defined(_EVENT_VERSION)
4900 #warn "_EVENT_VERSION is defined but not get_event_version(): Libevent is odd."
4901 #else
4902 /* Your libevent is ancient. */
4903 #endif
4905 event_init();
4906 suppress_libevent_log_msg(NULL);
4907 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4908 /* Making this a NOTICE for now so we can link bugs to a libevent versions
4909 * or methods better. */
4910 log(LOG_NOTICE, LD_GENERAL,
4911 "Initialized libevent version %s using method %s. Good.",
4912 event_get_version(), event_get_method());
4913 check_libevent_version(event_get_method(), get_options()->ORPort != 0);
4914 #else
4915 log(LOG_NOTICE, LD_GENERAL,
4916 "Initialized old libevent (version 1.0b or earlier).");
4917 log(LOG_WARN, LD_GENERAL,
4918 "You have a *VERY* old version of libevent. It is likely to be buggy; "
4919 "please build Tor with a more recent version.");
4920 #endif
4923 /** Table mapping return value of event_get_version() to le_version_t. */
4924 static const struct {
4925 const char *name; le_version_t version; int bincompat;
4926 } le_version_table[] = {
4927 /* earlier versions don't have get_version. */
4928 { "1.0c", LE_10C, 1},
4929 { "1.0d", LE_10D, 1},
4930 { "1.0e", LE_10E, 1},
4931 { "1.1", LE_11, 1 },
4932 { "1.1a", LE_11A, 1 },
4933 { "1.1b", LE_11B, 1 },
4934 { "1.2", LE_12, 1 },
4935 { "1.2a", LE_12A, 1 },
4936 { "1.3", LE_13, 1 },
4937 { "1.3a", LE_13A, 1 },
4938 { "1.3b", LE_13B, 1 },
4939 { "1.3c", LE_13C, 1 },
4940 { "1.3d", LE_13D, 1 },
4941 { "1.3e", LE_13E, 1 },
4942 { "1.4.0-beta", LE_140, 2 },
4943 { "1.4.1-beta", LE_141, 2 },
4944 { "1.4.2-rc", LE_142, 2 },
4945 { "1.4.3-stable", LE_143, 2 },
4946 { "1.4.4-stable", LE_144, 2 },
4947 { "1.4.5-stable", LE_145, 2 },
4948 { "1.4.6-stable", LE_146, 2 },
4949 { "1.4.7-stable", LE_147, 2 },
4950 { "1.4.8-stable", LE_148, 2 },
4951 { "1.4.99-trunk", LE_1499, 3 },
4952 { NULL, LE_OTHER, 0 }
4955 /** Return the le_version_t for the current version of libevent. If the
4956 * version is very new, return LE_OTHER. If the version is so old that it
4957 * doesn't support event_get_version(), return LE_OLD. */
4958 static le_version_t
4959 decode_libevent_version(const char *v, int *bincompat_out)
4961 int i;
4962 for (i=0; le_version_table[i].name; ++i) {
4963 if (!strcmp(le_version_table[i].name, v)) {
4964 if (bincompat_out)
4965 *bincompat_out = le_version_table[i].bincompat;
4966 return le_version_table[i].version;
4969 if (v[0] != '1' && bincompat_out)
4970 *bincompat_out = 100;
4971 else if (!strcmpstart(v, "1.4") && bincompat_out)
4972 *bincompat_out = 2;
4973 return LE_OTHER;
4976 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4978 * Compare the given libevent method and version to a list of versions
4979 * which are known not to work. Warn the user as appropriate.
4981 static void
4982 check_libevent_version(const char *m, int server)
4984 int buggy = 0, iffy = 0, slow = 0, thread_unsafe = 0;
4985 le_version_t version;
4986 const char *v = event_get_version();
4987 const char *badness = NULL;
4988 const char *sad_os = "";
4990 version = decode_libevent_version(v, NULL);
4992 /* XXX Would it be worthwhile disabling the methods that we know
4993 * are buggy, rather than just warning about them and then proceeding
4994 * to use them? If so, we should probably not wrap this whole thing
4995 * in HAVE_EVENT_GET_VERSION and HAVE_EVENT_GET_METHOD. -RD */
4996 /* XXXX The problem is that it's not trivial to get libevent to change it's
4997 * method once it's initialized, and it's not trivial to tell what method it
4998 * will use without initializing it. I guess we could preemptively disable
4999 * buggy libevent modes based on the version _before_ initializing it,
5000 * though, but then there's no good way (afaict) to warn "I would have used
5001 * kqueue, but instead I'm using select." -NM */
5002 if (!strcmp(m, "kqueue")) {
5003 if (version < LE_11B)
5004 buggy = 1;
5005 } else if (!strcmp(m, "epoll")) {
5006 if (version < LE_11)
5007 iffy = 1;
5008 } else if (!strcmp(m, "poll")) {
5009 if (version < LE_10E)
5010 buggy = 1;
5011 else if (version < LE_11)
5012 slow = 1;
5013 } else if (!strcmp(m, "select")) {
5014 if (version < LE_11)
5015 slow = 1;
5016 } else if (!strcmp(m, "win32")) {
5017 if (version < LE_11B)
5018 buggy = 1;
5021 /* Libevent versions before 1.3b do very badly on operating systems with
5022 * user-space threading implementations. */
5023 #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
5024 if (server && version < LE_13B) {
5025 thread_unsafe = 1;
5026 sad_os = "BSD variants";
5028 #elif defined(__APPLE__) || defined(__darwin__)
5029 if (server && version < LE_13B) {
5030 thread_unsafe = 1;
5031 sad_os = "Mac OS X";
5033 #endif
5035 if (thread_unsafe) {
5036 log(LOG_WARN, LD_GENERAL,
5037 "Libevent version %s often crashes when running a Tor server with %s. "
5038 "Please use the latest version of libevent (1.3b or later)",v,sad_os);
5039 badness = "BROKEN";
5040 } else if (buggy) {
5041 log(LOG_WARN, LD_GENERAL,
5042 "There are serious bugs in using %s with libevent %s. "
5043 "Please use the latest version of libevent.", m, v);
5044 badness = "BROKEN";
5045 } else if (iffy) {
5046 log(LOG_WARN, LD_GENERAL,
5047 "There are minor bugs in using %s with libevent %s. "
5048 "You may want to use the latest version of libevent.", m, v);
5049 badness = "BUGGY";
5050 } else if (slow && server) {
5051 log(LOG_WARN, LD_GENERAL,
5052 "libevent %s can be very slow with %s. "
5053 "When running a server, please use the latest version of libevent.",
5054 v,m);
5055 badness = "SLOW";
5057 if (badness) {
5058 control_event_general_status(LOG_WARN,
5059 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
5060 v, m, badness);
5064 #endif
5066 /** Return the persistent state struct for this Tor. */
5067 or_state_t *
5068 get_or_state(void)
5070 tor_assert(global_state);
5071 return global_state;
5074 /** Return a newly allocated string holding a filename relative to the data
5075 * directory. If <b>sub1</b> is present, it is the first path component after
5076 * the data directory. If <b>sub2</b> is also present, it is the second path
5077 * component after the data directory. If <b>suffix</b> is present, it
5078 * is appended to the filename.
5080 * Examples:
5081 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
5082 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
5083 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
5084 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
5086 * Note: Consider using the get_datadir_fname* macros in or.h.
5088 char *
5089 options_get_datadir_fname2_suffix(or_options_t *options,
5090 const char *sub1, const char *sub2,
5091 const char *suffix)
5093 char *fname = NULL;
5094 size_t len;
5095 tor_assert(options);
5096 tor_assert(options->DataDirectory);
5097 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
5098 len = strlen(options->DataDirectory);
5099 if (sub1) {
5100 len += strlen(sub1)+1;
5101 if (sub2)
5102 len += strlen(sub2)+1;
5104 if (suffix)
5105 len += strlen(suffix);
5106 len++;
5107 fname = tor_malloc(len);
5108 if (sub1) {
5109 if (sub2) {
5110 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
5111 options->DataDirectory, sub1, sub2);
5112 } else {
5113 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
5114 options->DataDirectory, sub1);
5116 } else {
5117 strlcpy(fname, options->DataDirectory, len);
5119 if (suffix)
5120 strlcat(fname, suffix, len);
5121 return fname;
5124 /** Return 0 if every setting in <b>state</b> is reasonable, and a
5125 * permissible transition from <b>old_state</b>. Else warn and return -1.
5126 * Should have no side effects, except for normalizing the contents of
5127 * <b>state</b>.
5129 /* XXX from_setconf is here because of bug 238 */
5130 static int
5131 or_state_validate(or_state_t *old_state, or_state_t *state,
5132 int from_setconf, char **msg)
5134 /* We don't use these; only options do. Still, we need to match that
5135 * signature. */
5136 (void) from_setconf;
5137 (void) old_state;
5139 if (entry_guards_parse_state(state, 0, msg)<0)
5140 return -1;
5142 return 0;
5145 /** Replace the current persistent state with <b>new_state</b> */
5146 static void
5147 or_state_set(or_state_t *new_state)
5149 char *err = NULL;
5150 tor_assert(new_state);
5151 if (global_state)
5152 config_free(&state_format, global_state);
5153 global_state = new_state;
5154 if (entry_guards_parse_state(global_state, 1, &err)<0) {
5155 log_warn(LD_GENERAL,"%s",err);
5156 tor_free(err);
5158 if (rep_hist_load_state(global_state, &err)<0) {
5159 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
5160 tor_free(err);
5164 /** Reload the persistent state from disk, generating a new state as needed.
5165 * Return 0 on success, less than 0 on failure.
5167 static int
5168 or_state_load(void)
5170 or_state_t *new_state = NULL;
5171 char *contents = NULL, *fname;
5172 char *errmsg = NULL;
5173 int r = -1, badstate = 0;
5175 fname = get_datadir_fname("state");
5176 switch (file_status(fname)) {
5177 case FN_FILE:
5178 if (!(contents = read_file_to_str(fname, 0, NULL))) {
5179 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
5180 goto done;
5182 break;
5183 case FN_NOENT:
5184 break;
5185 case FN_ERROR:
5186 case FN_DIR:
5187 default:
5188 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
5189 goto done;
5191 new_state = tor_malloc_zero(sizeof(or_state_t));
5192 new_state->_magic = OR_STATE_MAGIC;
5193 config_init(&state_format, new_state);
5194 if (contents) {
5195 config_line_t *lines=NULL;
5196 int assign_retval;
5197 if (config_get_lines(contents, &lines)<0)
5198 goto done;
5199 assign_retval = config_assign(&state_format, new_state,
5200 lines, 0, 0, &errmsg);
5201 config_free_lines(lines);
5202 if (assign_retval<0)
5203 badstate = 1;
5204 if (errmsg) {
5205 log_warn(LD_GENERAL, "%s", errmsg);
5206 tor_free(errmsg);
5210 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
5211 badstate = 1;
5213 if (errmsg) {
5214 log_warn(LD_GENERAL, "%s", errmsg);
5215 tor_free(errmsg);
5218 if (badstate && !contents) {
5219 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
5220 " This is a bug in Tor.");
5221 goto done;
5222 } else if (badstate && contents) {
5223 int i;
5224 file_status_t status;
5225 size_t len = strlen(fname)+16;
5226 char *fname2 = tor_malloc(len);
5227 for (i = 0; i < 100; ++i) {
5228 tor_snprintf(fname2, len, "%s.%d", fname, i);
5229 status = file_status(fname2);
5230 if (status == FN_NOENT)
5231 break;
5233 if (i == 100) {
5234 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
5235 "state files to move aside. Discarding the old state file.",
5236 fname);
5237 unlink(fname);
5238 } else {
5239 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
5240 "to \"%s\". This could be a bug in Tor; please tell "
5241 "the developers.", fname, fname2);
5242 if (rename(fname, fname2) < 0) {
5243 log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
5244 "OS gave an error of %s", strerror(errno));
5247 tor_free(fname2);
5248 tor_free(contents);
5249 config_free(&state_format, new_state);
5251 new_state = tor_malloc_zero(sizeof(or_state_t));
5252 new_state->_magic = OR_STATE_MAGIC;
5253 config_init(&state_format, new_state);
5254 } else if (contents) {
5255 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
5256 } else {
5257 log_info(LD_GENERAL, "Initialized state");
5259 or_state_set(new_state);
5260 new_state = NULL;
5261 if (!contents) {
5262 global_state->next_write = 0;
5263 or_state_save(time(NULL));
5265 r = 0;
5267 done:
5268 tor_free(fname);
5269 tor_free(contents);
5270 if (new_state)
5271 config_free(&state_format, new_state);
5273 return r;
5276 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
5278 or_state_save(time_t now)
5280 char *state, *contents;
5281 char tbuf[ISO_TIME_LEN+1];
5282 size_t len;
5283 char *fname;
5285 tor_assert(global_state);
5287 if (global_state->next_write > now)
5288 return 0;
5290 /* Call everything else that might dirty the state even more, in order
5291 * to avoid redundant writes. */
5292 entry_guards_update_state(global_state);
5293 rep_hist_update_state(global_state);
5294 if (accounting_is_enabled(get_options()))
5295 accounting_run_housekeeping(now);
5297 global_state->LastWritten = time(NULL);
5298 tor_free(global_state->TorVersion);
5299 len = strlen(get_version())+8;
5300 global_state->TorVersion = tor_malloc(len);
5301 tor_snprintf(global_state->TorVersion, len, "Tor %s", get_version());
5303 state = config_dump(&state_format, global_state, 1, 0);
5304 len = strlen(state)+256;
5305 contents = tor_malloc(len);
5306 format_local_iso_time(tbuf, time(NULL));
5307 tor_snprintf(contents, len,
5308 "# Tor state file last generated on %s local time\n"
5309 "# Other times below are in GMT\n"
5310 "# You *do not* need to edit this file.\n\n%s",
5311 tbuf, state);
5312 tor_free(state);
5313 fname = get_datadir_fname("state");
5314 if (write_str_to_file(fname, contents, 0)<0) {
5315 log_warn(LD_FS, "Unable to write state to file \"%s\"; "
5316 "will try again later", fname);
5317 tor_free(fname);
5318 tor_free(contents);
5319 return -1;
5321 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
5322 tor_free(fname);
5323 tor_free(contents);
5325 global_state->next_write = TIME_MAX;
5326 return 0;
5329 /** Given a file name check to see whether the file exists but has not been
5330 * modified for a very long time. If so, remove it. */
5331 void
5332 remove_file_if_very_old(const char *fname, time_t now)
5334 #define VERY_OLD_FILE_AGE (28*24*60*60)
5335 struct stat st;
5337 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
5338 char buf[ISO_TIME_LEN+1];
5339 format_local_iso_time(buf, st.st_mtime);
5340 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
5341 "Removing it.", fname, buf);
5342 unlink(fname);
5346 /** Helper to implement GETINFO functions about configuration variables (not
5347 * their values). Given a "config/names" question, set *<b>answer</b> to a
5348 * new string describing the supported configuration variables and their
5349 * types. */
5351 getinfo_helper_config(control_connection_t *conn,
5352 const char *question, char **answer)
5354 (void) conn;
5355 if (!strcmp(question, "config/names")) {
5356 smartlist_t *sl = smartlist_create();
5357 int i;
5358 for (i = 0; _option_vars[i].name; ++i) {
5359 config_var_t *var = &_option_vars[i];
5360 const char *type, *desc;
5361 char *line;
5362 size_t len;
5363 desc = config_find_description(&options_format, var->name);
5364 switch (var->type) {
5365 case CONFIG_TYPE_STRING: type = "String"; break;
5366 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
5367 case CONFIG_TYPE_UINT: type = "Integer"; break;
5368 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
5369 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
5370 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
5371 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
5372 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
5373 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
5374 case CONFIG_TYPE_CSV: type = "CommaList"; break;
5375 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
5376 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
5377 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
5378 default:
5379 case CONFIG_TYPE_OBSOLETE:
5380 type = NULL; break;
5382 if (!type)
5383 continue;
5384 len = strlen(var->name)+strlen(type)+16;
5385 if (desc)
5386 len += strlen(desc);
5387 line = tor_malloc(len);
5388 if (desc)
5389 tor_snprintf(line, len, "%s %s %s\n",var->name,type,desc);
5390 else
5391 tor_snprintf(line, len, "%s %s\n",var->name,type);
5392 smartlist_add(sl, line);
5394 *answer = smartlist_join_strings(sl, "", 0, NULL);
5395 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
5396 smartlist_free(sl);
5398 return 0;