Use | with flags, not +.
[tor/rransom.git] / src / or / config.c
blobb696b23a4cd2acf0115c3069b8a830b40c73eafc
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-formated 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) connectinos 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 uint64_t config_parse_memunit(const char *s, int *ok);
697 static int config_parse_interval(const char *s, int *ok);
698 static void init_libevent(void);
699 static int opt_streq(const char *s1, const char *s2);
700 /** Versions of libevent. */
701 typedef enum {
702 /* Note: we compare these, so it's important that "old" precede everything,
703 * and that "other" come last. */
704 LE_OLD=0, LE_10C, LE_10D, LE_10E, LE_11, LE_11A, LE_11B, LE_12, LE_12A,
705 LE_13, LE_13A, LE_13B, LE_13C, LE_13D, LE_13E,
706 LE_140, LE_141, LE_142, LE_143, LE_144, LE_145, LE_146, LE_147, LE_148,
707 LE_1499,
708 LE_OTHER
709 } le_version_t;
710 static le_version_t decode_libevent_version(const char *v, int *bincompat_out);
711 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
712 static void check_libevent_version(const char *m, int server);
713 #endif
715 /** Magic value for or_options_t. */
716 #define OR_OPTIONS_MAGIC 9090909
718 /** Configuration format for or_options_t. */
719 static config_format_t options_format = {
720 sizeof(or_options_t),
721 OR_OPTIONS_MAGIC,
722 STRUCT_OFFSET(or_options_t, _magic),
723 _option_abbrevs,
724 _option_vars,
725 (validate_fn_t)options_validate,
726 options_description,
727 NULL
730 /** Magic value for or_state_t. */
731 #define OR_STATE_MAGIC 0x57A73f57
733 /** "Extra" variable in the state that receives lines we can't parse. This
734 * lets us preserve options from versions of Tor newer than us. */
735 static config_var_t state_extra_var = {
736 "__extra", CONFIG_TYPE_LINELIST, STRUCT_OFFSET(or_state_t, ExtraLines), NULL
739 /** Configuration format for or_state_t. */
740 static config_format_t state_format = {
741 sizeof(or_state_t),
742 OR_STATE_MAGIC,
743 STRUCT_OFFSET(or_state_t, _magic),
744 _state_abbrevs,
745 _state_vars,
746 (validate_fn_t)or_state_validate,
747 state_description,
748 &state_extra_var,
752 * Functions to read and write the global options pointer.
755 /** Command-line and config-file options. */
756 static or_options_t *global_options = NULL;
757 /** Name of most recently read torrc file. */
758 static char *torrc_fname = NULL;
759 /** Persistent serialized state. */
760 static or_state_t *global_state = NULL;
761 /** Configuration Options set by command line. */
762 static config_line_t *global_cmdline_options = NULL;
763 /** Contents of most recently read DirPortFrontPage file. */
764 static char *global_dirfrontpagecontents = NULL;
766 /** Return the contents of our frontpage string, or NULL if not configured. */
767 const char *
768 get_dirportfrontpage(void)
770 return global_dirfrontpagecontents;
773 /** Allocate an empty configuration object of a given format type. */
774 static void *
775 config_alloc(config_format_t *fmt)
777 void *opts = tor_malloc_zero(fmt->size);
778 *(uint32_t*)STRUCT_VAR_P(opts, fmt->magic_offset) = fmt->magic;
779 CHECK(fmt, opts);
780 return opts;
783 /** Return the currently configured options. */
784 or_options_t *
785 get_options(void)
787 tor_assert(global_options);
788 return global_options;
791 /** Change the current global options to contain <b>new_val</b> instead of
792 * their current value; take action based on the new value; free the old value
793 * as necessary. Returns 0 on success, -1 on failure.
796 set_options(or_options_t *new_val, char **msg)
798 or_options_t *old_options = global_options;
799 global_options = new_val;
800 /* Note that we pass the *old* options below, for comparison. It
801 * pulls the new options directly out of global_options. */
802 if (options_act_reversible(old_options, msg)<0) {
803 tor_assert(*msg);
804 global_options = old_options;
805 return -1;
807 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
808 log_err(LD_BUG,
809 "Acting on config options left us in a broken state. Dying.");
810 exit(1);
812 if (old_options)
813 config_free(&options_format, old_options);
815 return 0;
818 extern const char tor_svn_revision[]; /* from tor_main.c */
820 /** The version of this Tor process, as parsed. */
821 static char *_version = NULL;
823 /** Return the current Tor version. */
824 const char *
825 get_version(void)
827 if (_version == NULL) {
828 if (strlen(tor_svn_revision)) {
829 size_t len = strlen(VERSION)+strlen(tor_svn_revision)+8;
830 _version = tor_malloc(len);
831 tor_snprintf(_version, len, "%s (r%s)", VERSION, tor_svn_revision);
832 } else {
833 _version = tor_strdup(VERSION);
836 return _version;
839 /** Release additional memory allocated in options
841 static void
842 or_options_free(or_options_t *options)
844 if (options->_ExcludeExitNodesUnion)
845 routerset_free(options->_ExcludeExitNodesUnion);
846 config_free(&options_format, options);
849 /** Release all memory and resources held by global configuration structures.
851 void
852 config_free_all(void)
854 if (global_options) {
855 or_options_free(global_options);
856 global_options = NULL;
858 if (global_state) {
859 config_free(&state_format, global_state);
860 global_state = NULL;
862 if (global_cmdline_options) {
863 config_free_lines(global_cmdline_options);
864 global_cmdline_options = NULL;
866 tor_free(torrc_fname);
867 tor_free(_version);
868 tor_free(global_dirfrontpagecontents);
871 /** If options->SafeLogging is on, return a not very useful string,
872 * else return address.
874 const char *
875 safe_str(const char *address)
877 tor_assert(address);
878 if (get_options()->SafeLogging)
879 return "[scrubbed]";
880 else
881 return address;
884 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
885 * escaped(): don't use this outside the main thread, or twice in the same
886 * log statement. */
887 const char *
888 escaped_safe_str(const char *address)
890 if (get_options()->SafeLogging)
891 return "[scrubbed]";
892 else
893 return escaped(address);
896 /** Add the default directory authorities directly into the trusted dir list,
897 * but only add them insofar as they share bits with <b>type</b>. */
898 static void
899 add_default_trusted_dir_authorities(authority_type_t type)
901 int i;
902 const char *dirservers[] = {
903 "moria1 v1 orport=9001 v3ident=E2A2AF570166665D738736D0DD58169CC61D8A8B "
904 "128.31.0.34:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441",
905 "moria2 v1 orport=9002 128.31.0.34:9032 "
906 "719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF",
907 "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
908 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
909 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
910 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
911 "Tonga orport=443 bridge no-v2 82.94.251.206:80 "
912 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
913 "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
914 "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
915 "gabelmoo orport=443 no-v2 "
916 "v3ident=81349FC1F2DBA2C2C11B45CB9706637D480AB913 "
917 "80.190.246.100:80 6833 3D07 61BC F397 A587 A0C0 B963 E4A9 E99E C4D3",
918 "dannenberg orport=443 no-v2 "
919 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
920 "213.73.91.31:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
921 NULL
923 for (i=0; dirservers[i]; i++) {
924 if (parse_dir_server_line(dirservers[i], type, 0)<0) {
925 log_err(LD_BUG, "Couldn't parse internal dirserver line %s",
926 dirservers[i]);
931 /** Look at all the config options for using alternate directory
932 * authorities, and make sure none of them are broken. Also, warn the
933 * user if we changed any dangerous ones.
935 static int
936 validate_dir_authorities(or_options_t *options, or_options_t *old_options)
938 config_line_t *cl;
940 if (options->DirServers &&
941 (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
942 options->AlternateHSAuthority)) {
943 log_warn(LD_CONFIG,
944 "You cannot set both DirServers and Alternate*Authority.");
945 return -1;
948 /* do we want to complain to the user about being partitionable? */
949 if ((options->DirServers &&
950 (!old_options ||
951 !config_lines_eq(options->DirServers, old_options->DirServers))) ||
952 (options->AlternateDirAuthority &&
953 (!old_options ||
954 !config_lines_eq(options->AlternateDirAuthority,
955 old_options->AlternateDirAuthority)))) {
956 log_warn(LD_CONFIG,
957 "You have used DirServer or AlternateDirAuthority to "
958 "specify alternate directory authorities in "
959 "your configuration. This is potentially dangerous: it can "
960 "make you look different from all other Tor users, and hurt "
961 "your anonymity. Even if you've specified the same "
962 "authorities as Tor uses by default, the defaults could "
963 "change in the future. Be sure you know what you're doing.");
966 /* Now go through the four ways you can configure an alternate
967 * set of directory authorities, and make sure none are broken. */
968 for (cl = options->DirServers; cl; cl = cl->next)
969 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
970 return -1;
971 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
972 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
973 return -1;
974 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
975 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
976 return -1;
977 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
978 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
979 return -1;
980 return 0;
983 /** Look at all the config options and assign new dir authorities
984 * as appropriate.
986 static int
987 consider_adding_dir_authorities(or_options_t *options,
988 or_options_t *old_options)
990 config_line_t *cl;
991 int need_to_update =
992 !smartlist_len(router_get_trusted_dir_servers()) || !old_options ||
993 !config_lines_eq(options->DirServers, old_options->DirServers) ||
994 !config_lines_eq(options->AlternateBridgeAuthority,
995 old_options->AlternateBridgeAuthority) ||
996 !config_lines_eq(options->AlternateDirAuthority,
997 old_options->AlternateDirAuthority) ||
998 !config_lines_eq(options->AlternateHSAuthority,
999 old_options->AlternateHSAuthority);
1001 if (!need_to_update)
1002 return 0; /* all done */
1004 /* Start from a clean slate. */
1005 clear_trusted_dir_servers();
1007 if (!options->DirServers) {
1008 /* then we may want some of the defaults */
1009 authority_type_t type = NO_AUTHORITY;
1010 if (!options->AlternateBridgeAuthority)
1011 type |= BRIDGE_AUTHORITY;
1012 if (!options->AlternateDirAuthority)
1013 type |= V1_AUTHORITY | V2_AUTHORITY | V3_AUTHORITY;
1014 if (!options->AlternateHSAuthority)
1015 type |= HIDSERV_AUTHORITY;
1016 add_default_trusted_dir_authorities(type);
1019 for (cl = options->DirServers; cl; cl = cl->next)
1020 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1021 return -1;
1022 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1023 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1024 return -1;
1025 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1026 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1027 return -1;
1028 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
1029 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1030 return -1;
1031 return 0;
1034 /** Fetch the active option list, and take actions based on it. All of the
1035 * things we do should survive being done repeatedly. If present,
1036 * <b>old_options</b> contains the previous value of the options.
1038 * Return 0 if all goes well, return -1 if things went badly.
1040 static int
1041 options_act_reversible(or_options_t *old_options, char **msg)
1043 smartlist_t *new_listeners = smartlist_create();
1044 smartlist_t *replaced_listeners = smartlist_create();
1045 static int libevent_initialized = 0;
1046 or_options_t *options = get_options();
1047 int running_tor = options->command == CMD_RUN_TOR;
1048 int set_conn_limit = 0;
1049 int r = -1;
1050 int logs_marked = 0;
1052 /* Daemonize _first_, since we only want to open most of this stuff in
1053 * the subprocess. Libevent bases can't be reliably inherited across
1054 * processes. */
1055 if (running_tor && options->RunAsDaemon) {
1056 /* No need to roll back, since you can't change the value. */
1057 start_daemon();
1060 #ifndef HAVE_SYS_UN_H
1061 if (options->ControlSocket) {
1062 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported"
1063 " on this OS/with this build.");
1064 goto rollback;
1066 #endif
1068 if (running_tor) {
1069 /* We need to set the connection limit before we can open the listeners. */
1070 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1071 &options->_ConnLimit) < 0) {
1072 *msg = tor_strdup("Problem with ConnLimit value. See logs for details.");
1073 goto rollback;
1075 set_conn_limit = 1;
1077 /* Set up libevent. (We need to do this before we can register the
1078 * listeners as listeners.) */
1079 if (running_tor && !libevent_initialized) {
1080 init_libevent();
1081 libevent_initialized = 1;
1084 /* Launch the listeners. (We do this before we setuid, so we can bind to
1085 * ports under 1024.) */
1086 if (retry_all_listeners(replaced_listeners, new_listeners) < 0) {
1087 *msg = tor_strdup("Failed to bind one of the listener ports.");
1088 goto rollback;
1092 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1093 /* Open /dev/pf before dropping privileges. */
1094 if (options->TransPort) {
1095 if (get_pf_socket() < 0) {
1096 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1097 goto rollback;
1100 #endif
1102 /* Setuid/setgid as appropriate */
1103 if (options->User) {
1104 if (switch_id(options->User) != 0) {
1105 /* No need to roll back, since you can't change the value. */
1106 *msg = tor_strdup("Problem with User value. See logs for details.");
1107 goto done;
1111 /* Ensure data directory is private; create if possible. */
1112 if (check_private_dir(options->DataDirectory,
1113 running_tor ? CPD_CREATE : CPD_CHECK)<0) {
1114 char buf[1024];
1115 int tmp = tor_snprintf(buf, sizeof(buf),
1116 "Couldn't access/create private data directory \"%s\"",
1117 options->DataDirectory);
1118 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1119 goto done;
1120 /* No need to roll back, since you can't change the value. */
1123 if (directory_caches_v2_dir_info(options)) {
1124 size_t len = strlen(options->DataDirectory)+32;
1125 char *fn = tor_malloc(len);
1126 tor_snprintf(fn, len, "%s"PATH_SEPARATOR"cached-status",
1127 options->DataDirectory);
1128 if (check_private_dir(fn, running_tor ? CPD_CREATE : CPD_CHECK) < 0) {
1129 char buf[1024];
1130 int tmp = tor_snprintf(buf, sizeof(buf),
1131 "Couldn't access/create private data directory \"%s\"", fn);
1132 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1133 tor_free(fn);
1134 goto done;
1136 tor_free(fn);
1139 /* Bail out at this point if we're not going to be a client or server:
1140 * we don't run Tor itself. */
1141 if (!running_tor)
1142 goto commit;
1144 mark_logs_temp(); /* Close current logs once new logs are open. */
1145 logs_marked = 1;
1146 if (options_init_logs(options, 0)<0) { /* Configure the log(s) */
1147 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1148 goto rollback;
1151 commit:
1152 r = 0;
1153 if (logs_marked) {
1154 log_severity_list_t *severity =
1155 tor_malloc_zero(sizeof(log_severity_list_t));
1156 close_temp_logs();
1157 add_callback_log(severity, control_event_logmsg);
1158 control_adjust_event_log_severity();
1159 tor_free(severity);
1161 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1163 log_notice(LD_NET, "Closing old %s on %s:%d",
1164 conn_type_to_string(conn->type), conn->address, conn->port);
1165 connection_close_immediate(conn);
1166 connection_mark_for_close(conn);
1168 goto done;
1170 rollback:
1171 r = -1;
1172 tor_assert(*msg);
1174 if (logs_marked) {
1175 rollback_log_changes();
1176 control_adjust_event_log_severity();
1179 if (set_conn_limit && old_options)
1180 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1181 &options->_ConnLimit);
1183 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1185 log_notice(LD_NET, "Closing partially-constructed listener %s on %s:%d",
1186 conn_type_to_string(conn->type), conn->address, conn->port);
1187 connection_close_immediate(conn);
1188 connection_mark_for_close(conn);
1191 done:
1192 smartlist_free(new_listeners);
1193 smartlist_free(replaced_listeners);
1194 return r;
1197 /** If we need to have a GEOIP ip-to-country map to run with our configured
1198 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1200 options_need_geoip_info(or_options_t *options, const char **reason_out)
1202 int bridge_usage =
1203 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1204 int routerset_usage =
1205 routerset_needs_geoip(options->EntryNodes) ||
1206 routerset_needs_geoip(options->ExitNodes) ||
1207 routerset_needs_geoip(options->ExcludeExitNodes) ||
1208 routerset_needs_geoip(options->ExcludeNodes);
1210 if (routerset_usage && reason_out) {
1211 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1212 "contries, and we need GEOIP information to figure out which ones they "
1213 "are.";
1214 } else if (bridge_usage && reason_out) {
1215 *reason_out = "We've been configured to see which countries can access "
1216 "us as a bridge, and we need GEOIP information to tell which countries "
1217 "clients are in.";
1219 return bridge_usage || routerset_usage;
1222 /** Fetch the active option list, and take actions based on it. All of the
1223 * things we do should survive being done repeatedly. If present,
1224 * <b>old_options</b> contains the previous value of the options.
1226 * Return 0 if all goes well, return -1 if it's time to die.
1228 * Note: We haven't moved all the "act on new configuration" logic
1229 * here yet. Some is still in do_hup() and other places.
1231 static int
1232 options_act(or_options_t *old_options)
1234 config_line_t *cl;
1235 or_options_t *options = get_options();
1236 int running_tor = options->command == CMD_RUN_TOR;
1237 char *msg;
1239 if (running_tor && !have_lockfile()) {
1240 if (try_locking(options, 1) < 0)
1241 return -1;
1244 if (consider_adding_dir_authorities(options, old_options) < 0)
1245 return -1;
1247 if (options->Bridges) {
1248 clear_bridge_list();
1249 for (cl = options->Bridges; cl; cl = cl->next) {
1250 if (parse_bridge_line(cl->value, 0)<0) {
1251 log_warn(LD_BUG,
1252 "Previously validated Bridge line could not be added!");
1253 return -1;
1258 if (running_tor && rend_config_services(options, 0)<0) {
1259 log_warn(LD_BUG,
1260 "Previously validated hidden services line could not be added!");
1261 return -1;
1264 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1265 log_warn(LD_BUG, "Previously validated client authorization for "
1266 "hidden services could not be added!");
1267 return -1;
1270 /* Load state */
1271 if (! global_state && running_tor) {
1272 if (or_state_load())
1273 return -1;
1274 rep_hist_load_mtbf_data(time(NULL));
1277 /* Bail out at this point if we're not going to be a client or server:
1278 * we want to not fork, and to log stuff to stderr. */
1279 if (!running_tor)
1280 return 0;
1282 /* Finish backgrounding the process */
1283 if (running_tor && options->RunAsDaemon) {
1284 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1285 finish_daemon(options->DataDirectory);
1288 /* Write our pid to the pid file. If we do not have write permissions we
1289 * will log a warning */
1290 if (running_tor && options->PidFile)
1291 write_pidfile(options->PidFile);
1293 /* Register addressmap directives */
1294 config_register_addressmaps(options);
1295 parse_virtual_addr_network(options->VirtualAddrNetwork, 0, &msg);
1297 /* Update address policies. */
1298 if (policies_parse_from_options(options) < 0) {
1299 /* This should be impossible, but let's be sure. */
1300 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1301 return -1;
1304 if (init_cookie_authentication(options->CookieAuthentication) < 0) {
1305 log_warn(LD_CONFIG,"Error creating cookie authentication file.");
1306 return -1;
1309 /* reload keys as needed for rendezvous services. */
1310 if (rend_service_load_keys()<0) {
1311 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1312 return -1;
1315 /* Set up accounting */
1316 if (accounting_parse_options(options, 0)<0) {
1317 log_warn(LD_CONFIG,"Error in accounting options");
1318 return -1;
1320 if (accounting_is_enabled(options))
1321 configure_accounting(time(NULL));
1323 /* Check for transitions that need action. */
1324 if (old_options) {
1325 if (options->UseEntryGuards && !old_options->UseEntryGuards) {
1326 log_info(LD_CIRC,
1327 "Switching to entry guards; abandoning previous circuits");
1328 circuit_mark_all_unused_circs();
1329 circuit_expire_all_dirty_circs();
1332 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
1333 log_info(LD_GENERAL, "Bridge status changed. Forgetting GeoIP stats.");
1334 geoip_remove_old_clients(time(NULL)+3600);
1337 if (options_transition_affects_workers(old_options, options)) {
1338 log_info(LD_GENERAL,
1339 "Worker-related options changed. Rotating workers.");
1340 if (server_mode(options) && !server_mode(old_options)) {
1341 if (init_keys() < 0) {
1342 log_warn(LD_BUG,"Error initializing keys; exiting");
1343 return -1;
1345 ip_address_changed(0);
1346 if (has_completed_circuit || !any_predicted_circuits(time(NULL)))
1347 inform_testing_reachability();
1349 cpuworkers_rotate();
1350 if (dns_reset())
1351 return -1;
1352 } else {
1353 if (dns_reset())
1354 return -1;
1357 if (options->V3AuthoritativeDir && !old_options->V3AuthoritativeDir)
1358 init_keys();
1361 /* Maybe load geoip file */
1362 if (options->GeoIPFile &&
1363 ((!old_options || !opt_streq(old_options->GeoIPFile, options->GeoIPFile))
1364 || !geoip_is_loaded())) {
1365 /* XXXX Don't use this "<default>" junk; make our filename options
1366 * understand prefixes somehow. -NM */
1367 /* XXXX021 Reload GeoIPFile on SIGHUP. -NM */
1368 char *actual_fname = tor_strdup(options->GeoIPFile);
1369 #ifdef WIN32
1370 if (!strcmp(actual_fname, "<default>")) {
1371 const char *conf_root = get_windows_conf_root();
1372 size_t len = strlen(conf_root)+16;
1373 tor_free(actual_fname);
1374 actual_fname = tor_malloc(len+1);
1375 tor_snprintf(actual_fname, len, "%s\\geoip", conf_root);
1377 #endif
1378 geoip_load_file(actual_fname, options);
1379 tor_free(actual_fname);
1381 /* Check if we need to parse and add the EntryNodes config option. */
1382 if (options->EntryNodes &&
1383 (!old_options ||
1384 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
1385 entry_nodes_should_be_added();
1387 /* Since our options changed, we might need to regenerate and upload our
1388 * server descriptor.
1390 if (!old_options ||
1391 options_transition_affects_descriptor(old_options, options))
1392 mark_my_descriptor_dirty();
1394 /* We may need to reschedule some directory stuff if our status changed. */
1395 if (old_options) {
1396 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1397 dirvote_recalculate_timing(options, time(NULL));
1398 if (!bool_eq(directory_fetches_dir_info_early(options),
1399 directory_fetches_dir_info_early(old_options)) ||
1400 !bool_eq(directory_fetches_dir_info_later(options),
1401 directory_fetches_dir_info_later(old_options))) {
1402 /* Make sure update_router_have_min_dir_info gets called. */
1403 router_dir_info_changed();
1404 /* We might need to download a new consensus status later or sooner than
1405 * we had expected. */
1406 update_consensus_networkstatus_fetch_time(time(NULL));
1410 /* Load the webpage we're going to serve everytime someone asks for '/' on
1411 our DirPort. */
1412 tor_free(global_dirfrontpagecontents);
1413 if (options->DirPortFrontPage) {
1414 global_dirfrontpagecontents =
1415 read_file_to_str(options->DirPortFrontPage, 0, NULL);
1416 if (!global_dirfrontpagecontents) {
1417 log_warn(LD_CONFIG,
1418 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1419 options->DirPortFrontPage);
1423 return 0;
1427 * Functions to parse config options
1430 /** If <b>option</b> is an official abbreviation for a longer option,
1431 * return the longer option. Otherwise return <b>option</b>.
1432 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1433 * apply abbreviations that work for the config file and the command line.
1434 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1435 static const char *
1436 expand_abbrev(config_format_t *fmt, const char *option, int command_line,
1437 int warn_obsolete)
1439 int i;
1440 if (! fmt->abbrevs)
1441 return option;
1442 for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
1443 /* Abbreviations are casei. */
1444 if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
1445 (command_line || !fmt->abbrevs[i].commandline_only)) {
1446 if (warn_obsolete && fmt->abbrevs[i].warn) {
1447 log_warn(LD_CONFIG,
1448 "The configuration option '%s' is deprecated; "
1449 "use '%s' instead.",
1450 fmt->abbrevs[i].abbreviated,
1451 fmt->abbrevs[i].full);
1453 return fmt->abbrevs[i].full;
1456 return option;
1459 /** Helper: Read a list of configuration options from the command line.
1460 * If successful, put them in *<b>result</b> and return 0, and return
1461 * -1 and leave *<b>result</b> alone. */
1462 static int
1463 config_get_commandlines(int argc, char **argv, config_line_t **result)
1465 config_line_t *front = NULL;
1466 config_line_t **new = &front;
1467 char *s;
1468 int i = 1;
1470 while (i < argc) {
1471 if (!strcmp(argv[i],"-f") ||
1472 !strcmp(argv[i],"--hash-password")) {
1473 i += 2; /* command-line option with argument. ignore them. */
1474 continue;
1475 } else if (!strcmp(argv[i],"--list-fingerprint") ||
1476 !strcmp(argv[i],"--verify-config") ||
1477 !strcmp(argv[i],"--ignore-missing-torrc") ||
1478 !strcmp(argv[i],"--quiet") ||
1479 !strcmp(argv[i],"--hush")) {
1480 i += 1; /* command-line option. ignore it. */
1481 continue;
1482 } else if (!strcmp(argv[i],"--nt-service") ||
1483 !strcmp(argv[i],"-nt-service")) {
1484 i += 1;
1485 continue;
1488 if (i == argc-1) {
1489 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1490 argv[i]);
1491 config_free_lines(front);
1492 return -1;
1495 *new = tor_malloc_zero(sizeof(config_line_t));
1496 s = argv[i];
1498 while (*s == '-')
1499 s++;
1501 (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1, 1));
1502 (*new)->value = tor_strdup(argv[i+1]);
1503 (*new)->next = NULL;
1504 log(LOG_DEBUG, LD_CONFIG, "Commandline: parsed keyword '%s', value '%s'",
1505 (*new)->key, (*new)->value);
1507 new = &((*new)->next);
1508 i += 2;
1510 *result = front;
1511 return 0;
1514 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1515 * append it to *<b>lst</b>. */
1516 static void
1517 config_line_append(config_line_t **lst,
1518 const char *key,
1519 const char *val)
1521 config_line_t *newline;
1523 newline = tor_malloc(sizeof(config_line_t));
1524 newline->key = tor_strdup(key);
1525 newline->value = tor_strdup(val);
1526 newline->next = NULL;
1527 while (*lst)
1528 lst = &((*lst)->next);
1530 (*lst) = newline;
1533 /** Helper: parse the config string and strdup into key/value
1534 * strings. Set *result to the list, or NULL if parsing the string
1535 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1536 * misformatted lines. */
1538 config_get_lines(const char *string, config_line_t **result)
1540 config_line_t *list = NULL, **next;
1541 char *k, *v;
1543 next = &list;
1544 do {
1545 k = v = NULL;
1546 string = parse_config_line_from_str(string, &k, &v);
1547 if (!string) {
1548 config_free_lines(list);
1549 tor_free(k);
1550 tor_free(v);
1551 return -1;
1553 if (k && v) {
1554 /* This list can get long, so we keep a pointer to the end of it
1555 * rather than using config_line_append over and over and getting
1556 * n^2 performance. */
1557 *next = tor_malloc(sizeof(config_line_t));
1558 (*next)->key = k;
1559 (*next)->value = v;
1560 (*next)->next = NULL;
1561 next = &((*next)->next);
1562 } else {
1563 tor_free(k);
1564 tor_free(v);
1566 } while (*string);
1568 *result = list;
1569 return 0;
1573 * Free all the configuration lines on the linked list <b>front</b>.
1575 void
1576 config_free_lines(config_line_t *front)
1578 config_line_t *tmp;
1580 while (front) {
1581 tmp = front;
1582 front = tmp->next;
1584 tor_free(tmp->key);
1585 tor_free(tmp->value);
1586 tor_free(tmp);
1590 /** Return the description for a given configuration variable, or NULL if no
1591 * description exists. */
1592 static const char *
1593 config_find_description(config_format_t *fmt, const char *name)
1595 int i;
1596 for (i=0; fmt->descriptions[i].name; ++i) {
1597 if (!strcasecmp(name, fmt->descriptions[i].name))
1598 return fmt->descriptions[i].description;
1600 return NULL;
1603 /** If <b>key</b> is a configuration option, return the corresponding
1604 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1605 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1607 static config_var_t *
1608 config_find_option(config_format_t *fmt, const char *key)
1610 int i;
1611 size_t keylen = strlen(key);
1612 if (!keylen)
1613 return NULL; /* if they say "--" on the commandline, it's not an option */
1614 /* First, check for an exact (case-insensitive) match */
1615 for (i=0; fmt->vars[i].name; ++i) {
1616 if (!strcasecmp(key, fmt->vars[i].name)) {
1617 return &fmt->vars[i];
1620 /* If none, check for an abbreviated match */
1621 for (i=0; fmt->vars[i].name; ++i) {
1622 if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
1623 log_warn(LD_CONFIG, "The abbreviation '%s' is deprecated. "
1624 "Please use '%s' instead",
1625 key, fmt->vars[i].name);
1626 return &fmt->vars[i];
1629 /* Okay, unrecognized option */
1630 return NULL;
1634 * Functions to assign config options.
1637 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1638 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1640 * Called from config_assign_line() and option_reset().
1642 static int
1643 config_assign_value(config_format_t *fmt, or_options_t *options,
1644 config_line_t *c, char **msg)
1646 int i, r, ok;
1647 char buf[1024];
1648 config_var_t *var;
1649 void *lvalue;
1651 CHECK(fmt, options);
1653 var = config_find_option(fmt, c->key);
1654 tor_assert(var);
1656 lvalue = STRUCT_VAR_P(options, var->var_offset);
1658 switch (var->type) {
1660 case CONFIG_TYPE_UINT:
1661 i = (int)tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
1662 if (!ok) {
1663 r = tor_snprintf(buf, sizeof(buf),
1664 "Int keyword '%s %s' is malformed or out of bounds.",
1665 c->key, c->value);
1666 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1667 return -1;
1669 *(int *)lvalue = i;
1670 break;
1672 case CONFIG_TYPE_INTERVAL: {
1673 i = config_parse_interval(c->value, &ok);
1674 if (!ok) {
1675 r = tor_snprintf(buf, sizeof(buf),
1676 "Interval '%s %s' is malformed or out of bounds.",
1677 c->key, c->value);
1678 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1679 return -1;
1681 *(int *)lvalue = i;
1682 break;
1685 case CONFIG_TYPE_MEMUNIT: {
1686 uint64_t u64 = config_parse_memunit(c->value, &ok);
1687 if (!ok) {
1688 r = tor_snprintf(buf, sizeof(buf),
1689 "Value '%s %s' is malformed or out of bounds.",
1690 c->key, c->value);
1691 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1692 return -1;
1694 *(uint64_t *)lvalue = u64;
1695 break;
1698 case CONFIG_TYPE_BOOL:
1699 i = (int)tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
1700 if (!ok) {
1701 r = tor_snprintf(buf, sizeof(buf),
1702 "Boolean '%s %s' expects 0 or 1.",
1703 c->key, c->value);
1704 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1705 return -1;
1707 *(int *)lvalue = i;
1708 break;
1710 case CONFIG_TYPE_STRING:
1711 case CONFIG_TYPE_FILENAME:
1712 tor_free(*(char **)lvalue);
1713 *(char **)lvalue = tor_strdup(c->value);
1714 break;
1716 case CONFIG_TYPE_DOUBLE:
1717 *(double *)lvalue = atof(c->value);
1718 break;
1720 case CONFIG_TYPE_ISOTIME:
1721 if (parse_iso_time(c->value, (time_t *)lvalue)) {
1722 r = tor_snprintf(buf, sizeof(buf),
1723 "Invalid time '%s' for keyword '%s'", c->value, c->key);
1724 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1725 return -1;
1727 break;
1729 case CONFIG_TYPE_ROUTERSET:
1730 if (*(routerset_t**)lvalue) {
1731 routerset_free(*(routerset_t**)lvalue);
1733 *(routerset_t**)lvalue = routerset_new();
1734 if (routerset_parse(*(routerset_t**)lvalue, c->value, c->key)<0) {
1735 tor_snprintf(buf, sizeof(buf), "Invalid exit list '%s' for option '%s'",
1736 c->value, c->key);
1737 *msg = tor_strdup(buf);
1738 return -1;
1740 break;
1742 case CONFIG_TYPE_CSV:
1743 if (*(smartlist_t**)lvalue) {
1744 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
1745 smartlist_clear(*(smartlist_t**)lvalue);
1746 } else {
1747 *(smartlist_t**)lvalue = smartlist_create();
1750 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
1751 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1752 break;
1754 case CONFIG_TYPE_LINELIST:
1755 case CONFIG_TYPE_LINELIST_S:
1756 config_line_append((config_line_t**)lvalue, c->key, c->value);
1757 break;
1758 case CONFIG_TYPE_OBSOLETE:
1759 log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
1760 break;
1761 case CONFIG_TYPE_LINELIST_V:
1762 r = tor_snprintf(buf, sizeof(buf),
1763 "You may not provide a value for virtual option '%s'", c->key);
1764 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1765 return -1;
1766 default:
1767 tor_assert(0);
1768 break;
1770 return 0;
1773 /** If <b>c</b> is a syntactically valid configuration line, update
1774 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1775 * key, -2 for bad value.
1777 * If <b>clear_first</b> is set, clear the value first. Then if
1778 * <b>use_defaults</b> is set, set the value to the default.
1780 * Called from config_assign().
1782 static int
1783 config_assign_line(config_format_t *fmt, or_options_t *options,
1784 config_line_t *c, int use_defaults,
1785 int clear_first, char **msg)
1787 config_var_t *var;
1789 CHECK(fmt, options);
1791 var = config_find_option(fmt, c->key);
1792 if (!var) {
1793 if (fmt->extra) {
1794 void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
1795 log_info(LD_CONFIG,
1796 "Found unrecognized option '%s'; saving it.", c->key);
1797 config_line_append((config_line_t**)lvalue, c->key, c->value);
1798 return 0;
1799 } else {
1800 char buf[1024];
1801 int tmp = tor_snprintf(buf, sizeof(buf),
1802 "Unknown option '%s'. Failing.", c->key);
1803 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1804 return -1;
1807 /* Put keyword into canonical case. */
1808 if (strcmp(var->name, c->key)) {
1809 tor_free(c->key);
1810 c->key = tor_strdup(var->name);
1813 if (!strlen(c->value)) {
1814 /* reset or clear it, then return */
1815 if (!clear_first) {
1816 if (var->type == CONFIG_TYPE_LINELIST ||
1817 var->type == CONFIG_TYPE_LINELIST_S) {
1818 /* We got an empty linelist from the torrc or commandline.
1819 As a special case, call this an error. Warn and ignore. */
1820 log_warn(LD_CONFIG,
1821 "Linelist option '%s' has no value. Skipping.", c->key);
1822 } else { /* not already cleared */
1823 option_reset(fmt, options, var, use_defaults);
1826 return 0;
1829 if (config_assign_value(fmt, options, c, msg) < 0)
1830 return -2;
1831 return 0;
1834 /** Restore the option named <b>key</b> in options to its default value.
1835 * Called from config_assign(). */
1836 static void
1837 config_reset_line(config_format_t *fmt, or_options_t *options,
1838 const char *key, int use_defaults)
1840 config_var_t *var;
1842 CHECK(fmt, options);
1844 var = config_find_option(fmt, key);
1845 if (!var)
1846 return; /* give error on next pass. */
1848 option_reset(fmt, options, var, use_defaults);
1851 /** Return true iff key is a valid configuration option. */
1853 option_is_recognized(const char *key)
1855 config_var_t *var = config_find_option(&options_format, key);
1856 return (var != NULL);
1859 /** Return the canonical name of a configuration option, or NULL
1860 * if no such option exists. */
1861 const char *
1862 option_get_canonical_name(const char *key)
1864 config_var_t *var = config_find_option(&options_format, key);
1865 return var ? var->name : NULL;
1868 /** Return a canonicalized list of the options assigned for key.
1870 config_line_t *
1871 option_get_assignment(or_options_t *options, const char *key)
1873 return get_assigned_option(&options_format, options, key, 1);
1876 /** Return true iff value needs to be quoted and escaped to be used in
1877 * a configuration file. */
1878 static int
1879 config_value_needs_escape(const char *value)
1881 if (*value == '\"')
1882 return 1;
1883 while (*value) {
1884 switch (*value)
1886 case '\r':
1887 case '\n':
1888 case '#':
1889 /* Note: quotes and backspaces need special handling when we are using
1890 * quotes, not otherwise, so they don't trigger escaping on their
1891 * own. */
1892 return 1;
1893 default:
1894 if (!TOR_ISPRINT(*value))
1895 return 1;
1897 ++value;
1899 return 0;
1902 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1903 static config_line_t *
1904 config_lines_dup(const config_line_t *inp)
1906 config_line_t *result = NULL;
1907 config_line_t **next_out = &result;
1908 while (inp) {
1909 *next_out = tor_malloc(sizeof(config_line_t));
1910 (*next_out)->key = tor_strdup(inp->key);
1911 (*next_out)->value = tor_strdup(inp->value);
1912 inp = inp->next;
1913 next_out = &((*next_out)->next);
1915 (*next_out) = NULL;
1916 return result;
1919 /** Return newly allocated line or lines corresponding to <b>key</b> in the
1920 * configuration <b>options</b>. If <b>escape_val</b> is true and a
1921 * value needs to be quoted before it's put in a config file, quote and
1922 * escape that value. Return NULL if no such key exists. */
1923 static config_line_t *
1924 get_assigned_option(config_format_t *fmt, void *options,
1925 const char *key, int escape_val)
1927 config_var_t *var;
1928 const void *value;
1929 char buf[32];
1930 config_line_t *result;
1931 tor_assert(options && key);
1933 CHECK(fmt, options);
1935 var = config_find_option(fmt, key);
1936 if (!var) {
1937 log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
1938 return NULL;
1940 value = STRUCT_VAR_P(options, var->var_offset);
1942 result = tor_malloc_zero(sizeof(config_line_t));
1943 result->key = tor_strdup(var->name);
1944 switch (var->type)
1946 case CONFIG_TYPE_STRING:
1947 case CONFIG_TYPE_FILENAME:
1948 if (*(char**)value) {
1949 result->value = tor_strdup(*(char**)value);
1950 } else {
1951 tor_free(result->key);
1952 tor_free(result);
1953 return NULL;
1955 break;
1956 case CONFIG_TYPE_ISOTIME:
1957 if (*(time_t*)value) {
1958 result->value = tor_malloc(ISO_TIME_LEN+1);
1959 format_iso_time(result->value, *(time_t*)value);
1960 } else {
1961 tor_free(result->key);
1962 tor_free(result);
1964 escape_val = 0; /* Can't need escape. */
1965 break;
1966 case CONFIG_TYPE_INTERVAL:
1967 case CONFIG_TYPE_UINT:
1968 /* This means every or_options_t uint or bool element
1969 * needs to be an int. Not, say, a uint16_t or char. */
1970 tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
1971 result->value = tor_strdup(buf);
1972 escape_val = 0; /* Can't need escape. */
1973 break;
1974 case CONFIG_TYPE_MEMUNIT:
1975 tor_snprintf(buf, sizeof(buf), U64_FORMAT,
1976 U64_PRINTF_ARG(*(uint64_t*)value));
1977 result->value = tor_strdup(buf);
1978 escape_val = 0; /* Can't need escape. */
1979 break;
1980 case CONFIG_TYPE_DOUBLE:
1981 tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
1982 result->value = tor_strdup(buf);
1983 escape_val = 0; /* Can't need escape. */
1984 break;
1985 case CONFIG_TYPE_BOOL:
1986 result->value = tor_strdup(*(int*)value ? "1" : "0");
1987 escape_val = 0; /* Can't need escape. */
1988 break;
1989 case CONFIG_TYPE_ROUTERSET:
1990 result->value = routerset_to_string(*(routerset_t**)value);
1991 break;
1992 case CONFIG_TYPE_CSV:
1993 if (*(smartlist_t**)value)
1994 result->value =
1995 smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
1996 else
1997 result->value = tor_strdup("");
1998 break;
1999 case CONFIG_TYPE_OBSOLETE:
2000 log_fn(LOG_PROTOCOL_WARN, LD_CONFIG,
2001 "You asked me for the value of an obsolete config option '%s'.",
2002 key);
2003 tor_free(result->key);
2004 tor_free(result);
2005 return NULL;
2006 case CONFIG_TYPE_LINELIST_S:
2007 log_warn(LD_CONFIG,
2008 "Can't return context-sensitive '%s' on its own", key);
2009 tor_free(result->key);
2010 tor_free(result);
2011 return NULL;
2012 case CONFIG_TYPE_LINELIST:
2013 case CONFIG_TYPE_LINELIST_V:
2014 tor_free(result->key);
2015 tor_free(result);
2016 result = config_lines_dup(*(const config_line_t**)value);
2017 break;
2018 default:
2019 tor_free(result->key);
2020 tor_free(result);
2021 log_warn(LD_BUG,"Unknown type %d for known key '%s'",
2022 var->type, key);
2023 return NULL;
2026 if (escape_val) {
2027 config_line_t *line;
2028 for (line = result; line; line = line->next) {
2029 if (line->value && config_value_needs_escape(line->value)) {
2030 char *newval = esc_for_log(line->value);
2031 tor_free(line->value);
2032 line->value = newval;
2037 return result;
2040 /** Iterate through the linked list of requested options <b>list</b>.
2041 * For each item, convert as appropriate and assign to <b>options</b>.
2042 * If an item is unrecognized, set *msg and return -1 immediately,
2043 * else return 0 for success.
2045 * If <b>clear_first</b>, interpret config options as replacing (not
2046 * extending) their previous values. If <b>clear_first</b> is set,
2047 * then <b>use_defaults</b> to decide if you set to defaults after
2048 * clearing, or make the value 0 or NULL.
2050 * Here are the use cases:
2051 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
2052 * if linelist, replaces current if csv.
2053 * 2. An empty AllowInvalid line in your torrc. Should clear it.
2054 * 3. "RESETCONF AllowInvalid" sets it to default.
2055 * 4. "SETCONF AllowInvalid" makes it NULL.
2056 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
2058 * Use_defaults Clear_first
2059 * 0 0 "append"
2060 * 1 0 undefined, don't use
2061 * 0 1 "set to null first"
2062 * 1 1 "set to defaults first"
2063 * Return 0 on success, -1 on bad key, -2 on bad value.
2065 * As an additional special case, if a LINELIST config option has
2066 * no value and clear_first is 0, then warn and ignore it.
2070 There are three call cases for config_assign() currently.
2072 Case one: Torrc entry
2073 options_init_from_torrc() calls config_assign(0, 0)
2074 calls config_assign_line(0, 0).
2075 if value is empty, calls option_reset(0) and returns.
2076 calls config_assign_value(), appends.
2078 Case two: setconf
2079 options_trial_assign() calls config_assign(0, 1)
2080 calls config_reset_line(0)
2081 calls option_reset(0)
2082 calls option_clear().
2083 calls config_assign_line(0, 1).
2084 if value is empty, returns.
2085 calls config_assign_value(), appends.
2087 Case three: resetconf
2088 options_trial_assign() calls config_assign(1, 1)
2089 calls config_reset_line(1)
2090 calls option_reset(1)
2091 calls option_clear().
2092 calls config_assign_value(default)
2093 calls config_assign_line(1, 1).
2094 returns.
2096 static int
2097 config_assign(config_format_t *fmt, void *options, config_line_t *list,
2098 int use_defaults, int clear_first, char **msg)
2100 config_line_t *p;
2102 CHECK(fmt, options);
2104 /* pass 1: normalize keys */
2105 for (p = list; p; p = p->next) {
2106 const char *full = expand_abbrev(fmt, p->key, 0, 1);
2107 if (strcmp(full,p->key)) {
2108 tor_free(p->key);
2109 p->key = tor_strdup(full);
2113 /* pass 2: if we're reading from a resetting source, clear all
2114 * mentioned config options, and maybe set to their defaults. */
2115 if (clear_first) {
2116 for (p = list; p; p = p->next)
2117 config_reset_line(fmt, options, p->key, use_defaults);
2120 /* pass 3: assign. */
2121 while (list) {
2122 int r;
2123 if ((r=config_assign_line(fmt, options, list, use_defaults,
2124 clear_first, msg)))
2125 return r;
2126 list = list->next;
2128 return 0;
2131 /** Try assigning <b>list</b> to the global options. You do this by duping
2132 * options, assigning list to the new one, then validating it. If it's
2133 * ok, then throw out the old one and stick with the new one. Else,
2134 * revert to old and return failure. Return SETOPT_OK on success, or
2135 * a setopt_err_t on failure.
2137 * If not success, point *<b>msg</b> to a newly allocated string describing
2138 * what went wrong.
2140 setopt_err_t
2141 options_trial_assign(config_line_t *list, int use_defaults,
2142 int clear_first, char **msg)
2144 int r;
2145 or_options_t *trial_options = options_dup(&options_format, get_options());
2147 if ((r=config_assign(&options_format, trial_options,
2148 list, use_defaults, clear_first, msg)) < 0) {
2149 config_free(&options_format, trial_options);
2150 return r;
2153 if (options_validate(get_options(), trial_options, 1, msg) < 0) {
2154 config_free(&options_format, trial_options);
2155 return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2158 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2159 config_free(&options_format, trial_options);
2160 return SETOPT_ERR_TRANSITION;
2163 if (set_options(trial_options, msg)<0) {
2164 config_free(&options_format, trial_options);
2165 return SETOPT_ERR_SETTING;
2168 /* we liked it. put it in place. */
2169 return SETOPT_OK;
2172 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2173 * Called from option_reset() and config_free(). */
2174 static void
2175 option_clear(config_format_t *fmt, or_options_t *options, config_var_t *var)
2177 void *lvalue = STRUCT_VAR_P(options, var->var_offset);
2178 (void)fmt; /* unused */
2179 switch (var->type) {
2180 case CONFIG_TYPE_STRING:
2181 case CONFIG_TYPE_FILENAME:
2182 tor_free(*(char**)lvalue);
2183 break;
2184 case CONFIG_TYPE_DOUBLE:
2185 *(double*)lvalue = 0.0;
2186 break;
2187 case CONFIG_TYPE_ISOTIME:
2188 *(time_t*)lvalue = 0;
2189 case CONFIG_TYPE_INTERVAL:
2190 case CONFIG_TYPE_UINT:
2191 case CONFIG_TYPE_BOOL:
2192 *(int*)lvalue = 0;
2193 break;
2194 case CONFIG_TYPE_MEMUNIT:
2195 *(uint64_t*)lvalue = 0;
2196 break;
2197 case CONFIG_TYPE_ROUTERSET:
2198 if (*(routerset_t**)lvalue) {
2199 routerset_free(*(routerset_t**)lvalue);
2200 *(routerset_t**)lvalue = NULL;
2202 case CONFIG_TYPE_CSV:
2203 if (*(smartlist_t**)lvalue) {
2204 SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
2205 smartlist_free(*(smartlist_t **)lvalue);
2206 *(smartlist_t **)lvalue = NULL;
2208 break;
2209 case CONFIG_TYPE_LINELIST:
2210 case CONFIG_TYPE_LINELIST_S:
2211 config_free_lines(*(config_line_t **)lvalue);
2212 *(config_line_t **)lvalue = NULL;
2213 break;
2214 case CONFIG_TYPE_LINELIST_V:
2215 /* handled by linelist_s. */
2216 break;
2217 case CONFIG_TYPE_OBSOLETE:
2218 break;
2222 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2223 * <b>use_defaults</b>, set it to its default value.
2224 * Called by config_init() and option_reset_line() and option_assign_line(). */
2225 static void
2226 option_reset(config_format_t *fmt, or_options_t *options,
2227 config_var_t *var, int use_defaults)
2229 config_line_t *c;
2230 char *msg = NULL;
2231 CHECK(fmt, options);
2232 option_clear(fmt, options, var); /* clear it first */
2233 if (!use_defaults)
2234 return; /* all done */
2235 if (var->initvalue) {
2236 c = tor_malloc_zero(sizeof(config_line_t));
2237 c->key = tor_strdup(var->name);
2238 c->value = tor_strdup(var->initvalue);
2239 if (config_assign_value(fmt, options, c, &msg) < 0) {
2240 log_warn(LD_BUG, "Failed to assign default: %s", msg);
2241 tor_free(msg); /* if this happens it's a bug */
2243 config_free_lines(c);
2247 /** Print a usage message for tor. */
2248 static void
2249 print_usage(void)
2251 printf(
2252 "Copyright (c) 2001-2004, Roger Dingledine\n"
2253 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2254 "Copyright (c) 2007-2009, The Tor Project, Inc.\n\n"
2255 "tor -f <torrc> [args]\n"
2256 "See man page for options, or https://www.torproject.org/ for "
2257 "documentation.\n");
2260 /** Print all non-obsolete torrc options. */
2261 static void
2262 list_torrc_options(void)
2264 int i;
2265 smartlist_t *lines = smartlist_create();
2266 for (i = 0; _option_vars[i].name; ++i) {
2267 config_var_t *var = &_option_vars[i];
2268 const char *desc;
2269 if (var->type == CONFIG_TYPE_OBSOLETE ||
2270 var->type == CONFIG_TYPE_LINELIST_V)
2271 continue;
2272 desc = config_find_description(&options_format, var->name);
2273 printf("%s\n", var->name);
2274 if (desc) {
2275 wrap_string(lines, desc, 76, " ", " ");
2276 SMARTLIST_FOREACH(lines, char *, cp, {
2277 printf("%s", cp);
2278 tor_free(cp);
2280 smartlist_clear(lines);
2283 smartlist_free(lines);
2286 /** Last value actually set by resolve_my_address. */
2287 static uint32_t last_resolved_addr = 0;
2289 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2290 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2291 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2292 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2293 * public IP address.
2296 resolve_my_address(int warn_severity, or_options_t *options,
2297 uint32_t *addr_out, char **hostname_out)
2299 struct in_addr in;
2300 struct hostent *rent;
2301 char hostname[256];
2302 int explicit_ip=1;
2303 int explicit_hostname=1;
2304 int from_interface=0;
2305 char tmpbuf[INET_NTOA_BUF_LEN];
2306 const char *address = options->Address;
2307 int notice_severity = warn_severity <= LOG_NOTICE ?
2308 LOG_NOTICE : warn_severity;
2310 tor_assert(addr_out);
2312 if (address && *address) {
2313 strlcpy(hostname, address, sizeof(hostname));
2314 } else { /* then we need to guess our address */
2315 explicit_ip = 0; /* it's implicit */
2316 explicit_hostname = 0; /* it's implicit */
2318 if (gethostname(hostname, sizeof(hostname)) < 0) {
2319 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2320 return -1;
2322 log_debug(LD_CONFIG,"Guessed local host name as '%s'",hostname);
2325 /* now we know hostname. resolve it and keep only the IP address */
2327 if (tor_inet_aton(hostname, &in) == 0) {
2328 /* then we have to resolve it */
2329 explicit_ip = 0;
2330 rent = (struct hostent *)gethostbyname(hostname);
2331 if (!rent) {
2332 uint32_t interface_ip;
2334 if (explicit_hostname) {
2335 log_fn(warn_severity, LD_CONFIG,
2336 "Could not resolve local Address '%s'. Failing.", hostname);
2337 return -1;
2339 log_fn(notice_severity, LD_CONFIG,
2340 "Could not resolve guessed local hostname '%s'. "
2341 "Trying something else.", hostname);
2342 if (get_interface_address(warn_severity, &interface_ip)) {
2343 log_fn(warn_severity, LD_CONFIG,
2344 "Could not get local interface IP address. Failing.");
2345 return -1;
2347 from_interface = 1;
2348 in.s_addr = htonl(interface_ip);
2349 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2350 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2351 "local interface. Using that.", tmpbuf);
2352 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2353 } else {
2354 tor_assert(rent->h_length == 4);
2355 memcpy(&in.s_addr, rent->h_addr, rent->h_length);
2357 if (!explicit_hostname &&
2358 is_internal_IP(ntohl(in.s_addr), 0)) {
2359 uint32_t interface_ip;
2361 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2362 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2363 "resolves to a private IP address (%s). Trying something "
2364 "else.", hostname, tmpbuf);
2366 if (get_interface_address(warn_severity, &interface_ip)) {
2367 log_fn(warn_severity, LD_CONFIG,
2368 "Could not get local interface IP address. Too bad.");
2369 } else if (is_internal_IP(interface_ip, 0)) {
2370 struct in_addr in2;
2371 in2.s_addr = htonl(interface_ip);
2372 tor_inet_ntoa(&in2,tmpbuf,sizeof(tmpbuf));
2373 log_fn(notice_severity, LD_CONFIG,
2374 "Interface IP address '%s' is a private address too. "
2375 "Ignoring.", tmpbuf);
2376 } else {
2377 from_interface = 1;
2378 in.s_addr = htonl(interface_ip);
2379 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2380 log_fn(notice_severity, LD_CONFIG,
2381 "Learned IP address '%s' for local interface."
2382 " Using that.", tmpbuf);
2383 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2389 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2390 if (is_internal_IP(ntohl(in.s_addr), 0) &&
2391 options->_PublishServerDescriptor) {
2392 /* make sure we're ok with publishing an internal IP */
2393 if (!options->DirServers && !options->AlternateDirAuthority) {
2394 /* if they are using the default dirservers, disallow internal IPs
2395 * always. */
2396 log_fn(warn_severity, LD_CONFIG,
2397 "Address '%s' resolves to private IP address '%s'. "
2398 "Tor servers that use the default DirServers must have public "
2399 "IP addresses.", hostname, tmpbuf);
2400 return -1;
2402 if (!explicit_ip) {
2403 /* even if they've set their own dirservers, require an explicit IP if
2404 * they're using an internal address. */
2405 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2406 "IP address '%s'. Please set the Address config option to be "
2407 "the IP address you want to use.", hostname, tmpbuf);
2408 return -1;
2412 log_debug(LD_CONFIG, "Resolved Address to '%s'.", tmpbuf);
2413 *addr_out = ntohl(in.s_addr);
2414 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2415 /* Leave this as a notice, regardless of the requested severity,
2416 * at least until dynamic IP address support becomes bulletproof. */
2417 log_notice(LD_NET,
2418 "Your IP address seems to have changed to %s. Updating.",
2419 tmpbuf);
2420 ip_address_changed(0);
2422 if (last_resolved_addr != *addr_out) {
2423 const char *method;
2424 const char *h = hostname;
2425 if (explicit_ip) {
2426 method = "CONFIGURED";
2427 h = NULL;
2428 } else if (explicit_hostname) {
2429 method = "RESOLVED";
2430 } else if (from_interface) {
2431 method = "INTERFACE";
2432 h = NULL;
2433 } else {
2434 method = "GETHOSTNAME";
2436 control_event_server_status(LOG_NOTICE,
2437 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2438 tmpbuf, method, h?"HOSTNAME=":"", h);
2440 last_resolved_addr = *addr_out;
2441 if (hostname_out)
2442 *hostname_out = tor_strdup(hostname);
2443 return 0;
2446 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2447 * on a private network.
2450 is_local_addr(const tor_addr_t *addr)
2452 if (tor_addr_is_internal(addr, 0))
2453 return 1;
2454 /* Check whether ip is on the same /24 as we are. */
2455 if (get_options()->EnforceDistinctSubnets == 0)
2456 return 0;
2457 if (tor_addr_family(addr) == AF_INET) {
2458 /*XXXX022 IP6 what corresponds to an /24? */
2459 uint32_t ip = tor_addr_to_ipv4h(addr);
2461 /* It's possible that this next check will hit before the first time
2462 * resolve_my_address actually succeeds. (For clients, it is likely that
2463 * resolve_my_address will never be called at all). In those cases,
2464 * last_resolved_addr will be 0, and so checking to see whether ip is on
2465 * the same /24 as last_resolved_addr will be the same as checking whether
2466 * it was on net 0, which is already done by is_internal_IP.
2468 if ((last_resolved_addr & 0xffffff00ul) == (ip & 0xffffff00ul))
2469 return 1;
2471 return 0;
2474 /** Called when we don't have a nickname set. Try to guess a good nickname
2475 * based on the hostname, and return it in a newly allocated string. If we
2476 * can't, return NULL and let the caller warn if it wants to. */
2477 static char *
2478 get_default_nickname(void)
2480 static const char * const bad_default_nicknames[] = {
2481 "localhost",
2482 NULL,
2484 char localhostname[256];
2485 char *cp, *out, *outp;
2486 int i;
2488 if (gethostname(localhostname, sizeof(localhostname)) < 0)
2489 return NULL;
2491 /* Put it in lowercase; stop at the first dot. */
2492 if ((cp = strchr(localhostname, '.')))
2493 *cp = '\0';
2494 tor_strlower(localhostname);
2496 /* Strip invalid characters. */
2497 cp = localhostname;
2498 out = outp = tor_malloc(strlen(localhostname) + 1);
2499 while (*cp) {
2500 if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
2501 *outp++ = *cp++;
2502 else
2503 cp++;
2505 *outp = '\0';
2507 /* Enforce length. */
2508 if (strlen(out) > MAX_NICKNAME_LEN)
2509 out[MAX_NICKNAME_LEN]='\0';
2511 /* Check for dumb names. */
2512 for (i = 0; bad_default_nicknames[i]; ++i) {
2513 if (!strcmp(out, bad_default_nicknames[i])) {
2514 tor_free(out);
2515 return NULL;
2519 return out;
2522 /** Release storage held by <b>options</b>. */
2523 static void
2524 config_free(config_format_t *fmt, void *options)
2526 int i;
2528 tor_assert(options);
2530 for (i=0; fmt->vars[i].name; ++i)
2531 option_clear(fmt, options, &(fmt->vars[i]));
2532 if (fmt->extra) {
2533 config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
2534 config_free_lines(*linep);
2535 *linep = NULL;
2537 tor_free(options);
2540 /** Return true iff a and b contain identical keys and values in identical
2541 * order. */
2542 static int
2543 config_lines_eq(config_line_t *a, config_line_t *b)
2545 while (a && b) {
2546 if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
2547 return 0;
2548 a = a->next;
2549 b = b->next;
2551 if (a || b)
2552 return 0;
2553 return 1;
2556 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2557 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2559 static int
2560 option_is_same(config_format_t *fmt,
2561 or_options_t *o1, or_options_t *o2, const char *name)
2563 config_line_t *c1, *c2;
2564 int r = 1;
2565 CHECK(fmt, o1);
2566 CHECK(fmt, o2);
2568 c1 = get_assigned_option(fmt, o1, name, 0);
2569 c2 = get_assigned_option(fmt, o2, name, 0);
2570 r = config_lines_eq(c1, c2);
2571 config_free_lines(c1);
2572 config_free_lines(c2);
2573 return r;
2576 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2577 static or_options_t *
2578 options_dup(config_format_t *fmt, or_options_t *old)
2580 or_options_t *newopts;
2581 int i;
2582 config_line_t *line;
2584 newopts = config_alloc(fmt);
2585 for (i=0; fmt->vars[i].name; ++i) {
2586 if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2587 continue;
2588 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
2589 continue;
2590 line = get_assigned_option(fmt, old, fmt->vars[i].name, 0);
2591 if (line) {
2592 char *msg = NULL;
2593 if (config_assign(fmt, newopts, line, 0, 0, &msg) < 0) {
2594 log_err(LD_BUG, "Config_get_assigned_option() generated "
2595 "something we couldn't config_assign(): %s", msg);
2596 tor_free(msg);
2597 tor_assert(0);
2600 config_free_lines(line);
2602 return newopts;
2605 /** Return a new empty or_options_t. Used for testing. */
2606 or_options_t *
2607 options_new(void)
2609 return config_alloc(&options_format);
2612 /** Set <b>options</b> to hold reasonable defaults for most options.
2613 * Each option defaults to zero. */
2614 void
2615 options_init(or_options_t *options)
2617 config_init(&options_format, options);
2620 /** Set all vars in the configuration object <b>options</b> to their default
2621 * values. */
2622 static void
2623 config_init(config_format_t *fmt, void *options)
2625 int i;
2626 config_var_t *var;
2627 CHECK(fmt, options);
2629 for (i=0; fmt->vars[i].name; ++i) {
2630 var = &fmt->vars[i];
2631 if (!var->initvalue)
2632 continue; /* defaults to NULL or 0 */
2633 option_reset(fmt, options, var, 1);
2637 /** Allocate and return a new string holding the written-out values of the vars
2638 * in 'options'. If 'minimal', do not write out any default-valued vars.
2639 * Else, if comment_defaults, write default values as comments.
2641 static char *
2642 config_dump(config_format_t *fmt, void *options, int minimal,
2643 int comment_defaults)
2645 smartlist_t *elements;
2646 or_options_t *defaults;
2647 config_line_t *line, *assigned;
2648 char *result;
2649 int i;
2650 const char *desc;
2651 char *msg = NULL;
2653 defaults = config_alloc(fmt);
2654 config_init(fmt, defaults);
2656 /* XXX use a 1 here so we don't add a new log line while dumping */
2657 if (fmt->validate_fn(NULL,defaults, 1, &msg) < 0) {
2658 log_err(LD_BUG, "Failed to validate default config.");
2659 tor_free(msg);
2660 tor_assert(0);
2663 elements = smartlist_create();
2664 for (i=0; fmt->vars[i].name; ++i) {
2665 int comment_option = 0;
2666 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
2667 fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2668 continue;
2669 /* Don't save 'hidden' control variables. */
2670 if (!strcmpstart(fmt->vars[i].name, "__"))
2671 continue;
2672 if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
2673 continue;
2674 else if (comment_defaults &&
2675 option_is_same(fmt, options, defaults, fmt->vars[i].name))
2676 comment_option = 1;
2678 desc = config_find_description(fmt, fmt->vars[i].name);
2679 line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name, 1);
2681 if (line && desc) {
2682 /* Only dump the description if there's something to describe. */
2683 wrap_string(elements, desc, 78, "# ", "# ");
2686 for (; line; line = line->next) {
2687 size_t len = strlen(line->key) + strlen(line->value) + 5;
2688 char *tmp;
2689 tmp = tor_malloc(len);
2690 if (tor_snprintf(tmp, len, "%s%s %s\n",
2691 comment_option ? "# " : "",
2692 line->key, line->value)<0) {
2693 log_err(LD_BUG,"Internal error writing option value");
2694 tor_assert(0);
2696 smartlist_add(elements, tmp);
2698 config_free_lines(assigned);
2701 if (fmt->extra) {
2702 line = *(config_line_t**)STRUCT_VAR_P(options, fmt->extra->var_offset);
2703 for (; line; line = line->next) {
2704 size_t len = strlen(line->key) + strlen(line->value) + 3;
2705 char *tmp;
2706 tmp = tor_malloc(len);
2707 if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
2708 log_err(LD_BUG,"Internal error writing option value");
2709 tor_assert(0);
2711 smartlist_add(elements, tmp);
2715 result = smartlist_join_strings(elements, "", 0, NULL);
2716 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2717 smartlist_free(elements);
2718 config_free(fmt, defaults);
2719 return result;
2722 /** Return a string containing a possible configuration file that would give
2723 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2724 * include options that are the same as Tor's defaults.
2726 static char *
2727 options_dump(or_options_t *options, int minimal)
2729 return config_dump(&options_format, options, minimal, 0);
2732 /** Return 0 if every element of sl is a string holding a decimal
2733 * representation of a port number, or if sl is NULL.
2734 * Otherwise set *msg and return -1. */
2735 static int
2736 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2738 int i;
2739 char buf[1024];
2740 tor_assert(name);
2742 if (!sl)
2743 return 0;
2745 SMARTLIST_FOREACH(sl, const char *, cp,
2747 i = atoi(cp);
2748 if (i < 1 || i > 65535) {
2749 int r = tor_snprintf(buf, sizeof(buf),
2750 "Port '%s' out of range in %s", cp, name);
2751 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2752 return -1;
2755 return 0;
2758 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2759 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2760 * Else return 0.
2762 static int
2763 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2765 int r;
2766 char buf[1024];
2767 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2768 /* This handles an understandable special case where somebody says "2gb"
2769 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2770 --*value;
2772 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2773 r = tor_snprintf(buf, sizeof(buf), "%s ("U64_FORMAT") must be at most %d",
2774 desc, U64_PRINTF_ARG(*value),
2775 ROUTER_MAX_DECLARED_BANDWIDTH);
2776 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2777 return -1;
2779 return 0;
2782 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2783 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2784 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2785 * Treat "0" as "".
2786 * Return 0 on success or -1 if not a recognized authority type (in which
2787 * case the value of _PublishServerDescriptor is undefined). */
2788 static int
2789 compute_publishserverdescriptor(or_options_t *options)
2791 smartlist_t *list = options->PublishServerDescriptor;
2792 authority_type_t *auth = &options->_PublishServerDescriptor;
2793 *auth = NO_AUTHORITY;
2794 if (!list) /* empty list, answer is none */
2795 return 0;
2796 SMARTLIST_FOREACH(list, const char *, string, {
2797 if (!strcasecmp(string, "v1"))
2798 *auth |= V1_AUTHORITY;
2799 else if (!strcmp(string, "1"))
2800 if (options->BridgeRelay)
2801 *auth |= BRIDGE_AUTHORITY;
2802 else
2803 *auth |= V2_AUTHORITY | V3_AUTHORITY;
2804 else if (!strcasecmp(string, "v2"))
2805 *auth |= V2_AUTHORITY;
2806 else if (!strcasecmp(string, "v3"))
2807 *auth |= V3_AUTHORITY;
2808 else if (!strcasecmp(string, "bridge"))
2809 *auth |= BRIDGE_AUTHORITY;
2810 else if (!strcasecmp(string, "hidserv"))
2811 *auth |= HIDSERV_AUTHORITY;
2812 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2813 /* no authority */;
2814 else
2815 return -1;
2817 return 0;
2820 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2821 * services can overload the directory system. */
2822 #define MIN_REND_POST_PERIOD (10*60)
2824 /** Highest allowable value for RendPostPeriod. */
2825 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2827 /** Lowest allowable value for CircuitBuildTimeout; values too low will
2828 * increase network load because of failing connections being retried, and
2829 * might prevent users from connecting to the network at all. */
2830 #define MIN_CIRCUIT_BUILD_TIMEOUT 30
2832 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2833 * will generate too many circuits and potentially overload the network. */
2834 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2836 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2837 * permissible transition from <b>old_options</b>. Else return -1.
2838 * Should have no side effects, except for normalizing the contents of
2839 * <b>options</b>.
2841 * On error, tor_strdup an error explanation into *<b>msg</b>.
2843 * XXX
2844 * If <b>from_setconf</b>, we were called by the controller, and our
2845 * Log line should stay empty. If it's 0, then give us a default log
2846 * if there are no logs defined.
2848 static int
2849 options_validate(or_options_t *old_options, or_options_t *options,
2850 int from_setconf, char **msg)
2852 int i, r;
2853 config_line_t *cl;
2854 const char *uname = get_uname();
2855 char buf[1024];
2856 #define REJECT(arg) \
2857 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2858 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2860 tor_assert(msg);
2861 *msg = NULL;
2863 if (options->ORPort < 0 || options->ORPort > 65535)
2864 REJECT("ORPort option out of bounds.");
2866 if (server_mode(options) &&
2867 (!strcmpstart(uname, "Windows 95") ||
2868 !strcmpstart(uname, "Windows 98") ||
2869 !strcmpstart(uname, "Windows Me"))) {
2870 log(LOG_WARN, LD_CONFIG, "Tor is running as a server, but you are "
2871 "running %s; this probably won't work. See "
2872 "http://wiki.noreply.org/noreply/TheOnionRouter/TorFAQ#ServerOS "
2873 "for details.", uname);
2876 if (options->ORPort == 0 && options->ORListenAddress != NULL)
2877 REJECT("ORPort must be defined if ORListenAddress is defined.");
2879 if (options->DirPort == 0 && options->DirListenAddress != NULL)
2880 REJECT("DirPort must be defined if DirListenAddress is defined.");
2882 if (options->DNSPort == 0 && options->DNSListenAddress != NULL)
2883 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
2885 if (options->ControlPort == 0 && options->ControlListenAddress != NULL)
2886 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
2888 if (options->TransPort == 0 && options->TransListenAddress != NULL)
2889 REJECT("TransPort must be defined if TransListenAddress is defined.");
2891 if (options->NatdPort == 0 && options->NatdListenAddress != NULL)
2892 REJECT("NatdPort must be defined if NatdListenAddress is defined.");
2894 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
2895 * configuration does this. */
2897 for (i = 0; i < 3; ++i) {
2898 int is_socks = i==0;
2899 int is_trans = i==1;
2900 config_line_t *line, *opt, *old;
2901 const char *tp;
2902 if (is_socks) {
2903 opt = options->SocksListenAddress;
2904 old = old_options ? old_options->SocksListenAddress : NULL;
2905 tp = "SOCKS proxy";
2906 } else if (is_trans) {
2907 opt = options->TransListenAddress;
2908 old = old_options ? old_options->TransListenAddress : NULL;
2909 tp = "transparent proxy";
2910 } else {
2911 opt = options->NatdListenAddress;
2912 old = old_options ? old_options->NatdListenAddress : NULL;
2913 tp = "natd proxy";
2916 for (line = opt; line; line = line->next) {
2917 char *address = NULL;
2918 uint16_t port;
2919 uint32_t addr;
2920 if (parse_addr_port(LOG_WARN, line->value, &address, &addr, &port)<0)
2921 continue; /* We'll warn about this later. */
2922 if (!is_internal_IP(addr, 1) &&
2923 (!old_options || !config_lines_eq(old, opt))) {
2924 log_warn(LD_CONFIG,
2925 "You specified a public address '%s' for a %s. Other "
2926 "people on the Internet might find your computer and use it as "
2927 "an open %s. Please don't allow this unless you have "
2928 "a good reason.", address, tp, tp);
2930 tor_free(address);
2934 if (validate_data_directory(options)<0)
2935 REJECT("Invalid DataDirectory");
2937 if (options->Nickname == NULL) {
2938 if (server_mode(options)) {
2939 if (!(options->Nickname = get_default_nickname())) {
2940 log_notice(LD_CONFIG, "Couldn't pick a nickname based on "
2941 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME);
2942 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
2943 } else {
2944 log_notice(LD_CONFIG, "Choosing default nickname '%s'",
2945 options->Nickname);
2948 } else {
2949 if (!is_legal_nickname(options->Nickname)) {
2950 r = tor_snprintf(buf, sizeof(buf),
2951 "Nickname '%s' is wrong length or contains illegal characters.",
2952 options->Nickname);
2953 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2954 return -1;
2958 if (server_mode(options) && !options->ContactInfo)
2959 log(LOG_NOTICE, LD_CONFIG, "Your ContactInfo config option is not set. "
2960 "Please consider setting it, so we can contact you if your server is "
2961 "misconfigured or something else goes wrong.");
2963 /* Special case on first boot if no Log options are given. */
2964 if (!options->Logs && !options->RunAsDaemon && !from_setconf)
2965 config_line_append(&options->Logs, "Log", "notice stdout");
2967 if (options_init_logs(options, 1)<0) /* Validate the log(s) */
2968 REJECT("Failed to validate Log options. See logs for details.");
2970 if (options->NoPublish) {
2971 log(LOG_WARN, LD_CONFIG,
2972 "NoPublish is obsolete. Use PublishServerDescriptor instead.");
2973 SMARTLIST_FOREACH(options->PublishServerDescriptor, char *, s,
2974 tor_free(s));
2975 smartlist_clear(options->PublishServerDescriptor);
2978 if (authdir_mode(options)) {
2979 /* confirm that our address isn't broken, so we can complain now */
2980 uint32_t tmp;
2981 if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
2982 REJECT("Failed to resolve/guess local address. See logs for details.");
2985 #ifndef MS_WINDOWS
2986 if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
2987 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
2988 #endif
2990 if (options->SocksPort < 0 || options->SocksPort > 65535)
2991 REJECT("SocksPort option out of bounds.");
2993 if (options->DNSPort < 0 || options->DNSPort > 65535)
2994 REJECT("DNSPort option out of bounds.");
2996 if (options->TransPort < 0 || options->TransPort > 65535)
2997 REJECT("TransPort option out of bounds.");
2999 if (options->NatdPort < 0 || options->NatdPort > 65535)
3000 REJECT("NatdPort option out of bounds.");
3002 if (options->SocksPort == 0 && options->TransPort == 0 &&
3003 options->NatdPort == 0 && options->ORPort == 0 &&
3004 options->DNSPort == 0 && !options->RendConfigLines)
3005 log(LOG_WARN, LD_CONFIG,
3006 "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
3007 "undefined, and there aren't any hidden services configured. "
3008 "Tor will still run, but probably won't do anything.");
3010 if (options->ControlPort < 0 || options->ControlPort > 65535)
3011 REJECT("ControlPort option out of bounds.");
3013 if (options->DirPort < 0 || options->DirPort > 65535)
3014 REJECT("DirPort option out of bounds.");
3016 #ifndef USE_TRANSPARENT
3017 if (options->TransPort || options->TransListenAddress)
3018 REJECT("TransPort and TransListenAddress are disabled in this build.");
3019 #endif
3021 #ifndef MS_WINDOWS
3022 if (options->AccountingMax &&
3023 (options->DirPort < 1024 || options->ORPort < 1024))
3024 log(LOG_WARN, LD_CONFIG,
3025 "You have set AccountingMax to use hibernation. You have also "
3026 "chosen a low DirPort or OrPort. This combination can make Tor stop "
3027 "working when it tries to re-attach the port after a period of "
3028 "hibernation. Please choose a different port or turn off "
3029 "hibernation unless you know this combination will work on your "
3030 "platform.");
3031 #endif
3033 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3034 options->_ExcludeExitNodesUnion = routerset_new();
3035 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeExitNodes);
3036 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeNodes);
3039 if (options->StrictExitNodes &&
3040 (!options->ExitNodes) &&
3041 (!old_options ||
3042 (old_options->StrictExitNodes != options->StrictExitNodes) ||
3043 (!routerset_equal(old_options->ExitNodes,options->ExitNodes))))
3044 COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
3046 if (options->StrictEntryNodes &&
3047 (!options->EntryNodes) &&
3048 (!old_options ||
3049 (old_options->StrictEntryNodes != options->StrictEntryNodes) ||
3050 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
3051 COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
3053 if (options->EntryNodes && !routerset_is_list(options->EntryNodes)) {
3054 /* XXXX fix this; see entry_guards_prepend_from_config(). */
3055 REJECT("IPs or countries are not yet supported in EntryNodes.");
3058 if (options->AuthoritativeDir) {
3059 if (!options->ContactInfo && !options->TestingTorNetwork)
3060 REJECT("Authoritative directory servers must set ContactInfo");
3061 if (options->V1AuthoritativeDir && !options->RecommendedVersions)
3062 REJECT("V1 auth dir servers must set RecommendedVersions.");
3063 if (!options->RecommendedClientVersions)
3064 options->RecommendedClientVersions =
3065 config_lines_dup(options->RecommendedVersions);
3066 if (!options->RecommendedServerVersions)
3067 options->RecommendedServerVersions =
3068 config_lines_dup(options->RecommendedVersions);
3069 if (options->VersioningAuthoritativeDir &&
3070 (!options->RecommendedClientVersions ||
3071 !options->RecommendedServerVersions))
3072 REJECT("Versioning auth dir servers must set Recommended*Versions.");
3073 if (options->UseEntryGuards) {
3074 log_info(LD_CONFIG, "Authoritative directory servers can't set "
3075 "UseEntryGuards. Disabling.");
3076 options->UseEntryGuards = 0;
3078 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
3079 log_info(LD_CONFIG, "Authoritative directories always try to download "
3080 "extra-info documents. Setting DownloadExtraInfo.");
3081 options->DownloadExtraInfo = 1;
3083 if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
3084 options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
3085 options->V3AuthoritativeDir))
3086 REJECT("AuthoritativeDir is set, but none of "
3087 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
3090 if (options->AuthoritativeDir && !options->DirPort)
3091 REJECT("Running as authoritative directory, but no DirPort set.");
3093 if (options->AuthoritativeDir && !options->ORPort)
3094 REJECT("Running as authoritative directory, but no ORPort set.");
3096 if (options->AuthoritativeDir && options->ClientOnly)
3097 REJECT("Running as authoritative directory, but ClientOnly also set.");
3099 if (options->HSAuthorityRecordStats && !options->HSAuthoritativeDir)
3100 REJECT("HSAuthorityRecordStats is set but we're not running as "
3101 "a hidden service authority.");
3103 if (options->ConnLimit <= 0) {
3104 r = tor_snprintf(buf, sizeof(buf),
3105 "ConnLimit must be greater than 0, but was set to %d",
3106 options->ConnLimit);
3107 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3108 return -1;
3111 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3112 return -1;
3114 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3115 return -1;
3117 if (validate_ports_csv(options->RejectPlaintextPorts,
3118 "RejectPlaintextPorts", msg) < 0)
3119 return -1;
3121 if (validate_ports_csv(options->WarnPlaintextPorts,
3122 "WarnPlaintextPorts", msg) < 0)
3123 return -1;
3125 if (options->FascistFirewall && !options->ReachableAddresses) {
3126 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3127 /* We already have firewall ports set, so migrate them to
3128 * ReachableAddresses, which will set ReachableORAddresses and
3129 * ReachableDirAddresses if they aren't set explicitly. */
3130 smartlist_t *instead = smartlist_create();
3131 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3132 new_line->key = tor_strdup("ReachableAddresses");
3133 /* If we're configured with the old format, we need to prepend some
3134 * open ports. */
3135 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3137 int p = atoi(portno);
3138 char *s;
3139 if (p<0) continue;
3140 s = tor_malloc(16);
3141 tor_snprintf(s, 16, "*:%d", p);
3142 smartlist_add(instead, s);
3144 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3145 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3146 log(LOG_NOTICE, LD_CONFIG,
3147 "Converting FascistFirewall and FirewallPorts "
3148 "config options to new format: \"ReachableAddresses %s\"",
3149 new_line->value);
3150 options->ReachableAddresses = new_line;
3151 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3152 smartlist_free(instead);
3153 } else {
3154 /* We do not have FirewallPorts set, so add 80 to
3155 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3156 if (!options->ReachableDirAddresses) {
3157 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3158 new_line->key = tor_strdup("ReachableDirAddresses");
3159 new_line->value = tor_strdup("*:80");
3160 options->ReachableDirAddresses = new_line;
3161 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3162 "to new format: \"ReachableDirAddresses *:80\"");
3164 if (!options->ReachableORAddresses) {
3165 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3166 new_line->key = tor_strdup("ReachableORAddresses");
3167 new_line->value = tor_strdup("*:443");
3168 options->ReachableORAddresses = new_line;
3169 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3170 "to new format: \"ReachableORAddresses *:443\"");
3175 for (i=0; i<3; i++) {
3176 config_line_t **linep =
3177 (i==0) ? &options->ReachableAddresses :
3178 (i==1) ? &options->ReachableORAddresses :
3179 &options->ReachableDirAddresses;
3180 if (!*linep)
3181 continue;
3182 /* We need to end with a reject *:*, not an implicit accept *:* */
3183 for (;;) {
3184 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
3185 break;
3186 linep = &((*linep)->next);
3187 if (!*linep) {
3188 *linep = tor_malloc_zero(sizeof(config_line_t));
3189 (*linep)->key = tor_strdup(
3190 (i==0) ? "ReachableAddresses" :
3191 (i==1) ? "ReachableORAddresses" :
3192 "ReachableDirAddresses");
3193 (*linep)->value = tor_strdup("reject *:*");
3194 break;
3199 if ((options->ReachableAddresses ||
3200 options->ReachableORAddresses ||
3201 options->ReachableDirAddresses) &&
3202 server_mode(options))
3203 REJECT("Servers must be able to freely connect to the rest "
3204 "of the Internet, so they must not set Reachable*Addresses "
3205 "or FascistFirewall.");
3207 if (options->UseBridges &&
3208 server_mode(options))
3209 REJECT("Servers must be able to freely connect to the rest "
3210 "of the Internet, so they must not set UseBridges.");
3212 options->_AllowInvalid = 0;
3213 if (options->AllowInvalidNodes) {
3214 SMARTLIST_FOREACH(options->AllowInvalidNodes, const char *, cp, {
3215 if (!strcasecmp(cp, "entry"))
3216 options->_AllowInvalid |= ALLOW_INVALID_ENTRY;
3217 else if (!strcasecmp(cp, "exit"))
3218 options->_AllowInvalid |= ALLOW_INVALID_EXIT;
3219 else if (!strcasecmp(cp, "middle"))
3220 options->_AllowInvalid |= ALLOW_INVALID_MIDDLE;
3221 else if (!strcasecmp(cp, "introduction"))
3222 options->_AllowInvalid |= ALLOW_INVALID_INTRODUCTION;
3223 else if (!strcasecmp(cp, "rendezvous"))
3224 options->_AllowInvalid |= ALLOW_INVALID_RENDEZVOUS;
3225 else {
3226 r = tor_snprintf(buf, sizeof(buf),
3227 "Unrecognized value '%s' in AllowInvalidNodes", cp);
3228 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3229 return -1;
3234 if (compute_publishserverdescriptor(options) < 0) {
3235 r = tor_snprintf(buf, sizeof(buf),
3236 "Unrecognized value in PublishServerDescriptor");
3237 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3238 return -1;
3241 if ((options->BridgeRelay
3242 || options->_PublishServerDescriptor & BRIDGE_AUTHORITY)
3243 && (options->_PublishServerDescriptor
3244 & (V1_AUTHORITY|V2_AUTHORITY|V3_AUTHORITY))) {
3245 REJECT("Bridges are not supposed to publish router descriptors to the "
3246 "directory authorities. Please correct your "
3247 "PublishServerDescriptor line.");
3250 if (options->MinUptimeHidServDirectoryV2 < 0) {
3251 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3252 "least 0 seconds. Changing to 0.");
3253 options->MinUptimeHidServDirectoryV2 = 0;
3256 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
3257 log(LOG_WARN,LD_CONFIG,"RendPostPeriod option is too short; "
3258 "raising to %d seconds.", MIN_REND_POST_PERIOD);
3259 options->RendPostPeriod = MIN_REND_POST_PERIOD;
3262 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3263 log(LOG_WARN, LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3264 MAX_DIR_PERIOD);
3265 options->RendPostPeriod = MAX_DIR_PERIOD;
3268 if (options->CircuitBuildTimeout < MIN_CIRCUIT_BUILD_TIMEOUT) {
3269 log(LOG_WARN, LD_CONFIG, "CircuitBuildTimeout option is too short; "
3270 "raising to %d seconds.", MIN_CIRCUIT_BUILD_TIMEOUT);
3271 options->CircuitBuildTimeout = MIN_CIRCUIT_BUILD_TIMEOUT;
3274 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3275 log(LOG_WARN, LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3276 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3277 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3280 if (options->KeepalivePeriod < 1)
3281 REJECT("KeepalivePeriod option must be positive.");
3283 if (ensure_bandwidth_cap(&options->BandwidthRate,
3284 "BandwidthRate", msg) < 0)
3285 return -1;
3286 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3287 "BandwidthBurst", msg) < 0)
3288 return -1;
3289 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3290 "MaxAdvertisedBandwidth", msg) < 0)
3291 return -1;
3292 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3293 "RelayBandwidthRate", msg) < 0)
3294 return -1;
3295 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3296 "RelayBandwidthBurst", msg) < 0)
3297 return -1;
3299 if (server_mode(options)) {
3300 if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3301 r = tor_snprintf(buf, sizeof(buf),
3302 "BandwidthRate is set to %d bytes/second. "
3303 "For servers, it must be at least %d.",
3304 (int)options->BandwidthRate,
3305 ROUTER_REQUIRED_MIN_BANDWIDTH);
3306 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3307 return -1;
3308 } else if (options->MaxAdvertisedBandwidth <
3309 ROUTER_REQUIRED_MIN_BANDWIDTH/2) {
3310 r = tor_snprintf(buf, sizeof(buf),
3311 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3312 "For servers, it must be at least %d.",
3313 (int)options->MaxAdvertisedBandwidth,
3314 ROUTER_REQUIRED_MIN_BANDWIDTH/2);
3315 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3316 return -1;
3318 if (options->RelayBandwidthRate &&
3319 options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3320 r = tor_snprintf(buf, sizeof(buf),
3321 "RelayBandwidthRate is set to %d bytes/second. "
3322 "For servers, it must be at least %d.",
3323 (int)options->RelayBandwidthRate,
3324 ROUTER_REQUIRED_MIN_BANDWIDTH);
3325 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3326 return -1;
3330 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3331 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3333 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3334 REJECT("RelayBandwidthBurst must be at least equal "
3335 "to RelayBandwidthRate.");
3337 if (options->BandwidthRate > options->BandwidthBurst)
3338 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3340 /* if they set relaybandwidth* really high but left bandwidth*
3341 * at the default, raise the defaults. */
3342 if (options->RelayBandwidthRate > options->BandwidthRate)
3343 options->BandwidthRate = options->RelayBandwidthRate;
3344 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3345 options->BandwidthBurst = options->RelayBandwidthBurst;
3347 if (accounting_parse_options(options, 1)<0)
3348 REJECT("Failed to parse accounting options. See logs for details.");
3350 if (options->HttpProxy) { /* parse it now */
3351 if (parse_addr_port(LOG_WARN, options->HttpProxy, NULL,
3352 &options->HttpProxyAddr, &options->HttpProxyPort) < 0)
3353 REJECT("HttpProxy failed to parse or resolve. Please fix.");
3354 if (options->HttpProxyPort == 0) { /* give it a default */
3355 options->HttpProxyPort = 80;
3359 if (options->HttpProxyAuthenticator) {
3360 if (strlen(options->HttpProxyAuthenticator) >= 48)
3361 REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
3364 if (options->HttpsProxy) { /* parse it now */
3365 if (parse_addr_port(LOG_WARN, options->HttpsProxy, NULL,
3366 &options->HttpsProxyAddr, &options->HttpsProxyPort) <0)
3367 REJECT("HttpsProxy failed to parse or resolve. Please fix.");
3368 if (options->HttpsProxyPort == 0) { /* give it a default */
3369 options->HttpsProxyPort = 443;
3373 if (options->HttpsProxyAuthenticator) {
3374 if (strlen(options->HttpsProxyAuthenticator) >= 48)
3375 REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
3378 if (options->HashedControlPassword) {
3379 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3380 if (!sl) {
3381 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3382 } else {
3383 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3384 smartlist_free(sl);
3388 if (options->HashedControlSessionPassword) {
3389 smartlist_t *sl = decode_hashed_passwords(
3390 options->HashedControlSessionPassword);
3391 if (!sl) {
3392 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3393 } else {
3394 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3395 smartlist_free(sl);
3399 if (options->ControlListenAddress) {
3400 int all_are_local = 1;
3401 config_line_t *ln;
3402 for (ln = options->ControlListenAddress; ln; ln = ln->next) {
3403 if (strcmpstart(ln->value, "127."))
3404 all_are_local = 0;
3406 if (!all_are_local) {
3407 if (!options->HashedControlPassword &&
3408 !options->HashedControlSessionPassword &&
3409 !options->CookieAuthentication) {
3410 log_warn(LD_CONFIG,
3411 "You have a ControlListenAddress set to accept "
3412 "unauthenticated connections from a non-local address. "
3413 "This means that programs not running on your computer "
3414 "can reconfigure your Tor, without even having to guess a "
3415 "password. That's so bad that I'm closing your ControlPort "
3416 "for you. If you need to control your Tor remotely, try "
3417 "enabling authentication and using a tool like stunnel or "
3418 "ssh to encrypt remote access.");
3419 options->ControlPort = 0;
3420 } else {
3421 log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
3422 "connections from a non-local address. This means that "
3423 "programs not running on your computer can reconfigure your "
3424 "Tor. That's pretty bad, since the controller "
3425 "protocol isn't encrypted! Maybe you should just listen on "
3426 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
3427 "remote connections to your control port.");
3432 if (options->ControlPort && !options->HashedControlPassword &&
3433 !options->HashedControlSessionPassword &&
3434 !options->CookieAuthentication) {
3435 log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
3436 "has been configured. This means that any program on your "
3437 "computer can reconfigure your Tor. That's bad! You should "
3438 "upgrade your Tor controller as soon as possible.");
3441 if (options->UseEntryGuards && ! options->NumEntryGuards)
3442 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3444 if (check_nickname_list(options->MyFamily, "MyFamily", msg))
3445 return -1;
3446 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3447 if (check_nickname_list(cl->value, "NodeFamily", msg))
3448 return -1;
3451 if (validate_addr_policies(options, msg) < 0)
3452 return -1;
3454 if (validate_dir_authorities(options, old_options) < 0)
3455 REJECT("Directory authority line did not parse. See logs for details.");
3457 if (options->UseBridges && !options->Bridges)
3458 REJECT("If you set UseBridges, you must specify at least one bridge.");
3459 if (options->UseBridges && !options->TunnelDirConns)
3460 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3461 if (options->Bridges) {
3462 for (cl = options->Bridges; cl; cl = cl->next) {
3463 if (parse_bridge_line(cl->value, 1)<0)
3464 REJECT("Bridge line did not parse. See logs for details.");
3468 if (options->ConstrainedSockets) {
3469 /* If the user wants to constrain socket buffer use, make sure the desired
3470 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3471 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3472 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3473 options->ConstrainedSockSize % 1024) {
3474 r = tor_snprintf(buf, sizeof(buf),
3475 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3476 "in 1024 byte increments.",
3477 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3478 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3479 return -1;
3481 if (options->DirPort) {
3482 /* Providing cached directory entries while system TCP buffers are scarce
3483 * will exacerbate the socket errors. Suggest that this be disabled. */
3484 COMPLAIN("You have requested constrained socket buffers while also "
3485 "serving directory entries via DirPort. It is strongly "
3486 "suggested that you disable serving directory requests when "
3487 "system TCP buffer resources are scarce.");
3491 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3492 options->V3AuthVotingInterval/2) {
3493 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3494 "V3AuthVotingInterval");
3496 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
3497 REJECT("V3AuthVoteDelay is way too low.");
3498 if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
3499 REJECT("V3AuthDistDelay is way too low.");
3501 if (options->V3AuthNIntervalsValid < 2)
3502 REJECT("V3AuthNIntervalsValid must be at least 2.");
3504 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3505 REJECT("V3AuthVotingInterval is insanely low.");
3506 } else if (options->V3AuthVotingInterval > 24*60*60) {
3507 REJECT("V3AuthVotingInterval is insanely high.");
3508 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3509 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3512 if (rend_config_services(options, 1) < 0)
3513 REJECT("Failed to configure rendezvous options. See logs for details.");
3515 /* Parse client-side authorization for hidden services. */
3516 if (rend_parse_service_authorization(options, 1) < 0)
3517 REJECT("Failed to configure client authorization for hidden services. "
3518 "See logs for details.");
3520 if (parse_virtual_addr_network(options->VirtualAddrNetwork, 1, NULL)<0)
3521 return -1;
3523 if (options->PreferTunneledDirConns && !options->TunnelDirConns)
3524 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3526 if (options->AutomapHostsSuffixes) {
3527 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
3529 size_t len = strlen(suf);
3530 if (len && suf[len-1] == '.')
3531 suf[len-1] = '\0';
3535 if (options->TestingTorNetwork && !options->DirServers) {
3536 REJECT("TestingTorNetwork may only be configured in combination with "
3537 "a non-default set of DirServers.");
3540 /*XXXX022 checking for defaults manually like this is a bit fragile.*/
3542 /* Keep changes to hard-coded values synchronous to man page and default
3543 * values table. */
3544 if (options->TestingV3AuthInitialVotingInterval != 30*60 &&
3545 !options->TestingTorNetwork) {
3546 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
3547 "Tor networks!");
3548 } else if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
3549 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3550 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
3551 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3552 "30 minutes.");
3555 if (options->TestingV3AuthInitialVoteDelay != 5*60 &&
3556 !options->TestingTorNetwork) {
3557 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
3558 "Tor networks!");
3559 } else if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
3560 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3563 if (options->TestingV3AuthInitialDistDelay != 5*60 &&
3564 !options->TestingTorNetwork) {
3565 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
3566 "Tor networks!");
3567 } else if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
3568 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3571 if (options->TestingV3AuthInitialVoteDelay +
3572 options->TestingV3AuthInitialDistDelay >=
3573 options->TestingV3AuthInitialVotingInterval/2) {
3574 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3575 "must be less than half TestingV3AuthInitialVotingInterval");
3578 if (options->TestingAuthDirTimeToLearnReachability != 30*60 &&
3579 !options->TestingTorNetwork) {
3580 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
3581 "testing Tor networks!");
3582 } else if (options->TestingAuthDirTimeToLearnReachability < 0) {
3583 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3584 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
3585 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3588 if (options->TestingEstimatedDescriptorPropagationTime != 10*60 &&
3589 !options->TestingTorNetwork) {
3590 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
3591 "testing Tor networks!");
3592 } else if (options->TestingEstimatedDescriptorPropagationTime < 0) {
3593 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3594 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
3595 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3598 if (options->TestingTorNetwork) {
3599 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
3600 "almost unusable in the public Tor network, and is "
3601 "therefore only advised if you are building a "
3602 "testing Tor network!");
3605 return 0;
3606 #undef REJECT
3607 #undef COMPLAIN
3610 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3611 * equal strings. */
3612 static int
3613 opt_streq(const char *s1, const char *s2)
3615 if (!s1 && !s2)
3616 return 1;
3617 else if (s1 && s2 && !strcmp(s1,s2))
3618 return 1;
3619 else
3620 return 0;
3623 /** Check if any of the previous options have changed but aren't allowed to. */
3624 static int
3625 options_transition_allowed(or_options_t *old, or_options_t *new_val,
3626 char **msg)
3628 if (!old)
3629 return 0;
3631 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3632 *msg = tor_strdup("PidFile is not allowed to change.");
3633 return -1;
3636 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3637 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3638 "is not allowed.");
3639 return -1;
3642 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
3643 char buf[1024];
3644 int r = tor_snprintf(buf, sizeof(buf),
3645 "While Tor is running, changing DataDirectory "
3646 "(\"%s\"->\"%s\") is not allowed.",
3647 old->DataDirectory, new_val->DataDirectory);
3648 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3649 return -1;
3652 if (!opt_streq(old->User, new_val->User)) {
3653 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
3654 return -1;
3657 if (!opt_streq(old->Group, new_val->Group)) {
3658 *msg = tor_strdup("While Tor is running, changing Group is not allowed.");
3659 return -1;
3662 if (old->HardwareAccel != new_val->HardwareAccel) {
3663 *msg = tor_strdup("While Tor is running, changing HardwareAccel is "
3664 "not allowed.");
3665 return -1;
3668 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
3669 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
3670 "is not allowed.");
3671 return -1;
3674 return 0;
3677 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3678 * will require us to rotate the cpu and dns workers; else return 0. */
3679 static int
3680 options_transition_affects_workers(or_options_t *old_options,
3681 or_options_t *new_options)
3683 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3684 old_options->NumCpus != new_options->NumCpus ||
3685 old_options->ORPort != new_options->ORPort ||
3686 old_options->ServerDNSSearchDomains !=
3687 new_options->ServerDNSSearchDomains ||
3688 old_options->SafeLogging != new_options->SafeLogging ||
3689 old_options->ClientOnly != new_options->ClientOnly ||
3690 !config_lines_eq(old_options->Logs, new_options->Logs))
3691 return 1;
3693 /* Check whether log options match. */
3695 /* Nothing that changed matters. */
3696 return 0;
3699 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3700 * will require us to generate a new descriptor; else return 0. */
3701 static int
3702 options_transition_affects_descriptor(or_options_t *old_options,
3703 or_options_t *new_options)
3705 /* XXX We can be smarter here. If your DirPort isn't being
3706 * published and you just turned it off, no need to republish. If
3707 * you changed your bandwidthrate but maxadvertisedbandwidth still
3708 * trumps, no need to republish. Etc. */
3709 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3710 !opt_streq(old_options->Nickname,new_options->Nickname) ||
3711 !opt_streq(old_options->Address,new_options->Address) ||
3712 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
3713 old_options->ExitPolicyRejectPrivate !=
3714 new_options->ExitPolicyRejectPrivate ||
3715 old_options->ORPort != new_options->ORPort ||
3716 old_options->DirPort != new_options->DirPort ||
3717 old_options->ClientOnly != new_options->ClientOnly ||
3718 old_options->NoPublish != new_options->NoPublish ||
3719 old_options->_PublishServerDescriptor !=
3720 new_options->_PublishServerDescriptor ||
3721 old_options->BandwidthRate != new_options->BandwidthRate ||
3722 old_options->BandwidthBurst != new_options->BandwidthBurst ||
3723 old_options->MaxAdvertisedBandwidth !=
3724 new_options->MaxAdvertisedBandwidth ||
3725 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
3726 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
3727 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
3728 old_options->AccountingMax != new_options->AccountingMax)
3729 return 1;
3731 return 0;
3734 #ifdef MS_WINDOWS
3735 /** Return the directory on windows where we expect to find our application
3736 * data. */
3737 static char *
3738 get_windows_conf_root(void)
3740 static int is_set = 0;
3741 static char path[MAX_PATH+1];
3743 LPITEMIDLIST idl;
3744 IMalloc *m;
3745 HRESULT result;
3747 if (is_set)
3748 return path;
3750 /* Find X:\documents and settings\username\application data\ .
3751 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3753 #ifdef ENABLE_LOCAL_APPDATA
3754 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
3755 #else
3756 #define APPDATA_PATH CSIDL_APPDATA
3757 #endif
3758 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
3759 GetCurrentDirectory(MAX_PATH, path);
3760 is_set = 1;
3761 log_warn(LD_CONFIG,
3762 "I couldn't find your application data folder: are you "
3763 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3764 path);
3765 return path;
3767 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3768 result = SHGetPathFromIDList(idl, path);
3769 /* Now we need to free the */
3770 SHGetMalloc(&m);
3771 if (m) {
3772 m->lpVtbl->Free(m, idl);
3773 m->lpVtbl->Release(m);
3775 if (!SUCCEEDED(result)) {
3776 return NULL;
3778 strlcat(path,"\\tor",MAX_PATH);
3779 is_set = 1;
3780 return path;
3782 #endif
3784 /** Return the default location for our torrc file. */
3785 static const char *
3786 get_default_conf_file(void)
3788 #ifdef MS_WINDOWS
3789 static char path[MAX_PATH+1];
3790 strlcpy(path, get_windows_conf_root(), MAX_PATH);
3791 strlcat(path,"\\torrc",MAX_PATH);
3792 return path;
3793 #else
3794 return (CONFDIR "/torrc");
3795 #endif
3798 /** Verify whether lst is a string containing valid-looking comma-separated
3799 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3801 static int
3802 check_nickname_list(const char *lst, const char *name, char **msg)
3804 int r = 0;
3805 smartlist_t *sl;
3807 if (!lst)
3808 return 0;
3809 sl = smartlist_create();
3811 smartlist_split_string(sl, lst, ",",
3812 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
3814 SMARTLIST_FOREACH(sl, const char *, s,
3816 if (!is_legal_nickname_or_hexdigest(s)) {
3817 char buf[1024];
3818 int tmp = tor_snprintf(buf, sizeof(buf),
3819 "Invalid nickname '%s' in %s line", s, name);
3820 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
3821 r = -1;
3822 break;
3825 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
3826 smartlist_free(sl);
3827 return r;
3830 /** Learn config file name from command line arguments, or use the default */
3831 static char *
3832 find_torrc_filename(int argc, char **argv,
3833 int *using_default_torrc, int *ignore_missing_torrc)
3835 char *fname=NULL;
3836 int i;
3838 for (i = 1; i < argc; ++i) {
3839 if (i < argc-1 && !strcmp(argv[i],"-f")) {
3840 if (fname) {
3841 log(LOG_WARN, LD_CONFIG, "Duplicate -f options on command line.");
3842 tor_free(fname);
3844 #ifdef MS_WINDOWS
3845 /* XXX one day we might want to extend expand_filename to work
3846 * under Windows as well. */
3847 fname = tor_strdup(argv[i+1]);
3848 #else
3849 fname = expand_filename(argv[i+1]);
3850 #endif
3851 *using_default_torrc = 0;
3852 ++i;
3853 } else if (!strcmp(argv[i],"--ignore-missing-torrc")) {
3854 *ignore_missing_torrc = 1;
3858 if (*using_default_torrc) {
3859 /* didn't find one, try CONFDIR */
3860 const char *dflt = get_default_conf_file();
3861 if (dflt && file_status(dflt) == FN_FILE) {
3862 fname = tor_strdup(dflt);
3863 } else {
3864 #ifndef MS_WINDOWS
3865 char *fn;
3866 fn = expand_filename("~/.torrc");
3867 if (fn && file_status(fn) == FN_FILE) {
3868 fname = fn;
3869 } else {
3870 tor_free(fn);
3871 fname = tor_strdup(dflt);
3873 #else
3874 fname = tor_strdup(dflt);
3875 #endif
3878 return fname;
3881 /** Load torrc from disk, setting torrc_fname if successful */
3882 static char *
3883 load_torrc_from_disk(int argc, char **argv)
3885 char *fname=NULL;
3886 char *cf = NULL;
3887 int using_default_torrc = 1;
3888 int ignore_missing_torrc = 0;
3890 fname = find_torrc_filename(argc, argv,
3891 &using_default_torrc, &ignore_missing_torrc);
3892 tor_assert(fname);
3893 log(LOG_DEBUG, LD_CONFIG, "Opening config file \"%s\"", fname);
3895 tor_free(torrc_fname);
3896 torrc_fname = fname;
3898 /* Open config file */
3899 if (file_status(fname) != FN_FILE ||
3900 !(cf = read_file_to_str(fname,0,NULL))) {
3901 if (using_default_torrc == 1 || ignore_missing_torrc ) {
3902 log(LOG_NOTICE, LD_CONFIG, "Configuration file \"%s\" not present, "
3903 "using reasonable defaults.", fname);
3904 tor_free(fname); /* sets fname to NULL */
3905 torrc_fname = NULL;
3906 cf = tor_strdup("");
3907 } else {
3908 log(LOG_WARN, LD_CONFIG,
3909 "Unable to open configuration file \"%s\".", fname);
3910 goto err;
3914 return cf;
3915 err:
3916 tor_free(fname);
3917 torrc_fname = NULL;
3918 return NULL;
3921 /** Read a configuration file into <b>options</b>, finding the configuration
3922 * file location based on the command line. After loading the file
3923 * call options_init_from_string() to load the config.
3924 * Return 0 if success, -1 if failure. */
3926 options_init_from_torrc(int argc, char **argv)
3928 char *cf=NULL;
3929 int i, retval, command;
3930 static char **backup_argv;
3931 static int backup_argc;
3932 char *command_arg = NULL;
3933 char *errmsg=NULL;
3935 if (argv) { /* first time we're called. save commandline args */
3936 backup_argv = argv;
3937 backup_argc = argc;
3938 } else { /* we're reloading. need to clean up old options first. */
3939 argv = backup_argv;
3940 argc = backup_argc;
3942 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
3943 print_usage();
3944 exit(0);
3946 if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
3947 /* For documenting validating whether we've documented everything. */
3948 list_torrc_options();
3949 exit(0);
3952 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
3953 printf("Tor version %s.\n",get_version());
3954 exit(0);
3957 /* Go through command-line variables */
3958 if (!global_cmdline_options) {
3959 /* Or we could redo the list every time we pass this place.
3960 * It does not really matter */
3961 if (config_get_commandlines(argc, argv, &global_cmdline_options) < 0) {
3962 goto err;
3966 command = CMD_RUN_TOR;
3967 for (i = 1; i < argc; ++i) {
3968 if (!strcmp(argv[i],"--list-fingerprint")) {
3969 command = CMD_LIST_FINGERPRINT;
3970 } else if (!strcmp(argv[i],"--hash-password")) {
3971 command = CMD_HASH_PASSWORD;
3972 command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
3973 ++i;
3974 } else if (!strcmp(argv[i],"--verify-config")) {
3975 command = CMD_VERIFY_CONFIG;
3979 if (command == CMD_HASH_PASSWORD) {
3980 cf = tor_strdup("");
3981 } else {
3982 cf = load_torrc_from_disk(argc, argv);
3983 if (!cf)
3984 goto err;
3987 retval = options_init_from_string(cf, command, command_arg, &errmsg);
3988 tor_free(cf);
3989 if (retval < 0)
3990 goto err;
3992 return 0;
3994 err:
3995 if (errmsg) {
3996 log(LOG_WARN,LD_CONFIG,"%s", errmsg);
3997 tor_free(errmsg);
3999 return -1;
4002 /** Load the options from the configuration in <b>cf</b>, validate
4003 * them for consistency and take actions based on them.
4005 * Return 0 if success, negative on error:
4006 * * -1 for general errors.
4007 * * -2 for failure to parse/validate,
4008 * * -3 for transition not allowed
4009 * * -4 for error while setting the new options
4011 setopt_err_t
4012 options_init_from_string(const char *cf,
4013 int command, const char *command_arg,
4014 char **msg)
4016 or_options_t *oldoptions, *newoptions;
4017 config_line_t *cl;
4018 int retval;
4019 setopt_err_t err = SETOPT_ERR_MISC;
4020 tor_assert(msg);
4022 oldoptions = global_options; /* get_options unfortunately asserts if
4023 this is the first time we run*/
4025 newoptions = tor_malloc_zero(sizeof(or_options_t));
4026 newoptions->_magic = OR_OPTIONS_MAGIC;
4027 options_init(newoptions);
4028 newoptions->command = command;
4029 newoptions->command_arg = command_arg;
4031 /* get config lines, assign them */
4032 retval = config_get_lines(cf, &cl);
4033 if (retval < 0) {
4034 err = SETOPT_ERR_PARSE;
4035 goto err;
4037 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4038 config_free_lines(cl);
4039 if (retval < 0) {
4040 err = SETOPT_ERR_PARSE;
4041 goto err;
4044 /* Go through command-line variables too */
4045 retval = config_assign(&options_format, newoptions,
4046 global_cmdline_options, 0, 0, msg);
4047 if (retval < 0) {
4048 err = SETOPT_ERR_PARSE;
4049 goto err;
4052 /* If this is a testing network configuration, change defaults
4053 * for a list of dependent config options, re-initialize newoptions
4054 * with the new defaults, and assign all options to it second time. */
4055 if (newoptions->TestingTorNetwork) {
4056 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4057 * this? We could, for example, make the parsing algorithm do two passes
4058 * over the configuration. If it finds any "suite" options like
4059 * TestingTorNetwork, it could change the defaults before its second pass.
4060 * Not urgent so long as this seems to work, but at any sign of trouble,
4061 * let's clean it up. -NM */
4063 /* Change defaults. */
4064 int i;
4065 for (i = 0; testing_tor_network_defaults[i].name; ++i) {
4066 config_var_t *new_var = &testing_tor_network_defaults[i];
4067 config_var_t *old_var =
4068 config_find_option(&options_format, new_var->name);
4069 tor_assert(new_var);
4070 tor_assert(old_var);
4071 old_var->initvalue = new_var->initvalue;
4074 /* Clear newoptions and re-initialize them with new defaults. */
4075 config_free(&options_format, newoptions);
4076 newoptions = tor_malloc_zero(sizeof(or_options_t));
4077 newoptions->_magic = OR_OPTIONS_MAGIC;
4078 options_init(newoptions);
4079 newoptions->command = command;
4080 newoptions->command_arg = command_arg;
4082 /* Assign all options a second time. */
4083 retval = config_get_lines(cf, &cl);
4084 if (retval < 0) {
4085 err = SETOPT_ERR_PARSE;
4086 goto err;
4088 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4089 config_free_lines(cl);
4090 if (retval < 0) {
4091 err = SETOPT_ERR_PARSE;
4092 goto err;
4094 retval = config_assign(&options_format, newoptions,
4095 global_cmdline_options, 0, 0, msg);
4096 if (retval < 0) {
4097 err = SETOPT_ERR_PARSE;
4098 goto err;
4102 /* Validate newoptions */
4103 if (options_validate(oldoptions, newoptions, 0, msg) < 0) {
4104 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
4105 goto err;
4108 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
4109 err = SETOPT_ERR_TRANSITION;
4110 goto err;
4113 if (set_options(newoptions, msg)) {
4114 err = SETOPT_ERR_SETTING;
4115 goto err; /* frees and replaces old options */
4118 return SETOPT_OK;
4120 err:
4121 config_free(&options_format, newoptions);
4122 if (*msg) {
4123 int len = strlen(*msg)+256;
4124 char *newmsg = tor_malloc(len);
4126 tor_snprintf(newmsg, len, "Failed to parse/validate config: %s", *msg);
4127 tor_free(*msg);
4128 *msg = newmsg;
4130 return err;
4133 /** Return the location for our configuration file.
4135 const char *
4136 get_torrc_fname(void)
4138 if (torrc_fname)
4139 return torrc_fname;
4140 else
4141 return get_default_conf_file();
4144 /** Adjust the address map mased on the MapAddress elements in the
4145 * configuration <b>options</b>
4147 static void
4148 config_register_addressmaps(or_options_t *options)
4150 smartlist_t *elts;
4151 config_line_t *opt;
4152 char *from, *to;
4154 addressmap_clear_configured();
4155 elts = smartlist_create();
4156 for (opt = options->AddressMap; opt; opt = opt->next) {
4157 smartlist_split_string(elts, opt->value, NULL,
4158 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4159 if (smartlist_len(elts) >= 2) {
4160 from = smartlist_get(elts,0);
4161 to = smartlist_get(elts,1);
4162 if (address_is_invalid_destination(to, 1)) {
4163 log_warn(LD_CONFIG,
4164 "Skipping invalid argument '%s' to MapAddress", to);
4165 } else {
4166 addressmap_register(from, tor_strdup(to), 0, ADDRMAPSRC_TORRC);
4167 if (smartlist_len(elts)>2) {
4168 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
4171 } else {
4172 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
4173 opt->value);
4175 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4176 smartlist_clear(elts);
4178 smartlist_free(elts);
4182 * Initialize the logs based on the configuration file.
4184 static int
4185 options_init_logs(or_options_t *options, int validate_only)
4187 config_line_t *opt;
4188 int ok;
4189 smartlist_t *elts;
4190 int daemon =
4191 #ifdef MS_WINDOWS
4193 #else
4194 options->RunAsDaemon;
4195 #endif
4197 ok = 1;
4198 elts = smartlist_create();
4200 for (opt = options->Logs; opt; opt = opt->next) {
4201 log_severity_list_t *severity;
4202 const char *cfg = opt->value;
4203 severity = tor_malloc_zero(sizeof(log_severity_list_t));
4204 if (parse_log_severity_config(&cfg, severity) < 0) {
4205 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
4206 opt->value);
4207 ok = 0; goto cleanup;
4210 smartlist_split_string(elts, cfg, NULL,
4211 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4213 if (smartlist_len(elts) == 0)
4214 smartlist_add(elts, tor_strdup("stdout"));
4216 if (smartlist_len(elts) == 1 &&
4217 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
4218 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
4219 int err = smartlist_len(elts) &&
4220 !strcasecmp(smartlist_get(elts,0), "stderr");
4221 if (!validate_only) {
4222 if (daemon) {
4223 log_warn(LD_CONFIG,
4224 "Can't log to %s with RunAsDaemon set; skipping stdout",
4225 err?"stderr":"stdout");
4226 } else {
4227 add_stream_log(severity, err?"<stderr>":"<stdout>",
4228 fileno(err?stderr:stdout));
4231 goto cleanup;
4233 if (smartlist_len(elts) == 1 &&
4234 !strcasecmp(smartlist_get(elts,0), "syslog")) {
4235 #ifdef HAVE_SYSLOG_H
4236 if (!validate_only) {
4237 add_syslog_log(severity);
4239 #else
4240 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
4241 #endif
4242 goto cleanup;
4245 if (smartlist_len(elts) == 2 &&
4246 !strcasecmp(smartlist_get(elts,0), "file")) {
4247 if (!validate_only) {
4248 if (add_file_log(severity, smartlist_get(elts, 1)) < 0) {
4249 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
4250 opt->value, strerror(errno));
4251 ok = 0;
4254 goto cleanup;
4257 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
4258 opt->value);
4259 ok = 0; goto cleanup;
4261 cleanup:
4262 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4263 smartlist_clear(elts);
4264 tor_free(severity);
4266 smartlist_free(elts);
4268 return ok?0:-1;
4271 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4272 * if the line is well-formed, and -1 if it isn't. If
4273 * <b>validate_only</b> is 0, and the line is well-formed, then add
4274 * the bridge described in the line to our internal bridge list. */
4275 static int
4276 parse_bridge_line(const char *line, int validate_only)
4278 smartlist_t *items = NULL;
4279 int r;
4280 char *addrport=NULL, *fingerprint=NULL;
4281 tor_addr_t addr;
4282 uint16_t port = 0;
4283 char digest[DIGEST_LEN];
4285 items = smartlist_create();
4286 smartlist_split_string(items, line, NULL,
4287 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4288 if (smartlist_len(items) < 1) {
4289 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
4290 goto err;
4292 addrport = smartlist_get(items, 0);
4293 smartlist_del_keeporder(items, 0);
4294 if (tor_addr_port_parse(addrport, &addr, &port)<0) {
4295 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
4296 goto err;
4298 if (!port) {
4299 log_info(LD_CONFIG,
4300 "Bridge address '%s' has no port; using default port 443.",
4301 addrport);
4302 port = 443;
4305 if (smartlist_len(items)) {
4306 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4307 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4308 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
4309 goto err;
4311 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4312 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
4313 goto err;
4317 if (!validate_only) {
4318 log_debug(LD_DIR, "Bridge at %s:%d (%s)", fmt_addr(&addr),
4319 (int)port,
4320 fingerprint ? fingerprint : "no key listed");
4321 bridge_add_from_config(&addr, port, fingerprint ? digest : NULL);
4324 r = 0;
4325 goto done;
4327 err:
4328 r = -1;
4330 done:
4331 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4332 smartlist_free(items);
4333 tor_free(addrport);
4334 tor_free(fingerprint);
4335 return r;
4338 /** Read the contents of a DirServer line from <b>line</b>. If
4339 * <b>validate_only</b> is 0, and the line is well-formed, and it
4340 * shares any bits with <b>required_type</b> or <b>required_type</b>
4341 * is 0, then add the dirserver described in the line (minus whatever
4342 * bits it's missing) as a valid authority. Return 0 on success,
4343 * or -1 if the line isn't well-formed or if we can't add it. */
4344 static int
4345 parse_dir_server_line(const char *line, authority_type_t required_type,
4346 int validate_only)
4348 smartlist_t *items = NULL;
4349 int r;
4350 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
4351 uint16_t dir_port = 0, or_port = 0;
4352 char digest[DIGEST_LEN];
4353 char v3_digest[DIGEST_LEN];
4354 authority_type_t type = V2_AUTHORITY;
4355 int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
4357 items = smartlist_create();
4358 smartlist_split_string(items, line, NULL,
4359 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4360 if (smartlist_len(items) < 1) {
4361 log_warn(LD_CONFIG, "No arguments on DirServer line.");
4362 goto err;
4365 if (is_legal_nickname(smartlist_get(items, 0))) {
4366 nickname = smartlist_get(items, 0);
4367 smartlist_del_keeporder(items, 0);
4370 while (smartlist_len(items)) {
4371 char *flag = smartlist_get(items, 0);
4372 if (TOR_ISDIGIT(flag[0]))
4373 break;
4374 if (!strcasecmp(flag, "v1")) {
4375 type |= (V1_AUTHORITY | HIDSERV_AUTHORITY);
4376 } else if (!strcasecmp(flag, "hs")) {
4377 type |= HIDSERV_AUTHORITY;
4378 } else if (!strcasecmp(flag, "no-hs")) {
4379 is_not_hidserv_authority = 1;
4380 } else if (!strcasecmp(flag, "bridge")) {
4381 type |= BRIDGE_AUTHORITY;
4382 } else if (!strcasecmp(flag, "no-v2")) {
4383 is_not_v2_authority = 1;
4384 } else if (!strcasecmpstart(flag, "orport=")) {
4385 int ok;
4386 char *portstring = flag + strlen("orport=");
4387 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
4388 if (!ok)
4389 log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
4390 portstring);
4391 } else if (!strcasecmpstart(flag, "v3ident=")) {
4392 char *idstr = flag + strlen("v3ident=");
4393 if (strlen(idstr) != HEX_DIGEST_LEN ||
4394 base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
4395 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirServer line",
4396 flag);
4397 } else {
4398 type |= V3_AUTHORITY;
4400 } else {
4401 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
4402 flag);
4404 tor_free(flag);
4405 smartlist_del_keeporder(items, 0);
4407 if (is_not_hidserv_authority)
4408 type &= ~HIDSERV_AUTHORITY;
4409 if (is_not_v2_authority)
4410 type &= ~V2_AUTHORITY;
4412 if (smartlist_len(items) < 2) {
4413 log_warn(LD_CONFIG, "Too few arguments to DirServer line.");
4414 goto err;
4416 addrport = smartlist_get(items, 0);
4417 smartlist_del_keeporder(items, 0);
4418 if (parse_addr_port(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
4419 log_warn(LD_CONFIG, "Error parsing DirServer address '%s'", addrport);
4420 goto err;
4422 if (!dir_port) {
4423 log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
4424 goto err;
4427 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4428 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4429 log_warn(LD_CONFIG, "Key digest for DirServer is wrong length %d.",
4430 (int)strlen(fingerprint));
4431 goto err;
4433 if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4434 /* a known bad fingerprint. refuse to use it. We can remove this
4435 * clause once Tor 0.1.2.17 is obsolete. */
4436 log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
4437 "torrc file (%s), or reinstall Tor and use the default torrc.",
4438 get_torrc_fname());
4439 goto err;
4441 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4442 log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
4443 goto err;
4446 if (!validate_only && (!required_type || required_type & type)) {
4447 if (required_type)
4448 type &= required_type; /* pare down what we think of them as an
4449 * authority for. */
4450 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
4451 address, (int)dir_port, (char*)smartlist_get(items,0));
4452 if (!add_trusted_dir_server(nickname, address, dir_port, or_port,
4453 digest, v3_digest, type))
4454 goto err;
4457 r = 0;
4458 goto done;
4460 err:
4461 r = -1;
4463 done:
4464 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4465 smartlist_free(items);
4466 tor_free(addrport);
4467 tor_free(address);
4468 tor_free(nickname);
4469 tor_free(fingerprint);
4470 return r;
4473 /** Adjust the value of options->DataDirectory, or fill it in if it's
4474 * absent. Return 0 on success, -1 on failure. */
4475 static int
4476 normalize_data_directory(or_options_t *options)
4478 #ifdef MS_WINDOWS
4479 char *p;
4480 if (options->DataDirectory)
4481 return 0; /* all set */
4482 p = tor_malloc(MAX_PATH);
4483 strlcpy(p,get_windows_conf_root(),MAX_PATH);
4484 options->DataDirectory = p;
4485 return 0;
4486 #else
4487 const char *d = options->DataDirectory;
4488 if (!d)
4489 d = "~/.tor";
4491 if (strncmp(d,"~/",2) == 0) {
4492 char *fn = expand_filename(d);
4493 if (!fn) {
4494 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
4495 return -1;
4497 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
4498 /* If our homedir is /, we probably don't want to use it. */
4499 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4500 * want. */
4501 log_warn(LD_CONFIG,
4502 "Default DataDirectory is \"~/.tor\". This expands to "
4503 "\"%s\", which is probably not what you want. Using "
4504 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
4505 tor_free(fn);
4506 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
4508 tor_free(options->DataDirectory);
4509 options->DataDirectory = fn;
4511 return 0;
4512 #endif
4515 /** Check and normalize the value of options->DataDirectory; return 0 if it
4516 * sane, -1 otherwise. */
4517 static int
4518 validate_data_directory(or_options_t *options)
4520 if (normalize_data_directory(options) < 0)
4521 return -1;
4522 tor_assert(options->DataDirectory);
4523 if (strlen(options->DataDirectory) > (512-128)) {
4524 log_warn(LD_CONFIG, "DataDirectory is too long.");
4525 return -1;
4527 return 0;
4530 /** This string must remain the same forevermore. It is how we
4531 * recognize that the torrc file doesn't need to be backed up. */
4532 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4533 "if you edit it, comments will not be preserved"
4534 /** This string can change; it tries to give the reader an idea
4535 * that editing this file by hand is not a good plan. */
4536 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4537 "to torrc.orig.1 or similar, and Tor will ignore it"
4539 /** Save a configuration file for the configuration in <b>options</b>
4540 * into the file <b>fname</b>. If the file already exists, and
4541 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4542 * replace it. Return 0 on success, -1 on failure. */
4543 static int
4544 write_configuration_file(const char *fname, or_options_t *options)
4546 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4547 int rename_old = 0, r;
4548 size_t len;
4550 tor_assert(fname);
4552 switch (file_status(fname)) {
4553 case FN_FILE:
4554 old_val = read_file_to_str(fname, 0, NULL);
4555 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4556 rename_old = 1;
4558 tor_free(old_val);
4559 break;
4560 case FN_NOENT:
4561 break;
4562 case FN_ERROR:
4563 case FN_DIR:
4564 default:
4565 log_warn(LD_CONFIG,
4566 "Config file \"%s\" is not a file? Failing.", fname);
4567 return -1;
4570 if (!(new_conf = options_dump(options, 1))) {
4571 log_warn(LD_BUG, "Couldn't get configuration string");
4572 goto err;
4575 len = strlen(new_conf)+256;
4576 new_val = tor_malloc(len);
4577 tor_snprintf(new_val, len, "%s\n%s\n\n%s",
4578 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4580 if (rename_old) {
4581 int i = 1;
4582 size_t fn_tmp_len = strlen(fname)+32;
4583 char *fn_tmp;
4584 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4585 fn_tmp = tor_malloc(fn_tmp_len);
4586 while (1) {
4587 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4588 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4589 tor_free(fn_tmp);
4590 goto err;
4592 if (file_status(fn_tmp) == FN_NOENT)
4593 break;
4594 ++i;
4596 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4597 if (rename(fname, fn_tmp) < 0) {
4598 log_warn(LD_FS,
4599 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4600 fname, fn_tmp, strerror(errno));
4601 tor_free(fn_tmp);
4602 goto err;
4604 tor_free(fn_tmp);
4607 if (write_str_to_file(fname, new_val, 0) < 0)
4608 goto err;
4610 r = 0;
4611 goto done;
4612 err:
4613 r = -1;
4614 done:
4615 tor_free(new_val);
4616 tor_free(new_conf);
4617 return r;
4621 * Save the current configuration file value to disk. Return 0 on
4622 * success, -1 on failure.
4625 options_save_current(void)
4627 if (torrc_fname) {
4628 /* This fails if we can't write to our configuration file.
4630 * If we try falling back to datadirectory or something, we have a better
4631 * chance of saving the configuration, but a better chance of doing
4632 * something the user never expected. Let's just warn instead. */
4633 return write_configuration_file(torrc_fname, get_options());
4635 return write_configuration_file(get_default_conf_file(), get_options());
4638 /** Mapping from a unit name to a multiplier for converting that unit into a
4639 * base unit. */
4640 struct unit_table_t {
4641 const char *unit;
4642 uint64_t multiplier;
4645 /** Table to map the names of memory units to the number of bytes they
4646 * contain. */
4647 static struct unit_table_t memory_units[] = {
4648 { "", 1 },
4649 { "b", 1<< 0 },
4650 { "byte", 1<< 0 },
4651 { "bytes", 1<< 0 },
4652 { "kb", 1<<10 },
4653 { "kbyte", 1<<10 },
4654 { "kbytes", 1<<10 },
4655 { "kilobyte", 1<<10 },
4656 { "kilobytes", 1<<10 },
4657 { "m", 1<<20 },
4658 { "mb", 1<<20 },
4659 { "mbyte", 1<<20 },
4660 { "mbytes", 1<<20 },
4661 { "megabyte", 1<<20 },
4662 { "megabytes", 1<<20 },
4663 { "gb", 1<<30 },
4664 { "gbyte", 1<<30 },
4665 { "gbytes", 1<<30 },
4666 { "gigabyte", 1<<30 },
4667 { "gigabytes", 1<<30 },
4668 { "tb", U64_LITERAL(1)<<40 },
4669 { "terabyte", U64_LITERAL(1)<<40 },
4670 { "terabytes", U64_LITERAL(1)<<40 },
4671 { NULL, 0 },
4674 /** Table to map the names of time units to the number of seconds they
4675 * contain. */
4676 static struct unit_table_t time_units[] = {
4677 { "", 1 },
4678 { "second", 1 },
4679 { "seconds", 1 },
4680 { "minute", 60 },
4681 { "minutes", 60 },
4682 { "hour", 60*60 },
4683 { "hours", 60*60 },
4684 { "day", 24*60*60 },
4685 { "days", 24*60*60 },
4686 { "week", 7*24*60*60 },
4687 { "weeks", 7*24*60*60 },
4688 { NULL, 0 },
4691 /** Parse a string <b>val</b> containing a number, zero or more
4692 * spaces, and an optional unit string. If the unit appears in the
4693 * table <b>u</b>, then multiply the number by the unit multiplier.
4694 * On success, set *<b>ok</b> to 1 and return this product.
4695 * Otherwise, set *<b>ok</b> to 0.
4697 static uint64_t
4698 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4700 uint64_t v;
4701 char *cp;
4703 tor_assert(ok);
4705 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4706 if (!*ok)
4707 return 0;
4708 if (!cp) {
4709 *ok = 1;
4710 return v;
4712 while (TOR_ISSPACE(*cp))
4713 ++cp;
4714 for ( ;u->unit;++u) {
4715 if (!strcasecmp(u->unit, cp)) {
4716 v *= u->multiplier;
4717 *ok = 1;
4718 return v;
4721 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4722 *ok = 0;
4723 return 0;
4726 /** Parse a string in the format "number unit", where unit is a unit of
4727 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4728 * and return the number of bytes specified. Otherwise, set
4729 * *<b>ok</b> to false and return 0. */
4730 static uint64_t
4731 config_parse_memunit(const char *s, int *ok)
4733 return config_parse_units(s, memory_units, ok);
4736 /** Parse a string in the format "number unit", where unit is a unit of time.
4737 * On success, set *<b>ok</b> to true and return the number of seconds in
4738 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4740 static int
4741 config_parse_interval(const char *s, int *ok)
4743 uint64_t r;
4744 r = config_parse_units(s, time_units, ok);
4745 if (!ok)
4746 return -1;
4747 if (r > INT_MAX) {
4748 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4749 *ok = 0;
4750 return -1;
4752 return (int)r;
4755 /* This is what passes for version detection on OSX. We set
4756 * MACOSX_KQUEUE_IS_BROKEN to true iff we're on a version of OSX before
4757 * 10.4.0 (aka 1040). */
4758 #ifdef __APPLE__
4759 #ifdef __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__
4760 #define MACOSX_KQUEUE_IS_BROKEN \
4761 (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1040)
4762 #else
4763 #define MACOSX_KQUEUE_IS_BROKEN 0
4764 #endif
4765 #endif
4768 * Initialize the libevent library.
4770 static void
4771 init_libevent(void)
4773 configure_libevent_logging();
4774 /* If the kernel complains that some method (say, epoll) doesn't
4775 * exist, we don't care about it, since libevent will cope.
4777 suppress_libevent_log_msg("Function not implemented");
4778 #ifdef __APPLE__
4779 if (MACOSX_KQUEUE_IS_BROKEN ||
4780 decode_libevent_version(event_get_version(), NULL) < LE_11B) {
4781 setenv("EVENT_NOKQUEUE","1",1);
4783 #endif
4785 /* In libevent versions before 2.0, it's hard to keep binary compatibility
4786 * between upgrades, and unpleasant to detect when the version we compiled
4787 * against is unlike the version we have linked against. Here's how. */
4788 #if defined(_EVENT_VERSION) && defined(HAVE_EVENT_GET_VERSION)
4789 /* We have a header-file version and a function-call version. Easy. */
4790 if (strcmp(_EVENT_VERSION, event_get_version())) {
4791 int compat1 = -1, compat2 = -1;
4792 int verybad, prettybad ;
4793 decode_libevent_version(_EVENT_VERSION, &compat1);
4794 decode_libevent_version(event_get_version(), &compat2);
4795 verybad = compat1 != compat2;
4796 prettybad = (compat1 == -1 || compat2 == -1) && compat1 != compat2;
4798 log(verybad ? LOG_WARN : (prettybad ? LOG_NOTICE : LOG_INFO),
4799 LD_GENERAL, "We were compiled with headers from version %s "
4800 "of Libevent, but we're using a Libevent library that says it's "
4801 "version %s.", _EVENT_VERSION, event_get_version());
4802 if (verybad)
4803 log_warn(LD_GENERAL, "This will almost certainly make Tor crash.");
4804 else if (prettybad)
4805 log_notice(LD_GENERAL, "If Tor crashes, this might be why.");
4806 else
4807 log_info(LD_GENERAL, "I think these versions are binary-compatible.");
4809 #elif defined(HAVE_EVENT_GET_VERSION)
4810 /* event_get_version but no _EVENT_VERSION. We might be in 1.4.0-beta or
4811 earlier, where that's normal. To see whether we were compiled with an
4812 earlier version, let's see whether the struct event defines MIN_HEAP_IDX.
4814 #ifdef HAVE_STRUCT_EVENT_MIN_HEAP_IDX
4815 /* The header files are 1.4.0-beta or later. If the version is not
4816 * 1.4.0-beta, we are incompatible. */
4818 if (strcmp(event_get_version(), "1.4.0-beta")) {
4819 log_warn(LD_GENERAL, "It's a little hard to tell, but you seem to have "
4820 "Libevent 1.4.0-beta header files, whereas you have linked "
4821 "against Libevent %s. This will probably make Tor crash.",
4822 event_get_version());
4825 #else
4826 /* Our headers are 1.3e or earlier. If the library version is not 1.4.x or
4827 later, we're probably fine. */
4829 const char *v = event_get_version();
4830 if ((v[0] == '1' && v[2] == '.' && v[3] > '3') || v[0] > '1') {
4831 log_warn(LD_GENERAL, "It's a little hard to tell, but you seem to have "
4832 "Libevent header file from 1.3e or earlier, whereas you have "
4833 "linked against Libevent %s. This will probably make Tor "
4834 "crash.", event_get_version());
4837 #endif
4839 #elif defined(_EVENT_VERSION)
4840 #warn "_EVENT_VERSION is defined but not get_event_version(): Libevent is odd."
4841 #else
4842 /* Your libevent is ancient. */
4843 #endif
4845 event_init();
4846 suppress_libevent_log_msg(NULL);
4847 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4848 /* Making this a NOTICE for now so we can link bugs to a libevent versions
4849 * or methods better. */
4850 log(LOG_NOTICE, LD_GENERAL,
4851 "Initialized libevent version %s using method %s. Good.",
4852 event_get_version(), event_get_method());
4853 check_libevent_version(event_get_method(), get_options()->ORPort != 0);
4854 #else
4855 log(LOG_NOTICE, LD_GENERAL,
4856 "Initialized old libevent (version 1.0b or earlier).");
4857 log(LOG_WARN, LD_GENERAL,
4858 "You have a *VERY* old version of libevent. It is likely to be buggy; "
4859 "please build Tor with a more recent version.");
4860 #endif
4863 /** Table mapping return value of event_get_version() to le_version_t. */
4864 static const struct {
4865 const char *name; le_version_t version; int bincompat;
4866 } le_version_table[] = {
4867 /* earlier versions don't have get_version. */
4868 { "1.0c", LE_10C, 1},
4869 { "1.0d", LE_10D, 1},
4870 { "1.0e", LE_10E, 1},
4871 { "1.1", LE_11, 1 },
4872 { "1.1a", LE_11A, 1 },
4873 { "1.1b", LE_11B, 1 },
4874 { "1.2", LE_12, 1 },
4875 { "1.2a", LE_12A, 1 },
4876 { "1.3", LE_13, 1 },
4877 { "1.3a", LE_13A, 1 },
4878 { "1.3b", LE_13B, 1 },
4879 { "1.3c", LE_13C, 1 },
4880 { "1.3d", LE_13D, 1 },
4881 { "1.3e", LE_13E, 1 },
4882 { "1.4.0-beta", LE_140, 2 },
4883 { "1.4.1-beta", LE_141, 2 },
4884 { "1.4.2-rc", LE_142, 2 },
4885 { "1.4.3-stable", LE_143, 2 },
4886 { "1.4.4-stable", LE_144, 2 },
4887 { "1.4.5-stable", LE_145, 2 },
4888 { "1.4.6-stable", LE_146, 2 },
4889 { "1.4.7-stable", LE_147, 2 },
4890 { "1.4.8-stable", LE_148, 2 },
4891 { "1.4.99-trunk", LE_1499, 3 },
4892 { NULL, LE_OTHER, 0 }
4895 /** Return the le_version_t for the current version of libevent. If the
4896 * version is very new, return LE_OTHER. If the version is so old that it
4897 * doesn't support event_get_version(), return LE_OLD. */
4898 static le_version_t
4899 decode_libevent_version(const char *v, int *bincompat_out)
4901 int i;
4902 for (i=0; le_version_table[i].name; ++i) {
4903 if (!strcmp(le_version_table[i].name, v)) {
4904 if (bincompat_out)
4905 *bincompat_out = le_version_table[i].bincompat;
4906 return le_version_table[i].version;
4909 if (v[0] != '1' && bincompat_out)
4910 *bincompat_out = 100;
4911 else if (!strcmpstart(v, "1.4") && bincompat_out)
4912 *bincompat_out = 2;
4913 return LE_OTHER;
4916 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4918 * Compare the given libevent method and version to a list of versions
4919 * which are known not to work. Warn the user as appropriate.
4921 static void
4922 check_libevent_version(const char *m, int server)
4924 int buggy = 0, iffy = 0, slow = 0, thread_unsafe = 0;
4925 le_version_t version;
4926 const char *v = event_get_version();
4927 const char *badness = NULL;
4928 const char *sad_os = "";
4930 version = decode_libevent_version(v, NULL);
4932 /* XXX Would it be worthwhile disabling the methods that we know
4933 * are buggy, rather than just warning about them and then proceeding
4934 * to use them? If so, we should probably not wrap this whole thing
4935 * in HAVE_EVENT_GET_VERSION and HAVE_EVENT_GET_METHOD. -RD */
4936 /* XXXX The problem is that it's not trivial to get libevent to change it's
4937 * method once it's initialized, and it's not trivial to tell what method it
4938 * will use without initializing it. I guess we could preemptively disable
4939 * buggy libevent modes based on the version _before_ initializing it,
4940 * though, but then there's no good way (afaict) to warn "I would have used
4941 * kqueue, but instead I'm using select." -NM */
4942 if (!strcmp(m, "kqueue")) {
4943 if (version < LE_11B)
4944 buggy = 1;
4945 } else if (!strcmp(m, "epoll")) {
4946 if (version < LE_11)
4947 iffy = 1;
4948 } else if (!strcmp(m, "poll")) {
4949 if (version < LE_10E)
4950 buggy = 1;
4951 else if (version < LE_11)
4952 slow = 1;
4953 } else if (!strcmp(m, "select")) {
4954 if (version < LE_11)
4955 slow = 1;
4956 } else if (!strcmp(m, "win32")) {
4957 if (version < LE_11B)
4958 buggy = 1;
4961 /* Libevent versions before 1.3b do very badly on operating systems with
4962 * user-space threading implementations. */
4963 #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
4964 if (server && version < LE_13B) {
4965 thread_unsafe = 1;
4966 sad_os = "BSD variants";
4968 #elif defined(__APPLE__) || defined(__darwin__)
4969 if (server && version < LE_13B) {
4970 thread_unsafe = 1;
4971 sad_os = "Mac OS X";
4973 #endif
4975 if (thread_unsafe) {
4976 log(LOG_WARN, LD_GENERAL,
4977 "Libevent version %s often crashes when running a Tor server with %s. "
4978 "Please use the latest version of libevent (1.3b or later)",v,sad_os);
4979 badness = "BROKEN";
4980 } else if (buggy) {
4981 log(LOG_WARN, LD_GENERAL,
4982 "There are serious bugs in using %s with libevent %s. "
4983 "Please use the latest version of libevent.", m, v);
4984 badness = "BROKEN";
4985 } else if (iffy) {
4986 log(LOG_WARN, LD_GENERAL,
4987 "There are minor bugs in using %s with libevent %s. "
4988 "You may want to use the latest version of libevent.", m, v);
4989 badness = "BUGGY";
4990 } else if (slow && server) {
4991 log(LOG_WARN, LD_GENERAL,
4992 "libevent %s can be very slow with %s. "
4993 "When running a server, please use the latest version of libevent.",
4994 v,m);
4995 badness = "SLOW";
4997 if (badness) {
4998 control_event_general_status(LOG_WARN,
4999 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
5000 v, m, badness);
5004 #endif
5006 /** Return the persistent state struct for this Tor. */
5007 or_state_t *
5008 get_or_state(void)
5010 tor_assert(global_state);
5011 return global_state;
5014 /** Return a newly allocated string holding a filename relative to the data
5015 * directory. If <b>sub1</b> is present, it is the first path component after
5016 * the data directory. If <b>sub2</b> is also present, it is the second path
5017 * component after the data directory. If <b>suffix</b> is present, it
5018 * is appended to the filename.
5020 * Examples:
5021 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
5022 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
5023 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
5024 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
5026 * Note: Consider using the get_datadir_fname* macros in or.h.
5028 char *
5029 options_get_datadir_fname2_suffix(or_options_t *options,
5030 const char *sub1, const char *sub2,
5031 const char *suffix)
5033 char *fname = NULL;
5034 size_t len;
5035 tor_assert(options);
5036 tor_assert(options->DataDirectory);
5037 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
5038 len = strlen(options->DataDirectory);
5039 if (sub1) {
5040 len += strlen(sub1)+1;
5041 if (sub2)
5042 len += strlen(sub2)+1;
5044 if (suffix)
5045 len += strlen(suffix);
5046 len++;
5047 fname = tor_malloc(len);
5048 if (sub1) {
5049 if (sub2) {
5050 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
5051 options->DataDirectory, sub1, sub2);
5052 } else {
5053 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
5054 options->DataDirectory, sub1);
5056 } else {
5057 strlcpy(fname, options->DataDirectory, len);
5059 if (suffix)
5060 strlcat(fname, suffix, len);
5061 return fname;
5064 /** Return 0 if every setting in <b>state</b> is reasonable, and a
5065 * permissible transition from <b>old_state</b>. Else warn and return -1.
5066 * Should have no side effects, except for normalizing the contents of
5067 * <b>state</b>.
5069 /* XXX from_setconf is here because of bug 238 */
5070 static int
5071 or_state_validate(or_state_t *old_state, or_state_t *state,
5072 int from_setconf, char **msg)
5074 /* We don't use these; only options do. Still, we need to match that
5075 * signature. */
5076 (void) from_setconf;
5077 (void) old_state;
5079 if (entry_guards_parse_state(state, 0, msg)<0)
5080 return -1;
5082 return 0;
5085 /** Replace the current persistent state with <b>new_state</b> */
5086 static void
5087 or_state_set(or_state_t *new_state)
5089 char *err = NULL;
5090 tor_assert(new_state);
5091 if (global_state)
5092 config_free(&state_format, global_state);
5093 global_state = new_state;
5094 if (entry_guards_parse_state(global_state, 1, &err)<0) {
5095 log_warn(LD_GENERAL,"%s",err);
5096 tor_free(err);
5098 if (rep_hist_load_state(global_state, &err)<0) {
5099 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
5100 tor_free(err);
5104 /** Reload the persistent state from disk, generating a new state as needed.
5105 * Return 0 on success, less than 0 on failure.
5107 static int
5108 or_state_load(void)
5110 or_state_t *new_state = NULL;
5111 char *contents = NULL, *fname;
5112 char *errmsg = NULL;
5113 int r = -1, badstate = 0;
5115 fname = get_datadir_fname("state");
5116 switch (file_status(fname)) {
5117 case FN_FILE:
5118 if (!(contents = read_file_to_str(fname, 0, NULL))) {
5119 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
5120 goto done;
5122 break;
5123 case FN_NOENT:
5124 break;
5125 case FN_ERROR:
5126 case FN_DIR:
5127 default:
5128 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
5129 goto done;
5131 new_state = tor_malloc_zero(sizeof(or_state_t));
5132 new_state->_magic = OR_STATE_MAGIC;
5133 config_init(&state_format, new_state);
5134 if (contents) {
5135 config_line_t *lines=NULL;
5136 int assign_retval;
5137 if (config_get_lines(contents, &lines)<0)
5138 goto done;
5139 assign_retval = config_assign(&state_format, new_state,
5140 lines, 0, 0, &errmsg);
5141 config_free_lines(lines);
5142 if (assign_retval<0)
5143 badstate = 1;
5144 if (errmsg) {
5145 log_warn(LD_GENERAL, "%s", errmsg);
5146 tor_free(errmsg);
5150 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
5151 badstate = 1;
5153 if (errmsg) {
5154 log_warn(LD_GENERAL, "%s", errmsg);
5155 tor_free(errmsg);
5158 if (badstate && !contents) {
5159 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
5160 " This is a bug in Tor.");
5161 goto done;
5162 } else if (badstate && contents) {
5163 int i;
5164 file_status_t status;
5165 size_t len = strlen(fname)+16;
5166 char *fname2 = tor_malloc(len);
5167 for (i = 0; i < 100; ++i) {
5168 tor_snprintf(fname2, len, "%s.%d", fname, i);
5169 status = file_status(fname2);
5170 if (status == FN_NOENT)
5171 break;
5173 if (i == 100) {
5174 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
5175 "state files to move aside. Discarding the old state file.",
5176 fname);
5177 unlink(fname);
5178 } else {
5179 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
5180 "to \"%s\". This could be a bug in Tor; please tell "
5181 "the developers.", fname, fname2);
5182 if (rename(fname, fname2) < 0) {
5183 log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
5184 "OS gave an error of %s", strerror(errno));
5187 tor_free(fname2);
5188 tor_free(contents);
5189 config_free(&state_format, new_state);
5191 new_state = tor_malloc_zero(sizeof(or_state_t));
5192 new_state->_magic = OR_STATE_MAGIC;
5193 config_init(&state_format, new_state);
5194 } else if (contents) {
5195 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
5196 } else {
5197 log_info(LD_GENERAL, "Initialized state");
5199 or_state_set(new_state);
5200 new_state = NULL;
5201 if (!contents) {
5202 global_state->next_write = 0;
5203 or_state_save(time(NULL));
5205 r = 0;
5207 done:
5208 tor_free(fname);
5209 tor_free(contents);
5210 if (new_state)
5211 config_free(&state_format, new_state);
5213 return r;
5216 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
5218 or_state_save(time_t now)
5220 char *state, *contents;
5221 char tbuf[ISO_TIME_LEN+1];
5222 size_t len;
5223 char *fname;
5225 tor_assert(global_state);
5227 if (global_state->next_write > now)
5228 return 0;
5230 /* Call everything else that might dirty the state even more, in order
5231 * to avoid redundant writes. */
5232 entry_guards_update_state(global_state);
5233 rep_hist_update_state(global_state);
5234 if (accounting_is_enabled(get_options()))
5235 accounting_run_housekeeping(now);
5237 global_state->LastWritten = time(NULL);
5238 tor_free(global_state->TorVersion);
5239 len = strlen(get_version())+8;
5240 global_state->TorVersion = tor_malloc(len);
5241 tor_snprintf(global_state->TorVersion, len, "Tor %s", get_version());
5243 state = config_dump(&state_format, global_state, 1, 0);
5244 len = strlen(state)+256;
5245 contents = tor_malloc(len);
5246 format_local_iso_time(tbuf, time(NULL));
5247 tor_snprintf(contents, len,
5248 "# Tor state file last generated on %s local time\n"
5249 "# Other times below are in GMT\n"
5250 "# You *do not* need to edit this file.\n\n%s",
5251 tbuf, state);
5252 tor_free(state);
5253 fname = get_datadir_fname("state");
5254 if (write_str_to_file(fname, contents, 0)<0) {
5255 log_warn(LD_FS, "Unable to write state to file \"%s\"", fname);
5256 tor_free(fname);
5257 tor_free(contents);
5258 return -1;
5260 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
5261 tor_free(fname);
5262 tor_free(contents);
5264 global_state->next_write = TIME_MAX;
5265 return 0;
5268 /** Given a file name check to see whether the file exists but has not been
5269 * modified for a very long time. If so, remove it. */
5270 void
5271 remove_file_if_very_old(const char *fname, time_t now)
5273 #define VERY_OLD_FILE_AGE (28*24*60*60)
5274 struct stat st;
5276 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
5277 char buf[ISO_TIME_LEN+1];
5278 format_local_iso_time(buf, st.st_mtime);
5279 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
5280 "Removing it.", fname, buf);
5281 unlink(fname);
5285 /** Helper to implement GETINFO functions about configuration variables (not
5286 * their values). Given a "config/names" question, set *<b>answer</b> to a
5287 * new string describing the supported configuration variables and their
5288 * types. */
5290 getinfo_helper_config(control_connection_t *conn,
5291 const char *question, char **answer)
5293 (void) conn;
5294 if (!strcmp(question, "config/names")) {
5295 smartlist_t *sl = smartlist_create();
5296 int i;
5297 for (i = 0; _option_vars[i].name; ++i) {
5298 config_var_t *var = &_option_vars[i];
5299 const char *type, *desc;
5300 char *line;
5301 size_t len;
5302 desc = config_find_description(&options_format, var->name);
5303 switch (var->type) {
5304 case CONFIG_TYPE_STRING: type = "String"; break;
5305 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
5306 case CONFIG_TYPE_UINT: type = "Integer"; break;
5307 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
5308 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
5309 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
5310 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
5311 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
5312 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
5313 case CONFIG_TYPE_CSV: type = "CommaList"; break;
5314 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
5315 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
5316 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
5317 default:
5318 case CONFIG_TYPE_OBSOLETE:
5319 type = NULL; break;
5321 if (!type)
5322 continue;
5323 len = strlen(var->name)+strlen(type)+16;
5324 if (desc)
5325 len += strlen(desc);
5326 line = tor_malloc(len);
5327 if (desc)
5328 tor_snprintf(line, len, "%s %s %s\n",var->name,type,desc);
5329 else
5330 tor_snprintf(line, len, "%s %s\n",var->name,type);
5331 smartlist_add(sl, line);
5333 *answer = smartlist_join_strings(sl, "", 0, NULL);
5334 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
5335 smartlist_free(sl);
5337 return 0;