Clean up a bit of C logic, and fix an erroneous warning.
[tor/rransom.git] / src / or / config.c
blob81999516ddb5ad25018eb9f0ec7dae92a3c0f0f6
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2009, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file config.c
9 * \brief Code to parse and interpret configuration files.
10 **/
12 #define CONFIG_PRIVATE
14 #include "or.h"
15 #ifdef MS_WINDOWS
16 #include <shlobj.h>
17 #endif
19 /** Enumeration of types which option values can take */
20 typedef enum config_type_t {
21 CONFIG_TYPE_STRING = 0, /**< An arbitrary string. */
22 CONFIG_TYPE_FILENAME, /**< A filename: some prefixes get expanded. */
23 CONFIG_TYPE_UINT, /**< A non-negative integer less than MAX_INT */
24 CONFIG_TYPE_INTERVAL, /**< A number of seconds, with optional units*/
25 CONFIG_TYPE_MEMUNIT, /**< A number of bytes, with optional units*/
26 CONFIG_TYPE_DOUBLE, /**< A floating-point value */
27 CONFIG_TYPE_BOOL, /**< A boolean value, expressed as 0 or 1. */
28 CONFIG_TYPE_ISOTIME, /**< An ISO-formatted time relative to GMT. */
29 CONFIG_TYPE_CSV, /**< A list of strings, separated by commas and
30 * optional whitespace. */
31 CONFIG_TYPE_LINELIST, /**< Uninterpreted config lines */
32 CONFIG_TYPE_LINELIST_S, /**< Uninterpreted, context-sensitive config lines,
33 * mixed with other keywords. */
34 CONFIG_TYPE_LINELIST_V, /**< Catch-all "virtual" option to summarize
35 * context-sensitive config lines when fetching.
37 CONFIG_TYPE_ROUTERSET, /**< A list of router names, addrs, and fps,
38 * parsed into a routerset_t. */
39 CONFIG_TYPE_OBSOLETE, /**< Obsolete (ignored) option. */
40 } config_type_t;
42 /** An abbreviation for a configuration option allowed on the command line. */
43 typedef struct config_abbrev_t {
44 const char *abbreviated;
45 const char *full;
46 int commandline_only;
47 int warn;
48 } config_abbrev_t;
50 /* Handy macro for declaring "In the config file or on the command line,
51 * you can abbreviate <b>tok</b>s as <b>tok</b>". */
52 #define PLURAL(tok) { #tok, #tok "s", 0, 0 }
54 /** A list of abbreviations and aliases to map command-line options, obsolete
55 * option names, or alternative option names, to their current values. */
56 static config_abbrev_t _option_abbrevs[] = {
57 PLURAL(ExitNode),
58 PLURAL(EntryNode),
59 PLURAL(ExcludeNode),
60 PLURAL(FirewallPort),
61 PLURAL(LongLivedPort),
62 PLURAL(HiddenServiceNode),
63 PLURAL(HiddenServiceExcludeNode),
64 PLURAL(NumCpu),
65 PLURAL(RendNode),
66 PLURAL(RendExcludeNode),
67 PLURAL(StrictEntryNode),
68 PLURAL(StrictExitNode),
69 { "l", "Log", 1, 0},
70 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
71 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
72 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
73 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
74 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
75 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
76 { "MaxConn", "ConnLimit", 0, 1},
77 { "ORBindAddress", "ORListenAddress", 0, 0},
78 { "DirBindAddress", "DirListenAddress", 0, 0},
79 { "SocksBindAddress", "SocksListenAddress", 0, 0},
80 { "UseHelperNodes", "UseEntryGuards", 0, 0},
81 { "NumHelperNodes", "NumEntryGuards", 0, 0},
82 { "UseEntryNodes", "UseEntryGuards", 0, 0},
83 { "NumEntryNodes", "NumEntryGuards", 0, 0},
84 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
85 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
86 { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0 },
87 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
88 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
89 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
90 { NULL, NULL, 0, 0},
93 /** A list of state-file "abbreviations," for compatibility. */
94 static config_abbrev_t _state_abbrevs[] = {
95 { "AccountingBytesReadInterval", "AccountingBytesReadInInterval", 0, 0 },
96 { "HelperNode", "EntryGuard", 0, 0 },
97 { "HelperNodeDownSince", "EntryGuardDownSince", 0, 0 },
98 { "HelperNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
99 { "EntryNode", "EntryGuard", 0, 0 },
100 { "EntryNodeDownSince", "EntryGuardDownSince", 0, 0 },
101 { "EntryNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
102 { NULL, NULL, 0, 0},
104 #undef PLURAL
106 /** A variable allowed in the configuration file or on the command line. */
107 typedef struct config_var_t {
108 const char *name; /**< The full keyword (case insensitive). */
109 config_type_t type; /**< How to interpret the type and turn it into a
110 * value. */
111 off_t var_offset; /**< Offset of the corresponding member of or_options_t. */
112 const char *initvalue; /**< String (or null) describing initial value. */
113 } config_var_t;
115 /** An entry for config_vars: "The option <b>name</b> has type
116 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
117 * or_options_t.<b>member</b>"
119 #define VAR(name,conftype,member,initvalue) \
120 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
121 initvalue }
122 /** As VAR, but the option name and member name are the same. */
123 #define V(member,conftype,initvalue) \
124 VAR(#member, conftype, member, initvalue)
125 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
126 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
128 /** Array of configuration options. Until we disallow nonstandard
129 * abbreviations, order is significant, since the first matching option will
130 * be chosen first.
132 static config_var_t _option_vars[] = {
133 OBSOLETE("AccountingMaxKB"),
134 V(AccountingMax, MEMUNIT, "0 bytes"),
135 V(AccountingStart, STRING, NULL),
136 V(Address, STRING, NULL),
137 V(AllowInvalidNodes, CSV, "middle,rendezvous"),
138 V(AllowNonRFC953Hostnames, BOOL, "0"),
139 V(AllowSingleHopCircuits, BOOL, "0"),
140 V(AllowSingleHopExits, BOOL, "0"),
141 V(AlternateBridgeAuthority, LINELIST, NULL),
142 V(AlternateDirAuthority, LINELIST, NULL),
143 V(AlternateHSAuthority, LINELIST, NULL),
144 V(AssumeReachable, BOOL, "0"),
145 V(AuthDirBadDir, LINELIST, NULL),
146 V(AuthDirBadExit, LINELIST, NULL),
147 V(AuthDirInvalid, LINELIST, NULL),
148 V(AuthDirReject, LINELIST, NULL),
149 V(AuthDirRejectUnlisted, BOOL, "0"),
150 V(AuthDirListBadDirs, BOOL, "0"),
151 V(AuthDirListBadExits, BOOL, "0"),
152 V(AuthDirMaxServersPerAddr, UINT, "2"),
153 V(AuthDirMaxServersPerAuthAddr,UINT, "5"),
154 VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
155 V(AutomapHostsOnResolve, BOOL, "0"),
156 V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
157 V(AvoidDiskWrites, BOOL, "0"),
158 V(BandwidthBurst, MEMUNIT, "10 MB"),
159 V(BandwidthRate, MEMUNIT, "5 MB"),
160 V(BridgeAuthoritativeDir, BOOL, "0"),
161 VAR("Bridge", LINELIST, Bridges, NULL),
162 V(BridgePassword, STRING, NULL),
163 V(BridgeRecordUsageByCountry, BOOL, "1"),
164 V(BridgeRelay, BOOL, "0"),
165 V(CircuitBuildTimeout, INTERVAL, "1 minute"),
166 V(CircuitIdleTimeout, INTERVAL, "1 hour"),
167 V(ClientDNSRejectInternalAddresses, BOOL,"1"),
168 V(ClientOnly, BOOL, "0"),
169 V(ConnLimit, UINT, "1000"),
170 V(ConstrainedSockets, BOOL, "0"),
171 V(ConstrainedSockSize, MEMUNIT, "8192"),
172 V(ContactInfo, STRING, NULL),
173 V(ControlListenAddress, LINELIST, NULL),
174 V(ControlPort, UINT, "0"),
175 V(ControlSocket, LINELIST, NULL),
176 V(CookieAuthentication, BOOL, "0"),
177 V(CookieAuthFileGroupReadable, BOOL, "0"),
178 V(CookieAuthFile, STRING, NULL),
179 V(DataDirectory, FILENAME, NULL),
180 OBSOLETE("DebugLogFile"),
181 V(DirAllowPrivateAddresses, BOOL, NULL),
182 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
183 V(DirListenAddress, LINELIST, NULL),
184 OBSOLETE("DirFetchPeriod"),
185 V(DirPolicy, LINELIST, NULL),
186 V(DirPort, UINT, "0"),
187 V(DirPortFrontPage, FILENAME, NULL),
188 OBSOLETE("DirPostPeriod"),
189 #ifdef ENABLE_GEOIP_STATS
190 V(DirRecordUsageByCountry, BOOL, "0"),
191 V(DirRecordUsageGranularity, UINT, "4"),
192 V(DirRecordUsageRetainIPs, INTERVAL, "14 days"),
193 V(DirRecordUsageSaveInterval, INTERVAL, "6 hours"),
194 #endif
195 VAR("DirServer", LINELIST, DirServers, NULL),
196 V(DNSPort, UINT, "0"),
197 V(DNSListenAddress, LINELIST, NULL),
198 V(DownloadExtraInfo, BOOL, "0"),
199 V(EnforceDistinctSubnets, BOOL, "1"),
200 V(EntryNodes, ROUTERSET, NULL),
201 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
202 V(ExcludeNodes, ROUTERSET, NULL),
203 V(ExcludeExitNodes, ROUTERSET, NULL),
204 V(ExcludeSingleHopRelays, BOOL, "1"),
205 V(ExitNodes, ROUTERSET, NULL),
206 V(ExitPolicy, LINELIST, NULL),
207 V(ExitPolicyRejectPrivate, BOOL, "1"),
208 V(FallbackNetworkstatusFile, FILENAME,
209 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "fallback-consensus"),
210 V(FascistFirewall, BOOL, "0"),
211 V(FirewallPorts, CSV, ""),
212 V(FastFirstHopPK, BOOL, "1"),
213 V(FetchDirInfoEarly, BOOL, "0"),
214 V(FetchServerDescriptors, BOOL, "1"),
215 V(FetchHidServDescriptors, BOOL, "1"),
216 V(FetchUselessDescriptors, BOOL, "0"),
217 #ifdef WIN32
218 V(GeoIPFile, FILENAME, "<default>"),
219 #else
220 V(GeoIPFile, FILENAME,
221 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
222 #endif
223 OBSOLETE("Group"),
224 V(HardwareAccel, BOOL, "0"),
225 V(HashedControlPassword, LINELIST, NULL),
226 V(HidServDirectoryV2, BOOL, "1"),
227 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
228 OBSOLETE("HiddenServiceExcludeNodes"),
229 OBSOLETE("HiddenServiceNodes"),
230 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
231 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
232 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
233 VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
234 V(HidServAuth, LINELIST, NULL),
235 V(HSAuthoritativeDir, BOOL, "0"),
236 V(HSAuthorityRecordStats, BOOL, "0"),
237 V(HttpProxy, STRING, NULL),
238 V(HttpProxyAuthenticator, STRING, NULL),
239 V(HttpsProxy, STRING, NULL),
240 V(HttpsProxyAuthenticator, STRING, NULL),
241 OBSOLETE("IgnoreVersion"),
242 V(KeepalivePeriod, INTERVAL, "5 minutes"),
243 VAR("Log", LINELIST, Logs, NULL),
244 OBSOLETE("LinkPadding"),
245 OBSOLETE("LogLevel"),
246 OBSOLETE("LogFile"),
247 V(LongLivedPorts, CSV,
248 "21,22,706,1863,5050,5190,5222,5223,6667,6697,8300"),
249 VAR("MapAddress", LINELIST, AddressMap, NULL),
250 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
251 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
252 V(MaxOnionsPending, UINT, "100"),
253 OBSOLETE("MonthlyAccountingStart"),
254 V(MyFamily, STRING, NULL),
255 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
256 VAR("NamingAuthoritativeDirectory",BOOL, NamingAuthoritativeDir, "0"),
257 V(NatdListenAddress, LINELIST, NULL),
258 V(NatdPort, UINT, "0"),
259 V(Nickname, STRING, NULL),
260 V(NoPublish, BOOL, "0"),
261 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
262 V(NumCpus, UINT, "1"),
263 V(NumEntryGuards, UINT, "3"),
264 V(ORListenAddress, LINELIST, NULL),
265 V(ORPort, UINT, "0"),
266 V(OutboundBindAddress, STRING, NULL),
267 OBSOLETE("PathlenCoinWeight"),
268 V(PidFile, STRING, NULL),
269 V(TestingTorNetwork, BOOL, "0"),
270 V(PreferTunneledDirConns, BOOL, "1"),
271 V(ProtocolWarnings, BOOL, "0"),
272 V(PublishServerDescriptor, CSV, "1"),
273 V(PublishHidServDescriptors, BOOL, "1"),
274 V(ReachableAddresses, LINELIST, NULL),
275 V(ReachableDirAddresses, LINELIST, NULL),
276 V(ReachableORAddresses, LINELIST, NULL),
277 V(RecommendedVersions, LINELIST, NULL),
278 V(RecommendedClientVersions, LINELIST, NULL),
279 V(RecommendedServerVersions, LINELIST, NULL),
280 OBSOLETE("RedirectExit"),
281 V(RejectPlaintextPorts, CSV, ""),
282 V(RelayBandwidthBurst, MEMUNIT, "0"),
283 V(RelayBandwidthRate, MEMUNIT, "0"),
284 OBSOLETE("RendExcludeNodes"),
285 OBSOLETE("RendNodes"),
286 V(RendPostPeriod, INTERVAL, "1 hour"),
287 V(RephistTrackTime, INTERVAL, "24 hours"),
288 OBSOLETE("RouterFile"),
289 V(RunAsDaemon, BOOL, "0"),
290 V(RunTesting, BOOL, "0"),
291 V(SafeLogging, BOOL, "1"),
292 V(SafeSocks, BOOL, "0"),
293 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
294 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
295 V(ServerDNSDetectHijacking, BOOL, "1"),
296 V(ServerDNSRandomizeCase, BOOL, "1"),
297 V(ServerDNSResolvConfFile, STRING, NULL),
298 V(ServerDNSSearchDomains, BOOL, "0"),
299 V(ServerDNSTestAddresses, CSV,
300 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
301 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
302 V(SocksListenAddress, LINELIST, NULL),
303 V(SocksPolicy, LINELIST, NULL),
304 V(SocksPort, UINT, "9050"),
305 V(SocksTimeout, INTERVAL, "2 minutes"),
306 OBSOLETE("StatusFetchPeriod"),
307 V(StrictEntryNodes, BOOL, "0"),
308 V(StrictExitNodes, BOOL, "0"),
309 OBSOLETE("SysLog"),
310 V(TestSocks, BOOL, "0"),
311 OBSOLETE("TestVia"),
312 V(TrackHostExits, CSV, NULL),
313 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
314 OBSOLETE("TrafficShaping"),
315 V(TransListenAddress, LINELIST, NULL),
316 V(TransPort, UINT, "0"),
317 V(TunnelDirConns, BOOL, "1"),
318 V(UpdateBridgesFromAuthority, BOOL, "0"),
319 V(UseBridges, BOOL, "0"),
320 V(UseEntryGuards, BOOL, "1"),
321 V(User, STRING, NULL),
322 VAR("V1AuthoritativeDirectory",BOOL, V1AuthoritativeDir, "0"),
323 VAR("V2AuthoritativeDirectory",BOOL, V2AuthoritativeDir, "0"),
324 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
325 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
326 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
327 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
328 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
329 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
330 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
331 V(V3AuthNIntervalsValid, UINT, "3"),
332 V(V3AuthUseLegacyKey, BOOL, "0"),
333 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
334 V(VirtualAddrNetwork, STRING, "127.192.0.0/10"),
335 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
336 VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
337 VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
338 VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
339 VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
340 VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
341 NULL),
342 V(MinUptimeHidServDirectoryV2, INTERVAL, "24 hours"),
343 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
346 /** Override default values with these if the user sets the TestingTorNetwork
347 * option. */
348 static config_var_t testing_tor_network_defaults[] = {
349 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
350 V(DirAllowPrivateAddresses, BOOL, "1"),
351 V(EnforceDistinctSubnets, BOOL, "0"),
352 V(AssumeReachable, BOOL, "1"),
353 V(AuthDirMaxServersPerAddr, UINT, "0"),
354 V(AuthDirMaxServersPerAuthAddr,UINT, "0"),
355 V(ClientDNSRejectInternalAddresses, BOOL,"0"),
356 V(ExitPolicyRejectPrivate, BOOL, "0"),
357 V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
358 V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
359 V(V3AuthDistDelay, INTERVAL, "20 seconds"),
360 V(TestingV3AuthInitialVotingInterval, INTERVAL, "5 minutes"),
361 V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
362 V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
363 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
364 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
365 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
367 #undef VAR
369 #define VAR(name,conftype,member,initvalue) \
370 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
371 initvalue }
373 /** Array of "state" variables saved to the ~/.tor/state file. */
374 static config_var_t _state_vars[] = {
375 V(AccountingBytesReadInInterval, MEMUNIT, NULL),
376 V(AccountingBytesWrittenInInterval, MEMUNIT, NULL),
377 V(AccountingExpectedUsage, MEMUNIT, NULL),
378 V(AccountingIntervalStart, ISOTIME, NULL),
379 V(AccountingSecondsActive, INTERVAL, NULL),
381 VAR("EntryGuard", LINELIST_S, EntryGuards, NULL),
382 VAR("EntryGuardDownSince", LINELIST_S, EntryGuards, NULL),
383 VAR("EntryGuardUnlistedSince", LINELIST_S, EntryGuards, NULL),
384 VAR("EntryGuardAddedBy", LINELIST_S, EntryGuards, NULL),
385 V(EntryGuards, LINELIST_V, NULL),
387 V(BWHistoryReadEnds, ISOTIME, NULL),
388 V(BWHistoryReadInterval, UINT, "900"),
389 V(BWHistoryReadValues, CSV, ""),
390 V(BWHistoryWriteEnds, ISOTIME, NULL),
391 V(BWHistoryWriteInterval, UINT, "900"),
392 V(BWHistoryWriteValues, CSV, ""),
394 V(TorVersion, STRING, NULL),
396 V(LastRotatedOnionKey, ISOTIME, NULL),
397 V(LastWritten, ISOTIME, NULL),
399 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
402 #undef VAR
403 #undef V
404 #undef OBSOLETE
406 /** Represents an English description of a configuration variable; used when
407 * generating configuration file comments. */
408 typedef struct config_var_description_t {
409 const char *name;
410 const char *description;
411 } config_var_description_t;
413 /** Descriptions of the configuration options, to be displayed by online
414 * option browsers */
415 /* XXXX022 did anybody want this? at all? If not, kill it.*/
416 static config_var_description_t options_description[] = {
417 /* ==== general options */
418 { "AvoidDiskWrites", "If non-zero, try to write to disk less frequently than"
419 " we would otherwise." },
420 { "BandwidthRate", "A token bucket limits the average incoming bandwidth on "
421 "this node to the specified number of bytes per second." },
422 { "BandwidthBurst", "Limit the maximum token buffer size (also known as "
423 "burst) to the given number of bytes." },
424 { "ConnLimit", "Minimum number of simultaneous sockets we must have." },
425 { "ConstrainedSockets", "Shrink tx and rx buffers for sockets to avoid "
426 "system limits on vservers and related environments. See man page for "
427 "more information regarding this option." },
428 { "ConstrainedSockSize", "Limit socket buffers to this size when "
429 "ConstrainedSockets is enabled." },
430 /* ControlListenAddress */
431 { "ControlPort", "If set, Tor will accept connections from the same machine "
432 "(localhost only) on this port, and allow those connections to control "
433 "the Tor process using the Tor Control Protocol (described in "
434 "control-spec.txt).", },
435 { "CookieAuthentication", "If this option is set to 1, don't allow any "
436 "connections to the control port except when the connecting process "
437 "can read a file that Tor creates in its data directory." },
438 { "DataDirectory", "Store working data, state, keys, and caches here." },
439 { "DirServer", "Tor only trusts directories signed with one of these "
440 "servers' keys. Used to override the standard list of directory "
441 "authorities." },
442 /* { "FastFirstHopPK", "" }, */
443 /* FetchServerDescriptors, FetchHidServDescriptors,
444 * FetchUselessDescriptors */
445 { "HardwareAccel", "If set, Tor tries to use hardware crypto accelerators "
446 "when it can." },
447 /* HashedControlPassword */
448 { "HTTPProxy", "Force Tor to make all HTTP directory requests through this "
449 "host:port (or host:80 if port is not set)." },
450 { "HTTPProxyAuthenticator", "A username:password pair to be used with "
451 "HTTPProxy." },
452 { "HTTPSProxy", "Force Tor to make all TLS (SSL) connections through this "
453 "host:port (or host:80 if port is not set)." },
454 { "HTTPSProxyAuthenticator", "A username:password pair to be used with "
455 "HTTPSProxy." },
456 { "KeepalivePeriod", "Send a padding cell every N seconds to keep firewalls "
457 "from closing our connections while Tor is not in use." },
458 { "Log", "Where to send logging messages. Format is "
459 "minSeverity[-maxSeverity] (stderr|stdout|syslog|file FILENAME)." },
460 { "OutboundBindAddress", "Make all outbound connections originate from the "
461 "provided IP address (only useful for multiple network interfaces)." },
462 { "PIDFile", "On startup, write our PID to this file. On clean shutdown, "
463 "remove the file." },
464 { "PreferTunneledDirConns", "If non-zero, avoid directory servers that "
465 "don't support tunneled connections." },
466 /* PreferTunneledDirConns */
467 /* ProtocolWarnings */
468 /* RephistTrackTime */
469 { "RunAsDaemon", "If set, Tor forks and daemonizes to the background when "
470 "started. Unix only." },
471 { "SafeLogging", "If set to 0, Tor logs potentially sensitive strings "
472 "rather than replacing them with the string [scrubbed]." },
473 { "TunnelDirConns", "If non-zero, when a directory server we contact "
474 "supports it, we will build a one-hop circuit and make an encrypted "
475 "connection via its ORPort." },
476 { "User", "On startup, setuid to this user." },
478 /* ==== client options */
479 { "AllowInvalidNodes", "Where on our circuits should Tor allow servers "
480 "that the directory authorities haven't called \"valid\"?" },
481 { "AllowNonRFC953Hostnames", "If set to 1, we don't automatically reject "
482 "hostnames for having invalid characters." },
483 /* CircuitBuildTimeout, CircuitIdleTimeout */
484 { "ClientOnly", "If set to 1, Tor will under no circumstances run as a "
485 "server, even if ORPort is enabled." },
486 { "EntryNodes", "A list of preferred entry nodes to use for the first hop "
487 "in circuits, when possible." },
488 /* { "EnforceDistinctSubnets" , "" }, */
489 { "ExitNodes", "A list of preferred nodes to use for the last hop in "
490 "circuits, when possible." },
491 { "ExcludeNodes", "A list of nodes never to use when building a circuit." },
492 { "FascistFirewall", "If set, Tor will only create outgoing connections to "
493 "servers running on the ports listed in FirewallPorts." },
494 { "FirewallPorts", "A list of ports that we can connect to. Only used "
495 "when FascistFirewall is set." },
496 { "LongLivedPorts", "A list of ports for services that tend to require "
497 "high-uptime connections." },
498 { "MapAddress", "Force Tor to treat all requests for one address as if "
499 "they were for another." },
500 { "NewCircuitPeriod", "Force Tor to consider whether to build a new circuit "
501 "every NUM seconds." },
502 { "MaxCircuitDirtiness", "Do not attach new streams to a circuit that has "
503 "been used more than this many seconds ago." },
504 /* NatdPort, NatdListenAddress */
505 { "NodeFamily", "A list of servers that constitute a 'family' and should "
506 "never be used in the same circuit." },
507 { "NumEntryGuards", "How many entry guards should we keep at a time?" },
508 /* PathlenCoinWeight */
509 { "ReachableAddresses", "Addresses we can connect to, as IP/bits:port-port. "
510 "By default, we assume all addresses are reachable." },
511 /* reachablediraddresses, reachableoraddresses. */
512 /* SafeSOCKS */
513 { "SOCKSPort", "The port where we listen for SOCKS connections from "
514 "applications." },
515 { "SOCKSListenAddress", "Bind to this address to listen to connections from "
516 "SOCKS-speaking applications." },
517 { "SOCKSPolicy", "Set an entry policy to limit which addresses can connect "
518 "to the SOCKSPort." },
519 /* SocksTimeout */
520 { "StrictExitNodes", "If set, Tor will fail to operate when none of the "
521 "configured ExitNodes can be used." },
522 { "StrictEntryNodes", "If set, Tor will fail to operate when none of the "
523 "configured EntryNodes can be used." },
524 /* TestSocks */
525 { "TrackHostsExit", "Hosts and domains which should, if possible, be "
526 "accessed from the same exit node each time we connect to them." },
527 { "TrackHostsExitExpire", "Time after which we forget which exit we were "
528 "using to connect to hosts in TrackHostsExit." },
529 /* "TransPort", "TransListenAddress */
530 { "UseEntryGuards", "Set to 0 if we want to pick from the whole set of "
531 "servers for the first position in each circuit, rather than picking a "
532 "set of 'Guards' to prevent profiling attacks." },
534 /* === server options */
535 { "Address", "The advertised (external) address we should use." },
536 /* Accounting* options. */
537 /* AssumeReachable */
538 { "ContactInfo", "Administrative contact information to advertise for this "
539 "server." },
540 { "ExitPolicy", "Address/port ranges for which to accept or reject outgoing "
541 "connections on behalf of Tor users." },
542 /* { "ExitPolicyRejectPrivate, "" }, */
543 { "MaxAdvertisedBandwidth", "If set, we will not advertise more than this "
544 "amount of bandwidth for our bandwidth rate, regardless of how much "
545 "bandwidth we actually detect." },
546 { "MaxOnionsPending", "Reject new attempts to extend circuits when we "
547 "already have this many pending." },
548 { "MyFamily", "Declare a list of other servers as belonging to the same "
549 "family as this one, so that clients will not use two from the same "
550 "family in the same circuit." },
551 { "Nickname", "Set the server nickname." },
552 { "NoPublish", "{DEPRECATED}" },
553 { "NumCPUs", "How many processes to use at once for public-key crypto." },
554 { "ORPort", "Advertise this port to listen for connections from Tor clients "
555 "and servers." },
556 { "ORListenAddress", "Bind to this address to listen for connections from "
557 "clients and servers, instead of the default 0.0.0.0:ORPort." },
558 { "PublishServerDescriptor", "Set to 0 to keep the server from "
559 "uploading info to the directory authorities." },
560 /* ServerDNS: DetectHijacking, ResolvConfFile, SearchDomains */
561 { "ShutdownWaitLength", "Wait this long for clients to finish when "
562 "shutting down because of a SIGINT." },
564 /* === directory cache options */
565 { "DirPort", "Serve directory information from this port, and act as a "
566 "directory cache." },
567 { "DirPortFrontPage", "Serve a static html disclaimer on DirPort." },
568 { "DirListenAddress", "Bind to this address to listen for connections from "
569 "clients and servers, instead of the default 0.0.0.0:DirPort." },
570 { "DirPolicy", "Set a policy to limit who can connect to the directory "
571 "port." },
573 /* Authority options: AuthDirBadExit, AuthDirInvalid, AuthDirReject,
574 * AuthDirRejectUnlisted, AuthDirListBadExits, AuthoritativeDirectory,
575 * DirAllowPrivateAddresses, HSAuthoritativeDir,
576 * NamingAuthoritativeDirectory, RecommendedVersions,
577 * RecommendedClientVersions, RecommendedServerVersions, RendPostPeriod,
578 * RunTesting, V1AuthoritativeDirectory, VersioningAuthoritativeDirectory, */
580 /* Hidden service options: HiddenService: dir,excludenodes, nodes,
581 * options, port. PublishHidServDescriptor */
583 /* Nonpersistent options: __LeaveStreamsUnattached, __AllDirActionsPrivate */
584 { NULL, NULL },
587 /** Online description of state variables. */
588 static config_var_description_t state_description[] = {
589 { "AccountingBytesReadInInterval",
590 "How many bytes have we read in this accounting period?" },
591 { "AccountingBytesWrittenInInterval",
592 "How many bytes have we written in this accounting period?" },
593 { "AccountingExpectedUsage",
594 "How many bytes did we expect to use per minute? (0 for no estimate.)" },
595 { "AccountingIntervalStart", "When did this accounting period begin?" },
596 { "AccountingSecondsActive", "How long have we been awake in this period?" },
598 { "BWHistoryReadEnds", "When does the last-recorded read-interval end?" },
599 { "BWHistoryReadInterval", "How long is each read-interval (in seconds)?" },
600 { "BWHistoryReadValues", "Number of bytes read in each interval." },
601 { "BWHistoryWriteEnds", "When does the last-recorded write-interval end?" },
602 { "BWHistoryWriteInterval", "How long is each write-interval (in seconds)?"},
603 { "BWHistoryWriteValues", "Number of bytes written in each interval." },
605 { "EntryGuard", "One of the nodes we have chosen as a fixed entry" },
606 { "EntryGuardDownSince",
607 "The last entry guard has been unreachable since this time." },
608 { "EntryGuardUnlistedSince",
609 "The last entry guard has been unusable since this time." },
611 { "LastRotatedOnionKey",
612 "The last time at which we changed the medium-term private key used for "
613 "building circuits." },
614 { "LastWritten", "When was this state file last regenerated?" },
616 { "TorVersion", "Which version of Tor generated this state file?" },
617 { NULL, NULL },
620 /** Type of a callback to validate whether a given configuration is
621 * well-formed and consistent. See options_trial_assign() for documentation
622 * of arguments. */
623 typedef int (*validate_fn_t)(void*,void*,int,char**);
625 /** Information on the keys, value types, key-to-struct-member mappings,
626 * variable descriptions, validation functions, and abbreviations for a
627 * configuration or storage format. */
628 typedef struct {
629 size_t size; /**< Size of the struct that everything gets parsed into. */
630 uint32_t magic; /**< Required 'magic value' to make sure we have a struct
631 * of the right type. */
632 off_t magic_offset; /**< Offset of the magic value within the struct. */
633 config_abbrev_t *abbrevs; /**< List of abbreviations that we expand when
634 * parsing this format. */
635 config_var_t *vars; /**< List of variables we recognize, their default
636 * values, and where we stick them in the structure. */
637 validate_fn_t validate_fn; /**< Function to validate config. */
638 /** Documentation for configuration variables. */
639 config_var_description_t *descriptions;
640 /** If present, extra is a LINELIST variable for unrecognized
641 * lines. Otherwise, unrecognized lines are an error. */
642 config_var_t *extra;
643 } config_format_t;
645 /** Macro: assert that <b>cfg</b> has the right magic field for format
646 * <b>fmt</b>. */
647 #define CHECK(fmt, cfg) STMT_BEGIN \
648 tor_assert(fmt && cfg); \
649 tor_assert((fmt)->magic == \
650 *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
651 STMT_END
653 #ifdef MS_WINDOWS
654 static char *get_windows_conf_root(void);
655 #endif
656 static void config_line_append(config_line_t **lst,
657 const char *key, const char *val);
658 static void option_clear(config_format_t *fmt, or_options_t *options,
659 config_var_t *var);
660 static void option_reset(config_format_t *fmt, or_options_t *options,
661 config_var_t *var, int use_defaults);
662 static void config_free(config_format_t *fmt, void *options);
663 static int config_lines_eq(config_line_t *a, config_line_t *b);
664 static int option_is_same(config_format_t *fmt,
665 or_options_t *o1, or_options_t *o2,
666 const char *name);
667 static or_options_t *options_dup(config_format_t *fmt, or_options_t *old);
668 static int options_validate(or_options_t *old_options, or_options_t *options,
669 int from_setconf, char **msg);
670 static int options_act_reversible(or_options_t *old_options, char **msg);
671 static int options_act(or_options_t *old_options);
672 static int options_transition_allowed(or_options_t *old, or_options_t *new,
673 char **msg);
674 static int options_transition_affects_workers(or_options_t *old_options,
675 or_options_t *new_options);
676 static int options_transition_affects_descriptor(or_options_t *old_options,
677 or_options_t *new_options);
678 static int check_nickname_list(const char *lst, const char *name, char **msg);
679 static void config_register_addressmaps(or_options_t *options);
681 static int parse_bridge_line(const char *line, int validate_only);
682 static int parse_dir_server_line(const char *line,
683 authority_type_t required_type,
684 int validate_only);
685 static int validate_data_directory(or_options_t *options);
686 static int write_configuration_file(const char *fname, or_options_t *options);
687 static config_line_t *get_assigned_option(config_format_t *fmt,
688 void *options, const char *key,
689 int escape_val);
690 static void config_init(config_format_t *fmt, void *options);
691 static int or_state_validate(or_state_t *old_options, or_state_t *options,
692 int from_setconf, char **msg);
693 static int or_state_load(void);
694 static int options_init_logs(or_options_t *options, int validate_only);
696 static int is_listening_on_low_port(uint16_t port_option,
697 const config_line_t *listen_options);
699 static uint64_t config_parse_memunit(const char *s, int *ok);
700 static int config_parse_interval(const char *s, int *ok);
701 static void init_libevent(void);
702 static int opt_streq(const char *s1, const char *s2);
703 /** Versions of libevent. */
704 typedef enum {
705 /* Note: we compare these, so it's important that "old" precede everything,
706 * and that "other" come last. */
707 LE_OLD=0, LE_10C, LE_10D, LE_10E, LE_11, LE_11A, LE_11B, LE_12, LE_12A,
708 LE_13, LE_13A, LE_13B, LE_13C, LE_13D, LE_13E,
709 LE_140, LE_141, LE_142, LE_143, LE_144, LE_145, LE_146, LE_147, LE_148,
710 LE_1499,
711 LE_OTHER
712 } le_version_t;
713 static le_version_t decode_libevent_version(const char *v, int *bincompat_out);
714 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
715 static void check_libevent_version(const char *m, int server);
716 #endif
718 /** Magic value for or_options_t. */
719 #define OR_OPTIONS_MAGIC 9090909
721 /** Configuration format for or_options_t. */
722 static config_format_t options_format = {
723 sizeof(or_options_t),
724 OR_OPTIONS_MAGIC,
725 STRUCT_OFFSET(or_options_t, _magic),
726 _option_abbrevs,
727 _option_vars,
728 (validate_fn_t)options_validate,
729 options_description,
730 NULL
733 /** Magic value for or_state_t. */
734 #define OR_STATE_MAGIC 0x57A73f57
736 /** "Extra" variable in the state that receives lines we can't parse. This
737 * lets us preserve options from versions of Tor newer than us. */
738 static config_var_t state_extra_var = {
739 "__extra", CONFIG_TYPE_LINELIST, STRUCT_OFFSET(or_state_t, ExtraLines), NULL
742 /** Configuration format for or_state_t. */
743 static config_format_t state_format = {
744 sizeof(or_state_t),
745 OR_STATE_MAGIC,
746 STRUCT_OFFSET(or_state_t, _magic),
747 _state_abbrevs,
748 _state_vars,
749 (validate_fn_t)or_state_validate,
750 state_description,
751 &state_extra_var,
755 * Functions to read and write the global options pointer.
758 /** Command-line and config-file options. */
759 static or_options_t *global_options = NULL;
760 /** Name of most recently read torrc file. */
761 static char *torrc_fname = NULL;
762 /** Persistent serialized state. */
763 static or_state_t *global_state = NULL;
764 /** Configuration Options set by command line. */
765 static config_line_t *global_cmdline_options = NULL;
766 /** Contents of most recently read DirPortFrontPage file. */
767 static char *global_dirfrontpagecontents = NULL;
769 /** Return the contents of our frontpage string, or NULL if not configured. */
770 const char *
771 get_dirportfrontpage(void)
773 return global_dirfrontpagecontents;
776 /** Allocate an empty configuration object of a given format type. */
777 static void *
778 config_alloc(config_format_t *fmt)
780 void *opts = tor_malloc_zero(fmt->size);
781 *(uint32_t*)STRUCT_VAR_P(opts, fmt->magic_offset) = fmt->magic;
782 CHECK(fmt, opts);
783 return opts;
786 /** Return the currently configured options. */
787 or_options_t *
788 get_options(void)
790 tor_assert(global_options);
791 return global_options;
794 /** Change the current global options to contain <b>new_val</b> instead of
795 * their current value; take action based on the new value; free the old value
796 * as necessary. Returns 0 on success, -1 on failure.
799 set_options(or_options_t *new_val, char **msg)
801 or_options_t *old_options = global_options;
802 global_options = new_val;
803 /* Note that we pass the *old* options below, for comparison. It
804 * pulls the new options directly out of global_options. */
805 if (options_act_reversible(old_options, msg)<0) {
806 tor_assert(*msg);
807 global_options = old_options;
808 return -1;
810 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
811 log_err(LD_BUG,
812 "Acting on config options left us in a broken state. Dying.");
813 exit(1);
815 if (old_options)
816 config_free(&options_format, old_options);
818 return 0;
821 extern const char tor_svn_revision[]; /* from tor_main.c */
823 /** The version of this Tor process, as parsed. */
824 static char *_version = NULL;
826 /** Return the current Tor version. */
827 const char *
828 get_version(void)
830 if (_version == NULL) {
831 if (strlen(tor_svn_revision)) {
832 size_t len = strlen(VERSION)+strlen(tor_svn_revision)+8;
833 _version = tor_malloc(len);
834 tor_snprintf(_version, len, "%s (r%s)", VERSION, tor_svn_revision);
835 } else {
836 _version = tor_strdup(VERSION);
839 return _version;
842 /** Release additional memory allocated in options
844 static void
845 or_options_free(or_options_t *options)
847 if (options->_ExcludeExitNodesUnion)
848 routerset_free(options->_ExcludeExitNodesUnion);
849 config_free(&options_format, options);
852 /** Release all memory and resources held by global configuration structures.
854 void
855 config_free_all(void)
857 if (global_options) {
858 or_options_free(global_options);
859 global_options = NULL;
861 if (global_state) {
862 config_free(&state_format, global_state);
863 global_state = NULL;
865 if (global_cmdline_options) {
866 config_free_lines(global_cmdline_options);
867 global_cmdline_options = NULL;
869 tor_free(torrc_fname);
870 tor_free(_version);
871 tor_free(global_dirfrontpagecontents);
874 /** If options->SafeLogging is on, return a not very useful string,
875 * else return address.
877 const char *
878 safe_str(const char *address)
880 tor_assert(address);
881 if (get_options()->SafeLogging)
882 return "[scrubbed]";
883 else
884 return address;
887 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
888 * escaped(): don't use this outside the main thread, or twice in the same
889 * log statement. */
890 const char *
891 escaped_safe_str(const char *address)
893 if (get_options()->SafeLogging)
894 return "[scrubbed]";
895 else
896 return escaped(address);
899 /** Add the default directory authorities directly into the trusted dir list,
900 * but only add them insofar as they share bits with <b>type</b>. */
901 static void
902 add_default_trusted_dir_authorities(authority_type_t type)
904 int i;
905 const char *dirservers[] = {
906 "moria1 v1 orport=9001 v3ident=E2A2AF570166665D738736D0DD58169CC61D8A8B "
907 "128.31.0.34:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441",
908 "moria2 v1 orport=9002 128.31.0.34:9032 "
909 "719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF",
910 "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
911 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
912 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
913 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
914 "Tonga orport=443 bridge no-v2 82.94.251.206:80 "
915 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
916 "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
917 "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
918 "gabelmoo orport=443 no-v2 "
919 "v3ident=81349FC1F2DBA2C2C11B45CB9706637D480AB913 "
920 "80.190.246.100:80 6833 3D07 61BC F397 A587 A0C0 B963 E4A9 E99E C4D3",
921 "dannenberg orport=443 no-v2 "
922 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
923 "213.73.91.31:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
924 NULL
926 for (i=0; dirservers[i]; i++) {
927 if (parse_dir_server_line(dirservers[i], type, 0)<0) {
928 log_err(LD_BUG, "Couldn't parse internal dirserver line %s",
929 dirservers[i]);
934 /** Look at all the config options for using alternate directory
935 * authorities, and make sure none of them are broken. Also, warn the
936 * user if we changed any dangerous ones.
938 static int
939 validate_dir_authorities(or_options_t *options, or_options_t *old_options)
941 config_line_t *cl;
943 if (options->DirServers &&
944 (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
945 options->AlternateHSAuthority)) {
946 log_warn(LD_CONFIG,
947 "You cannot set both DirServers and Alternate*Authority.");
948 return -1;
951 /* do we want to complain to the user about being partitionable? */
952 if ((options->DirServers &&
953 (!old_options ||
954 !config_lines_eq(options->DirServers, old_options->DirServers))) ||
955 (options->AlternateDirAuthority &&
956 (!old_options ||
957 !config_lines_eq(options->AlternateDirAuthority,
958 old_options->AlternateDirAuthority)))) {
959 log_warn(LD_CONFIG,
960 "You have used DirServer or AlternateDirAuthority to "
961 "specify alternate directory authorities in "
962 "your configuration. This is potentially dangerous: it can "
963 "make you look different from all other Tor users, and hurt "
964 "your anonymity. Even if you've specified the same "
965 "authorities as Tor uses by default, the defaults could "
966 "change in the future. Be sure you know what you're doing.");
969 /* Now go through the four ways you can configure an alternate
970 * set of directory authorities, and make sure none are broken. */
971 for (cl = options->DirServers; cl; cl = cl->next)
972 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
973 return -1;
974 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
975 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
976 return -1;
977 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
978 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
979 return -1;
980 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
981 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
982 return -1;
983 return 0;
986 /** Look at all the config options and assign new dir authorities
987 * as appropriate.
989 static int
990 consider_adding_dir_authorities(or_options_t *options,
991 or_options_t *old_options)
993 config_line_t *cl;
994 int need_to_update =
995 !smartlist_len(router_get_trusted_dir_servers()) || !old_options ||
996 !config_lines_eq(options->DirServers, old_options->DirServers) ||
997 !config_lines_eq(options->AlternateBridgeAuthority,
998 old_options->AlternateBridgeAuthority) ||
999 !config_lines_eq(options->AlternateDirAuthority,
1000 old_options->AlternateDirAuthority) ||
1001 !config_lines_eq(options->AlternateHSAuthority,
1002 old_options->AlternateHSAuthority);
1004 if (!need_to_update)
1005 return 0; /* all done */
1007 /* Start from a clean slate. */
1008 clear_trusted_dir_servers();
1010 if (!options->DirServers) {
1011 /* then we may want some of the defaults */
1012 authority_type_t type = NO_AUTHORITY;
1013 if (!options->AlternateBridgeAuthority)
1014 type |= BRIDGE_AUTHORITY;
1015 if (!options->AlternateDirAuthority)
1016 type |= V1_AUTHORITY | V2_AUTHORITY | V3_AUTHORITY;
1017 if (!options->AlternateHSAuthority)
1018 type |= HIDSERV_AUTHORITY;
1019 add_default_trusted_dir_authorities(type);
1022 for (cl = options->DirServers; cl; cl = cl->next)
1023 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1024 return -1;
1025 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1026 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1027 return -1;
1028 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1029 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1030 return -1;
1031 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
1032 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1033 return -1;
1034 return 0;
1037 /** Fetch the active option list, and take actions based on it. All of the
1038 * things we do should survive being done repeatedly. If present,
1039 * <b>old_options</b> contains the previous value of the options.
1041 * Return 0 if all goes well, return -1 if things went badly.
1043 static int
1044 options_act_reversible(or_options_t *old_options, char **msg)
1046 smartlist_t *new_listeners = smartlist_create();
1047 smartlist_t *replaced_listeners = smartlist_create();
1048 static int libevent_initialized = 0;
1049 or_options_t *options = get_options();
1050 int running_tor = options->command == CMD_RUN_TOR;
1051 int set_conn_limit = 0;
1052 int r = -1;
1053 int logs_marked = 0;
1055 /* Daemonize _first_, since we only want to open most of this stuff in
1056 * the subprocess. Libevent bases can't be reliably inherited across
1057 * processes. */
1058 if (running_tor && options->RunAsDaemon) {
1059 /* No need to roll back, since you can't change the value. */
1060 start_daemon();
1063 #ifndef HAVE_SYS_UN_H
1064 if (options->ControlSocket) {
1065 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported"
1066 " on this OS/with this build.");
1067 goto rollback;
1069 #endif
1071 if (running_tor) {
1072 /* We need to set the connection limit before we can open the listeners. */
1073 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1074 &options->_ConnLimit) < 0) {
1075 *msg = tor_strdup("Problem with ConnLimit value. See logs for details.");
1076 goto rollback;
1078 set_conn_limit = 1;
1080 /* Set up libevent. (We need to do this before we can register the
1081 * listeners as listeners.) */
1082 if (running_tor && !libevent_initialized) {
1083 init_libevent();
1084 libevent_initialized = 1;
1087 /* Launch the listeners. (We do this before we setuid, so we can bind to
1088 * ports under 1024.) */
1089 if (retry_all_listeners(replaced_listeners, new_listeners) < 0) {
1090 *msg = tor_strdup("Failed to bind one of the listener ports.");
1091 goto rollback;
1095 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1096 /* Open /dev/pf before dropping privileges. */
1097 if (options->TransPort) {
1098 if (get_pf_socket() < 0) {
1099 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1100 goto rollback;
1103 #endif
1105 /* Setuid/setgid as appropriate */
1106 if (options->User) {
1107 if (switch_id(options->User) != 0) {
1108 /* No need to roll back, since you can't change the value. */
1109 *msg = tor_strdup("Problem with User value. See logs for details.");
1110 goto done;
1114 /* Ensure data directory is private; create if possible. */
1115 if (check_private_dir(options->DataDirectory,
1116 running_tor ? CPD_CREATE : CPD_CHECK)<0) {
1117 char buf[1024];
1118 int tmp = tor_snprintf(buf, sizeof(buf),
1119 "Couldn't access/create private data directory \"%s\"",
1120 options->DataDirectory);
1121 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1122 goto done;
1123 /* No need to roll back, since you can't change the value. */
1126 if (directory_caches_v2_dir_info(options)) {
1127 size_t len = strlen(options->DataDirectory)+32;
1128 char *fn = tor_malloc(len);
1129 tor_snprintf(fn, len, "%s"PATH_SEPARATOR"cached-status",
1130 options->DataDirectory);
1131 if (check_private_dir(fn, running_tor ? CPD_CREATE : CPD_CHECK) < 0) {
1132 char buf[1024];
1133 int tmp = tor_snprintf(buf, sizeof(buf),
1134 "Couldn't access/create private data directory \"%s\"", fn);
1135 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1136 tor_free(fn);
1137 goto done;
1139 tor_free(fn);
1142 /* Bail out at this point if we're not going to be a client or server:
1143 * we don't run Tor itself. */
1144 if (!running_tor)
1145 goto commit;
1147 mark_logs_temp(); /* Close current logs once new logs are open. */
1148 logs_marked = 1;
1149 if (options_init_logs(options, 0)<0) { /* Configure the log(s) */
1150 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1151 goto rollback;
1154 commit:
1155 r = 0;
1156 if (logs_marked) {
1157 log_severity_list_t *severity =
1158 tor_malloc_zero(sizeof(log_severity_list_t));
1159 close_temp_logs();
1160 add_callback_log(severity, control_event_logmsg);
1161 control_adjust_event_log_severity();
1162 tor_free(severity);
1164 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1166 log_notice(LD_NET, "Closing old %s on %s:%d",
1167 conn_type_to_string(conn->type), conn->address, conn->port);
1168 connection_close_immediate(conn);
1169 connection_mark_for_close(conn);
1171 goto done;
1173 rollback:
1174 r = -1;
1175 tor_assert(*msg);
1177 if (logs_marked) {
1178 rollback_log_changes();
1179 control_adjust_event_log_severity();
1182 if (set_conn_limit && old_options)
1183 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1184 &options->_ConnLimit);
1186 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1188 log_notice(LD_NET, "Closing partially-constructed listener %s on %s:%d",
1189 conn_type_to_string(conn->type), conn->address, conn->port);
1190 connection_close_immediate(conn);
1191 connection_mark_for_close(conn);
1194 done:
1195 smartlist_free(new_listeners);
1196 smartlist_free(replaced_listeners);
1197 return r;
1200 /** If we need to have a GEOIP ip-to-country map to run with our configured
1201 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1203 options_need_geoip_info(or_options_t *options, const char **reason_out)
1205 int bridge_usage =
1206 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1207 int routerset_usage =
1208 routerset_needs_geoip(options->EntryNodes) ||
1209 routerset_needs_geoip(options->ExitNodes) ||
1210 routerset_needs_geoip(options->ExcludeExitNodes) ||
1211 routerset_needs_geoip(options->ExcludeNodes);
1213 if (routerset_usage && reason_out) {
1214 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1215 "countries, and we need GEOIP information to figure out which ones they "
1216 "are.";
1217 } else if (bridge_usage && reason_out) {
1218 *reason_out = "We've been configured to see which countries can access "
1219 "us as a bridge, and we need GEOIP information to tell which countries "
1220 "clients are in.";
1222 return bridge_usage || routerset_usage;
1225 /** Fetch the active option list, and take actions based on it. All of the
1226 * things we do should survive being done repeatedly. If present,
1227 * <b>old_options</b> contains the previous value of the options.
1229 * Return 0 if all goes well, return -1 if it's time to die.
1231 * Note: We haven't moved all the "act on new configuration" logic
1232 * here yet. Some is still in do_hup() and other places.
1234 static int
1235 options_act(or_options_t *old_options)
1237 config_line_t *cl;
1238 or_options_t *options = get_options();
1239 int running_tor = options->command == CMD_RUN_TOR;
1240 char *msg;
1242 if (running_tor && !have_lockfile()) {
1243 if (try_locking(options, 1) < 0)
1244 return -1;
1247 if (consider_adding_dir_authorities(options, old_options) < 0)
1248 return -1;
1250 if (options->Bridges) {
1251 clear_bridge_list();
1252 for (cl = options->Bridges; cl; cl = cl->next) {
1253 if (parse_bridge_line(cl->value, 0)<0) {
1254 log_warn(LD_BUG,
1255 "Previously validated Bridge line could not be added!");
1256 return -1;
1261 if (running_tor && rend_config_services(options, 0)<0) {
1262 log_warn(LD_BUG,
1263 "Previously validated hidden services line could not be added!");
1264 return -1;
1267 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1268 log_warn(LD_BUG, "Previously validated client authorization for "
1269 "hidden services could not be added!");
1270 return -1;
1273 /* Load state */
1274 if (! global_state && running_tor) {
1275 if (or_state_load())
1276 return -1;
1277 rep_hist_load_mtbf_data(time(NULL));
1280 /* Bail out at this point if we're not going to be a client or server:
1281 * we want to not fork, and to log stuff to stderr. */
1282 if (!running_tor)
1283 return 0;
1285 /* Finish backgrounding the process */
1286 if (running_tor && options->RunAsDaemon) {
1287 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1288 finish_daemon(options->DataDirectory);
1291 /* Write our PID to the PID file. If we do not have write permissions we
1292 * will log a warning */
1293 if (running_tor && options->PidFile)
1294 write_pidfile(options->PidFile);
1296 /* Register addressmap directives */
1297 config_register_addressmaps(options);
1298 parse_virtual_addr_network(options->VirtualAddrNetwork, 0, &msg);
1300 /* Update address policies. */
1301 if (policies_parse_from_options(options) < 0) {
1302 /* This should be impossible, but let's be sure. */
1303 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1304 return -1;
1307 if (init_cookie_authentication(options->CookieAuthentication) < 0) {
1308 log_warn(LD_CONFIG,"Error creating cookie authentication file.");
1309 return -1;
1312 /* reload keys as needed for rendezvous services. */
1313 if (rend_service_load_keys()<0) {
1314 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1315 return -1;
1318 /* Set up accounting */
1319 if (accounting_parse_options(options, 0)<0) {
1320 log_warn(LD_CONFIG,"Error in accounting options");
1321 return -1;
1323 if (accounting_is_enabled(options))
1324 configure_accounting(time(NULL));
1326 /* Check for transitions that need action. */
1327 if (old_options) {
1328 if (options->UseEntryGuards && !old_options->UseEntryGuards) {
1329 log_info(LD_CIRC,
1330 "Switching to entry guards; abandoning previous circuits");
1331 circuit_mark_all_unused_circs();
1332 circuit_expire_all_dirty_circs();
1335 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
1336 log_info(LD_GENERAL, "Bridge status changed. Forgetting GeoIP stats.");
1337 geoip_remove_old_clients(time(NULL)+(2*60*60));
1340 if (options_transition_affects_workers(old_options, options)) {
1341 log_info(LD_GENERAL,
1342 "Worker-related options changed. Rotating workers.");
1343 if (server_mode(options) && !server_mode(old_options)) {
1344 if (init_keys() < 0) {
1345 log_warn(LD_BUG,"Error initializing keys; exiting");
1346 return -1;
1348 ip_address_changed(0);
1349 if (has_completed_circuit || !any_predicted_circuits(time(NULL)))
1350 inform_testing_reachability();
1352 cpuworkers_rotate();
1353 if (dns_reset())
1354 return -1;
1355 } else {
1356 if (dns_reset())
1357 return -1;
1360 if (options->V3AuthoritativeDir && !old_options->V3AuthoritativeDir)
1361 init_keys();
1364 /* Maybe load geoip file */
1365 if (options->GeoIPFile &&
1366 ((!old_options || !opt_streq(old_options->GeoIPFile, options->GeoIPFile))
1367 || !geoip_is_loaded())) {
1368 /* XXXX Don't use this "<default>" junk; make our filename options
1369 * understand prefixes somehow. -NM */
1370 /* XXXX021 Reload GeoIPFile on SIGHUP. -NM */
1371 char *actual_fname = tor_strdup(options->GeoIPFile);
1372 #ifdef WIN32
1373 if (!strcmp(actual_fname, "<default>")) {
1374 const char *conf_root = get_windows_conf_root();
1375 size_t len = strlen(conf_root)+16;
1376 tor_free(actual_fname);
1377 actual_fname = tor_malloc(len+1);
1378 tor_snprintf(actual_fname, len, "%s\\geoip", conf_root);
1380 #endif
1381 geoip_load_file(actual_fname, options);
1382 tor_free(actual_fname);
1384 /* Check if we need to parse and add the EntryNodes config option. */
1385 if (options->EntryNodes &&
1386 (!old_options ||
1387 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
1388 entry_nodes_should_be_added();
1390 /* Since our options changed, we might need to regenerate and upload our
1391 * server descriptor.
1393 if (!old_options ||
1394 options_transition_affects_descriptor(old_options, options))
1395 mark_my_descriptor_dirty();
1397 /* We may need to reschedule some directory stuff if our status changed. */
1398 if (old_options) {
1399 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1400 dirvote_recalculate_timing(options, time(NULL));
1401 if (!bool_eq(directory_fetches_dir_info_early(options),
1402 directory_fetches_dir_info_early(old_options)) ||
1403 !bool_eq(directory_fetches_dir_info_later(options),
1404 directory_fetches_dir_info_later(old_options))) {
1405 /* Make sure update_router_have_min_dir_info gets called. */
1406 router_dir_info_changed();
1407 /* We might need to download a new consensus status later or sooner than
1408 * we had expected. */
1409 update_consensus_networkstatus_fetch_time(time(NULL));
1413 /* Load the webpage we're going to serve every time someone asks for '/' on
1414 our DirPort. */
1415 tor_free(global_dirfrontpagecontents);
1416 if (options->DirPortFrontPage) {
1417 global_dirfrontpagecontents =
1418 read_file_to_str(options->DirPortFrontPage, 0, NULL);
1419 if (!global_dirfrontpagecontents) {
1420 log_warn(LD_CONFIG,
1421 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1422 options->DirPortFrontPage);
1426 return 0;
1430 * Functions to parse config options
1433 /** If <b>option</b> is an official abbreviation for a longer option,
1434 * return the longer option. Otherwise return <b>option</b>.
1435 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1436 * apply abbreviations that work for the config file and the command line.
1437 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1438 static const char *
1439 expand_abbrev(config_format_t *fmt, const char *option, int command_line,
1440 int warn_obsolete)
1442 int i;
1443 if (! fmt->abbrevs)
1444 return option;
1445 for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
1446 /* Abbreviations are case insensitive. */
1447 if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
1448 (command_line || !fmt->abbrevs[i].commandline_only)) {
1449 if (warn_obsolete && fmt->abbrevs[i].warn) {
1450 log_warn(LD_CONFIG,
1451 "The configuration option '%s' is deprecated; "
1452 "use '%s' instead.",
1453 fmt->abbrevs[i].abbreviated,
1454 fmt->abbrevs[i].full);
1456 return fmt->abbrevs[i].full;
1459 return option;
1462 /** Helper: Read a list of configuration options from the command line.
1463 * If successful, put them in *<b>result</b> and return 0, and return
1464 * -1 and leave *<b>result</b> alone. */
1465 static int
1466 config_get_commandlines(int argc, char **argv, config_line_t **result)
1468 config_line_t *front = NULL;
1469 config_line_t **new = &front;
1470 char *s;
1471 int i = 1;
1473 while (i < argc) {
1474 if (!strcmp(argv[i],"-f") ||
1475 !strcmp(argv[i],"--hash-password")) {
1476 i += 2; /* command-line option with argument. ignore them. */
1477 continue;
1478 } else if (!strcmp(argv[i],"--list-fingerprint") ||
1479 !strcmp(argv[i],"--verify-config") ||
1480 !strcmp(argv[i],"--ignore-missing-torrc") ||
1481 !strcmp(argv[i],"--quiet") ||
1482 !strcmp(argv[i],"--hush")) {
1483 i += 1; /* command-line option. ignore it. */
1484 continue;
1485 } else if (!strcmp(argv[i],"--nt-service") ||
1486 !strcmp(argv[i],"-nt-service")) {
1487 i += 1;
1488 continue;
1491 if (i == argc-1) {
1492 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1493 argv[i]);
1494 config_free_lines(front);
1495 return -1;
1498 *new = tor_malloc_zero(sizeof(config_line_t));
1499 s = argv[i];
1501 while (*s == '-')
1502 s++;
1504 (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1, 1));
1505 (*new)->value = tor_strdup(argv[i+1]);
1506 (*new)->next = NULL;
1507 log(LOG_DEBUG, LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
1508 (*new)->key, (*new)->value);
1510 new = &((*new)->next);
1511 i += 2;
1513 *result = front;
1514 return 0;
1517 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1518 * append it to *<b>lst</b>. */
1519 static void
1520 config_line_append(config_line_t **lst,
1521 const char *key,
1522 const char *val)
1524 config_line_t *newline;
1526 newline = tor_malloc(sizeof(config_line_t));
1527 newline->key = tor_strdup(key);
1528 newline->value = tor_strdup(val);
1529 newline->next = NULL;
1530 while (*lst)
1531 lst = &((*lst)->next);
1533 (*lst) = newline;
1536 /** Helper: parse the config string and strdup into key/value
1537 * strings. Set *result to the list, or NULL if parsing the string
1538 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1539 * misformatted lines. */
1541 config_get_lines(const char *string, config_line_t **result)
1543 config_line_t *list = NULL, **next;
1544 char *k, *v;
1546 next = &list;
1547 do {
1548 k = v = NULL;
1549 string = parse_config_line_from_str(string, &k, &v);
1550 if (!string) {
1551 config_free_lines(list);
1552 tor_free(k);
1553 tor_free(v);
1554 return -1;
1556 if (k && v) {
1557 /* This list can get long, so we keep a pointer to the end of it
1558 * rather than using config_line_append over and over and getting
1559 * n^2 performance. */
1560 *next = tor_malloc(sizeof(config_line_t));
1561 (*next)->key = k;
1562 (*next)->value = v;
1563 (*next)->next = NULL;
1564 next = &((*next)->next);
1565 } else {
1566 tor_free(k);
1567 tor_free(v);
1569 } while (*string);
1571 *result = list;
1572 return 0;
1576 * Free all the configuration lines on the linked list <b>front</b>.
1578 void
1579 config_free_lines(config_line_t *front)
1581 config_line_t *tmp;
1583 while (front) {
1584 tmp = front;
1585 front = tmp->next;
1587 tor_free(tmp->key);
1588 tor_free(tmp->value);
1589 tor_free(tmp);
1593 /** Return the description for a given configuration variable, or NULL if no
1594 * description exists. */
1595 static const char *
1596 config_find_description(config_format_t *fmt, const char *name)
1598 int i;
1599 for (i=0; fmt->descriptions[i].name; ++i) {
1600 if (!strcasecmp(name, fmt->descriptions[i].name))
1601 return fmt->descriptions[i].description;
1603 return NULL;
1606 /** If <b>key</b> is a configuration option, return the corresponding
1607 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1608 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1610 static config_var_t *
1611 config_find_option(config_format_t *fmt, const char *key)
1613 int i;
1614 size_t keylen = strlen(key);
1615 if (!keylen)
1616 return NULL; /* if they say "--" on the command line, it's not an option */
1617 /* First, check for an exact (case-insensitive) match */
1618 for (i=0; fmt->vars[i].name; ++i) {
1619 if (!strcasecmp(key, fmt->vars[i].name)) {
1620 return &fmt->vars[i];
1623 /* If none, check for an abbreviated match */
1624 for (i=0; fmt->vars[i].name; ++i) {
1625 if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
1626 log_warn(LD_CONFIG, "The abbreviation '%s' is deprecated. "
1627 "Please use '%s' instead",
1628 key, fmt->vars[i].name);
1629 return &fmt->vars[i];
1632 /* Okay, unrecognized option */
1633 return NULL;
1637 * Functions to assign config options.
1640 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1641 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1643 * Called from config_assign_line() and option_reset().
1645 static int
1646 config_assign_value(config_format_t *fmt, or_options_t *options,
1647 config_line_t *c, char **msg)
1649 int i, r, ok;
1650 char buf[1024];
1651 config_var_t *var;
1652 void *lvalue;
1654 CHECK(fmt, options);
1656 var = config_find_option(fmt, c->key);
1657 tor_assert(var);
1659 lvalue = STRUCT_VAR_P(options, var->var_offset);
1661 switch (var->type) {
1663 case CONFIG_TYPE_UINT:
1664 i = (int)tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
1665 if (!ok) {
1666 r = tor_snprintf(buf, sizeof(buf),
1667 "Int keyword '%s %s' is malformed or out of bounds.",
1668 c->key, c->value);
1669 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1670 return -1;
1672 *(int *)lvalue = i;
1673 break;
1675 case CONFIG_TYPE_INTERVAL: {
1676 i = config_parse_interval(c->value, &ok);
1677 if (!ok) {
1678 r = tor_snprintf(buf, sizeof(buf),
1679 "Interval '%s %s' is malformed or out of bounds.",
1680 c->key, c->value);
1681 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1682 return -1;
1684 *(int *)lvalue = i;
1685 break;
1688 case CONFIG_TYPE_MEMUNIT: {
1689 uint64_t u64 = config_parse_memunit(c->value, &ok);
1690 if (!ok) {
1691 r = tor_snprintf(buf, sizeof(buf),
1692 "Value '%s %s' is malformed or out of bounds.",
1693 c->key, c->value);
1694 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1695 return -1;
1697 *(uint64_t *)lvalue = u64;
1698 break;
1701 case CONFIG_TYPE_BOOL:
1702 i = (int)tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
1703 if (!ok) {
1704 r = tor_snprintf(buf, sizeof(buf),
1705 "Boolean '%s %s' expects 0 or 1.",
1706 c->key, c->value);
1707 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1708 return -1;
1710 *(int *)lvalue = i;
1711 break;
1713 case CONFIG_TYPE_STRING:
1714 case CONFIG_TYPE_FILENAME:
1715 tor_free(*(char **)lvalue);
1716 *(char **)lvalue = tor_strdup(c->value);
1717 break;
1719 case CONFIG_TYPE_DOUBLE:
1720 *(double *)lvalue = atof(c->value);
1721 break;
1723 case CONFIG_TYPE_ISOTIME:
1724 if (parse_iso_time(c->value, (time_t *)lvalue)) {
1725 r = tor_snprintf(buf, sizeof(buf),
1726 "Invalid time '%s' for keyword '%s'", c->value, c->key);
1727 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1728 return -1;
1730 break;
1732 case CONFIG_TYPE_ROUTERSET:
1733 if (*(routerset_t**)lvalue) {
1734 routerset_free(*(routerset_t**)lvalue);
1736 *(routerset_t**)lvalue = routerset_new();
1737 if (routerset_parse(*(routerset_t**)lvalue, c->value, c->key)<0) {
1738 tor_snprintf(buf, sizeof(buf), "Invalid exit list '%s' for option '%s'",
1739 c->value, c->key);
1740 *msg = tor_strdup(buf);
1741 return -1;
1743 break;
1745 case CONFIG_TYPE_CSV:
1746 if (*(smartlist_t**)lvalue) {
1747 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
1748 smartlist_clear(*(smartlist_t**)lvalue);
1749 } else {
1750 *(smartlist_t**)lvalue = smartlist_create();
1753 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
1754 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1755 break;
1757 case CONFIG_TYPE_LINELIST:
1758 case CONFIG_TYPE_LINELIST_S:
1759 config_line_append((config_line_t**)lvalue, c->key, c->value);
1760 break;
1761 case CONFIG_TYPE_OBSOLETE:
1762 log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
1763 break;
1764 case CONFIG_TYPE_LINELIST_V:
1765 r = tor_snprintf(buf, sizeof(buf),
1766 "You may not provide a value for virtual option '%s'", c->key);
1767 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1768 return -1;
1769 default:
1770 tor_assert(0);
1771 break;
1773 return 0;
1776 /** If <b>c</b> is a syntactically valid configuration line, update
1777 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1778 * key, -2 for bad value.
1780 * If <b>clear_first</b> is set, clear the value first. Then if
1781 * <b>use_defaults</b> is set, set the value to the default.
1783 * Called from config_assign().
1785 static int
1786 config_assign_line(config_format_t *fmt, or_options_t *options,
1787 config_line_t *c, int use_defaults,
1788 int clear_first, char **msg)
1790 config_var_t *var;
1792 CHECK(fmt, options);
1794 var = config_find_option(fmt, c->key);
1795 if (!var) {
1796 if (fmt->extra) {
1797 void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
1798 log_info(LD_CONFIG,
1799 "Found unrecognized option '%s'; saving it.", c->key);
1800 config_line_append((config_line_t**)lvalue, c->key, c->value);
1801 return 0;
1802 } else {
1803 char buf[1024];
1804 int tmp = tor_snprintf(buf, sizeof(buf),
1805 "Unknown option '%s'. Failing.", c->key);
1806 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1807 return -1;
1810 /* Put keyword into canonical case. */
1811 if (strcmp(var->name, c->key)) {
1812 tor_free(c->key);
1813 c->key = tor_strdup(var->name);
1816 if (!strlen(c->value)) {
1817 /* reset or clear it, then return */
1818 if (!clear_first) {
1819 if (var->type == CONFIG_TYPE_LINELIST ||
1820 var->type == CONFIG_TYPE_LINELIST_S) {
1821 /* We got an empty linelist from the torrc or command line.
1822 As a special case, call this an error. Warn and ignore. */
1823 log_warn(LD_CONFIG,
1824 "Linelist option '%s' has no value. Skipping.", c->key);
1825 } else { /* not already cleared */
1826 option_reset(fmt, options, var, use_defaults);
1829 return 0;
1832 if (config_assign_value(fmt, options, c, msg) < 0)
1833 return -2;
1834 return 0;
1837 /** Restore the option named <b>key</b> in options to its default value.
1838 * Called from config_assign(). */
1839 static void
1840 config_reset_line(config_format_t *fmt, or_options_t *options,
1841 const char *key, int use_defaults)
1843 config_var_t *var;
1845 CHECK(fmt, options);
1847 var = config_find_option(fmt, key);
1848 if (!var)
1849 return; /* give error on next pass. */
1851 option_reset(fmt, options, var, use_defaults);
1854 /** Return true iff key is a valid configuration option. */
1856 option_is_recognized(const char *key)
1858 config_var_t *var = config_find_option(&options_format, key);
1859 return (var != NULL);
1862 /** Return the canonical name of a configuration option, or NULL
1863 * if no such option exists. */
1864 const char *
1865 option_get_canonical_name(const char *key)
1867 config_var_t *var = config_find_option(&options_format, key);
1868 return var ? var->name : NULL;
1871 /** Return a canonical list of the options assigned for key.
1873 config_line_t *
1874 option_get_assignment(or_options_t *options, const char *key)
1876 return get_assigned_option(&options_format, options, key, 1);
1879 /** Return true iff value needs to be quoted and escaped to be used in
1880 * a configuration file. */
1881 static int
1882 config_value_needs_escape(const char *value)
1884 if (*value == '\"')
1885 return 1;
1886 while (*value) {
1887 switch (*value)
1889 case '\r':
1890 case '\n':
1891 case '#':
1892 /* Note: quotes and backspaces need special handling when we are using
1893 * quotes, not otherwise, so they don't trigger escaping on their
1894 * own. */
1895 return 1;
1896 default:
1897 if (!TOR_ISPRINT(*value))
1898 return 1;
1900 ++value;
1902 return 0;
1905 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1906 static config_line_t *
1907 config_lines_dup(const config_line_t *inp)
1909 config_line_t *result = NULL;
1910 config_line_t **next_out = &result;
1911 while (inp) {
1912 *next_out = tor_malloc(sizeof(config_line_t));
1913 (*next_out)->key = tor_strdup(inp->key);
1914 (*next_out)->value = tor_strdup(inp->value);
1915 inp = inp->next;
1916 next_out = &((*next_out)->next);
1918 (*next_out) = NULL;
1919 return result;
1922 /** Return newly allocated line or lines corresponding to <b>key</b> in the
1923 * configuration <b>options</b>. If <b>escape_val</b> is true and a
1924 * value needs to be quoted before it's put in a config file, quote and
1925 * escape that value. Return NULL if no such key exists. */
1926 static config_line_t *
1927 get_assigned_option(config_format_t *fmt, void *options,
1928 const char *key, int escape_val)
1930 config_var_t *var;
1931 const void *value;
1932 char buf[32];
1933 config_line_t *result;
1934 tor_assert(options && key);
1936 CHECK(fmt, options);
1938 var = config_find_option(fmt, key);
1939 if (!var) {
1940 log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
1941 return NULL;
1943 value = STRUCT_VAR_P(options, var->var_offset);
1945 result = tor_malloc_zero(sizeof(config_line_t));
1946 result->key = tor_strdup(var->name);
1947 switch (var->type)
1949 case CONFIG_TYPE_STRING:
1950 case CONFIG_TYPE_FILENAME:
1951 if (*(char**)value) {
1952 result->value = tor_strdup(*(char**)value);
1953 } else {
1954 tor_free(result->key);
1955 tor_free(result);
1956 return NULL;
1958 break;
1959 case CONFIG_TYPE_ISOTIME:
1960 if (*(time_t*)value) {
1961 result->value = tor_malloc(ISO_TIME_LEN+1);
1962 format_iso_time(result->value, *(time_t*)value);
1963 } else {
1964 tor_free(result->key);
1965 tor_free(result);
1967 escape_val = 0; /* Can't need escape. */
1968 break;
1969 case CONFIG_TYPE_INTERVAL:
1970 case CONFIG_TYPE_UINT:
1971 /* This means every or_options_t uint or bool element
1972 * needs to be an int. Not, say, a uint16_t or char. */
1973 tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
1974 result->value = tor_strdup(buf);
1975 escape_val = 0; /* Can't need escape. */
1976 break;
1977 case CONFIG_TYPE_MEMUNIT:
1978 tor_snprintf(buf, sizeof(buf), U64_FORMAT,
1979 U64_PRINTF_ARG(*(uint64_t*)value));
1980 result->value = tor_strdup(buf);
1981 escape_val = 0; /* Can't need escape. */
1982 break;
1983 case CONFIG_TYPE_DOUBLE:
1984 tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
1985 result->value = tor_strdup(buf);
1986 escape_val = 0; /* Can't need escape. */
1987 break;
1988 case CONFIG_TYPE_BOOL:
1989 result->value = tor_strdup(*(int*)value ? "1" : "0");
1990 escape_val = 0; /* Can't need escape. */
1991 break;
1992 case CONFIG_TYPE_ROUTERSET:
1993 result->value = routerset_to_string(*(routerset_t**)value);
1994 break;
1995 case CONFIG_TYPE_CSV:
1996 if (*(smartlist_t**)value)
1997 result->value =
1998 smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
1999 else
2000 result->value = tor_strdup("");
2001 break;
2002 case CONFIG_TYPE_OBSOLETE:
2003 log_fn(LOG_PROTOCOL_WARN, LD_CONFIG,
2004 "You asked me for the value of an obsolete config option '%s'.",
2005 key);
2006 tor_free(result->key);
2007 tor_free(result);
2008 return NULL;
2009 case CONFIG_TYPE_LINELIST_S:
2010 log_warn(LD_CONFIG,
2011 "Can't return context-sensitive '%s' on its own", key);
2012 tor_free(result->key);
2013 tor_free(result);
2014 return NULL;
2015 case CONFIG_TYPE_LINELIST:
2016 case CONFIG_TYPE_LINELIST_V:
2017 tor_free(result->key);
2018 tor_free(result);
2019 result = config_lines_dup(*(const config_line_t**)value);
2020 break;
2021 default:
2022 tor_free(result->key);
2023 tor_free(result);
2024 log_warn(LD_BUG,"Unknown type %d for known key '%s'",
2025 var->type, key);
2026 return NULL;
2029 if (escape_val) {
2030 config_line_t *line;
2031 for (line = result; line; line = line->next) {
2032 if (line->value && config_value_needs_escape(line->value)) {
2033 char *newval = esc_for_log(line->value);
2034 tor_free(line->value);
2035 line->value = newval;
2040 return result;
2043 /** Iterate through the linked list of requested options <b>list</b>.
2044 * For each item, convert as appropriate and assign to <b>options</b>.
2045 * If an item is unrecognized, set *msg and return -1 immediately,
2046 * else return 0 for success.
2048 * If <b>clear_first</b>, interpret config options as replacing (not
2049 * extending) their previous values. If <b>clear_first</b> is set,
2050 * then <b>use_defaults</b> to decide if you set to defaults after
2051 * clearing, or make the value 0 or NULL.
2053 * Here are the use cases:
2054 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
2055 * if linelist, replaces current if csv.
2056 * 2. An empty AllowInvalid line in your torrc. Should clear it.
2057 * 3. "RESETCONF AllowInvalid" sets it to default.
2058 * 4. "SETCONF AllowInvalid" makes it NULL.
2059 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
2061 * Use_defaults Clear_first
2062 * 0 0 "append"
2063 * 1 0 undefined, don't use
2064 * 0 1 "set to null first"
2065 * 1 1 "set to defaults first"
2066 * Return 0 on success, -1 on bad key, -2 on bad value.
2068 * As an additional special case, if a LINELIST config option has
2069 * no value and clear_first is 0, then warn and ignore it.
2073 There are three call cases for config_assign() currently.
2075 Case one: Torrc entry
2076 options_init_from_torrc() calls config_assign(0, 0)
2077 calls config_assign_line(0, 0).
2078 if value is empty, calls option_reset(0) and returns.
2079 calls config_assign_value(), appends.
2081 Case two: setconf
2082 options_trial_assign() calls config_assign(0, 1)
2083 calls config_reset_line(0)
2084 calls option_reset(0)
2085 calls option_clear().
2086 calls config_assign_line(0, 1).
2087 if value is empty, returns.
2088 calls config_assign_value(), appends.
2090 Case three: resetconf
2091 options_trial_assign() calls config_assign(1, 1)
2092 calls config_reset_line(1)
2093 calls option_reset(1)
2094 calls option_clear().
2095 calls config_assign_value(default)
2096 calls config_assign_line(1, 1).
2097 returns.
2099 static int
2100 config_assign(config_format_t *fmt, void *options, config_line_t *list,
2101 int use_defaults, int clear_first, char **msg)
2103 config_line_t *p;
2105 CHECK(fmt, options);
2107 /* pass 1: normalize keys */
2108 for (p = list; p; p = p->next) {
2109 const char *full = expand_abbrev(fmt, p->key, 0, 1);
2110 if (strcmp(full,p->key)) {
2111 tor_free(p->key);
2112 p->key = tor_strdup(full);
2116 /* pass 2: if we're reading from a resetting source, clear all
2117 * mentioned config options, and maybe set to their defaults. */
2118 if (clear_first) {
2119 for (p = list; p; p = p->next)
2120 config_reset_line(fmt, options, p->key, use_defaults);
2123 /* pass 3: assign. */
2124 while (list) {
2125 int r;
2126 if ((r=config_assign_line(fmt, options, list, use_defaults,
2127 clear_first, msg)))
2128 return r;
2129 list = list->next;
2131 return 0;
2134 /** Try assigning <b>list</b> to the global options. You do this by duping
2135 * options, assigning list to the new one, then validating it. If it's
2136 * ok, then throw out the old one and stick with the new one. Else,
2137 * revert to old and return failure. Return SETOPT_OK on success, or
2138 * a setopt_err_t on failure.
2140 * If not success, point *<b>msg</b> to a newly allocated string describing
2141 * what went wrong.
2143 setopt_err_t
2144 options_trial_assign(config_line_t *list, int use_defaults,
2145 int clear_first, char **msg)
2147 int r;
2148 or_options_t *trial_options = options_dup(&options_format, get_options());
2150 if ((r=config_assign(&options_format, trial_options,
2151 list, use_defaults, clear_first, msg)) < 0) {
2152 config_free(&options_format, trial_options);
2153 return r;
2156 if (options_validate(get_options(), trial_options, 1, msg) < 0) {
2157 config_free(&options_format, trial_options);
2158 return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2161 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2162 config_free(&options_format, trial_options);
2163 return SETOPT_ERR_TRANSITION;
2166 if (set_options(trial_options, msg)<0) {
2167 config_free(&options_format, trial_options);
2168 return SETOPT_ERR_SETTING;
2171 /* we liked it. put it in place. */
2172 return SETOPT_OK;
2175 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2176 * Called from option_reset() and config_free(). */
2177 static void
2178 option_clear(config_format_t *fmt, or_options_t *options, config_var_t *var)
2180 void *lvalue = STRUCT_VAR_P(options, var->var_offset);
2181 (void)fmt; /* unused */
2182 switch (var->type) {
2183 case CONFIG_TYPE_STRING:
2184 case CONFIG_TYPE_FILENAME:
2185 tor_free(*(char**)lvalue);
2186 break;
2187 case CONFIG_TYPE_DOUBLE:
2188 *(double*)lvalue = 0.0;
2189 break;
2190 case CONFIG_TYPE_ISOTIME:
2191 *(time_t*)lvalue = 0;
2192 case CONFIG_TYPE_INTERVAL:
2193 case CONFIG_TYPE_UINT:
2194 case CONFIG_TYPE_BOOL:
2195 *(int*)lvalue = 0;
2196 break;
2197 case CONFIG_TYPE_MEMUNIT:
2198 *(uint64_t*)lvalue = 0;
2199 break;
2200 case CONFIG_TYPE_ROUTERSET:
2201 if (*(routerset_t**)lvalue) {
2202 routerset_free(*(routerset_t**)lvalue);
2203 *(routerset_t**)lvalue = NULL;
2205 case CONFIG_TYPE_CSV:
2206 if (*(smartlist_t**)lvalue) {
2207 SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
2208 smartlist_free(*(smartlist_t **)lvalue);
2209 *(smartlist_t **)lvalue = NULL;
2211 break;
2212 case CONFIG_TYPE_LINELIST:
2213 case CONFIG_TYPE_LINELIST_S:
2214 config_free_lines(*(config_line_t **)lvalue);
2215 *(config_line_t **)lvalue = NULL;
2216 break;
2217 case CONFIG_TYPE_LINELIST_V:
2218 /* handled by linelist_s. */
2219 break;
2220 case CONFIG_TYPE_OBSOLETE:
2221 break;
2225 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2226 * <b>use_defaults</b>, set it to its default value.
2227 * Called by config_init() and option_reset_line() and option_assign_line(). */
2228 static void
2229 option_reset(config_format_t *fmt, or_options_t *options,
2230 config_var_t *var, int use_defaults)
2232 config_line_t *c;
2233 char *msg = NULL;
2234 CHECK(fmt, options);
2235 option_clear(fmt, options, var); /* clear it first */
2236 if (!use_defaults)
2237 return; /* all done */
2238 if (var->initvalue) {
2239 c = tor_malloc_zero(sizeof(config_line_t));
2240 c->key = tor_strdup(var->name);
2241 c->value = tor_strdup(var->initvalue);
2242 if (config_assign_value(fmt, options, c, &msg) < 0) {
2243 log_warn(LD_BUG, "Failed to assign default: %s", msg);
2244 tor_free(msg); /* if this happens it's a bug */
2246 config_free_lines(c);
2250 /** Print a usage message for tor. */
2251 static void
2252 print_usage(void)
2254 printf(
2255 "Copyright (c) 2001-2004, Roger Dingledine\n"
2256 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2257 "Copyright (c) 2007-2009, The Tor Project, Inc.\n\n"
2258 "tor -f <torrc> [args]\n"
2259 "See man page for options, or https://www.torproject.org/ for "
2260 "documentation.\n");
2263 /** Print all non-obsolete torrc options. */
2264 static void
2265 list_torrc_options(void)
2267 int i;
2268 smartlist_t *lines = smartlist_create();
2269 for (i = 0; _option_vars[i].name; ++i) {
2270 config_var_t *var = &_option_vars[i];
2271 const char *desc;
2272 if (var->type == CONFIG_TYPE_OBSOLETE ||
2273 var->type == CONFIG_TYPE_LINELIST_V)
2274 continue;
2275 desc = config_find_description(&options_format, var->name);
2276 printf("%s\n", var->name);
2277 if (desc) {
2278 wrap_string(lines, desc, 76, " ", " ");
2279 SMARTLIST_FOREACH(lines, char *, cp, {
2280 printf("%s", cp);
2281 tor_free(cp);
2283 smartlist_clear(lines);
2286 smartlist_free(lines);
2289 /** Last value actually set by resolve_my_address. */
2290 static uint32_t last_resolved_addr = 0;
2292 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2293 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2294 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2295 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2296 * public IP address.
2299 resolve_my_address(int warn_severity, or_options_t *options,
2300 uint32_t *addr_out, char **hostname_out)
2302 struct in_addr in;
2303 struct hostent *rent;
2304 char hostname[256];
2305 int explicit_ip=1;
2306 int explicit_hostname=1;
2307 int from_interface=0;
2308 char tmpbuf[INET_NTOA_BUF_LEN];
2309 const char *address = options->Address;
2310 int notice_severity = warn_severity <= LOG_NOTICE ?
2311 LOG_NOTICE : warn_severity;
2313 tor_assert(addr_out);
2315 if (address && *address) {
2316 strlcpy(hostname, address, sizeof(hostname));
2317 } else { /* then we need to guess our address */
2318 explicit_ip = 0; /* it's implicit */
2319 explicit_hostname = 0; /* it's implicit */
2321 if (gethostname(hostname, sizeof(hostname)) < 0) {
2322 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2323 return -1;
2325 log_debug(LD_CONFIG,"Guessed local host name as '%s'",hostname);
2328 /* now we know hostname. resolve it and keep only the IP address */
2330 if (tor_inet_aton(hostname, &in) == 0) {
2331 /* then we have to resolve it */
2332 explicit_ip = 0;
2333 rent = (struct hostent *)gethostbyname(hostname);
2334 if (!rent) {
2335 uint32_t interface_ip;
2337 if (explicit_hostname) {
2338 log_fn(warn_severity, LD_CONFIG,
2339 "Could not resolve local Address '%s'. Failing.", hostname);
2340 return -1;
2342 log_fn(notice_severity, LD_CONFIG,
2343 "Could not resolve guessed local hostname '%s'. "
2344 "Trying something else.", hostname);
2345 if (get_interface_address(warn_severity, &interface_ip)) {
2346 log_fn(warn_severity, LD_CONFIG,
2347 "Could not get local interface IP address. Failing.");
2348 return -1;
2350 from_interface = 1;
2351 in.s_addr = htonl(interface_ip);
2352 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2353 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2354 "local interface. Using that.", tmpbuf);
2355 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2356 } else {
2357 tor_assert(rent->h_length == 4);
2358 memcpy(&in.s_addr, rent->h_addr, rent->h_length);
2360 if (!explicit_hostname &&
2361 is_internal_IP(ntohl(in.s_addr), 0)) {
2362 uint32_t interface_ip;
2364 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2365 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2366 "resolves to a private IP address (%s). Trying something "
2367 "else.", hostname, tmpbuf);
2369 if (get_interface_address(warn_severity, &interface_ip)) {
2370 log_fn(warn_severity, LD_CONFIG,
2371 "Could not get local interface IP address. Too bad.");
2372 } else if (is_internal_IP(interface_ip, 0)) {
2373 struct in_addr in2;
2374 in2.s_addr = htonl(interface_ip);
2375 tor_inet_ntoa(&in2,tmpbuf,sizeof(tmpbuf));
2376 log_fn(notice_severity, LD_CONFIG,
2377 "Interface IP address '%s' is a private address too. "
2378 "Ignoring.", tmpbuf);
2379 } else {
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,
2384 "Learned IP address '%s' for local interface."
2385 " Using that.", tmpbuf);
2386 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2392 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2393 if (is_internal_IP(ntohl(in.s_addr), 0) &&
2394 options->_PublishServerDescriptor) {
2395 /* make sure we're ok with publishing an internal IP */
2396 if (!options->DirServers && !options->AlternateDirAuthority) {
2397 /* if they are using the default dirservers, disallow internal IPs
2398 * always. */
2399 log_fn(warn_severity, LD_CONFIG,
2400 "Address '%s' resolves to private IP address '%s'. "
2401 "Tor servers that use the default DirServers must have public "
2402 "IP addresses.", hostname, tmpbuf);
2403 return -1;
2405 if (!explicit_ip) {
2406 /* even if they've set their own dirservers, require an explicit IP if
2407 * they're using an internal address. */
2408 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2409 "IP address '%s'. Please set the Address config option to be "
2410 "the IP address you want to use.", hostname, tmpbuf);
2411 return -1;
2415 log_debug(LD_CONFIG, "Resolved Address to '%s'.", tmpbuf);
2416 *addr_out = ntohl(in.s_addr);
2417 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2418 /* Leave this as a notice, regardless of the requested severity,
2419 * at least until dynamic IP address support becomes bulletproof. */
2420 log_notice(LD_NET,
2421 "Your IP address seems to have changed to %s. Updating.",
2422 tmpbuf);
2423 ip_address_changed(0);
2425 if (last_resolved_addr != *addr_out) {
2426 const char *method;
2427 const char *h = hostname;
2428 if (explicit_ip) {
2429 method = "CONFIGURED";
2430 h = NULL;
2431 } else if (explicit_hostname) {
2432 method = "RESOLVED";
2433 } else if (from_interface) {
2434 method = "INTERFACE";
2435 h = NULL;
2436 } else {
2437 method = "GETHOSTNAME";
2439 control_event_server_status(LOG_NOTICE,
2440 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2441 tmpbuf, method, h?"HOSTNAME=":"", h);
2443 last_resolved_addr = *addr_out;
2444 if (hostname_out)
2445 *hostname_out = tor_strdup(hostname);
2446 return 0;
2449 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2450 * on a private network.
2453 is_local_addr(const tor_addr_t *addr)
2455 if (tor_addr_is_internal(addr, 0))
2456 return 1;
2457 /* Check whether ip is on the same /24 as we are. */
2458 if (get_options()->EnforceDistinctSubnets == 0)
2459 return 0;
2460 if (tor_addr_family(addr) == AF_INET) {
2461 /*XXXX022 IP6 what corresponds to an /24? */
2462 uint32_t ip = tor_addr_to_ipv4h(addr);
2464 /* It's possible that this next check will hit before the first time
2465 * resolve_my_address actually succeeds. (For clients, it is likely that
2466 * resolve_my_address will never be called at all). In those cases,
2467 * last_resolved_addr will be 0, and so checking to see whether ip is on
2468 * the same /24 as last_resolved_addr will be the same as checking whether
2469 * it was on net 0, which is already done by is_internal_IP.
2471 if ((last_resolved_addr & 0xffffff00ul) == (ip & 0xffffff00ul))
2472 return 1;
2474 return 0;
2477 /** Called when we don't have a nickname set. Try to guess a good nickname
2478 * based on the hostname, and return it in a newly allocated string. If we
2479 * can't, return NULL and let the caller warn if it wants to. */
2480 static char *
2481 get_default_nickname(void)
2483 static const char * const bad_default_nicknames[] = {
2484 "localhost",
2485 NULL,
2487 char localhostname[256];
2488 char *cp, *out, *outp;
2489 int i;
2491 if (gethostname(localhostname, sizeof(localhostname)) < 0)
2492 return NULL;
2494 /* Put it in lowercase; stop at the first dot. */
2495 if ((cp = strchr(localhostname, '.')))
2496 *cp = '\0';
2497 tor_strlower(localhostname);
2499 /* Strip invalid characters. */
2500 cp = localhostname;
2501 out = outp = tor_malloc(strlen(localhostname) + 1);
2502 while (*cp) {
2503 if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
2504 *outp++ = *cp++;
2505 else
2506 cp++;
2508 *outp = '\0';
2510 /* Enforce length. */
2511 if (strlen(out) > MAX_NICKNAME_LEN)
2512 out[MAX_NICKNAME_LEN]='\0';
2514 /* Check for dumb names. */
2515 for (i = 0; bad_default_nicknames[i]; ++i) {
2516 if (!strcmp(out, bad_default_nicknames[i])) {
2517 tor_free(out);
2518 return NULL;
2522 return out;
2525 /** Release storage held by <b>options</b>. */
2526 static void
2527 config_free(config_format_t *fmt, void *options)
2529 int i;
2531 tor_assert(options);
2533 for (i=0; fmt->vars[i].name; ++i)
2534 option_clear(fmt, options, &(fmt->vars[i]));
2535 if (fmt->extra) {
2536 config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
2537 config_free_lines(*linep);
2538 *linep = NULL;
2540 tor_free(options);
2543 /** Return true iff a and b contain identical keys and values in identical
2544 * order. */
2545 static int
2546 config_lines_eq(config_line_t *a, config_line_t *b)
2548 while (a && b) {
2549 if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
2550 return 0;
2551 a = a->next;
2552 b = b->next;
2554 if (a || b)
2555 return 0;
2556 return 1;
2559 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2560 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2562 static int
2563 option_is_same(config_format_t *fmt,
2564 or_options_t *o1, or_options_t *o2, const char *name)
2566 config_line_t *c1, *c2;
2567 int r = 1;
2568 CHECK(fmt, o1);
2569 CHECK(fmt, o2);
2571 c1 = get_assigned_option(fmt, o1, name, 0);
2572 c2 = get_assigned_option(fmt, o2, name, 0);
2573 r = config_lines_eq(c1, c2);
2574 config_free_lines(c1);
2575 config_free_lines(c2);
2576 return r;
2579 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2580 static or_options_t *
2581 options_dup(config_format_t *fmt, or_options_t *old)
2583 or_options_t *newopts;
2584 int i;
2585 config_line_t *line;
2587 newopts = config_alloc(fmt);
2588 for (i=0; fmt->vars[i].name; ++i) {
2589 if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2590 continue;
2591 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
2592 continue;
2593 line = get_assigned_option(fmt, old, fmt->vars[i].name, 0);
2594 if (line) {
2595 char *msg = NULL;
2596 if (config_assign(fmt, newopts, line, 0, 0, &msg) < 0) {
2597 log_err(LD_BUG, "Config_get_assigned_option() generated "
2598 "something we couldn't config_assign(): %s", msg);
2599 tor_free(msg);
2600 tor_assert(0);
2603 config_free_lines(line);
2605 return newopts;
2608 /** Return a new empty or_options_t. Used for testing. */
2609 or_options_t *
2610 options_new(void)
2612 return config_alloc(&options_format);
2615 /** Set <b>options</b> to hold reasonable defaults for most options.
2616 * Each option defaults to zero. */
2617 void
2618 options_init(or_options_t *options)
2620 config_init(&options_format, options);
2623 /* Check if the port number given in <b>port_option</b> in combination with
2624 * the specified port in <b>listen_options</b> will result in Tor actually
2625 * opening a low port (meaning a port lower than 1024). Return 1 if
2626 * it is, or 0 if it isn't or the concept of a low port isn't applicable for
2627 * the platform we're on. */
2628 static int
2629 is_listening_on_low_port(uint16_t port_option,
2630 const config_line_t *listen_options)
2632 #ifdef MS_WINDOWS
2633 return 0; /* No port is too low for windows. */
2634 #else
2635 const config_line_t *l;
2636 uint16_t p;
2637 if (port_option == 0)
2638 return 0; /* We're not listening */
2639 if (listen_options == NULL)
2640 return (port_option < 1024);
2642 for (l = listen_options; l; l = l->next) {
2643 parse_addr_port(LOG_WARN, l->value, NULL, NULL, &p);
2644 if (p<1024) {
2645 return 1;
2648 return 0;
2649 #endif
2652 /** Set all vars in the configuration object <b>options</b> to their default
2653 * values. */
2654 static void
2655 config_init(config_format_t *fmt, void *options)
2657 int i;
2658 config_var_t *var;
2659 CHECK(fmt, options);
2661 for (i=0; fmt->vars[i].name; ++i) {
2662 var = &fmt->vars[i];
2663 if (!var->initvalue)
2664 continue; /* defaults to NULL or 0 */
2665 option_reset(fmt, options, var, 1);
2669 /** Allocate and return a new string holding the written-out values of the vars
2670 * in 'options'. If 'minimal', do not write out any default-valued vars.
2671 * Else, if comment_defaults, write default values as comments.
2673 static char *
2674 config_dump(config_format_t *fmt, void *options, int minimal,
2675 int comment_defaults)
2677 smartlist_t *elements;
2678 or_options_t *defaults;
2679 config_line_t *line, *assigned;
2680 char *result;
2681 int i;
2682 const char *desc;
2683 char *msg = NULL;
2685 defaults = config_alloc(fmt);
2686 config_init(fmt, defaults);
2688 /* XXX use a 1 here so we don't add a new log line while dumping */
2689 if (fmt->validate_fn(NULL,defaults, 1, &msg) < 0) {
2690 log_err(LD_BUG, "Failed to validate default config.");
2691 tor_free(msg);
2692 tor_assert(0);
2695 elements = smartlist_create();
2696 for (i=0; fmt->vars[i].name; ++i) {
2697 int comment_option = 0;
2698 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
2699 fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2700 continue;
2701 /* Don't save 'hidden' control variables. */
2702 if (!strcmpstart(fmt->vars[i].name, "__"))
2703 continue;
2704 if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
2705 continue;
2706 else if (comment_defaults &&
2707 option_is_same(fmt, options, defaults, fmt->vars[i].name))
2708 comment_option = 1;
2710 desc = config_find_description(fmt, fmt->vars[i].name);
2711 line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name, 1);
2713 if (line && desc) {
2714 /* Only dump the description if there's something to describe. */
2715 wrap_string(elements, desc, 78, "# ", "# ");
2718 for (; line; line = line->next) {
2719 size_t len = strlen(line->key) + strlen(line->value) + 5;
2720 char *tmp;
2721 tmp = tor_malloc(len);
2722 if (tor_snprintf(tmp, len, "%s%s %s\n",
2723 comment_option ? "# " : "",
2724 line->key, line->value)<0) {
2725 log_err(LD_BUG,"Internal error writing option value");
2726 tor_assert(0);
2728 smartlist_add(elements, tmp);
2730 config_free_lines(assigned);
2733 if (fmt->extra) {
2734 line = *(config_line_t**)STRUCT_VAR_P(options, fmt->extra->var_offset);
2735 for (; line; line = line->next) {
2736 size_t len = strlen(line->key) + strlen(line->value) + 3;
2737 char *tmp;
2738 tmp = tor_malloc(len);
2739 if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
2740 log_err(LD_BUG,"Internal error writing option value");
2741 tor_assert(0);
2743 smartlist_add(elements, tmp);
2747 result = smartlist_join_strings(elements, "", 0, NULL);
2748 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2749 smartlist_free(elements);
2750 config_free(fmt, defaults);
2751 return result;
2754 /** Return a string containing a possible configuration file that would give
2755 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2756 * include options that are the same as Tor's defaults.
2758 static char *
2759 options_dump(or_options_t *options, int minimal)
2761 return config_dump(&options_format, options, minimal, 0);
2764 /** Return 0 if every element of sl is a string holding a decimal
2765 * representation of a port number, or if sl is NULL.
2766 * Otherwise set *msg and return -1. */
2767 static int
2768 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2770 int i;
2771 char buf[1024];
2772 tor_assert(name);
2774 if (!sl)
2775 return 0;
2777 SMARTLIST_FOREACH(sl, const char *, cp,
2779 i = atoi(cp);
2780 if (i < 1 || i > 65535) {
2781 int r = tor_snprintf(buf, sizeof(buf),
2782 "Port '%s' out of range in %s", cp, name);
2783 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2784 return -1;
2787 return 0;
2790 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2791 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2792 * Else return 0.
2794 static int
2795 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2797 int r;
2798 char buf[1024];
2799 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2800 /* This handles an understandable special case where somebody says "2gb"
2801 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2802 --*value;
2804 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2805 r = tor_snprintf(buf, sizeof(buf), "%s ("U64_FORMAT") must be at most %d",
2806 desc, U64_PRINTF_ARG(*value),
2807 ROUTER_MAX_DECLARED_BANDWIDTH);
2808 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2809 return -1;
2811 return 0;
2814 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2815 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2816 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2817 * Treat "0" as "".
2818 * Return 0 on success or -1 if not a recognized authority type (in which
2819 * case the value of _PublishServerDescriptor is undefined). */
2820 static int
2821 compute_publishserverdescriptor(or_options_t *options)
2823 smartlist_t *list = options->PublishServerDescriptor;
2824 authority_type_t *auth = &options->_PublishServerDescriptor;
2825 *auth = NO_AUTHORITY;
2826 if (!list) /* empty list, answer is none */
2827 return 0;
2828 SMARTLIST_FOREACH(list, const char *, string, {
2829 if (!strcasecmp(string, "v1"))
2830 *auth |= V1_AUTHORITY;
2831 else if (!strcmp(string, "1"))
2832 if (options->BridgeRelay)
2833 *auth |= BRIDGE_AUTHORITY;
2834 else
2835 *auth |= V2_AUTHORITY | V3_AUTHORITY;
2836 else if (!strcasecmp(string, "v2"))
2837 *auth |= V2_AUTHORITY;
2838 else if (!strcasecmp(string, "v3"))
2839 *auth |= V3_AUTHORITY;
2840 else if (!strcasecmp(string, "bridge"))
2841 *auth |= BRIDGE_AUTHORITY;
2842 else if (!strcasecmp(string, "hidserv"))
2843 *auth |= HIDSERV_AUTHORITY;
2844 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2845 /* no authority */;
2846 else
2847 return -1;
2849 return 0;
2852 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2853 * services can overload the directory system. */
2854 #define MIN_REND_POST_PERIOD (10*60)
2856 /** Highest allowable value for RendPostPeriod. */
2857 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2859 /** Lowest allowable value for CircuitBuildTimeout; values too low will
2860 * increase network load because of failing connections being retried, and
2861 * might prevent users from connecting to the network at all. */
2862 #define MIN_CIRCUIT_BUILD_TIMEOUT 30
2864 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2865 * will generate too many circuits and potentially overload the network. */
2866 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2868 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2869 * permissible transition from <b>old_options</b>. Else return -1.
2870 * Should have no side effects, except for normalizing the contents of
2871 * <b>options</b>.
2873 * On error, tor_strdup an error explanation into *<b>msg</b>.
2875 * XXX
2876 * If <b>from_setconf</b>, we were called by the controller, and our
2877 * Log line should stay empty. If it's 0, then give us a default log
2878 * if there are no logs defined.
2880 static int
2881 options_validate(or_options_t *old_options, or_options_t *options,
2882 int from_setconf, char **msg)
2884 int i, r;
2885 config_line_t *cl;
2886 const char *uname = get_uname();
2887 char buf[1024];
2888 #define REJECT(arg) \
2889 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2890 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2892 tor_assert(msg);
2893 *msg = NULL;
2895 if (options->ORPort < 0 || options->ORPort > 65535)
2896 REJECT("ORPort option out of bounds.");
2898 if (server_mode(options) &&
2899 (!strcmpstart(uname, "Windows 95") ||
2900 !strcmpstart(uname, "Windows 98") ||
2901 !strcmpstart(uname, "Windows Me"))) {
2902 log(LOG_WARN, LD_CONFIG, "Tor is running as a server, but you are "
2903 "running %s; this probably won't work. See "
2904 "http://wiki.noreply.org/noreply/TheOnionRouter/TorFAQ#ServerOS "
2905 "for details.", uname);
2908 if (options->ORPort == 0 && options->ORListenAddress != NULL)
2909 REJECT("ORPort must be defined if ORListenAddress is defined.");
2911 if (options->DirPort == 0 && options->DirListenAddress != NULL)
2912 REJECT("DirPort must be defined if DirListenAddress is defined.");
2914 if (options->DNSPort == 0 && options->DNSListenAddress != NULL)
2915 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
2917 if (options->ControlPort == 0 && options->ControlListenAddress != NULL)
2918 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
2920 if (options->TransPort == 0 && options->TransListenAddress != NULL)
2921 REJECT("TransPort must be defined if TransListenAddress is defined.");
2923 if (options->NatdPort == 0 && options->NatdListenAddress != NULL)
2924 REJECT("NatdPort must be defined if NatdListenAddress is defined.");
2926 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
2927 * configuration does this. */
2929 for (i = 0; i < 3; ++i) {
2930 int is_socks = i==0;
2931 int is_trans = i==1;
2932 config_line_t *line, *opt, *old;
2933 const char *tp;
2934 if (is_socks) {
2935 opt = options->SocksListenAddress;
2936 old = old_options ? old_options->SocksListenAddress : NULL;
2937 tp = "SOCKS proxy";
2938 } else if (is_trans) {
2939 opt = options->TransListenAddress;
2940 old = old_options ? old_options->TransListenAddress : NULL;
2941 tp = "transparent proxy";
2942 } else {
2943 opt = options->NatdListenAddress;
2944 old = old_options ? old_options->NatdListenAddress : NULL;
2945 tp = "natd proxy";
2948 for (line = opt; line; line = line->next) {
2949 char *address = NULL;
2950 uint16_t port;
2951 uint32_t addr;
2952 if (parse_addr_port(LOG_WARN, line->value, &address, &addr, &port)<0)
2953 continue; /* We'll warn about this later. */
2954 if (!is_internal_IP(addr, 1) &&
2955 (!old_options || !config_lines_eq(old, opt))) {
2956 log_warn(LD_CONFIG,
2957 "You specified a public address '%s' for a %s. Other "
2958 "people on the Internet might find your computer and use it as "
2959 "an open %s. Please don't allow this unless you have "
2960 "a good reason.", address, tp, tp);
2962 tor_free(address);
2966 if (validate_data_directory(options)<0)
2967 REJECT("Invalid DataDirectory");
2969 if (options->Nickname == NULL) {
2970 if (server_mode(options)) {
2971 if (!(options->Nickname = get_default_nickname())) {
2972 log_notice(LD_CONFIG, "Couldn't pick a nickname based on "
2973 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME);
2974 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
2975 } else {
2976 log_notice(LD_CONFIG, "Choosing default nickname '%s'",
2977 options->Nickname);
2980 } else {
2981 if (!is_legal_nickname(options->Nickname)) {
2982 r = tor_snprintf(buf, sizeof(buf),
2983 "Nickname '%s' is wrong length or contains illegal characters.",
2984 options->Nickname);
2985 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2986 return -1;
2990 if (server_mode(options) && !options->ContactInfo)
2991 log(LOG_NOTICE, LD_CONFIG, "Your ContactInfo config option is not set. "
2992 "Please consider setting it, so we can contact you if your server is "
2993 "misconfigured or something else goes wrong.");
2995 /* Special case on first boot if no Log options are given. */
2996 if (!options->Logs && !options->RunAsDaemon && !from_setconf)
2997 config_line_append(&options->Logs, "Log", "notice stdout");
2999 if (options_init_logs(options, 1)<0) /* Validate the log(s) */
3000 REJECT("Failed to validate Log options. See logs for details.");
3002 if (options->NoPublish) {
3003 log(LOG_WARN, LD_CONFIG,
3004 "NoPublish is obsolete. Use PublishServerDescriptor instead.");
3005 SMARTLIST_FOREACH(options->PublishServerDescriptor, char *, s,
3006 tor_free(s));
3007 smartlist_clear(options->PublishServerDescriptor);
3010 if (authdir_mode(options)) {
3011 /* confirm that our address isn't broken, so we can complain now */
3012 uint32_t tmp;
3013 if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
3014 REJECT("Failed to resolve/guess local address. See logs for details.");
3017 #ifndef MS_WINDOWS
3018 if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
3019 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
3020 #endif
3022 if (options->SocksPort < 0 || options->SocksPort > 65535)
3023 REJECT("SocksPort option out of bounds.");
3025 if (options->DNSPort < 0 || options->DNSPort > 65535)
3026 REJECT("DNSPort option out of bounds.");
3028 if (options->TransPort < 0 || options->TransPort > 65535)
3029 REJECT("TransPort option out of bounds.");
3031 if (options->NatdPort < 0 || options->NatdPort > 65535)
3032 REJECT("NatdPort option out of bounds.");
3034 if (options->SocksPort == 0 && options->TransPort == 0 &&
3035 options->NatdPort == 0 && options->ORPort == 0 &&
3036 options->DNSPort == 0 && !options->RendConfigLines)
3037 log(LOG_WARN, LD_CONFIG,
3038 "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
3039 "undefined, and there aren't any hidden services configured. "
3040 "Tor will still run, but probably won't do anything.");
3042 if (options->ControlPort < 0 || options->ControlPort > 65535)
3043 REJECT("ControlPort option out of bounds.");
3045 if (options->DirPort < 0 || options->DirPort > 65535)
3046 REJECT("DirPort option out of bounds.");
3048 #ifndef USE_TRANSPARENT
3049 if (options->TransPort || options->TransListenAddress)
3050 REJECT("TransPort and TransListenAddress are disabled in this build.");
3051 #endif
3053 if (options->AccountingMax &&
3054 (is_listening_on_low_port(options->ORPort, options->ORListenAddress) ||
3055 is_listening_on_low_port(options->DirPort, options->DirListenAddress)))
3057 log(LOG_WARN, LD_CONFIG,
3058 "You have set AccountingMax to use hibernation. You have also "
3059 "chosen a low DirPort or OrPort. This combination can make Tor stop "
3060 "working when it tries to re-attach the port after a period of "
3061 "hibernation. Please choose a different port or turn off "
3062 "hibernation unless you know this combination will work on your "
3063 "platform.");
3066 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3067 options->_ExcludeExitNodesUnion = routerset_new();
3068 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeExitNodes);
3069 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeNodes);
3072 if (options->StrictExitNodes &&
3073 (!options->ExitNodes) &&
3074 (!old_options ||
3075 (old_options->StrictExitNodes != options->StrictExitNodes) ||
3076 (!routerset_equal(old_options->ExitNodes,options->ExitNodes))))
3077 COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
3079 if (options->StrictEntryNodes &&
3080 (!options->EntryNodes) &&
3081 (!old_options ||
3082 (old_options->StrictEntryNodes != options->StrictEntryNodes) ||
3083 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
3084 COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
3086 if (options->EntryNodes && !routerset_is_list(options->EntryNodes)) {
3087 /* XXXX fix this; see entry_guards_prepend_from_config(). */
3088 REJECT("IPs or countries are not yet supported in EntryNodes.");
3091 if (options->AuthoritativeDir) {
3092 if (!options->ContactInfo && !options->TestingTorNetwork)
3093 REJECT("Authoritative directory servers must set ContactInfo");
3094 if (options->V1AuthoritativeDir && !options->RecommendedVersions)
3095 REJECT("V1 authoritative dir servers must set RecommendedVersions.");
3096 if (!options->RecommendedClientVersions)
3097 options->RecommendedClientVersions =
3098 config_lines_dup(options->RecommendedVersions);
3099 if (!options->RecommendedServerVersions)
3100 options->RecommendedServerVersions =
3101 config_lines_dup(options->RecommendedVersions);
3102 if (options->VersioningAuthoritativeDir &&
3103 (!options->RecommendedClientVersions ||
3104 !options->RecommendedServerVersions))
3105 REJECT("Versioning authoritative dir servers must set "
3106 "Recommended*Versions.");
3107 if (options->UseEntryGuards) {
3108 log_info(LD_CONFIG, "Authoritative directory servers can't set "
3109 "UseEntryGuards. Disabling.");
3110 options->UseEntryGuards = 0;
3112 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
3113 log_info(LD_CONFIG, "Authoritative directories always try to download "
3114 "extra-info documents. Setting DownloadExtraInfo.");
3115 options->DownloadExtraInfo = 1;
3117 if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
3118 options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
3119 options->V3AuthoritativeDir))
3120 REJECT("AuthoritativeDir is set, but none of "
3121 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
3124 if (options->AuthoritativeDir && !options->DirPort)
3125 REJECT("Running as authoritative directory, but no DirPort set.");
3127 if (options->AuthoritativeDir && !options->ORPort)
3128 REJECT("Running as authoritative directory, but no ORPort set.");
3130 if (options->AuthoritativeDir && options->ClientOnly)
3131 REJECT("Running as authoritative directory, but ClientOnly also set.");
3133 if (options->HSAuthorityRecordStats && !options->HSAuthoritativeDir)
3134 REJECT("HSAuthorityRecordStats is set but we're not running as "
3135 "a hidden service authority.");
3137 if (options->ConnLimit <= 0) {
3138 r = tor_snprintf(buf, sizeof(buf),
3139 "ConnLimit must be greater than 0, but was set to %d",
3140 options->ConnLimit);
3141 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3142 return -1;
3145 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3146 return -1;
3148 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3149 return -1;
3151 if (validate_ports_csv(options->RejectPlaintextPorts,
3152 "RejectPlaintextPorts", msg) < 0)
3153 return -1;
3155 if (validate_ports_csv(options->WarnPlaintextPorts,
3156 "WarnPlaintextPorts", msg) < 0)
3157 return -1;
3159 if (options->FascistFirewall && !options->ReachableAddresses) {
3160 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3161 /* We already have firewall ports set, so migrate them to
3162 * ReachableAddresses, which will set ReachableORAddresses and
3163 * ReachableDirAddresses if they aren't set explicitly. */
3164 smartlist_t *instead = smartlist_create();
3165 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3166 new_line->key = tor_strdup("ReachableAddresses");
3167 /* If we're configured with the old format, we need to prepend some
3168 * open ports. */
3169 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3171 int p = atoi(portno);
3172 char *s;
3173 if (p<0) continue;
3174 s = tor_malloc(16);
3175 tor_snprintf(s, 16, "*:%d", p);
3176 smartlist_add(instead, s);
3178 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3179 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3180 log(LOG_NOTICE, LD_CONFIG,
3181 "Converting FascistFirewall and FirewallPorts "
3182 "config options to new format: \"ReachableAddresses %s\"",
3183 new_line->value);
3184 options->ReachableAddresses = new_line;
3185 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3186 smartlist_free(instead);
3187 } else {
3188 /* We do not have FirewallPorts set, so add 80 to
3189 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3190 if (!options->ReachableDirAddresses) {
3191 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3192 new_line->key = tor_strdup("ReachableDirAddresses");
3193 new_line->value = tor_strdup("*:80");
3194 options->ReachableDirAddresses = new_line;
3195 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3196 "to new format: \"ReachableDirAddresses *:80\"");
3198 if (!options->ReachableORAddresses) {
3199 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3200 new_line->key = tor_strdup("ReachableORAddresses");
3201 new_line->value = tor_strdup("*:443");
3202 options->ReachableORAddresses = new_line;
3203 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3204 "to new format: \"ReachableORAddresses *:443\"");
3209 for (i=0; i<3; i++) {
3210 config_line_t **linep =
3211 (i==0) ? &options->ReachableAddresses :
3212 (i==1) ? &options->ReachableORAddresses :
3213 &options->ReachableDirAddresses;
3214 if (!*linep)
3215 continue;
3216 /* We need to end with a reject *:*, not an implicit accept *:* */
3217 for (;;) {
3218 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
3219 break;
3220 linep = &((*linep)->next);
3221 if (!*linep) {
3222 *linep = tor_malloc_zero(sizeof(config_line_t));
3223 (*linep)->key = tor_strdup(
3224 (i==0) ? "ReachableAddresses" :
3225 (i==1) ? "ReachableORAddresses" :
3226 "ReachableDirAddresses");
3227 (*linep)->value = tor_strdup("reject *:*");
3228 break;
3233 if ((options->ReachableAddresses ||
3234 options->ReachableORAddresses ||
3235 options->ReachableDirAddresses) &&
3236 server_mode(options))
3237 REJECT("Servers must be able to freely connect to the rest "
3238 "of the Internet, so they must not set Reachable*Addresses "
3239 "or FascistFirewall.");
3241 if (options->UseBridges &&
3242 server_mode(options))
3243 REJECT("Servers must be able to freely connect to the rest "
3244 "of the Internet, so they must not set UseBridges.");
3246 options->_AllowInvalid = 0;
3247 if (options->AllowInvalidNodes) {
3248 SMARTLIST_FOREACH(options->AllowInvalidNodes, const char *, cp, {
3249 if (!strcasecmp(cp, "entry"))
3250 options->_AllowInvalid |= ALLOW_INVALID_ENTRY;
3251 else if (!strcasecmp(cp, "exit"))
3252 options->_AllowInvalid |= ALLOW_INVALID_EXIT;
3253 else if (!strcasecmp(cp, "middle"))
3254 options->_AllowInvalid |= ALLOW_INVALID_MIDDLE;
3255 else if (!strcasecmp(cp, "introduction"))
3256 options->_AllowInvalid |= ALLOW_INVALID_INTRODUCTION;
3257 else if (!strcasecmp(cp, "rendezvous"))
3258 options->_AllowInvalid |= ALLOW_INVALID_RENDEZVOUS;
3259 else {
3260 r = tor_snprintf(buf, sizeof(buf),
3261 "Unrecognized value '%s' in AllowInvalidNodes", cp);
3262 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3263 return -1;
3268 if (compute_publishserverdescriptor(options) < 0) {
3269 r = tor_snprintf(buf, sizeof(buf),
3270 "Unrecognized value in PublishServerDescriptor");
3271 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3272 return -1;
3275 if ((options->BridgeRelay
3276 || options->_PublishServerDescriptor & BRIDGE_AUTHORITY)
3277 && (options->_PublishServerDescriptor
3278 & (V1_AUTHORITY|V2_AUTHORITY|V3_AUTHORITY))) {
3279 REJECT("Bridges are not supposed to publish router descriptors to the "
3280 "directory authorities. Please correct your "
3281 "PublishServerDescriptor line.");
3284 if (options->MinUptimeHidServDirectoryV2 < 0) {
3285 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3286 "least 0 seconds. Changing to 0.");
3287 options->MinUptimeHidServDirectoryV2 = 0;
3290 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
3291 log(LOG_WARN,LD_CONFIG,"RendPostPeriod option is too short; "
3292 "raising to %d seconds.", MIN_REND_POST_PERIOD);
3293 options->RendPostPeriod = MIN_REND_POST_PERIOD;
3296 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3297 log(LOG_WARN, LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3298 MAX_DIR_PERIOD);
3299 options->RendPostPeriod = MAX_DIR_PERIOD;
3302 if (options->CircuitBuildTimeout < MIN_CIRCUIT_BUILD_TIMEOUT) {
3303 log(LOG_WARN, LD_CONFIG, "CircuitBuildTimeout option is too short; "
3304 "raising to %d seconds.", MIN_CIRCUIT_BUILD_TIMEOUT);
3305 options->CircuitBuildTimeout = MIN_CIRCUIT_BUILD_TIMEOUT;
3308 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3309 log(LOG_WARN, LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3310 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3311 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3314 if (options->KeepalivePeriod < 1)
3315 REJECT("KeepalivePeriod option must be positive.");
3317 if (ensure_bandwidth_cap(&options->BandwidthRate,
3318 "BandwidthRate", msg) < 0)
3319 return -1;
3320 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3321 "BandwidthBurst", msg) < 0)
3322 return -1;
3323 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3324 "MaxAdvertisedBandwidth", msg) < 0)
3325 return -1;
3326 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3327 "RelayBandwidthRate", msg) < 0)
3328 return -1;
3329 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3330 "RelayBandwidthBurst", msg) < 0)
3331 return -1;
3333 if (server_mode(options)) {
3334 if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3335 r = tor_snprintf(buf, sizeof(buf),
3336 "BandwidthRate is set to %d bytes/second. "
3337 "For servers, it must be at least %d.",
3338 (int)options->BandwidthRate,
3339 ROUTER_REQUIRED_MIN_BANDWIDTH);
3340 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3341 return -1;
3342 } else if (options->MaxAdvertisedBandwidth <
3343 ROUTER_REQUIRED_MIN_BANDWIDTH/2) {
3344 r = tor_snprintf(buf, sizeof(buf),
3345 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3346 "For servers, it must be at least %d.",
3347 (int)options->MaxAdvertisedBandwidth,
3348 ROUTER_REQUIRED_MIN_BANDWIDTH/2);
3349 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3350 return -1;
3352 if (options->RelayBandwidthRate &&
3353 options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3354 r = tor_snprintf(buf, sizeof(buf),
3355 "RelayBandwidthRate is set to %d bytes/second. "
3356 "For servers, it must be at least %d.",
3357 (int)options->RelayBandwidthRate,
3358 ROUTER_REQUIRED_MIN_BANDWIDTH);
3359 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3360 return -1;
3364 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3365 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3367 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3368 REJECT("RelayBandwidthBurst must be at least equal "
3369 "to RelayBandwidthRate.");
3371 if (options->BandwidthRate > options->BandwidthBurst)
3372 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3374 /* if they set relaybandwidth* really high but left bandwidth*
3375 * at the default, raise the defaults. */
3376 if (options->RelayBandwidthRate > options->BandwidthRate)
3377 options->BandwidthRate = options->RelayBandwidthRate;
3378 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3379 options->BandwidthBurst = options->RelayBandwidthBurst;
3381 if (accounting_parse_options(options, 1)<0)
3382 REJECT("Failed to parse accounting options. See logs for details.");
3384 if (options->HttpProxy) { /* parse it now */
3385 if (parse_addr_port(LOG_WARN, options->HttpProxy, NULL,
3386 &options->HttpProxyAddr, &options->HttpProxyPort) < 0)
3387 REJECT("HttpProxy failed to parse or resolve. Please fix.");
3388 if (options->HttpProxyPort == 0) { /* give it a default */
3389 options->HttpProxyPort = 80;
3393 if (options->HttpProxyAuthenticator) {
3394 if (strlen(options->HttpProxyAuthenticator) >= 48)
3395 REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
3398 if (options->HttpsProxy) { /* parse it now */
3399 if (parse_addr_port(LOG_WARN, options->HttpsProxy, NULL,
3400 &options->HttpsProxyAddr, &options->HttpsProxyPort) <0)
3401 REJECT("HttpsProxy failed to parse or resolve. Please fix.");
3402 if (options->HttpsProxyPort == 0) { /* give it a default */
3403 options->HttpsProxyPort = 443;
3407 if (options->HttpsProxyAuthenticator) {
3408 if (strlen(options->HttpsProxyAuthenticator) >= 48)
3409 REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
3412 if (options->HashedControlPassword) {
3413 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3414 if (!sl) {
3415 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3416 } else {
3417 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3418 smartlist_free(sl);
3422 if (options->HashedControlSessionPassword) {
3423 smartlist_t *sl = decode_hashed_passwords(
3424 options->HashedControlSessionPassword);
3425 if (!sl) {
3426 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3427 } else {
3428 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3429 smartlist_free(sl);
3433 if (options->ControlListenAddress) {
3434 int all_are_local = 1;
3435 config_line_t *ln;
3436 for (ln = options->ControlListenAddress; ln; ln = ln->next) {
3437 if (strcmpstart(ln->value, "127."))
3438 all_are_local = 0;
3440 if (!all_are_local) {
3441 if (!options->HashedControlPassword &&
3442 !options->HashedControlSessionPassword &&
3443 !options->CookieAuthentication) {
3444 log_warn(LD_CONFIG,
3445 "You have a ControlListenAddress set to accept "
3446 "unauthenticated connections from a non-local address. "
3447 "This means that programs not running on your computer "
3448 "can reconfigure your Tor, without even having to guess a "
3449 "password. That's so bad that I'm closing your ControlPort "
3450 "for you. If you need to control your Tor remotely, try "
3451 "enabling authentication and using a tool like stunnel or "
3452 "ssh to encrypt remote access.");
3453 options->ControlPort = 0;
3454 } else {
3455 log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
3456 "connections from a non-local address. This means that "
3457 "programs not running on your computer can reconfigure your "
3458 "Tor. That's pretty bad, since the controller "
3459 "protocol isn't encrypted! Maybe you should just listen on "
3460 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
3461 "remote connections to your control port.");
3466 if (options->ControlPort && !options->HashedControlPassword &&
3467 !options->HashedControlSessionPassword &&
3468 !options->CookieAuthentication) {
3469 log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
3470 "has been configured. This means that any program on your "
3471 "computer can reconfigure your Tor. That's bad! You should "
3472 "upgrade your Tor controller as soon as possible.");
3475 if (options->UseEntryGuards && ! options->NumEntryGuards)
3476 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3478 if (check_nickname_list(options->MyFamily, "MyFamily", msg))
3479 return -1;
3480 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3481 if (check_nickname_list(cl->value, "NodeFamily", msg))
3482 return -1;
3485 if (validate_addr_policies(options, msg) < 0)
3486 return -1;
3488 if (validate_dir_authorities(options, old_options) < 0)
3489 REJECT("Directory authority line did not parse. See logs for details.");
3491 if (options->UseBridges && !options->Bridges)
3492 REJECT("If you set UseBridges, you must specify at least one bridge.");
3493 if (options->UseBridges && !options->TunnelDirConns)
3494 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3495 if (options->Bridges) {
3496 for (cl = options->Bridges; cl; cl = cl->next) {
3497 if (parse_bridge_line(cl->value, 1)<0)
3498 REJECT("Bridge line did not parse. See logs for details.");
3502 if (options->ConstrainedSockets) {
3503 /* If the user wants to constrain socket buffer use, make sure the desired
3504 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3505 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3506 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3507 options->ConstrainedSockSize % 1024) {
3508 r = tor_snprintf(buf, sizeof(buf),
3509 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3510 "in 1024 byte increments.",
3511 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3512 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3513 return -1;
3515 if (options->DirPort) {
3516 /* Providing cached directory entries while system TCP buffers are scarce
3517 * will exacerbate the socket errors. Suggest that this be disabled. */
3518 COMPLAIN("You have requested constrained socket buffers while also "
3519 "serving directory entries via DirPort. It is strongly "
3520 "suggested that you disable serving directory requests when "
3521 "system TCP buffer resources are scarce.");
3525 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3526 options->V3AuthVotingInterval/2) {
3527 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3528 "V3AuthVotingInterval");
3530 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
3531 REJECT("V3AuthVoteDelay is way too low.");
3532 if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
3533 REJECT("V3AuthDistDelay is way too low.");
3535 if (options->V3AuthNIntervalsValid < 2)
3536 REJECT("V3AuthNIntervalsValid must be at least 2.");
3538 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3539 REJECT("V3AuthVotingInterval is insanely low.");
3540 } else if (options->V3AuthVotingInterval > 24*60*60) {
3541 REJECT("V3AuthVotingInterval is insanely high.");
3542 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3543 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3546 if (rend_config_services(options, 1) < 0)
3547 REJECT("Failed to configure rendezvous options. See logs for details.");
3549 /* Parse client-side authorization for hidden services. */
3550 if (rend_parse_service_authorization(options, 1) < 0)
3551 REJECT("Failed to configure client authorization for hidden services. "
3552 "See logs for details.");
3554 if (parse_virtual_addr_network(options->VirtualAddrNetwork, 1, NULL)<0)
3555 return -1;
3557 if (options->PreferTunneledDirConns && !options->TunnelDirConns)
3558 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3560 if (options->AutomapHostsSuffixes) {
3561 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
3563 size_t len = strlen(suf);
3564 if (len && suf[len-1] == '.')
3565 suf[len-1] = '\0';
3569 if (options->TestingTorNetwork && !options->DirServers) {
3570 REJECT("TestingTorNetwork may only be configured in combination with "
3571 "a non-default set of DirServers.");
3574 /*XXXX022 checking for defaults manually like this is a bit fragile.*/
3576 /* Keep changes to hard-coded values synchronous to man page and default
3577 * values table. */
3578 if (options->TestingV3AuthInitialVotingInterval != 30*60 &&
3579 !options->TestingTorNetwork) {
3580 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
3581 "Tor networks!");
3582 } else if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
3583 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3584 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
3585 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3586 "30 minutes.");
3589 if (options->TestingV3AuthInitialVoteDelay != 5*60 &&
3590 !options->TestingTorNetwork) {
3591 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
3592 "Tor networks!");
3593 } else if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
3594 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3597 if (options->TestingV3AuthInitialDistDelay != 5*60 &&
3598 !options->TestingTorNetwork) {
3599 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
3600 "Tor networks!");
3601 } else if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
3602 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3605 if (options->TestingV3AuthInitialVoteDelay +
3606 options->TestingV3AuthInitialDistDelay >=
3607 options->TestingV3AuthInitialVotingInterval/2) {
3608 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3609 "must be less than half TestingV3AuthInitialVotingInterval");
3612 if (options->TestingAuthDirTimeToLearnReachability != 30*60 &&
3613 !options->TestingTorNetwork) {
3614 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
3615 "testing Tor networks!");
3616 } else if (options->TestingAuthDirTimeToLearnReachability < 0) {
3617 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3618 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
3619 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3622 if (options->TestingEstimatedDescriptorPropagationTime != 10*60 &&
3623 !options->TestingTorNetwork) {
3624 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
3625 "testing Tor networks!");
3626 } else if (options->TestingEstimatedDescriptorPropagationTime < 0) {
3627 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3628 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
3629 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3632 if (options->TestingTorNetwork) {
3633 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
3634 "almost unusable in the public Tor network, and is "
3635 "therefore only advised if you are building a "
3636 "testing Tor network!");
3639 return 0;
3640 #undef REJECT
3641 #undef COMPLAIN
3644 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3645 * equal strings. */
3646 static int
3647 opt_streq(const char *s1, const char *s2)
3649 if (!s1 && !s2)
3650 return 1;
3651 else if (s1 && s2 && !strcmp(s1,s2))
3652 return 1;
3653 else
3654 return 0;
3657 /** Check if any of the previous options have changed but aren't allowed to. */
3658 static int
3659 options_transition_allowed(or_options_t *old, or_options_t *new_val,
3660 char **msg)
3662 if (!old)
3663 return 0;
3665 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3666 *msg = tor_strdup("PidFile is not allowed to change.");
3667 return -1;
3670 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3671 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3672 "is not allowed.");
3673 return -1;
3676 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
3677 char buf[1024];
3678 int r = tor_snprintf(buf, sizeof(buf),
3679 "While Tor is running, changing DataDirectory "
3680 "(\"%s\"->\"%s\") is not allowed.",
3681 old->DataDirectory, new_val->DataDirectory);
3682 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3683 return -1;
3686 if (!opt_streq(old->User, new_val->User)) {
3687 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
3688 return -1;
3691 if (!opt_streq(old->Group, new_val->Group)) {
3692 *msg = tor_strdup("While Tor is running, changing Group is not allowed.");
3693 return -1;
3696 if (old->HardwareAccel != new_val->HardwareAccel) {
3697 *msg = tor_strdup("While Tor is running, changing HardwareAccel is "
3698 "not allowed.");
3699 return -1;
3702 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
3703 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
3704 "is not allowed.");
3705 return -1;
3708 return 0;
3711 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3712 * will require us to rotate the CPU and DNS workers; else return 0. */
3713 static int
3714 options_transition_affects_workers(or_options_t *old_options,
3715 or_options_t *new_options)
3717 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3718 old_options->NumCpus != new_options->NumCpus ||
3719 old_options->ORPort != new_options->ORPort ||
3720 old_options->ServerDNSSearchDomains !=
3721 new_options->ServerDNSSearchDomains ||
3722 old_options->SafeLogging != new_options->SafeLogging ||
3723 old_options->ClientOnly != new_options->ClientOnly ||
3724 !config_lines_eq(old_options->Logs, new_options->Logs))
3725 return 1;
3727 /* Check whether log options match. */
3729 /* Nothing that changed matters. */
3730 return 0;
3733 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3734 * will require us to generate a new descriptor; else return 0. */
3735 static int
3736 options_transition_affects_descriptor(or_options_t *old_options,
3737 or_options_t *new_options)
3739 /* XXX We can be smarter here. If your DirPort isn't being
3740 * published and you just turned it off, no need to republish. If
3741 * you changed your bandwidthrate but maxadvertisedbandwidth still
3742 * trumps, no need to republish. Etc. */
3743 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3744 !opt_streq(old_options->Nickname,new_options->Nickname) ||
3745 !opt_streq(old_options->Address,new_options->Address) ||
3746 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
3747 old_options->ExitPolicyRejectPrivate !=
3748 new_options->ExitPolicyRejectPrivate ||
3749 old_options->ORPort != new_options->ORPort ||
3750 old_options->DirPort != new_options->DirPort ||
3751 old_options->ClientOnly != new_options->ClientOnly ||
3752 old_options->NoPublish != new_options->NoPublish ||
3753 old_options->_PublishServerDescriptor !=
3754 new_options->_PublishServerDescriptor ||
3755 old_options->BandwidthRate != new_options->BandwidthRate ||
3756 old_options->BandwidthBurst != new_options->BandwidthBurst ||
3757 old_options->MaxAdvertisedBandwidth !=
3758 new_options->MaxAdvertisedBandwidth ||
3759 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
3760 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
3761 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
3762 old_options->AccountingMax != new_options->AccountingMax)
3763 return 1;
3765 return 0;
3768 #ifdef MS_WINDOWS
3769 /** Return the directory on windows where we expect to find our application
3770 * data. */
3771 static char *
3772 get_windows_conf_root(void)
3774 static int is_set = 0;
3775 static char path[MAX_PATH+1];
3777 LPITEMIDLIST idl;
3778 IMalloc *m;
3779 HRESULT result;
3781 if (is_set)
3782 return path;
3784 /* Find X:\documents and settings\username\application data\ .
3785 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3787 #ifdef ENABLE_LOCAL_APPDATA
3788 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
3789 #else
3790 #define APPDATA_PATH CSIDL_APPDATA
3791 #endif
3792 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
3793 GetCurrentDirectory(MAX_PATH, path);
3794 is_set = 1;
3795 log_warn(LD_CONFIG,
3796 "I couldn't find your application data folder: are you "
3797 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3798 path);
3799 return path;
3801 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3802 result = SHGetPathFromIDList(idl, path);
3803 /* Now we need to free the */
3804 SHGetMalloc(&m);
3805 if (m) {
3806 m->lpVtbl->Free(m, idl);
3807 m->lpVtbl->Release(m);
3809 if (!SUCCEEDED(result)) {
3810 return NULL;
3812 strlcat(path,"\\tor",MAX_PATH);
3813 is_set = 1;
3814 return path;
3816 #endif
3818 /** Return the default location for our torrc file. */
3819 static const char *
3820 get_default_conf_file(void)
3822 #ifdef MS_WINDOWS
3823 static char path[MAX_PATH+1];
3824 strlcpy(path, get_windows_conf_root(), MAX_PATH);
3825 strlcat(path,"\\torrc",MAX_PATH);
3826 return path;
3827 #else
3828 return (CONFDIR "/torrc");
3829 #endif
3832 /** Verify whether lst is a string containing valid-looking comma-separated
3833 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3835 static int
3836 check_nickname_list(const char *lst, const char *name, char **msg)
3838 int r = 0;
3839 smartlist_t *sl;
3841 if (!lst)
3842 return 0;
3843 sl = smartlist_create();
3845 smartlist_split_string(sl, lst, ",",
3846 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
3848 SMARTLIST_FOREACH(sl, const char *, s,
3850 if (!is_legal_nickname_or_hexdigest(s)) {
3851 char buf[1024];
3852 int tmp = tor_snprintf(buf, sizeof(buf),
3853 "Invalid nickname '%s' in %s line", s, name);
3854 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
3855 r = -1;
3856 break;
3859 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
3860 smartlist_free(sl);
3861 return r;
3864 /** Learn config file name from command line arguments, or use the default */
3865 static char *
3866 find_torrc_filename(int argc, char **argv,
3867 int *using_default_torrc, int *ignore_missing_torrc)
3869 char *fname=NULL;
3870 int i;
3872 for (i = 1; i < argc; ++i) {
3873 if (i < argc-1 && !strcmp(argv[i],"-f")) {
3874 if (fname) {
3875 log(LOG_WARN, LD_CONFIG, "Duplicate -f options on command line.");
3876 tor_free(fname);
3878 #ifdef MS_WINDOWS
3879 /* XXX one day we might want to extend expand_filename to work
3880 * under Windows as well. */
3881 fname = tor_strdup(argv[i+1]);
3882 #else
3883 fname = expand_filename(argv[i+1]);
3884 #endif
3885 *using_default_torrc = 0;
3886 ++i;
3887 } else if (!strcmp(argv[i],"--ignore-missing-torrc")) {
3888 *ignore_missing_torrc = 1;
3892 if (*using_default_torrc) {
3893 /* didn't find one, try CONFDIR */
3894 const char *dflt = get_default_conf_file();
3895 if (dflt && file_status(dflt) == FN_FILE) {
3896 fname = tor_strdup(dflt);
3897 } else {
3898 #ifndef MS_WINDOWS
3899 char *fn;
3900 fn = expand_filename("~/.torrc");
3901 if (fn && file_status(fn) == FN_FILE) {
3902 fname = fn;
3903 } else {
3904 tor_free(fn);
3905 fname = tor_strdup(dflt);
3907 #else
3908 fname = tor_strdup(dflt);
3909 #endif
3912 return fname;
3915 /** Load torrc from disk, setting torrc_fname if successful */
3916 static char *
3917 load_torrc_from_disk(int argc, char **argv)
3919 char *fname=NULL;
3920 char *cf = NULL;
3921 int using_default_torrc = 1;
3922 int ignore_missing_torrc = 0;
3924 fname = find_torrc_filename(argc, argv,
3925 &using_default_torrc, &ignore_missing_torrc);
3926 tor_assert(fname);
3927 log(LOG_DEBUG, LD_CONFIG, "Opening config file \"%s\"", fname);
3929 tor_free(torrc_fname);
3930 torrc_fname = fname;
3932 /* Open config file */
3933 if (file_status(fname) != FN_FILE ||
3934 !(cf = read_file_to_str(fname,0,NULL))) {
3935 if (using_default_torrc == 1 || ignore_missing_torrc ) {
3936 log(LOG_NOTICE, LD_CONFIG, "Configuration file \"%s\" not present, "
3937 "using reasonable defaults.", fname);
3938 tor_free(fname); /* sets fname to NULL */
3939 torrc_fname = NULL;
3940 cf = tor_strdup("");
3941 } else {
3942 log(LOG_WARN, LD_CONFIG,
3943 "Unable to open configuration file \"%s\".", fname);
3944 goto err;
3948 return cf;
3949 err:
3950 tor_free(fname);
3951 torrc_fname = NULL;
3952 return NULL;
3955 /** Read a configuration file into <b>options</b>, finding the configuration
3956 * file location based on the command line. After loading the file
3957 * call options_init_from_string() to load the config.
3958 * Return 0 if success, -1 if failure. */
3960 options_init_from_torrc(int argc, char **argv)
3962 char *cf=NULL;
3963 int i, retval, command;
3964 static char **backup_argv;
3965 static int backup_argc;
3966 char *command_arg = NULL;
3967 char *errmsg=NULL;
3969 if (argv) { /* first time we're called. save command line args */
3970 backup_argv = argv;
3971 backup_argc = argc;
3972 } else { /* we're reloading. need to clean up old options first. */
3973 argv = backup_argv;
3974 argc = backup_argc;
3976 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
3977 print_usage();
3978 exit(0);
3980 if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
3981 /* For documenting validating whether we've documented everything. */
3982 list_torrc_options();
3983 exit(0);
3986 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
3987 printf("Tor version %s.\n",get_version());
3988 exit(0);
3991 /* Go through command-line variables */
3992 if (!global_cmdline_options) {
3993 /* Or we could redo the list every time we pass this place.
3994 * It does not really matter */
3995 if (config_get_commandlines(argc, argv, &global_cmdline_options) < 0) {
3996 goto err;
4000 command = CMD_RUN_TOR;
4001 for (i = 1; i < argc; ++i) {
4002 if (!strcmp(argv[i],"--list-fingerprint")) {
4003 command = CMD_LIST_FINGERPRINT;
4004 } else if (!strcmp(argv[i],"--hash-password")) {
4005 command = CMD_HASH_PASSWORD;
4006 command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
4007 ++i;
4008 } else if (!strcmp(argv[i],"--verify-config")) {
4009 command = CMD_VERIFY_CONFIG;
4013 if (command == CMD_HASH_PASSWORD) {
4014 cf = tor_strdup("");
4015 } else {
4016 cf = load_torrc_from_disk(argc, argv);
4017 if (!cf)
4018 goto err;
4021 retval = options_init_from_string(cf, command, command_arg, &errmsg);
4022 tor_free(cf);
4023 if (retval < 0)
4024 goto err;
4026 return 0;
4028 err:
4029 if (errmsg) {
4030 log(LOG_WARN,LD_CONFIG,"%s", errmsg);
4031 tor_free(errmsg);
4033 return -1;
4036 /** Load the options from the configuration in <b>cf</b>, validate
4037 * them for consistency and take actions based on them.
4039 * Return 0 if success, negative on error:
4040 * * -1 for general errors.
4041 * * -2 for failure to parse/validate,
4042 * * -3 for transition not allowed
4043 * * -4 for error while setting the new options
4045 setopt_err_t
4046 options_init_from_string(const char *cf,
4047 int command, const char *command_arg,
4048 char **msg)
4050 or_options_t *oldoptions, *newoptions;
4051 config_line_t *cl;
4052 int retval;
4053 setopt_err_t err = SETOPT_ERR_MISC;
4054 tor_assert(msg);
4056 oldoptions = global_options; /* get_options unfortunately asserts if
4057 this is the first time we run*/
4059 newoptions = tor_malloc_zero(sizeof(or_options_t));
4060 newoptions->_magic = OR_OPTIONS_MAGIC;
4061 options_init(newoptions);
4062 newoptions->command = command;
4063 newoptions->command_arg = command_arg;
4065 /* get config lines, assign them */
4066 retval = config_get_lines(cf, &cl);
4067 if (retval < 0) {
4068 err = SETOPT_ERR_PARSE;
4069 goto err;
4071 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4072 config_free_lines(cl);
4073 if (retval < 0) {
4074 err = SETOPT_ERR_PARSE;
4075 goto err;
4078 /* Go through command-line variables too */
4079 retval = config_assign(&options_format, newoptions,
4080 global_cmdline_options, 0, 0, msg);
4081 if (retval < 0) {
4082 err = SETOPT_ERR_PARSE;
4083 goto err;
4086 /* If this is a testing network configuration, change defaults
4087 * for a list of dependent config options, re-initialize newoptions
4088 * with the new defaults, and assign all options to it second time. */
4089 if (newoptions->TestingTorNetwork) {
4090 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4091 * this? We could, for example, make the parsing algorithm do two passes
4092 * over the configuration. If it finds any "suite" options like
4093 * TestingTorNetwork, it could change the defaults before its second pass.
4094 * Not urgent so long as this seems to work, but at any sign of trouble,
4095 * let's clean it up. -NM */
4097 /* Change defaults. */
4098 int i;
4099 for (i = 0; testing_tor_network_defaults[i].name; ++i) {
4100 config_var_t *new_var = &testing_tor_network_defaults[i];
4101 config_var_t *old_var =
4102 config_find_option(&options_format, new_var->name);
4103 tor_assert(new_var);
4104 tor_assert(old_var);
4105 old_var->initvalue = new_var->initvalue;
4108 /* Clear newoptions and re-initialize them with new defaults. */
4109 config_free(&options_format, newoptions);
4110 newoptions = tor_malloc_zero(sizeof(or_options_t));
4111 newoptions->_magic = OR_OPTIONS_MAGIC;
4112 options_init(newoptions);
4113 newoptions->command = command;
4114 newoptions->command_arg = command_arg;
4116 /* Assign all options a second time. */
4117 retval = config_get_lines(cf, &cl);
4118 if (retval < 0) {
4119 err = SETOPT_ERR_PARSE;
4120 goto err;
4122 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4123 config_free_lines(cl);
4124 if (retval < 0) {
4125 err = SETOPT_ERR_PARSE;
4126 goto err;
4128 retval = config_assign(&options_format, newoptions,
4129 global_cmdline_options, 0, 0, msg);
4130 if (retval < 0) {
4131 err = SETOPT_ERR_PARSE;
4132 goto err;
4136 /* Validate newoptions */
4137 if (options_validate(oldoptions, newoptions, 0, msg) < 0) {
4138 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
4139 goto err;
4142 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
4143 err = SETOPT_ERR_TRANSITION;
4144 goto err;
4147 if (set_options(newoptions, msg)) {
4148 err = SETOPT_ERR_SETTING;
4149 goto err; /* frees and replaces old options */
4152 return SETOPT_OK;
4154 err:
4155 config_free(&options_format, newoptions);
4156 if (*msg) {
4157 int len = strlen(*msg)+256;
4158 char *newmsg = tor_malloc(len);
4160 tor_snprintf(newmsg, len, "Failed to parse/validate config: %s", *msg);
4161 tor_free(*msg);
4162 *msg = newmsg;
4164 return err;
4167 /** Return the location for our configuration file.
4169 const char *
4170 get_torrc_fname(void)
4172 if (torrc_fname)
4173 return torrc_fname;
4174 else
4175 return get_default_conf_file();
4178 /** Adjust the address map based on the MapAddress elements in the
4179 * configuration <b>options</b>
4181 static void
4182 config_register_addressmaps(or_options_t *options)
4184 smartlist_t *elts;
4185 config_line_t *opt;
4186 char *from, *to;
4188 addressmap_clear_configured();
4189 elts = smartlist_create();
4190 for (opt = options->AddressMap; opt; opt = opt->next) {
4191 smartlist_split_string(elts, opt->value, NULL,
4192 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4193 if (smartlist_len(elts) >= 2) {
4194 from = smartlist_get(elts,0);
4195 to = smartlist_get(elts,1);
4196 if (address_is_invalid_destination(to, 1)) {
4197 log_warn(LD_CONFIG,
4198 "Skipping invalid argument '%s' to MapAddress", to);
4199 } else {
4200 addressmap_register(from, tor_strdup(to), 0, ADDRMAPSRC_TORRC);
4201 if (smartlist_len(elts)>2) {
4202 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
4205 } else {
4206 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
4207 opt->value);
4209 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4210 smartlist_clear(elts);
4212 smartlist_free(elts);
4216 * Initialize the logs based on the configuration file.
4218 static int
4219 options_init_logs(or_options_t *options, int validate_only)
4221 config_line_t *opt;
4222 int ok;
4223 smartlist_t *elts;
4224 int daemon =
4225 #ifdef MS_WINDOWS
4227 #else
4228 options->RunAsDaemon;
4229 #endif
4231 ok = 1;
4232 elts = smartlist_create();
4234 for (opt = options->Logs; opt; opt = opt->next) {
4235 log_severity_list_t *severity;
4236 const char *cfg = opt->value;
4237 severity = tor_malloc_zero(sizeof(log_severity_list_t));
4238 if (parse_log_severity_config(&cfg, severity) < 0) {
4239 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
4240 opt->value);
4241 ok = 0; goto cleanup;
4244 smartlist_split_string(elts, cfg, NULL,
4245 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4247 if (smartlist_len(elts) == 0)
4248 smartlist_add(elts, tor_strdup("stdout"));
4250 if (smartlist_len(elts) == 1 &&
4251 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
4252 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
4253 int err = smartlist_len(elts) &&
4254 !strcasecmp(smartlist_get(elts,0), "stderr");
4255 if (!validate_only) {
4256 if (daemon) {
4257 log_warn(LD_CONFIG,
4258 "Can't log to %s with RunAsDaemon set; skipping stdout",
4259 err?"stderr":"stdout");
4260 } else {
4261 add_stream_log(severity, err?"<stderr>":"<stdout>",
4262 fileno(err?stderr:stdout));
4265 goto cleanup;
4267 if (smartlist_len(elts) == 1 &&
4268 !strcasecmp(smartlist_get(elts,0), "syslog")) {
4269 #ifdef HAVE_SYSLOG_H
4270 if (!validate_only) {
4271 add_syslog_log(severity);
4273 #else
4274 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
4275 #endif
4276 goto cleanup;
4279 if (smartlist_len(elts) == 2 &&
4280 !strcasecmp(smartlist_get(elts,0), "file")) {
4281 if (!validate_only) {
4282 if (add_file_log(severity, smartlist_get(elts, 1)) < 0) {
4283 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
4284 opt->value, strerror(errno));
4285 ok = 0;
4288 goto cleanup;
4291 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
4292 opt->value);
4293 ok = 0; goto cleanup;
4295 cleanup:
4296 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4297 smartlist_clear(elts);
4298 tor_free(severity);
4300 smartlist_free(elts);
4302 return ok?0:-1;
4305 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4306 * if the line is well-formed, and -1 if it isn't. If
4307 * <b>validate_only</b> is 0, and the line is well-formed, then add
4308 * the bridge described in the line to our internal bridge list. */
4309 static int
4310 parse_bridge_line(const char *line, int validate_only)
4312 smartlist_t *items = NULL;
4313 int r;
4314 char *addrport=NULL, *fingerprint=NULL;
4315 tor_addr_t addr;
4316 uint16_t port = 0;
4317 char digest[DIGEST_LEN];
4319 items = smartlist_create();
4320 smartlist_split_string(items, line, NULL,
4321 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4322 if (smartlist_len(items) < 1) {
4323 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
4324 goto err;
4326 addrport = smartlist_get(items, 0);
4327 smartlist_del_keeporder(items, 0);
4328 if (tor_addr_port_parse(addrport, &addr, &port)<0) {
4329 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
4330 goto err;
4332 if (!port) {
4333 log_info(LD_CONFIG,
4334 "Bridge address '%s' has no port; using default port 443.",
4335 addrport);
4336 port = 443;
4339 if (smartlist_len(items)) {
4340 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4341 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4342 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
4343 goto err;
4345 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4346 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
4347 goto err;
4351 if (!validate_only) {
4352 log_debug(LD_DIR, "Bridge at %s:%d (%s)", fmt_addr(&addr),
4353 (int)port,
4354 fingerprint ? fingerprint : "no key listed");
4355 bridge_add_from_config(&addr, port, fingerprint ? digest : NULL);
4358 r = 0;
4359 goto done;
4361 err:
4362 r = -1;
4364 done:
4365 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4366 smartlist_free(items);
4367 tor_free(addrport);
4368 tor_free(fingerprint);
4369 return r;
4372 /** Read the contents of a DirServer line from <b>line</b>. If
4373 * <b>validate_only</b> is 0, and the line is well-formed, and it
4374 * shares any bits with <b>required_type</b> or <b>required_type</b>
4375 * is 0, then add the dirserver described in the line (minus whatever
4376 * bits it's missing) as a valid authority. Return 0 on success,
4377 * or -1 if the line isn't well-formed or if we can't add it. */
4378 static int
4379 parse_dir_server_line(const char *line, authority_type_t required_type,
4380 int validate_only)
4382 smartlist_t *items = NULL;
4383 int r;
4384 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
4385 uint16_t dir_port = 0, or_port = 0;
4386 char digest[DIGEST_LEN];
4387 char v3_digest[DIGEST_LEN];
4388 authority_type_t type = V2_AUTHORITY;
4389 int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
4391 items = smartlist_create();
4392 smartlist_split_string(items, line, NULL,
4393 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4394 if (smartlist_len(items) < 1) {
4395 log_warn(LD_CONFIG, "No arguments on DirServer line.");
4396 goto err;
4399 if (is_legal_nickname(smartlist_get(items, 0))) {
4400 nickname = smartlist_get(items, 0);
4401 smartlist_del_keeporder(items, 0);
4404 while (smartlist_len(items)) {
4405 char *flag = smartlist_get(items, 0);
4406 if (TOR_ISDIGIT(flag[0]))
4407 break;
4408 if (!strcasecmp(flag, "v1")) {
4409 type |= (V1_AUTHORITY | HIDSERV_AUTHORITY);
4410 } else if (!strcasecmp(flag, "hs")) {
4411 type |= HIDSERV_AUTHORITY;
4412 } else if (!strcasecmp(flag, "no-hs")) {
4413 is_not_hidserv_authority = 1;
4414 } else if (!strcasecmp(flag, "bridge")) {
4415 type |= BRIDGE_AUTHORITY;
4416 } else if (!strcasecmp(flag, "no-v2")) {
4417 is_not_v2_authority = 1;
4418 } else if (!strcasecmpstart(flag, "orport=")) {
4419 int ok;
4420 char *portstring = flag + strlen("orport=");
4421 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
4422 if (!ok)
4423 log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
4424 portstring);
4425 } else if (!strcasecmpstart(flag, "v3ident=")) {
4426 char *idstr = flag + strlen("v3ident=");
4427 if (strlen(idstr) != HEX_DIGEST_LEN ||
4428 base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
4429 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirServer line",
4430 flag);
4431 } else {
4432 type |= V3_AUTHORITY;
4434 } else {
4435 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
4436 flag);
4438 tor_free(flag);
4439 smartlist_del_keeporder(items, 0);
4441 if (is_not_hidserv_authority)
4442 type &= ~HIDSERV_AUTHORITY;
4443 if (is_not_v2_authority)
4444 type &= ~V2_AUTHORITY;
4446 if (smartlist_len(items) < 2) {
4447 log_warn(LD_CONFIG, "Too few arguments to DirServer line.");
4448 goto err;
4450 addrport = smartlist_get(items, 0);
4451 smartlist_del_keeporder(items, 0);
4452 if (parse_addr_port(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
4453 log_warn(LD_CONFIG, "Error parsing DirServer address '%s'", addrport);
4454 goto err;
4456 if (!dir_port) {
4457 log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
4458 goto err;
4461 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4462 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4463 log_warn(LD_CONFIG, "Key digest for DirServer is wrong length %d.",
4464 (int)strlen(fingerprint));
4465 goto err;
4467 if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4468 /* a known bad fingerprint. refuse to use it. We can remove this
4469 * clause once Tor 0.1.2.17 is obsolete. */
4470 log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
4471 "torrc file (%s), or reinstall Tor and use the default torrc.",
4472 get_torrc_fname());
4473 goto err;
4475 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4476 log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
4477 goto err;
4480 if (!validate_only && (!required_type || required_type & type)) {
4481 if (required_type)
4482 type &= required_type; /* pare down what we think of them as an
4483 * authority for. */
4484 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
4485 address, (int)dir_port, (char*)smartlist_get(items,0));
4486 if (!add_trusted_dir_server(nickname, address, dir_port, or_port,
4487 digest, v3_digest, type))
4488 goto err;
4491 r = 0;
4492 goto done;
4494 err:
4495 r = -1;
4497 done:
4498 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4499 smartlist_free(items);
4500 tor_free(addrport);
4501 tor_free(address);
4502 tor_free(nickname);
4503 tor_free(fingerprint);
4504 return r;
4507 /** Adjust the value of options->DataDirectory, or fill it in if it's
4508 * absent. Return 0 on success, -1 on failure. */
4509 static int
4510 normalize_data_directory(or_options_t *options)
4512 #ifdef MS_WINDOWS
4513 char *p;
4514 if (options->DataDirectory)
4515 return 0; /* all set */
4516 p = tor_malloc(MAX_PATH);
4517 strlcpy(p,get_windows_conf_root(),MAX_PATH);
4518 options->DataDirectory = p;
4519 return 0;
4520 #else
4521 const char *d = options->DataDirectory;
4522 if (!d)
4523 d = "~/.tor";
4525 if (strncmp(d,"~/",2) == 0) {
4526 char *fn = expand_filename(d);
4527 if (!fn) {
4528 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
4529 return -1;
4531 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
4532 /* If our homedir is /, we probably don't want to use it. */
4533 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4534 * want. */
4535 log_warn(LD_CONFIG,
4536 "Default DataDirectory is \"~/.tor\". This expands to "
4537 "\"%s\", which is probably not what you want. Using "
4538 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
4539 tor_free(fn);
4540 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
4542 tor_free(options->DataDirectory);
4543 options->DataDirectory = fn;
4545 return 0;
4546 #endif
4549 /** Check and normalize the value of options->DataDirectory; return 0 if it
4550 * sane, -1 otherwise. */
4551 static int
4552 validate_data_directory(or_options_t *options)
4554 if (normalize_data_directory(options) < 0)
4555 return -1;
4556 tor_assert(options->DataDirectory);
4557 if (strlen(options->DataDirectory) > (512-128)) {
4558 log_warn(LD_CONFIG, "DataDirectory is too long.");
4559 return -1;
4561 return 0;
4564 /** This string must remain the same forevermore. It is how we
4565 * recognize that the torrc file doesn't need to be backed up. */
4566 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4567 "if you edit it, comments will not be preserved"
4568 /** This string can change; it tries to give the reader an idea
4569 * that editing this file by hand is not a good plan. */
4570 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4571 "to torrc.orig.1 or similar, and Tor will ignore it"
4573 /** Save a configuration file for the configuration in <b>options</b>
4574 * into the file <b>fname</b>. If the file already exists, and
4575 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4576 * replace it. Return 0 on success, -1 on failure. */
4577 static int
4578 write_configuration_file(const char *fname, or_options_t *options)
4580 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4581 int rename_old = 0, r;
4582 size_t len;
4584 tor_assert(fname);
4586 switch (file_status(fname)) {
4587 case FN_FILE:
4588 old_val = read_file_to_str(fname, 0, NULL);
4589 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4590 rename_old = 1;
4592 tor_free(old_val);
4593 break;
4594 case FN_NOENT:
4595 break;
4596 case FN_ERROR:
4597 case FN_DIR:
4598 default:
4599 log_warn(LD_CONFIG,
4600 "Config file \"%s\" is not a file? Failing.", fname);
4601 return -1;
4604 if (!(new_conf = options_dump(options, 1))) {
4605 log_warn(LD_BUG, "Couldn't get configuration string");
4606 goto err;
4609 len = strlen(new_conf)+256;
4610 new_val = tor_malloc(len);
4611 tor_snprintf(new_val, len, "%s\n%s\n\n%s",
4612 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4614 if (rename_old) {
4615 int i = 1;
4616 size_t fn_tmp_len = strlen(fname)+32;
4617 char *fn_tmp;
4618 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4619 fn_tmp = tor_malloc(fn_tmp_len);
4620 while (1) {
4621 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4622 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4623 tor_free(fn_tmp);
4624 goto err;
4626 if (file_status(fn_tmp) == FN_NOENT)
4627 break;
4628 ++i;
4630 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4631 if (rename(fname, fn_tmp) < 0) {
4632 log_warn(LD_FS,
4633 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4634 fname, fn_tmp, strerror(errno));
4635 tor_free(fn_tmp);
4636 goto err;
4638 tor_free(fn_tmp);
4641 if (write_str_to_file(fname, new_val, 0) < 0)
4642 goto err;
4644 r = 0;
4645 goto done;
4646 err:
4647 r = -1;
4648 done:
4649 tor_free(new_val);
4650 tor_free(new_conf);
4651 return r;
4655 * Save the current configuration file value to disk. Return 0 on
4656 * success, -1 on failure.
4659 options_save_current(void)
4661 if (torrc_fname) {
4662 /* This fails if we can't write to our configuration file.
4664 * If we try falling back to datadirectory or something, we have a better
4665 * chance of saving the configuration, but a better chance of doing
4666 * something the user never expected. Let's just warn instead. */
4667 return write_configuration_file(torrc_fname, get_options());
4669 return write_configuration_file(get_default_conf_file(), get_options());
4672 /** Mapping from a unit name to a multiplier for converting that unit into a
4673 * base unit. */
4674 struct unit_table_t {
4675 const char *unit;
4676 uint64_t multiplier;
4679 /** Table to map the names of memory units to the number of bytes they
4680 * contain. */
4681 static struct unit_table_t memory_units[] = {
4682 { "", 1 },
4683 { "b", 1<< 0 },
4684 { "byte", 1<< 0 },
4685 { "bytes", 1<< 0 },
4686 { "kb", 1<<10 },
4687 { "kbyte", 1<<10 },
4688 { "kbytes", 1<<10 },
4689 { "kilobyte", 1<<10 },
4690 { "kilobytes", 1<<10 },
4691 { "m", 1<<20 },
4692 { "mb", 1<<20 },
4693 { "mbyte", 1<<20 },
4694 { "mbytes", 1<<20 },
4695 { "megabyte", 1<<20 },
4696 { "megabytes", 1<<20 },
4697 { "gb", 1<<30 },
4698 { "gbyte", 1<<30 },
4699 { "gbytes", 1<<30 },
4700 { "gigabyte", 1<<30 },
4701 { "gigabytes", 1<<30 },
4702 { "tb", U64_LITERAL(1)<<40 },
4703 { "terabyte", U64_LITERAL(1)<<40 },
4704 { "terabytes", U64_LITERAL(1)<<40 },
4705 { NULL, 0 },
4708 /** Table to map the names of time units to the number of seconds they
4709 * contain. */
4710 static struct unit_table_t time_units[] = {
4711 { "", 1 },
4712 { "second", 1 },
4713 { "seconds", 1 },
4714 { "minute", 60 },
4715 { "minutes", 60 },
4716 { "hour", 60*60 },
4717 { "hours", 60*60 },
4718 { "day", 24*60*60 },
4719 { "days", 24*60*60 },
4720 { "week", 7*24*60*60 },
4721 { "weeks", 7*24*60*60 },
4722 { NULL, 0 },
4725 /** Parse a string <b>val</b> containing a number, zero or more
4726 * spaces, and an optional unit string. If the unit appears in the
4727 * table <b>u</b>, then multiply the number by the unit multiplier.
4728 * On success, set *<b>ok</b> to 1 and return this product.
4729 * Otherwise, set *<b>ok</b> to 0.
4731 static uint64_t
4732 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4734 uint64_t v;
4735 char *cp;
4737 tor_assert(ok);
4739 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4740 if (!*ok)
4741 return 0;
4742 if (!cp) {
4743 *ok = 1;
4744 return v;
4746 while (TOR_ISSPACE(*cp))
4747 ++cp;
4748 for ( ;u->unit;++u) {
4749 if (!strcasecmp(u->unit, cp)) {
4750 v *= u->multiplier;
4751 *ok = 1;
4752 return v;
4755 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4756 *ok = 0;
4757 return 0;
4760 /** Parse a string in the format "number unit", where unit is a unit of
4761 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4762 * and return the number of bytes specified. Otherwise, set
4763 * *<b>ok</b> to false and return 0. */
4764 static uint64_t
4765 config_parse_memunit(const char *s, int *ok)
4767 return config_parse_units(s, memory_units, ok);
4770 /** Parse a string in the format "number unit", where unit is a unit of time.
4771 * On success, set *<b>ok</b> to true and return the number of seconds in
4772 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4774 static int
4775 config_parse_interval(const char *s, int *ok)
4777 uint64_t r;
4778 r = config_parse_units(s, time_units, ok);
4779 if (!ok)
4780 return -1;
4781 if (r > INT_MAX) {
4782 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4783 *ok = 0;
4784 return -1;
4786 return (int)r;
4789 /* This is what passes for version detection on OSX. We set
4790 * MACOSX_KQUEUE_IS_BROKEN to true iff we're on a version of OSX before
4791 * 10.4.0 (aka 1040). */
4792 #ifdef __APPLE__
4793 #ifdef __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__
4794 #define MACOSX_KQUEUE_IS_BROKEN \
4795 (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1040)
4796 #else
4797 #define MACOSX_KQUEUE_IS_BROKEN 0
4798 #endif
4799 #endif
4802 * Initialize the libevent library.
4804 static void
4805 init_libevent(void)
4807 configure_libevent_logging();
4808 /* If the kernel complains that some method (say, epoll) doesn't
4809 * exist, we don't care about it, since libevent will cope.
4811 suppress_libevent_log_msg("Function not implemented");
4812 #ifdef __APPLE__
4813 if (MACOSX_KQUEUE_IS_BROKEN ||
4814 decode_libevent_version(event_get_version(), NULL) < LE_11B) {
4815 setenv("EVENT_NOKQUEUE","1",1);
4817 #endif
4819 /* In libevent versions before 2.0, it's hard to keep binary compatibility
4820 * between upgrades, and unpleasant to detect when the version we compiled
4821 * against is unlike the version we have linked against. Here's how. */
4822 #if defined(_EVENT_VERSION) && defined(HAVE_EVENT_GET_VERSION)
4823 /* We have a header-file version and a function-call version. Easy. */
4824 if (strcmp(_EVENT_VERSION, event_get_version())) {
4825 int compat1 = -1, compat2 = -1;
4826 int verybad, prettybad ;
4827 decode_libevent_version(_EVENT_VERSION, &compat1);
4828 decode_libevent_version(event_get_version(), &compat2);
4829 verybad = compat1 != compat2;
4830 prettybad = (compat1 == -1 || compat2 == -1) && compat1 != compat2;
4832 log(verybad ? LOG_WARN : (prettybad ? LOG_NOTICE : LOG_INFO),
4833 LD_GENERAL, "We were compiled with headers from version %s "
4834 "of Libevent, but we're using a Libevent library that says it's "
4835 "version %s.", _EVENT_VERSION, event_get_version());
4836 if (verybad)
4837 log_warn(LD_GENERAL, "This will almost certainly make Tor crash.");
4838 else if (prettybad)
4839 log_notice(LD_GENERAL, "If Tor crashes, this might be why.");
4840 else
4841 log_info(LD_GENERAL, "I think these versions are binary-compatible.");
4843 #elif defined(HAVE_EVENT_GET_VERSION)
4844 /* event_get_version but no _EVENT_VERSION. We might be in 1.4.0-beta or
4845 earlier, where that's normal. To see whether we were compiled with an
4846 earlier version, let's see whether the struct event defines MIN_HEAP_IDX.
4848 #ifdef HAVE_STRUCT_EVENT_MIN_HEAP_IDX
4849 /* The header files are 1.4.0-beta or later. If the version is not
4850 * 1.4.0-beta, we are incompatible. */
4852 if (strcmp(event_get_version(), "1.4.0-beta")) {
4853 log_warn(LD_GENERAL, "It's a little hard to tell, but you seem to have "
4854 "Libevent 1.4.0-beta header files, whereas you have linked "
4855 "against Libevent %s. This will probably make Tor crash.",
4856 event_get_version());
4859 #else
4860 /* Our headers are 1.3e or earlier. If the library version is not 1.4.x or
4861 later, we're probably fine. */
4863 const char *v = event_get_version();
4864 if ((v[0] == '1' && v[2] == '.' && v[3] > '3') || v[0] > '1') {
4865 log_warn(LD_GENERAL, "It's a little hard to tell, but you seem to have "
4866 "Libevent header file from 1.3e or earlier, whereas you have "
4867 "linked against Libevent %s. This will probably make Tor "
4868 "crash.", event_get_version());
4871 #endif
4873 #elif defined(_EVENT_VERSION)
4874 #warn "_EVENT_VERSION is defined but not get_event_version(): Libevent is odd."
4875 #else
4876 /* Your libevent is ancient. */
4877 #endif
4879 event_init();
4880 suppress_libevent_log_msg(NULL);
4881 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4882 /* Making this a NOTICE for now so we can link bugs to a libevent versions
4883 * or methods better. */
4884 log(LOG_NOTICE, LD_GENERAL,
4885 "Initialized libevent version %s using method %s. Good.",
4886 event_get_version(), event_get_method());
4887 check_libevent_version(event_get_method(), get_options()->ORPort != 0);
4888 #else
4889 log(LOG_NOTICE, LD_GENERAL,
4890 "Initialized old libevent (version 1.0b or earlier).");
4891 log(LOG_WARN, LD_GENERAL,
4892 "You have a *VERY* old version of libevent. It is likely to be buggy; "
4893 "please build Tor with a more recent version.");
4894 #endif
4897 /** Table mapping return value of event_get_version() to le_version_t. */
4898 static const struct {
4899 const char *name; le_version_t version; int bincompat;
4900 } le_version_table[] = {
4901 /* earlier versions don't have get_version. */
4902 { "1.0c", LE_10C, 1},
4903 { "1.0d", LE_10D, 1},
4904 { "1.0e", LE_10E, 1},
4905 { "1.1", LE_11, 1 },
4906 { "1.1a", LE_11A, 1 },
4907 { "1.1b", LE_11B, 1 },
4908 { "1.2", LE_12, 1 },
4909 { "1.2a", LE_12A, 1 },
4910 { "1.3", LE_13, 1 },
4911 { "1.3a", LE_13A, 1 },
4912 { "1.3b", LE_13B, 1 },
4913 { "1.3c", LE_13C, 1 },
4914 { "1.3d", LE_13D, 1 },
4915 { "1.3e", LE_13E, 1 },
4916 { "1.4.0-beta", LE_140, 2 },
4917 { "1.4.1-beta", LE_141, 2 },
4918 { "1.4.2-rc", LE_142, 2 },
4919 { "1.4.3-stable", LE_143, 2 },
4920 { "1.4.4-stable", LE_144, 2 },
4921 { "1.4.5-stable", LE_145, 2 },
4922 { "1.4.6-stable", LE_146, 2 },
4923 { "1.4.7-stable", LE_147, 2 },
4924 { "1.4.8-stable", LE_148, 2 },
4925 { "1.4.99-trunk", LE_1499, 3 },
4926 { NULL, LE_OTHER, 0 }
4929 /** Return the le_version_t for the current version of libevent. If the
4930 * version is very new, return LE_OTHER. If the version is so old that it
4931 * doesn't support event_get_version(), return LE_OLD. */
4932 static le_version_t
4933 decode_libevent_version(const char *v, int *bincompat_out)
4935 int i;
4936 for (i=0; le_version_table[i].name; ++i) {
4937 if (!strcmp(le_version_table[i].name, v)) {
4938 if (bincompat_out)
4939 *bincompat_out = le_version_table[i].bincompat;
4940 return le_version_table[i].version;
4943 if (v[0] != '1' && bincompat_out)
4944 *bincompat_out = 100;
4945 else if (!strcmpstart(v, "1.4") && bincompat_out)
4946 *bincompat_out = 2;
4947 return LE_OTHER;
4950 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4952 * Compare the given libevent method and version to a list of versions
4953 * which are known not to work. Warn the user as appropriate.
4955 static void
4956 check_libevent_version(const char *m, int server)
4958 int buggy = 0, iffy = 0, slow = 0, thread_unsafe = 0;
4959 le_version_t version;
4960 const char *v = event_get_version();
4961 const char *badness = NULL;
4962 const char *sad_os = "";
4964 version = decode_libevent_version(v, NULL);
4966 /* XXX Would it be worthwhile disabling the methods that we know
4967 * are buggy, rather than just warning about them and then proceeding
4968 * to use them? If so, we should probably not wrap this whole thing
4969 * in HAVE_EVENT_GET_VERSION and HAVE_EVENT_GET_METHOD. -RD */
4970 /* XXXX The problem is that it's not trivial to get libevent to change it's
4971 * method once it's initialized, and it's not trivial to tell what method it
4972 * will use without initializing it. I guess we could preemptively disable
4973 * buggy libevent modes based on the version _before_ initializing it,
4974 * though, but then there's no good way (afaict) to warn "I would have used
4975 * kqueue, but instead I'm using select." -NM */
4976 if (!strcmp(m, "kqueue")) {
4977 if (version < LE_11B)
4978 buggy = 1;
4979 } else if (!strcmp(m, "epoll")) {
4980 if (version < LE_11)
4981 iffy = 1;
4982 } else if (!strcmp(m, "poll")) {
4983 if (version < LE_10E)
4984 buggy = 1;
4985 else if (version < LE_11)
4986 slow = 1;
4987 } else if (!strcmp(m, "select")) {
4988 if (version < LE_11)
4989 slow = 1;
4990 } else if (!strcmp(m, "win32")) {
4991 if (version < LE_11B)
4992 buggy = 1;
4995 /* Libevent versions before 1.3b do very badly on operating systems with
4996 * user-space threading implementations. */
4997 #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
4998 if (server && version < LE_13B) {
4999 thread_unsafe = 1;
5000 sad_os = "BSD variants";
5002 #elif defined(__APPLE__) || defined(__darwin__)
5003 if (server && version < LE_13B) {
5004 thread_unsafe = 1;
5005 sad_os = "Mac OS X";
5007 #endif
5009 if (thread_unsafe) {
5010 log(LOG_WARN, LD_GENERAL,
5011 "Libevent version %s often crashes when running a Tor server with %s. "
5012 "Please use the latest version of libevent (1.3b or later)",v,sad_os);
5013 badness = "BROKEN";
5014 } else if (buggy) {
5015 log(LOG_WARN, LD_GENERAL,
5016 "There are serious bugs in using %s with libevent %s. "
5017 "Please use the latest version of libevent.", m, v);
5018 badness = "BROKEN";
5019 } else if (iffy) {
5020 log(LOG_WARN, LD_GENERAL,
5021 "There are minor bugs in using %s with libevent %s. "
5022 "You may want to use the latest version of libevent.", m, v);
5023 badness = "BUGGY";
5024 } else if (slow && server) {
5025 log(LOG_WARN, LD_GENERAL,
5026 "libevent %s can be very slow with %s. "
5027 "When running a server, please use the latest version of libevent.",
5028 v,m);
5029 badness = "SLOW";
5031 if (badness) {
5032 control_event_general_status(LOG_WARN,
5033 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
5034 v, m, badness);
5038 #endif
5040 /** Return the persistent state struct for this Tor. */
5041 or_state_t *
5042 get_or_state(void)
5044 tor_assert(global_state);
5045 return global_state;
5048 /** Return a newly allocated string holding a filename relative to the data
5049 * directory. If <b>sub1</b> is present, it is the first path component after
5050 * the data directory. If <b>sub2</b> is also present, it is the second path
5051 * component after the data directory. If <b>suffix</b> is present, it
5052 * is appended to the filename.
5054 * Examples:
5055 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
5056 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
5057 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
5058 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
5060 * Note: Consider using the get_datadir_fname* macros in or.h.
5062 char *
5063 options_get_datadir_fname2_suffix(or_options_t *options,
5064 const char *sub1, const char *sub2,
5065 const char *suffix)
5067 char *fname = NULL;
5068 size_t len;
5069 tor_assert(options);
5070 tor_assert(options->DataDirectory);
5071 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
5072 len = strlen(options->DataDirectory);
5073 if (sub1) {
5074 len += strlen(sub1)+1;
5075 if (sub2)
5076 len += strlen(sub2)+1;
5078 if (suffix)
5079 len += strlen(suffix);
5080 len++;
5081 fname = tor_malloc(len);
5082 if (sub1) {
5083 if (sub2) {
5084 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
5085 options->DataDirectory, sub1, sub2);
5086 } else {
5087 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
5088 options->DataDirectory, sub1);
5090 } else {
5091 strlcpy(fname, options->DataDirectory, len);
5093 if (suffix)
5094 strlcat(fname, suffix, len);
5095 return fname;
5098 /** Return 0 if every setting in <b>state</b> is reasonable, and a
5099 * permissible transition from <b>old_state</b>. Else warn and return -1.
5100 * Should have no side effects, except for normalizing the contents of
5101 * <b>state</b>.
5103 /* XXX from_setconf is here because of bug 238 */
5104 static int
5105 or_state_validate(or_state_t *old_state, or_state_t *state,
5106 int from_setconf, char **msg)
5108 /* We don't use these; only options do. Still, we need to match that
5109 * signature. */
5110 (void) from_setconf;
5111 (void) old_state;
5113 if (entry_guards_parse_state(state, 0, msg)<0)
5114 return -1;
5116 return 0;
5119 /** Replace the current persistent state with <b>new_state</b> */
5120 static void
5121 or_state_set(or_state_t *new_state)
5123 char *err = NULL;
5124 tor_assert(new_state);
5125 if (global_state)
5126 config_free(&state_format, global_state);
5127 global_state = new_state;
5128 if (entry_guards_parse_state(global_state, 1, &err)<0) {
5129 log_warn(LD_GENERAL,"%s",err);
5130 tor_free(err);
5132 if (rep_hist_load_state(global_state, &err)<0) {
5133 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
5134 tor_free(err);
5138 /** Reload the persistent state from disk, generating a new state as needed.
5139 * Return 0 on success, less than 0 on failure.
5141 static int
5142 or_state_load(void)
5144 or_state_t *new_state = NULL;
5145 char *contents = NULL, *fname;
5146 char *errmsg = NULL;
5147 int r = -1, badstate = 0;
5149 fname = get_datadir_fname("state");
5150 switch (file_status(fname)) {
5151 case FN_FILE:
5152 if (!(contents = read_file_to_str(fname, 0, NULL))) {
5153 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
5154 goto done;
5156 break;
5157 case FN_NOENT:
5158 break;
5159 case FN_ERROR:
5160 case FN_DIR:
5161 default:
5162 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
5163 goto done;
5165 new_state = tor_malloc_zero(sizeof(or_state_t));
5166 new_state->_magic = OR_STATE_MAGIC;
5167 config_init(&state_format, new_state);
5168 if (contents) {
5169 config_line_t *lines=NULL;
5170 int assign_retval;
5171 if (config_get_lines(contents, &lines)<0)
5172 goto done;
5173 assign_retval = config_assign(&state_format, new_state,
5174 lines, 0, 0, &errmsg);
5175 config_free_lines(lines);
5176 if (assign_retval<0)
5177 badstate = 1;
5178 if (errmsg) {
5179 log_warn(LD_GENERAL, "%s", errmsg);
5180 tor_free(errmsg);
5184 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
5185 badstate = 1;
5187 if (errmsg) {
5188 log_warn(LD_GENERAL, "%s", errmsg);
5189 tor_free(errmsg);
5192 if (badstate && !contents) {
5193 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
5194 " This is a bug in Tor.");
5195 goto done;
5196 } else if (badstate && contents) {
5197 int i;
5198 file_status_t status;
5199 size_t len = strlen(fname)+16;
5200 char *fname2 = tor_malloc(len);
5201 for (i = 0; i < 100; ++i) {
5202 tor_snprintf(fname2, len, "%s.%d", fname, i);
5203 status = file_status(fname2);
5204 if (status == FN_NOENT)
5205 break;
5207 if (i == 100) {
5208 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
5209 "state files to move aside. Discarding the old state file.",
5210 fname);
5211 unlink(fname);
5212 } else {
5213 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
5214 "to \"%s\". This could be a bug in Tor; please tell "
5215 "the developers.", fname, fname2);
5216 if (rename(fname, fname2) < 0) {
5217 log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
5218 "OS gave an error of %s", strerror(errno));
5221 tor_free(fname2);
5222 tor_free(contents);
5223 config_free(&state_format, new_state);
5225 new_state = tor_malloc_zero(sizeof(or_state_t));
5226 new_state->_magic = OR_STATE_MAGIC;
5227 config_init(&state_format, new_state);
5228 } else if (contents) {
5229 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
5230 } else {
5231 log_info(LD_GENERAL, "Initialized state");
5233 or_state_set(new_state);
5234 new_state = NULL;
5235 if (!contents) {
5236 global_state->next_write = 0;
5237 or_state_save(time(NULL));
5239 r = 0;
5241 done:
5242 tor_free(fname);
5243 tor_free(contents);
5244 if (new_state)
5245 config_free(&state_format, new_state);
5247 return r;
5250 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
5252 or_state_save(time_t now)
5254 char *state, *contents;
5255 char tbuf[ISO_TIME_LEN+1];
5256 size_t len;
5257 char *fname;
5259 tor_assert(global_state);
5261 if (global_state->next_write > now)
5262 return 0;
5264 /* Call everything else that might dirty the state even more, in order
5265 * to avoid redundant writes. */
5266 entry_guards_update_state(global_state);
5267 rep_hist_update_state(global_state);
5268 if (accounting_is_enabled(get_options()))
5269 accounting_run_housekeeping(now);
5271 global_state->LastWritten = time(NULL);
5272 tor_free(global_state->TorVersion);
5273 len = strlen(get_version())+8;
5274 global_state->TorVersion = tor_malloc(len);
5275 tor_snprintf(global_state->TorVersion, len, "Tor %s", get_version());
5277 state = config_dump(&state_format, global_state, 1, 0);
5278 len = strlen(state)+256;
5279 contents = tor_malloc(len);
5280 format_local_iso_time(tbuf, time(NULL));
5281 tor_snprintf(contents, len,
5282 "# Tor state file last generated on %s local time\n"
5283 "# Other times below are in GMT\n"
5284 "# You *do not* need to edit this file.\n\n%s",
5285 tbuf, state);
5286 tor_free(state);
5287 fname = get_datadir_fname("state");
5288 if (write_str_to_file(fname, contents, 0)<0) {
5289 log_warn(LD_FS, "Unable to write state to file \"%s\"", fname);
5290 tor_free(fname);
5291 tor_free(contents);
5292 return -1;
5294 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
5295 tor_free(fname);
5296 tor_free(contents);
5298 global_state->next_write = TIME_MAX;
5299 return 0;
5302 /** Given a file name check to see whether the file exists but has not been
5303 * modified for a very long time. If so, remove it. */
5304 void
5305 remove_file_if_very_old(const char *fname, time_t now)
5307 #define VERY_OLD_FILE_AGE (28*24*60*60)
5308 struct stat st;
5310 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
5311 char buf[ISO_TIME_LEN+1];
5312 format_local_iso_time(buf, st.st_mtime);
5313 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
5314 "Removing it.", fname, buf);
5315 unlink(fname);
5319 /** Helper to implement GETINFO functions about configuration variables (not
5320 * their values). Given a "config/names" question, set *<b>answer</b> to a
5321 * new string describing the supported configuration variables and their
5322 * types. */
5324 getinfo_helper_config(control_connection_t *conn,
5325 const char *question, char **answer)
5327 (void) conn;
5328 if (!strcmp(question, "config/names")) {
5329 smartlist_t *sl = smartlist_create();
5330 int i;
5331 for (i = 0; _option_vars[i].name; ++i) {
5332 config_var_t *var = &_option_vars[i];
5333 const char *type, *desc;
5334 char *line;
5335 size_t len;
5336 desc = config_find_description(&options_format, var->name);
5337 switch (var->type) {
5338 case CONFIG_TYPE_STRING: type = "String"; break;
5339 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
5340 case CONFIG_TYPE_UINT: type = "Integer"; break;
5341 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
5342 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
5343 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
5344 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
5345 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
5346 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
5347 case CONFIG_TYPE_CSV: type = "CommaList"; break;
5348 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
5349 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
5350 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
5351 default:
5352 case CONFIG_TYPE_OBSOLETE:
5353 type = NULL; break;
5355 if (!type)
5356 continue;
5357 len = strlen(var->name)+strlen(type)+16;
5358 if (desc)
5359 len += strlen(desc);
5360 line = tor_malloc(len);
5361 if (desc)
5362 tor_snprintf(line, len, "%s %s %s\n",var->name,type,desc);
5363 else
5364 tor_snprintf(line, len, "%s %s\n",var->name,type);
5365 smartlist_add(sl, line);
5367 *answer = smartlist_join_strings(sl, "", 0, NULL);
5368 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
5369 smartlist_free(sl);
5371 return 0;