Raise the minimum bandwidth to be a relay from 20000 bytes to 20480
[tor/rransom.git] / src / or / config.c
blobaa61ecf9a56367de74dc4254640e345f496a8c96
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-2008, 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 (options_transition_affects_workers(old_options, options)) {
1333 log_info(LD_GENERAL,
1334 "Worker-related options changed. Rotating workers.");
1335 if (server_mode(options) && !server_mode(old_options)) {
1336 if (init_keys() < 0) {
1337 log_warn(LD_BUG,"Error initializing keys; exiting");
1338 return -1;
1340 ip_address_changed(0);
1341 if (has_completed_circuit || !any_predicted_circuits(time(NULL)))
1342 inform_testing_reachability();
1344 cpuworkers_rotate();
1345 if (dns_reset())
1346 return -1;
1347 } else {
1348 if (dns_reset())
1349 return -1;
1352 if (options->V3AuthoritativeDir && !old_options->V3AuthoritativeDir)
1353 init_keys();
1356 /* Maybe load geoip file */
1357 if (options->GeoIPFile &&
1358 ((!old_options || !opt_streq(old_options->GeoIPFile, options->GeoIPFile))
1359 || !geoip_is_loaded())) {
1360 /* XXXX Don't use this "<default>" junk; make our filename options
1361 * understand prefixes somehow. -NM */
1362 /* XXXX021 Reload GeoIPFile on SIGHUP. -NM */
1363 char *actual_fname = tor_strdup(options->GeoIPFile);
1364 #ifdef WIN32
1365 if (!strcmp(actual_fname, "<default>")) {
1366 const char *conf_root = get_windows_conf_root();
1367 size_t len = strlen(conf_root)+16;
1368 tor_free(actual_fname);
1369 actual_fname = tor_malloc(len+1);
1370 tor_snprintf(actual_fname, len, "%s\\geoip", conf_root);
1372 #endif
1373 geoip_load_file(actual_fname, options);
1374 tor_free(actual_fname);
1376 /* Check if we need to parse and add the EntryNodes config option. */
1377 if (options->EntryNodes &&
1378 (!old_options ||
1379 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
1380 entry_nodes_should_be_added();
1382 /* Since our options changed, we might need to regenerate and upload our
1383 * server descriptor.
1385 if (!old_options ||
1386 options_transition_affects_descriptor(old_options, options))
1387 mark_my_descriptor_dirty();
1389 /* We may need to reschedule some directory stuff if our status changed. */
1390 if (old_options) {
1391 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1392 dirvote_recalculate_timing(options, time(NULL));
1393 if (!bool_eq(directory_fetches_dir_info_early(options),
1394 directory_fetches_dir_info_early(old_options)) ||
1395 !bool_eq(directory_fetches_dir_info_later(options),
1396 directory_fetches_dir_info_later(old_options))) {
1397 /* Make sure update_router_have_min_dir_info gets called. */
1398 router_dir_info_changed();
1399 /* We might need to download a new consensus status later or sooner than
1400 * we had expected. */
1401 update_consensus_networkstatus_fetch_time(time(NULL));
1405 /* Load the webpage we're going to serve everytime someone asks for '/' on
1406 our DirPort. */
1407 tor_free(global_dirfrontpagecontents);
1408 if (options->DirPortFrontPage) {
1409 global_dirfrontpagecontents =
1410 read_file_to_str(options->DirPortFrontPage, 0, NULL);
1411 if (!global_dirfrontpagecontents) {
1412 log_warn(LD_CONFIG,
1413 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1414 options->DirPortFrontPage);
1418 return 0;
1422 * Functions to parse config options
1425 /** If <b>option</b> is an official abbreviation for a longer option,
1426 * return the longer option. Otherwise return <b>option</b>.
1427 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1428 * apply abbreviations that work for the config file and the command line.
1429 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1430 static const char *
1431 expand_abbrev(config_format_t *fmt, const char *option, int command_line,
1432 int warn_obsolete)
1434 int i;
1435 if (! fmt->abbrevs)
1436 return option;
1437 for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
1438 /* Abbreviations are casei. */
1439 if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
1440 (command_line || !fmt->abbrevs[i].commandline_only)) {
1441 if (warn_obsolete && fmt->abbrevs[i].warn) {
1442 log_warn(LD_CONFIG,
1443 "The configuration option '%s' is deprecated; "
1444 "use '%s' instead.",
1445 fmt->abbrevs[i].abbreviated,
1446 fmt->abbrevs[i].full);
1448 return fmt->abbrevs[i].full;
1451 return option;
1454 /** Helper: Read a list of configuration options from the command line.
1455 * If successful, put them in *<b>result</b> and return 0, and return
1456 * -1 and leave *<b>result</b> alone. */
1457 static int
1458 config_get_commandlines(int argc, char **argv, config_line_t **result)
1460 config_line_t *front = NULL;
1461 config_line_t **new = &front;
1462 char *s;
1463 int i = 1;
1465 while (i < argc) {
1466 if (!strcmp(argv[i],"-f") ||
1467 !strcmp(argv[i],"--hash-password")) {
1468 i += 2; /* command-line option with argument. ignore them. */
1469 continue;
1470 } else if (!strcmp(argv[i],"--list-fingerprint") ||
1471 !strcmp(argv[i],"--verify-config") ||
1472 !strcmp(argv[i],"--ignore-missing-torrc") ||
1473 !strcmp(argv[i],"--quiet") ||
1474 !strcmp(argv[i],"--hush")) {
1475 i += 1; /* command-line option. ignore it. */
1476 continue;
1477 } else if (!strcmp(argv[i],"--nt-service") ||
1478 !strcmp(argv[i],"-nt-service")) {
1479 i += 1;
1480 continue;
1483 if (i == argc-1) {
1484 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1485 argv[i]);
1486 config_free_lines(front);
1487 return -1;
1490 *new = tor_malloc_zero(sizeof(config_line_t));
1491 s = argv[i];
1493 while (*s == '-')
1494 s++;
1496 (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1, 1));
1497 (*new)->value = tor_strdup(argv[i+1]);
1498 (*new)->next = NULL;
1499 log(LOG_DEBUG, LD_CONFIG, "Commandline: parsed keyword '%s', value '%s'",
1500 (*new)->key, (*new)->value);
1502 new = &((*new)->next);
1503 i += 2;
1505 *result = front;
1506 return 0;
1509 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1510 * append it to *<b>lst</b>. */
1511 static void
1512 config_line_append(config_line_t **lst,
1513 const char *key,
1514 const char *val)
1516 config_line_t *newline;
1518 newline = tor_malloc(sizeof(config_line_t));
1519 newline->key = tor_strdup(key);
1520 newline->value = tor_strdup(val);
1521 newline->next = NULL;
1522 while (*lst)
1523 lst = &((*lst)->next);
1525 (*lst) = newline;
1528 /** Helper: parse the config string and strdup into key/value
1529 * strings. Set *result to the list, or NULL if parsing the string
1530 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1531 * misformatted lines. */
1533 config_get_lines(const char *string, config_line_t **result)
1535 config_line_t *list = NULL, **next;
1536 char *k, *v;
1538 next = &list;
1539 do {
1540 k = v = NULL;
1541 string = parse_config_line_from_str(string, &k, &v);
1542 if (!string) {
1543 config_free_lines(list);
1544 tor_free(k);
1545 tor_free(v);
1546 return -1;
1548 if (k && v) {
1549 /* This list can get long, so we keep a pointer to the end of it
1550 * rather than using config_line_append over and over and getting
1551 * n^2 performance. */
1552 *next = tor_malloc(sizeof(config_line_t));
1553 (*next)->key = k;
1554 (*next)->value = v;
1555 (*next)->next = NULL;
1556 next = &((*next)->next);
1557 } else {
1558 tor_free(k);
1559 tor_free(v);
1561 } while (*string);
1563 *result = list;
1564 return 0;
1568 * Free all the configuration lines on the linked list <b>front</b>.
1570 void
1571 config_free_lines(config_line_t *front)
1573 config_line_t *tmp;
1575 while (front) {
1576 tmp = front;
1577 front = tmp->next;
1579 tor_free(tmp->key);
1580 tor_free(tmp->value);
1581 tor_free(tmp);
1585 /** Return the description for a given configuration variable, or NULL if no
1586 * description exists. */
1587 static const char *
1588 config_find_description(config_format_t *fmt, const char *name)
1590 int i;
1591 for (i=0; fmt->descriptions[i].name; ++i) {
1592 if (!strcasecmp(name, fmt->descriptions[i].name))
1593 return fmt->descriptions[i].description;
1595 return NULL;
1598 /** If <b>key</b> is a configuration option, return the corresponding
1599 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1600 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1602 static config_var_t *
1603 config_find_option(config_format_t *fmt, const char *key)
1605 int i;
1606 size_t keylen = strlen(key);
1607 if (!keylen)
1608 return NULL; /* if they say "--" on the commandline, it's not an option */
1609 /* First, check for an exact (case-insensitive) match */
1610 for (i=0; fmt->vars[i].name; ++i) {
1611 if (!strcasecmp(key, fmt->vars[i].name)) {
1612 return &fmt->vars[i];
1615 /* If none, check for an abbreviated match */
1616 for (i=0; fmt->vars[i].name; ++i) {
1617 if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
1618 log_warn(LD_CONFIG, "The abbreviation '%s' is deprecated. "
1619 "Please use '%s' instead",
1620 key, fmt->vars[i].name);
1621 return &fmt->vars[i];
1624 /* Okay, unrecognized option */
1625 return NULL;
1629 * Functions to assign config options.
1632 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1633 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1635 * Called from config_assign_line() and option_reset().
1637 static int
1638 config_assign_value(config_format_t *fmt, or_options_t *options,
1639 config_line_t *c, char **msg)
1641 int i, r, ok;
1642 char buf[1024];
1643 config_var_t *var;
1644 void *lvalue;
1646 CHECK(fmt, options);
1648 var = config_find_option(fmt, c->key);
1649 tor_assert(var);
1651 lvalue = STRUCT_VAR_P(options, var->var_offset);
1653 switch (var->type) {
1655 case CONFIG_TYPE_UINT:
1656 i = (int)tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
1657 if (!ok) {
1658 r = tor_snprintf(buf, sizeof(buf),
1659 "Int keyword '%s %s' is malformed or out of bounds.",
1660 c->key, c->value);
1661 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1662 return -1;
1664 *(int *)lvalue = i;
1665 break;
1667 case CONFIG_TYPE_INTERVAL: {
1668 i = config_parse_interval(c->value, &ok);
1669 if (!ok) {
1670 r = tor_snprintf(buf, sizeof(buf),
1671 "Interval '%s %s' is malformed or out of bounds.",
1672 c->key, c->value);
1673 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1674 return -1;
1676 *(int *)lvalue = i;
1677 break;
1680 case CONFIG_TYPE_MEMUNIT: {
1681 uint64_t u64 = config_parse_memunit(c->value, &ok);
1682 if (!ok) {
1683 r = tor_snprintf(buf, sizeof(buf),
1684 "Value '%s %s' is malformed or out of bounds.",
1685 c->key, c->value);
1686 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1687 return -1;
1689 *(uint64_t *)lvalue = u64;
1690 break;
1693 case CONFIG_TYPE_BOOL:
1694 i = (int)tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
1695 if (!ok) {
1696 r = tor_snprintf(buf, sizeof(buf),
1697 "Boolean '%s %s' expects 0 or 1.",
1698 c->key, c->value);
1699 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1700 return -1;
1702 *(int *)lvalue = i;
1703 break;
1705 case CONFIG_TYPE_STRING:
1706 case CONFIG_TYPE_FILENAME:
1707 tor_free(*(char **)lvalue);
1708 *(char **)lvalue = tor_strdup(c->value);
1709 break;
1711 case CONFIG_TYPE_DOUBLE:
1712 *(double *)lvalue = atof(c->value);
1713 break;
1715 case CONFIG_TYPE_ISOTIME:
1716 if (parse_iso_time(c->value, (time_t *)lvalue)) {
1717 r = tor_snprintf(buf, sizeof(buf),
1718 "Invalid time '%s' for keyword '%s'", c->value, c->key);
1719 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1720 return -1;
1722 break;
1724 case CONFIG_TYPE_ROUTERSET:
1725 if (*(routerset_t**)lvalue) {
1726 routerset_free(*(routerset_t**)lvalue);
1728 *(routerset_t**)lvalue = routerset_new();
1729 if (routerset_parse(*(routerset_t**)lvalue, c->value, c->key)<0) {
1730 tor_snprintf(buf, sizeof(buf), "Invalid exit list '%s' for option '%s'",
1731 c->value, c->key);
1732 *msg = tor_strdup(buf);
1733 return -1;
1735 break;
1737 case CONFIG_TYPE_CSV:
1738 if (*(smartlist_t**)lvalue) {
1739 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
1740 smartlist_clear(*(smartlist_t**)lvalue);
1741 } else {
1742 *(smartlist_t**)lvalue = smartlist_create();
1745 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
1746 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1747 break;
1749 case CONFIG_TYPE_LINELIST:
1750 case CONFIG_TYPE_LINELIST_S:
1751 config_line_append((config_line_t**)lvalue, c->key, c->value);
1752 break;
1753 case CONFIG_TYPE_OBSOLETE:
1754 log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
1755 break;
1756 case CONFIG_TYPE_LINELIST_V:
1757 r = tor_snprintf(buf, sizeof(buf),
1758 "You may not provide a value for virtual option '%s'", c->key);
1759 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1760 return -1;
1761 default:
1762 tor_assert(0);
1763 break;
1765 return 0;
1768 /** If <b>c</b> is a syntactically valid configuration line, update
1769 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1770 * key, -2 for bad value.
1772 * If <b>clear_first</b> is set, clear the value first. Then if
1773 * <b>use_defaults</b> is set, set the value to the default.
1775 * Called from config_assign().
1777 static int
1778 config_assign_line(config_format_t *fmt, or_options_t *options,
1779 config_line_t *c, int use_defaults,
1780 int clear_first, char **msg)
1782 config_var_t *var;
1784 CHECK(fmt, options);
1786 var = config_find_option(fmt, c->key);
1787 if (!var) {
1788 if (fmt->extra) {
1789 void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
1790 log_info(LD_CONFIG,
1791 "Found unrecognized option '%s'; saving it.", c->key);
1792 config_line_append((config_line_t**)lvalue, c->key, c->value);
1793 return 0;
1794 } else {
1795 char buf[1024];
1796 int tmp = tor_snprintf(buf, sizeof(buf),
1797 "Unknown option '%s'. Failing.", c->key);
1798 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1799 return -1;
1802 /* Put keyword into canonical case. */
1803 if (strcmp(var->name, c->key)) {
1804 tor_free(c->key);
1805 c->key = tor_strdup(var->name);
1808 if (!strlen(c->value)) {
1809 /* reset or clear it, then return */
1810 if (!clear_first) {
1811 if (var->type == CONFIG_TYPE_LINELIST ||
1812 var->type == CONFIG_TYPE_LINELIST_S) {
1813 /* We got an empty linelist from the torrc or commandline.
1814 As a special case, call this an error. Warn and ignore. */
1815 log_warn(LD_CONFIG,
1816 "Linelist option '%s' has no value. Skipping.", c->key);
1817 } else { /* not already cleared */
1818 option_reset(fmt, options, var, use_defaults);
1821 return 0;
1824 if (config_assign_value(fmt, options, c, msg) < 0)
1825 return -2;
1826 return 0;
1829 /** Restore the option named <b>key</b> in options to its default value.
1830 * Called from config_assign(). */
1831 static void
1832 config_reset_line(config_format_t *fmt, or_options_t *options,
1833 const char *key, int use_defaults)
1835 config_var_t *var;
1837 CHECK(fmt, options);
1839 var = config_find_option(fmt, key);
1840 if (!var)
1841 return; /* give error on next pass. */
1843 option_reset(fmt, options, var, use_defaults);
1846 /** Return true iff key is a valid configuration option. */
1848 option_is_recognized(const char *key)
1850 config_var_t *var = config_find_option(&options_format, key);
1851 return (var != NULL);
1854 /** Return the canonical name of a configuration option, or NULL
1855 * if no such option exists. */
1856 const char *
1857 option_get_canonical_name(const char *key)
1859 config_var_t *var = config_find_option(&options_format, key);
1860 return var ? var->name : NULL;
1863 /** Return a canonicalized list of the options assigned for key.
1865 config_line_t *
1866 option_get_assignment(or_options_t *options, const char *key)
1868 return get_assigned_option(&options_format, options, key, 1);
1871 /** Return true iff value needs to be quoted and escaped to be used in
1872 * a configuration file. */
1873 static int
1874 config_value_needs_escape(const char *value)
1876 if (*value == '\"')
1877 return 1;
1878 while (*value) {
1879 switch (*value)
1881 case '\r':
1882 case '\n':
1883 case '#':
1884 /* Note: quotes and backspaces need special handling when we are using
1885 * quotes, not otherwise, so they don't trigger escaping on their
1886 * own. */
1887 return 1;
1888 default:
1889 if (!TOR_ISPRINT(*value))
1890 return 1;
1892 ++value;
1894 return 0;
1897 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1898 static config_line_t *
1899 config_lines_dup(const config_line_t *inp)
1901 config_line_t *result = NULL;
1902 config_line_t **next_out = &result;
1903 while (inp) {
1904 *next_out = tor_malloc(sizeof(config_line_t));
1905 (*next_out)->key = tor_strdup(inp->key);
1906 (*next_out)->value = tor_strdup(inp->value);
1907 inp = inp->next;
1908 next_out = &((*next_out)->next);
1910 (*next_out) = NULL;
1911 return result;
1914 /** Return newly allocated line or lines corresponding to <b>key</b> in the
1915 * configuration <b>options</b>. If <b>escape_val</b> is true and a
1916 * value needs to be quoted before it's put in a config file, quote and
1917 * escape that value. Return NULL if no such key exists. */
1918 static config_line_t *
1919 get_assigned_option(config_format_t *fmt, void *options,
1920 const char *key, int escape_val)
1922 config_var_t *var;
1923 const void *value;
1924 char buf[32];
1925 config_line_t *result;
1926 tor_assert(options && key);
1928 CHECK(fmt, options);
1930 var = config_find_option(fmt, key);
1931 if (!var) {
1932 log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
1933 return NULL;
1935 value = STRUCT_VAR_P(options, var->var_offset);
1937 result = tor_malloc_zero(sizeof(config_line_t));
1938 result->key = tor_strdup(var->name);
1939 switch (var->type)
1941 case CONFIG_TYPE_STRING:
1942 case CONFIG_TYPE_FILENAME:
1943 if (*(char**)value) {
1944 result->value = tor_strdup(*(char**)value);
1945 } else {
1946 tor_free(result->key);
1947 tor_free(result);
1948 return NULL;
1950 break;
1951 case CONFIG_TYPE_ISOTIME:
1952 if (*(time_t*)value) {
1953 result->value = tor_malloc(ISO_TIME_LEN+1);
1954 format_iso_time(result->value, *(time_t*)value);
1955 } else {
1956 tor_free(result->key);
1957 tor_free(result);
1959 escape_val = 0; /* Can't need escape. */
1960 break;
1961 case CONFIG_TYPE_INTERVAL:
1962 case CONFIG_TYPE_UINT:
1963 /* This means every or_options_t uint or bool element
1964 * needs to be an int. Not, say, a uint16_t or char. */
1965 tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
1966 result->value = tor_strdup(buf);
1967 escape_val = 0; /* Can't need escape. */
1968 break;
1969 case CONFIG_TYPE_MEMUNIT:
1970 tor_snprintf(buf, sizeof(buf), U64_FORMAT,
1971 U64_PRINTF_ARG(*(uint64_t*)value));
1972 result->value = tor_strdup(buf);
1973 escape_val = 0; /* Can't need escape. */
1974 break;
1975 case CONFIG_TYPE_DOUBLE:
1976 tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
1977 result->value = tor_strdup(buf);
1978 escape_val = 0; /* Can't need escape. */
1979 break;
1980 case CONFIG_TYPE_BOOL:
1981 result->value = tor_strdup(*(int*)value ? "1" : "0");
1982 escape_val = 0; /* Can't need escape. */
1983 break;
1984 case CONFIG_TYPE_ROUTERSET:
1985 result->value = routerset_to_string(*(routerset_t**)value);
1986 break;
1987 case CONFIG_TYPE_CSV:
1988 if (*(smartlist_t**)value)
1989 result->value =
1990 smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
1991 else
1992 result->value = tor_strdup("");
1993 break;
1994 case CONFIG_TYPE_OBSOLETE:
1995 log_fn(LOG_PROTOCOL_WARN, LD_CONFIG,
1996 "You asked me for the value of an obsolete config option '%s'.",
1997 key);
1998 tor_free(result->key);
1999 tor_free(result);
2000 return NULL;
2001 case CONFIG_TYPE_LINELIST_S:
2002 log_warn(LD_CONFIG,
2003 "Can't return context-sensitive '%s' on its own", key);
2004 tor_free(result->key);
2005 tor_free(result);
2006 return NULL;
2007 case CONFIG_TYPE_LINELIST:
2008 case CONFIG_TYPE_LINELIST_V:
2009 tor_free(result->key);
2010 tor_free(result);
2011 result = config_lines_dup(*(const config_line_t**)value);
2012 break;
2013 default:
2014 tor_free(result->key);
2015 tor_free(result);
2016 log_warn(LD_BUG,"Unknown type %d for known key '%s'",
2017 var->type, key);
2018 return NULL;
2021 if (escape_val) {
2022 config_line_t *line;
2023 for (line = result; line; line = line->next) {
2024 if (line->value && config_value_needs_escape(line->value)) {
2025 char *newval = esc_for_log(line->value);
2026 tor_free(line->value);
2027 line->value = newval;
2032 return result;
2035 /** Iterate through the linked list of requested options <b>list</b>.
2036 * For each item, convert as appropriate and assign to <b>options</b>.
2037 * If an item is unrecognized, set *msg and return -1 immediately,
2038 * else return 0 for success.
2040 * If <b>clear_first</b>, interpret config options as replacing (not
2041 * extending) their previous values. If <b>clear_first</b> is set,
2042 * then <b>use_defaults</b> to decide if you set to defaults after
2043 * clearing, or make the value 0 or NULL.
2045 * Here are the use cases:
2046 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
2047 * if linelist, replaces current if csv.
2048 * 2. An empty AllowInvalid line in your torrc. Should clear it.
2049 * 3. "RESETCONF AllowInvalid" sets it to default.
2050 * 4. "SETCONF AllowInvalid" makes it NULL.
2051 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
2053 * Use_defaults Clear_first
2054 * 0 0 "append"
2055 * 1 0 undefined, don't use
2056 * 0 1 "set to null first"
2057 * 1 1 "set to defaults first"
2058 * Return 0 on success, -1 on bad key, -2 on bad value.
2060 * As an additional special case, if a LINELIST config option has
2061 * no value and clear_first is 0, then warn and ignore it.
2065 There are three call cases for config_assign() currently.
2067 Case one: Torrc entry
2068 options_init_from_torrc() calls config_assign(0, 0)
2069 calls config_assign_line(0, 0).
2070 if value is empty, calls option_reset(0) and returns.
2071 calls config_assign_value(), appends.
2073 Case two: setconf
2074 options_trial_assign() calls config_assign(0, 1)
2075 calls config_reset_line(0)
2076 calls option_reset(0)
2077 calls option_clear().
2078 calls config_assign_line(0, 1).
2079 if value is empty, returns.
2080 calls config_assign_value(), appends.
2082 Case three: resetconf
2083 options_trial_assign() calls config_assign(1, 1)
2084 calls config_reset_line(1)
2085 calls option_reset(1)
2086 calls option_clear().
2087 calls config_assign_value(default)
2088 calls config_assign_line(1, 1).
2089 returns.
2091 static int
2092 config_assign(config_format_t *fmt, void *options, config_line_t *list,
2093 int use_defaults, int clear_first, char **msg)
2095 config_line_t *p;
2097 CHECK(fmt, options);
2099 /* pass 1: normalize keys */
2100 for (p = list; p; p = p->next) {
2101 const char *full = expand_abbrev(fmt, p->key, 0, 1);
2102 if (strcmp(full,p->key)) {
2103 tor_free(p->key);
2104 p->key = tor_strdup(full);
2108 /* pass 2: if we're reading from a resetting source, clear all
2109 * mentioned config options, and maybe set to their defaults. */
2110 if (clear_first) {
2111 for (p = list; p; p = p->next)
2112 config_reset_line(fmt, options, p->key, use_defaults);
2115 /* pass 3: assign. */
2116 while (list) {
2117 int r;
2118 if ((r=config_assign_line(fmt, options, list, use_defaults,
2119 clear_first, msg)))
2120 return r;
2121 list = list->next;
2123 return 0;
2126 /** Try assigning <b>list</b> to the global options. You do this by duping
2127 * options, assigning list to the new one, then validating it. If it's
2128 * ok, then throw out the old one and stick with the new one. Else,
2129 * revert to old and return failure. Return SETOPT_OK on success, or
2130 * a setopt_err_t on failure.
2132 * If not success, point *<b>msg</b> to a newly allocated string describing
2133 * what went wrong.
2135 setopt_err_t
2136 options_trial_assign(config_line_t *list, int use_defaults,
2137 int clear_first, char **msg)
2139 int r;
2140 or_options_t *trial_options = options_dup(&options_format, get_options());
2142 if ((r=config_assign(&options_format, trial_options,
2143 list, use_defaults, clear_first, msg)) < 0) {
2144 config_free(&options_format, trial_options);
2145 return r;
2148 if (options_validate(get_options(), trial_options, 1, msg) < 0) {
2149 config_free(&options_format, trial_options);
2150 return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2153 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2154 config_free(&options_format, trial_options);
2155 return SETOPT_ERR_TRANSITION;
2158 if (set_options(trial_options, msg)<0) {
2159 config_free(&options_format, trial_options);
2160 return SETOPT_ERR_SETTING;
2163 /* we liked it. put it in place. */
2164 return SETOPT_OK;
2167 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2168 * Called from option_reset() and config_free(). */
2169 static void
2170 option_clear(config_format_t *fmt, or_options_t *options, config_var_t *var)
2172 void *lvalue = STRUCT_VAR_P(options, var->var_offset);
2173 (void)fmt; /* unused */
2174 switch (var->type) {
2175 case CONFIG_TYPE_STRING:
2176 case CONFIG_TYPE_FILENAME:
2177 tor_free(*(char**)lvalue);
2178 break;
2179 case CONFIG_TYPE_DOUBLE:
2180 *(double*)lvalue = 0.0;
2181 break;
2182 case CONFIG_TYPE_ISOTIME:
2183 *(time_t*)lvalue = 0;
2184 case CONFIG_TYPE_INTERVAL:
2185 case CONFIG_TYPE_UINT:
2186 case CONFIG_TYPE_BOOL:
2187 *(int*)lvalue = 0;
2188 break;
2189 case CONFIG_TYPE_MEMUNIT:
2190 *(uint64_t*)lvalue = 0;
2191 break;
2192 case CONFIG_TYPE_ROUTERSET:
2193 if (*(routerset_t**)lvalue) {
2194 routerset_free(*(routerset_t**)lvalue);
2195 *(routerset_t**)lvalue = NULL;
2197 case CONFIG_TYPE_CSV:
2198 if (*(smartlist_t**)lvalue) {
2199 SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
2200 smartlist_free(*(smartlist_t **)lvalue);
2201 *(smartlist_t **)lvalue = NULL;
2203 break;
2204 case CONFIG_TYPE_LINELIST:
2205 case CONFIG_TYPE_LINELIST_S:
2206 config_free_lines(*(config_line_t **)lvalue);
2207 *(config_line_t **)lvalue = NULL;
2208 break;
2209 case CONFIG_TYPE_LINELIST_V:
2210 /* handled by linelist_s. */
2211 break;
2212 case CONFIG_TYPE_OBSOLETE:
2213 break;
2217 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2218 * <b>use_defaults</b>, set it to its default value.
2219 * Called by config_init() and option_reset_line() and option_assign_line(). */
2220 static void
2221 option_reset(config_format_t *fmt, or_options_t *options,
2222 config_var_t *var, int use_defaults)
2224 config_line_t *c;
2225 char *msg = NULL;
2226 CHECK(fmt, options);
2227 option_clear(fmt, options, var); /* clear it first */
2228 if (!use_defaults)
2229 return; /* all done */
2230 if (var->initvalue) {
2231 c = tor_malloc_zero(sizeof(config_line_t));
2232 c->key = tor_strdup(var->name);
2233 c->value = tor_strdup(var->initvalue);
2234 if (config_assign_value(fmt, options, c, &msg) < 0) {
2235 log_warn(LD_BUG, "Failed to assign default: %s", msg);
2236 tor_free(msg); /* if this happens it's a bug */
2238 config_free_lines(c);
2242 /** Print a usage message for tor. */
2243 static void
2244 print_usage(void)
2246 printf(
2247 "Copyright (c) 2001-2004, Roger Dingledine\n"
2248 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2249 "Copyright (c) 2007-2008, The Tor Project, Inc.\n\n"
2250 "tor -f <torrc> [args]\n"
2251 "See man page for options, or https://www.torproject.org/ for "
2252 "documentation.\n");
2255 /** Print all non-obsolete torrc options. */
2256 static void
2257 list_torrc_options(void)
2259 int i;
2260 smartlist_t *lines = smartlist_create();
2261 for (i = 0; _option_vars[i].name; ++i) {
2262 config_var_t *var = &_option_vars[i];
2263 const char *desc;
2264 if (var->type == CONFIG_TYPE_OBSOLETE ||
2265 var->type == CONFIG_TYPE_LINELIST_V)
2266 continue;
2267 desc = config_find_description(&options_format, var->name);
2268 printf("%s\n", var->name);
2269 if (desc) {
2270 wrap_string(lines, desc, 76, " ", " ");
2271 SMARTLIST_FOREACH(lines, char *, cp, {
2272 printf("%s", cp);
2273 tor_free(cp);
2275 smartlist_clear(lines);
2278 smartlist_free(lines);
2281 /** Last value actually set by resolve_my_address. */
2282 static uint32_t last_resolved_addr = 0;
2284 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2285 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2286 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2287 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2288 * public IP address.
2291 resolve_my_address(int warn_severity, or_options_t *options,
2292 uint32_t *addr_out, char **hostname_out)
2294 struct in_addr in;
2295 struct hostent *rent;
2296 char hostname[256];
2297 int explicit_ip=1;
2298 int explicit_hostname=1;
2299 int from_interface=0;
2300 char tmpbuf[INET_NTOA_BUF_LEN];
2301 const char *address = options->Address;
2302 int notice_severity = warn_severity <= LOG_NOTICE ?
2303 LOG_NOTICE : warn_severity;
2305 tor_assert(addr_out);
2307 if (address && *address) {
2308 strlcpy(hostname, address, sizeof(hostname));
2309 } else { /* then we need to guess our address */
2310 explicit_ip = 0; /* it's implicit */
2311 explicit_hostname = 0; /* it's implicit */
2313 if (gethostname(hostname, sizeof(hostname)) < 0) {
2314 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2315 return -1;
2317 log_debug(LD_CONFIG,"Guessed local host name as '%s'",hostname);
2320 /* now we know hostname. resolve it and keep only the IP address */
2322 if (tor_inet_aton(hostname, &in) == 0) {
2323 /* then we have to resolve it */
2324 explicit_ip = 0;
2325 rent = (struct hostent *)gethostbyname(hostname);
2326 if (!rent) {
2327 uint32_t interface_ip;
2329 if (explicit_hostname) {
2330 log_fn(warn_severity, LD_CONFIG,
2331 "Could not resolve local Address '%s'. Failing.", hostname);
2332 return -1;
2334 log_fn(notice_severity, LD_CONFIG,
2335 "Could not resolve guessed local hostname '%s'. "
2336 "Trying something else.", hostname);
2337 if (get_interface_address(warn_severity, &interface_ip)) {
2338 log_fn(warn_severity, LD_CONFIG,
2339 "Could not get local interface IP address. Failing.");
2340 return -1;
2342 from_interface = 1;
2343 in.s_addr = htonl(interface_ip);
2344 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2345 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2346 "local interface. Using that.", tmpbuf);
2347 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2348 } else {
2349 tor_assert(rent->h_length == 4);
2350 memcpy(&in.s_addr, rent->h_addr, rent->h_length);
2352 if (!explicit_hostname &&
2353 is_internal_IP(ntohl(in.s_addr), 0)) {
2354 uint32_t interface_ip;
2356 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2357 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2358 "resolves to a private IP address (%s). Trying something "
2359 "else.", hostname, tmpbuf);
2361 if (get_interface_address(warn_severity, &interface_ip)) {
2362 log_fn(warn_severity, LD_CONFIG,
2363 "Could not get local interface IP address. Too bad.");
2364 } else if (is_internal_IP(interface_ip, 0)) {
2365 struct in_addr in2;
2366 in2.s_addr = htonl(interface_ip);
2367 tor_inet_ntoa(&in2,tmpbuf,sizeof(tmpbuf));
2368 log_fn(notice_severity, LD_CONFIG,
2369 "Interface IP address '%s' is a private address too. "
2370 "Ignoring.", tmpbuf);
2371 } else {
2372 from_interface = 1;
2373 in.s_addr = htonl(interface_ip);
2374 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2375 log_fn(notice_severity, LD_CONFIG,
2376 "Learned IP address '%s' for local interface."
2377 " Using that.", tmpbuf);
2378 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2384 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2385 if (is_internal_IP(ntohl(in.s_addr), 0) &&
2386 options->_PublishServerDescriptor) {
2387 /* make sure we're ok with publishing an internal IP */
2388 if (!options->DirServers && !options->AlternateDirAuthority) {
2389 /* if they are using the default dirservers, disallow internal IPs
2390 * always. */
2391 log_fn(warn_severity, LD_CONFIG,
2392 "Address '%s' resolves to private IP address '%s'. "
2393 "Tor servers that use the default DirServers must have public "
2394 "IP addresses.", hostname, tmpbuf);
2395 return -1;
2397 if (!explicit_ip) {
2398 /* even if they've set their own dirservers, require an explicit IP if
2399 * they're using an internal address. */
2400 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2401 "IP address '%s'. Please set the Address config option to be "
2402 "the IP address you want to use.", hostname, tmpbuf);
2403 return -1;
2407 log_debug(LD_CONFIG, "Resolved Address to '%s'.", tmpbuf);
2408 *addr_out = ntohl(in.s_addr);
2409 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2410 /* Leave this as a notice, regardless of the requested severity,
2411 * at least until dynamic IP address support becomes bulletproof. */
2412 log_notice(LD_NET,
2413 "Your IP address seems to have changed to %s. Updating.",
2414 tmpbuf);
2415 ip_address_changed(0);
2417 if (last_resolved_addr != *addr_out) {
2418 const char *method;
2419 const char *h = hostname;
2420 if (explicit_ip) {
2421 method = "CONFIGURED";
2422 h = NULL;
2423 } else if (explicit_hostname) {
2424 method = "RESOLVED";
2425 } else if (from_interface) {
2426 method = "INTERFACE";
2427 h = NULL;
2428 } else {
2429 method = "GETHOSTNAME";
2431 control_event_server_status(LOG_NOTICE,
2432 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2433 tmpbuf, method, h?"HOSTNAME=":"", h);
2435 last_resolved_addr = *addr_out;
2436 if (hostname_out)
2437 *hostname_out = tor_strdup(hostname);
2438 return 0;
2441 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2442 * on a private network.
2445 is_local_addr(const tor_addr_t *addr)
2447 if (tor_addr_is_internal(addr, 0))
2448 return 1;
2449 /* Check whether ip is on the same /24 as we are. */
2450 if (get_options()->EnforceDistinctSubnets == 0)
2451 return 0;
2452 if (tor_addr_family(addr) == AF_INET) {
2453 /*XXXX022 IP6 what corresponds to an /24? */
2454 uint32_t ip = tor_addr_to_ipv4h(addr);
2456 /* It's possible that this next check will hit before the first time
2457 * resolve_my_address actually succeeds. (For clients, it is likely that
2458 * resolve_my_address will never be called at all). In those cases,
2459 * last_resolved_addr will be 0, and so checking to see whether ip is on
2460 * the same /24 as last_resolved_addr will be the same as checking whether
2461 * it was on net 0, which is already done by is_internal_IP.
2463 if ((last_resolved_addr & 0xffffff00ul) == (ip & 0xffffff00ul))
2464 return 1;
2466 return 0;
2469 /** Called when we don't have a nickname set. Try to guess a good nickname
2470 * based on the hostname, and return it in a newly allocated string. If we
2471 * can't, return NULL and let the caller warn if it wants to. */
2472 static char *
2473 get_default_nickname(void)
2475 static const char * const bad_default_nicknames[] = {
2476 "localhost",
2477 NULL,
2479 char localhostname[256];
2480 char *cp, *out, *outp;
2481 int i;
2483 if (gethostname(localhostname, sizeof(localhostname)) < 0)
2484 return NULL;
2486 /* Put it in lowercase; stop at the first dot. */
2487 if ((cp = strchr(localhostname, '.')))
2488 *cp = '\0';
2489 tor_strlower(localhostname);
2491 /* Strip invalid characters. */
2492 cp = localhostname;
2493 out = outp = tor_malloc(strlen(localhostname) + 1);
2494 while (*cp) {
2495 if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
2496 *outp++ = *cp++;
2497 else
2498 cp++;
2500 *outp = '\0';
2502 /* Enforce length. */
2503 if (strlen(out) > MAX_NICKNAME_LEN)
2504 out[MAX_NICKNAME_LEN]='\0';
2506 /* Check for dumb names. */
2507 for (i = 0; bad_default_nicknames[i]; ++i) {
2508 if (!strcmp(out, bad_default_nicknames[i])) {
2509 tor_free(out);
2510 return NULL;
2514 return out;
2517 /** Release storage held by <b>options</b>. */
2518 static void
2519 config_free(config_format_t *fmt, void *options)
2521 int i;
2523 tor_assert(options);
2525 for (i=0; fmt->vars[i].name; ++i)
2526 option_clear(fmt, options, &(fmt->vars[i]));
2527 if (fmt->extra) {
2528 config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
2529 config_free_lines(*linep);
2530 *linep = NULL;
2532 tor_free(options);
2535 /** Return true iff a and b contain identical keys and values in identical
2536 * order. */
2537 static int
2538 config_lines_eq(config_line_t *a, config_line_t *b)
2540 while (a && b) {
2541 if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
2542 return 0;
2543 a = a->next;
2544 b = b->next;
2546 if (a || b)
2547 return 0;
2548 return 1;
2551 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2552 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2554 static int
2555 option_is_same(config_format_t *fmt,
2556 or_options_t *o1, or_options_t *o2, const char *name)
2558 config_line_t *c1, *c2;
2559 int r = 1;
2560 CHECK(fmt, o1);
2561 CHECK(fmt, o2);
2563 c1 = get_assigned_option(fmt, o1, name, 0);
2564 c2 = get_assigned_option(fmt, o2, name, 0);
2565 r = config_lines_eq(c1, c2);
2566 config_free_lines(c1);
2567 config_free_lines(c2);
2568 return r;
2571 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2572 static or_options_t *
2573 options_dup(config_format_t *fmt, or_options_t *old)
2575 or_options_t *newopts;
2576 int i;
2577 config_line_t *line;
2579 newopts = config_alloc(fmt);
2580 for (i=0; fmt->vars[i].name; ++i) {
2581 if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2582 continue;
2583 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
2584 continue;
2585 line = get_assigned_option(fmt, old, fmt->vars[i].name, 0);
2586 if (line) {
2587 char *msg = NULL;
2588 if (config_assign(fmt, newopts, line, 0, 0, &msg) < 0) {
2589 log_err(LD_BUG, "Config_get_assigned_option() generated "
2590 "something we couldn't config_assign(): %s", msg);
2591 tor_free(msg);
2592 tor_assert(0);
2595 config_free_lines(line);
2597 return newopts;
2600 /** Return a new empty or_options_t. Used for testing. */
2601 or_options_t *
2602 options_new(void)
2604 return config_alloc(&options_format);
2607 /** Set <b>options</b> to hold reasonable defaults for most options.
2608 * Each option defaults to zero. */
2609 void
2610 options_init(or_options_t *options)
2612 config_init(&options_format, options);
2615 /** Set all vars in the configuration object <b>options</b> to their default
2616 * values. */
2617 static void
2618 config_init(config_format_t *fmt, void *options)
2620 int i;
2621 config_var_t *var;
2622 CHECK(fmt, options);
2624 for (i=0; fmt->vars[i].name; ++i) {
2625 var = &fmt->vars[i];
2626 if (!var->initvalue)
2627 continue; /* defaults to NULL or 0 */
2628 option_reset(fmt, options, var, 1);
2632 /** Allocate and return a new string holding the written-out values of the vars
2633 * in 'options'. If 'minimal', do not write out any default-valued vars.
2634 * Else, if comment_defaults, write default values as comments.
2636 static char *
2637 config_dump(config_format_t *fmt, void *options, int minimal,
2638 int comment_defaults)
2640 smartlist_t *elements;
2641 or_options_t *defaults;
2642 config_line_t *line, *assigned;
2643 char *result;
2644 int i;
2645 const char *desc;
2646 char *msg = NULL;
2648 defaults = config_alloc(fmt);
2649 config_init(fmt, defaults);
2651 /* XXX use a 1 here so we don't add a new log line while dumping */
2652 if (fmt->validate_fn(NULL,defaults, 1, &msg) < 0) {
2653 log_err(LD_BUG, "Failed to validate default config.");
2654 tor_free(msg);
2655 tor_assert(0);
2658 elements = smartlist_create();
2659 for (i=0; fmt->vars[i].name; ++i) {
2660 int comment_option = 0;
2661 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
2662 fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2663 continue;
2664 /* Don't save 'hidden' control variables. */
2665 if (!strcmpstart(fmt->vars[i].name, "__"))
2666 continue;
2667 if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
2668 continue;
2669 else if (comment_defaults &&
2670 option_is_same(fmt, options, defaults, fmt->vars[i].name))
2671 comment_option = 1;
2673 desc = config_find_description(fmt, fmt->vars[i].name);
2674 line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name, 1);
2676 if (line && desc) {
2677 /* Only dump the description if there's something to describe. */
2678 wrap_string(elements, desc, 78, "# ", "# ");
2681 for (; line; line = line->next) {
2682 size_t len = strlen(line->key) + strlen(line->value) + 5;
2683 char *tmp;
2684 tmp = tor_malloc(len);
2685 if (tor_snprintf(tmp, len, "%s%s %s\n",
2686 comment_option ? "# " : "",
2687 line->key, line->value)<0) {
2688 log_err(LD_BUG,"Internal error writing option value");
2689 tor_assert(0);
2691 smartlist_add(elements, tmp);
2693 config_free_lines(assigned);
2696 if (fmt->extra) {
2697 line = *(config_line_t**)STRUCT_VAR_P(options, fmt->extra->var_offset);
2698 for (; line; line = line->next) {
2699 size_t len = strlen(line->key) + strlen(line->value) + 3;
2700 char *tmp;
2701 tmp = tor_malloc(len);
2702 if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
2703 log_err(LD_BUG,"Internal error writing option value");
2704 tor_assert(0);
2706 smartlist_add(elements, tmp);
2710 result = smartlist_join_strings(elements, "", 0, NULL);
2711 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2712 smartlist_free(elements);
2713 config_free(fmt, defaults);
2714 return result;
2717 /** Return a string containing a possible configuration file that would give
2718 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2719 * include options that are the same as Tor's defaults.
2721 static char *
2722 options_dump(or_options_t *options, int minimal)
2724 return config_dump(&options_format, options, minimal, 0);
2727 /** Return 0 if every element of sl is a string holding a decimal
2728 * representation of a port number, or if sl is NULL.
2729 * Otherwise set *msg and return -1. */
2730 static int
2731 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2733 int i;
2734 char buf[1024];
2735 tor_assert(name);
2737 if (!sl)
2738 return 0;
2740 SMARTLIST_FOREACH(sl, const char *, cp,
2742 i = atoi(cp);
2743 if (i < 1 || i > 65535) {
2744 int r = tor_snprintf(buf, sizeof(buf),
2745 "Port '%s' out of range in %s", cp, name);
2746 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2747 return -1;
2750 return 0;
2753 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2754 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2755 * Else return 0.
2757 static int
2758 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2760 int r;
2761 char buf[1024];
2762 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2763 /* This handles an understandable special case where somebody says "2gb"
2764 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2765 --*value;
2767 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2768 r = tor_snprintf(buf, sizeof(buf), "%s ("U64_FORMAT") must be at most %d",
2769 desc, U64_PRINTF_ARG(*value),
2770 ROUTER_MAX_DECLARED_BANDWIDTH);
2771 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2772 return -1;
2774 return 0;
2777 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2778 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2779 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2780 * Treat "0" as "".
2781 * Return 0 on success or -1 if not a recognized authority type (in which
2782 * case the value of _PublishServerDescriptor is undefined). */
2783 static int
2784 compute_publishserverdescriptor(or_options_t *options)
2786 smartlist_t *list = options->PublishServerDescriptor;
2787 authority_type_t *auth = &options->_PublishServerDescriptor;
2788 *auth = NO_AUTHORITY;
2789 if (!list) /* empty list, answer is none */
2790 return 0;
2791 SMARTLIST_FOREACH(list, const char *, string, {
2792 if (!strcasecmp(string, "v1"))
2793 *auth |= V1_AUTHORITY;
2794 else if (!strcmp(string, "1"))
2795 if (options->BridgeRelay)
2796 *auth |= BRIDGE_AUTHORITY;
2797 else
2798 *auth |= V2_AUTHORITY | V3_AUTHORITY;
2799 else if (!strcasecmp(string, "v2"))
2800 *auth |= V2_AUTHORITY;
2801 else if (!strcasecmp(string, "v3"))
2802 *auth |= V3_AUTHORITY;
2803 else if (!strcasecmp(string, "bridge"))
2804 *auth |= BRIDGE_AUTHORITY;
2805 else if (!strcasecmp(string, "hidserv"))
2806 *auth |= HIDSERV_AUTHORITY;
2807 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2808 /* no authority */;
2809 else
2810 return -1;
2812 return 0;
2815 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2816 * services can overload the directory system. */
2817 #define MIN_REND_POST_PERIOD (10*60)
2819 /** Highest allowable value for RendPostPeriod. */
2820 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2822 /** Lowest allowable value for CircuitBuildTimeout; values too low will
2823 * increase network load because of failing connections being retried, and
2824 * might prevent users from connecting to the network at all. */
2825 #define MIN_CIRCUIT_BUILD_TIMEOUT 30
2827 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2828 * will generate too many circuits and potentially overload the network. */
2829 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2831 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2832 * permissible transition from <b>old_options</b>. Else return -1.
2833 * Should have no side effects, except for normalizing the contents of
2834 * <b>options</b>.
2836 * On error, tor_strdup an error explanation into *<b>msg</b>.
2838 * XXX
2839 * If <b>from_setconf</b>, we were called by the controller, and our
2840 * Log line should stay empty. If it's 0, then give us a default log
2841 * if there are no logs defined.
2843 static int
2844 options_validate(or_options_t *old_options, or_options_t *options,
2845 int from_setconf, char **msg)
2847 int i, r;
2848 config_line_t *cl;
2849 const char *uname = get_uname();
2850 char buf[1024];
2851 #define REJECT(arg) \
2852 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2853 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2855 tor_assert(msg);
2856 *msg = NULL;
2858 if (options->ORPort < 0 || options->ORPort > 65535)
2859 REJECT("ORPort option out of bounds.");
2861 if (server_mode(options) &&
2862 (!strcmpstart(uname, "Windows 95") ||
2863 !strcmpstart(uname, "Windows 98") ||
2864 !strcmpstart(uname, "Windows Me"))) {
2865 log(LOG_WARN, LD_CONFIG, "Tor is running as a server, but you are "
2866 "running %s; this probably won't work. See "
2867 "http://wiki.noreply.org/noreply/TheOnionRouter/TorFAQ#ServerOS "
2868 "for details.", uname);
2871 if (options->ORPort == 0 && options->ORListenAddress != NULL)
2872 REJECT("ORPort must be defined if ORListenAddress is defined.");
2874 if (options->DirPort == 0 && options->DirListenAddress != NULL)
2875 REJECT("DirPort must be defined if DirListenAddress is defined.");
2877 if (options->DNSPort == 0 && options->DNSListenAddress != NULL)
2878 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
2880 if (options->ControlPort == 0 && options->ControlListenAddress != NULL)
2881 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
2883 if (options->TransPort == 0 && options->TransListenAddress != NULL)
2884 REJECT("TransPort must be defined if TransListenAddress is defined.");
2886 if (options->NatdPort == 0 && options->NatdListenAddress != NULL)
2887 REJECT("NatdPort must be defined if NatdListenAddress is defined.");
2889 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
2890 * configuration does this. */
2892 for (i = 0; i < 3; ++i) {
2893 int is_socks = i==0;
2894 int is_trans = i==1;
2895 config_line_t *line, *opt, *old;
2896 const char *tp;
2897 if (is_socks) {
2898 opt = options->SocksListenAddress;
2899 old = old_options ? old_options->SocksListenAddress : NULL;
2900 tp = "SOCKS proxy";
2901 } else if (is_trans) {
2902 opt = options->TransListenAddress;
2903 old = old_options ? old_options->TransListenAddress : NULL;
2904 tp = "transparent proxy";
2905 } else {
2906 opt = options->NatdListenAddress;
2907 old = old_options ? old_options->NatdListenAddress : NULL;
2908 tp = "natd proxy";
2911 for (line = opt; line; line = line->next) {
2912 char *address = NULL;
2913 uint16_t port;
2914 uint32_t addr;
2915 if (parse_addr_port(LOG_WARN, line->value, &address, &addr, &port)<0)
2916 continue; /* We'll warn about this later. */
2917 if (!is_internal_IP(addr, 1) &&
2918 (!old_options || !config_lines_eq(old, opt))) {
2919 log_warn(LD_CONFIG,
2920 "You specified a public address '%s' for a %s. Other "
2921 "people on the Internet might find your computer and use it as "
2922 "an open %s. Please don't allow this unless you have "
2923 "a good reason.", address, tp, tp);
2925 tor_free(address);
2929 if (validate_data_directory(options)<0)
2930 REJECT("Invalid DataDirectory");
2932 if (options->Nickname == NULL) {
2933 if (server_mode(options)) {
2934 if (!(options->Nickname = get_default_nickname())) {
2935 log_notice(LD_CONFIG, "Couldn't pick a nickname based on "
2936 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME);
2937 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
2938 } else {
2939 log_notice(LD_CONFIG, "Choosing default nickname '%s'",
2940 options->Nickname);
2943 } else {
2944 if (!is_legal_nickname(options->Nickname)) {
2945 r = tor_snprintf(buf, sizeof(buf),
2946 "Nickname '%s' is wrong length or contains illegal characters.",
2947 options->Nickname);
2948 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2949 return -1;
2953 if (server_mode(options) && !options->ContactInfo)
2954 log(LOG_NOTICE, LD_CONFIG, "Your ContactInfo config option is not set. "
2955 "Please consider setting it, so we can contact you if your server is "
2956 "misconfigured or something else goes wrong.");
2958 /* Special case on first boot if no Log options are given. */
2959 if (!options->Logs && !options->RunAsDaemon && !from_setconf)
2960 config_line_append(&options->Logs, "Log", "notice stdout");
2962 if (options_init_logs(options, 1)<0) /* Validate the log(s) */
2963 REJECT("Failed to validate Log options. See logs for details.");
2965 if (options->NoPublish) {
2966 log(LOG_WARN, LD_CONFIG,
2967 "NoPublish is obsolete. Use PublishServerDescriptor instead.");
2968 SMARTLIST_FOREACH(options->PublishServerDescriptor, char *, s,
2969 tor_free(s));
2970 smartlist_clear(options->PublishServerDescriptor);
2973 if (authdir_mode(options)) {
2974 /* confirm that our address isn't broken, so we can complain now */
2975 uint32_t tmp;
2976 if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
2977 REJECT("Failed to resolve/guess local address. See logs for details.");
2980 #ifndef MS_WINDOWS
2981 if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
2982 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
2983 #endif
2985 if (options->SocksPort < 0 || options->SocksPort > 65535)
2986 REJECT("SocksPort option out of bounds.");
2988 if (options->DNSPort < 0 || options->DNSPort > 65535)
2989 REJECT("DNSPort option out of bounds.");
2991 if (options->TransPort < 0 || options->TransPort > 65535)
2992 REJECT("TransPort option out of bounds.");
2994 if (options->NatdPort < 0 || options->NatdPort > 65535)
2995 REJECT("NatdPort option out of bounds.");
2997 if (options->SocksPort == 0 && options->TransPort == 0 &&
2998 options->NatdPort == 0 && options->ORPort == 0 &&
2999 options->DNSPort == 0 && !options->RendConfigLines)
3000 log(LOG_WARN, LD_CONFIG,
3001 "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
3002 "undefined, and there aren't any hidden services configured. "
3003 "Tor will still run, but probably won't do anything.");
3005 if (options->ControlPort < 0 || options->ControlPort > 65535)
3006 REJECT("ControlPort option out of bounds.");
3008 if (options->DirPort < 0 || options->DirPort > 65535)
3009 REJECT("DirPort option out of bounds.");
3011 #ifndef USE_TRANSPARENT
3012 if (options->TransPort || options->TransListenAddress)
3013 REJECT("TransPort and TransListenAddress are disabled in this build.");
3014 #endif
3016 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3017 options->_ExcludeExitNodesUnion = routerset_new();
3018 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeExitNodes);
3019 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeNodes);
3022 if (options->StrictExitNodes &&
3023 (!options->ExitNodes) &&
3024 (!old_options ||
3025 (old_options->StrictExitNodes != options->StrictExitNodes) ||
3026 (!routerset_equal(old_options->ExitNodes,options->ExitNodes))))
3027 COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
3029 if (options->StrictEntryNodes &&
3030 (!options->EntryNodes) &&
3031 (!old_options ||
3032 (old_options->StrictEntryNodes != options->StrictEntryNodes) ||
3033 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
3034 COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
3036 if (options->EntryNodes && !routerset_is_list(options->EntryNodes)) {
3037 /* XXXX fix this; see entry_guards_prepend_from_config(). */
3038 REJECT("IPs or countries are not yet supported in EntryNodes.");
3041 if (options->AuthoritativeDir) {
3042 if (!options->ContactInfo && !options->TestingTorNetwork)
3043 REJECT("Authoritative directory servers must set ContactInfo");
3044 if (options->V1AuthoritativeDir && !options->RecommendedVersions)
3045 REJECT("V1 auth dir servers must set RecommendedVersions.");
3046 if (!options->RecommendedClientVersions)
3047 options->RecommendedClientVersions =
3048 config_lines_dup(options->RecommendedVersions);
3049 if (!options->RecommendedServerVersions)
3050 options->RecommendedServerVersions =
3051 config_lines_dup(options->RecommendedVersions);
3052 if (options->VersioningAuthoritativeDir &&
3053 (!options->RecommendedClientVersions ||
3054 !options->RecommendedServerVersions))
3055 REJECT("Versioning auth dir servers must set Recommended*Versions.");
3056 if (options->UseEntryGuards) {
3057 log_info(LD_CONFIG, "Authoritative directory servers can't set "
3058 "UseEntryGuards. Disabling.");
3059 options->UseEntryGuards = 0;
3061 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
3062 log_info(LD_CONFIG, "Authoritative directories always try to download "
3063 "extra-info documents. Setting DownloadExtraInfo.");
3064 options->DownloadExtraInfo = 1;
3066 if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
3067 options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
3068 options->V3AuthoritativeDir))
3069 REJECT("AuthoritativeDir is set, but none of "
3070 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
3073 if (options->AuthoritativeDir && !options->DirPort)
3074 REJECT("Running as authoritative directory, but no DirPort set.");
3076 if (options->AuthoritativeDir && !options->ORPort)
3077 REJECT("Running as authoritative directory, but no ORPort set.");
3079 if (options->AuthoritativeDir && options->ClientOnly)
3080 REJECT("Running as authoritative directory, but ClientOnly also set.");
3082 if (options->HSAuthorityRecordStats && !options->HSAuthoritativeDir)
3083 REJECT("HSAuthorityRecordStats is set but we're not running as "
3084 "a hidden service authority.");
3086 if (options->ConnLimit <= 0) {
3087 r = tor_snprintf(buf, sizeof(buf),
3088 "ConnLimit must be greater than 0, but was set to %d",
3089 options->ConnLimit);
3090 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3091 return -1;
3094 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3095 return -1;
3097 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3098 return -1;
3100 if (validate_ports_csv(options->RejectPlaintextPorts,
3101 "RejectPlaintextPorts", msg) < 0)
3102 return -1;
3104 if (validate_ports_csv(options->WarnPlaintextPorts,
3105 "WarnPlaintextPorts", msg) < 0)
3106 return -1;
3108 if (options->FascistFirewall && !options->ReachableAddresses) {
3109 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3110 /* We already have firewall ports set, so migrate them to
3111 * ReachableAddresses, which will set ReachableORAddresses and
3112 * ReachableDirAddresses if they aren't set explicitly. */
3113 smartlist_t *instead = smartlist_create();
3114 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3115 new_line->key = tor_strdup("ReachableAddresses");
3116 /* If we're configured with the old format, we need to prepend some
3117 * open ports. */
3118 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3120 int p = atoi(portno);
3121 char *s;
3122 if (p<0) continue;
3123 s = tor_malloc(16);
3124 tor_snprintf(s, 16, "*:%d", p);
3125 smartlist_add(instead, s);
3127 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3128 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3129 log(LOG_NOTICE, LD_CONFIG,
3130 "Converting FascistFirewall and FirewallPorts "
3131 "config options to new format: \"ReachableAddresses %s\"",
3132 new_line->value);
3133 options->ReachableAddresses = new_line;
3134 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3135 smartlist_free(instead);
3136 } else {
3137 /* We do not have FirewallPorts set, so add 80 to
3138 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3139 if (!options->ReachableDirAddresses) {
3140 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3141 new_line->key = tor_strdup("ReachableDirAddresses");
3142 new_line->value = tor_strdup("*:80");
3143 options->ReachableDirAddresses = new_line;
3144 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3145 "to new format: \"ReachableDirAddresses *:80\"");
3147 if (!options->ReachableORAddresses) {
3148 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3149 new_line->key = tor_strdup("ReachableORAddresses");
3150 new_line->value = tor_strdup("*:443");
3151 options->ReachableORAddresses = new_line;
3152 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3153 "to new format: \"ReachableORAddresses *:443\"");
3158 for (i=0; i<3; i++) {
3159 config_line_t **linep =
3160 (i==0) ? &options->ReachableAddresses :
3161 (i==1) ? &options->ReachableORAddresses :
3162 &options->ReachableDirAddresses;
3163 if (!*linep)
3164 continue;
3165 /* We need to end with a reject *:*, not an implicit accept *:* */
3166 for (;;) {
3167 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
3168 break;
3169 linep = &((*linep)->next);
3170 if (!*linep) {
3171 *linep = tor_malloc_zero(sizeof(config_line_t));
3172 (*linep)->key = tor_strdup(
3173 (i==0) ? "ReachableAddresses" :
3174 (i==1) ? "ReachableORAddresses" :
3175 "ReachableDirAddresses");
3176 (*linep)->value = tor_strdup("reject *:*");
3177 break;
3182 if ((options->ReachableAddresses ||
3183 options->ReachableORAddresses ||
3184 options->ReachableDirAddresses) &&
3185 server_mode(options))
3186 REJECT("Servers must be able to freely connect to the rest "
3187 "of the Internet, so they must not set Reachable*Addresses "
3188 "or FascistFirewall.");
3190 if (options->UseBridges &&
3191 server_mode(options))
3192 REJECT("Servers must be able to freely connect to the rest "
3193 "of the Internet, so they must not set UseBridges.");
3195 options->_AllowInvalid = 0;
3196 if (options->AllowInvalidNodes) {
3197 SMARTLIST_FOREACH(options->AllowInvalidNodes, const char *, cp, {
3198 if (!strcasecmp(cp, "entry"))
3199 options->_AllowInvalid |= ALLOW_INVALID_ENTRY;
3200 else if (!strcasecmp(cp, "exit"))
3201 options->_AllowInvalid |= ALLOW_INVALID_EXIT;
3202 else if (!strcasecmp(cp, "middle"))
3203 options->_AllowInvalid |= ALLOW_INVALID_MIDDLE;
3204 else if (!strcasecmp(cp, "introduction"))
3205 options->_AllowInvalid |= ALLOW_INVALID_INTRODUCTION;
3206 else if (!strcasecmp(cp, "rendezvous"))
3207 options->_AllowInvalid |= ALLOW_INVALID_RENDEZVOUS;
3208 else {
3209 r = tor_snprintf(buf, sizeof(buf),
3210 "Unrecognized value '%s' in AllowInvalidNodes", cp);
3211 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3212 return -1;
3217 if (compute_publishserverdescriptor(options) < 0) {
3218 r = tor_snprintf(buf, sizeof(buf),
3219 "Unrecognized value in PublishServerDescriptor");
3220 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3221 return -1;
3224 if (options->MinUptimeHidServDirectoryV2 < 0) {
3225 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3226 "least 0 seconds. Changing to 0.");
3227 options->MinUptimeHidServDirectoryV2 = 0;
3230 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
3231 log(LOG_WARN,LD_CONFIG,"RendPostPeriod option is too short; "
3232 "raising to %d seconds.", MIN_REND_POST_PERIOD);
3233 options->RendPostPeriod = MIN_REND_POST_PERIOD;
3236 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3237 log(LOG_WARN, LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3238 MAX_DIR_PERIOD);
3239 options->RendPostPeriod = MAX_DIR_PERIOD;
3242 if (options->CircuitBuildTimeout < MIN_CIRCUIT_BUILD_TIMEOUT) {
3243 log(LOG_WARN, LD_CONFIG, "CircuitBuildTimeout option is too short; "
3244 "raising to %d seconds.", MIN_CIRCUIT_BUILD_TIMEOUT);
3245 options->CircuitBuildTimeout = MIN_CIRCUIT_BUILD_TIMEOUT;
3248 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3249 log(LOG_WARN, LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3250 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3251 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3254 if (options->KeepalivePeriod < 1)
3255 REJECT("KeepalivePeriod option must be positive.");
3257 if (ensure_bandwidth_cap(&options->BandwidthRate,
3258 "BandwidthRate", msg) < 0)
3259 return -1;
3260 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3261 "BandwidthBurst", msg) < 0)
3262 return -1;
3263 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3264 "MaxAdvertisedBandwidth", msg) < 0)
3265 return -1;
3266 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3267 "RelayBandwidthRate", msg) < 0)
3268 return -1;
3269 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3270 "RelayBandwidthBurst", msg) < 0)
3271 return -1;
3273 if (server_mode(options)) {
3274 if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3275 r = tor_snprintf(buf, sizeof(buf),
3276 "BandwidthRate is set to %d bytes/second. "
3277 "For servers, it must be at least %d.",
3278 (int)options->BandwidthRate,
3279 ROUTER_REQUIRED_MIN_BANDWIDTH);
3280 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3281 return -1;
3282 } else if (options->MaxAdvertisedBandwidth <
3283 ROUTER_REQUIRED_MIN_BANDWIDTH/2) {
3284 r = tor_snprintf(buf, sizeof(buf),
3285 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3286 "For servers, it must be at least %d.",
3287 (int)options->MaxAdvertisedBandwidth,
3288 ROUTER_REQUIRED_MIN_BANDWIDTH/2);
3289 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3290 return -1;
3292 if (options->RelayBandwidthRate &&
3293 options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3294 r = tor_snprintf(buf, sizeof(buf),
3295 "RelayBandwidthRate is set to %d bytes/second. "
3296 "For servers, it must be at least %d.",
3297 (int)options->RelayBandwidthRate,
3298 ROUTER_REQUIRED_MIN_BANDWIDTH);
3299 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3300 return -1;
3304 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3305 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3307 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3308 REJECT("RelayBandwidthBurst must be at least equal "
3309 "to RelayBandwidthRate.");
3311 if (options->BandwidthRate > options->BandwidthBurst)
3312 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3314 /* if they set relaybandwidth* really high but left bandwidth*
3315 * at the default, raise the defaults. */
3316 if (options->RelayBandwidthRate > options->BandwidthRate)
3317 options->BandwidthRate = options->RelayBandwidthRate;
3318 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3319 options->BandwidthBurst = options->RelayBandwidthBurst;
3321 if (accounting_parse_options(options, 1)<0)
3322 REJECT("Failed to parse accounting options. See logs for details.");
3324 if (options->HttpProxy) { /* parse it now */
3325 if (parse_addr_port(LOG_WARN, options->HttpProxy, NULL,
3326 &options->HttpProxyAddr, &options->HttpProxyPort) < 0)
3327 REJECT("HttpProxy failed to parse or resolve. Please fix.");
3328 if (options->HttpProxyPort == 0) { /* give it a default */
3329 options->HttpProxyPort = 80;
3333 if (options->HttpProxyAuthenticator) {
3334 if (strlen(options->HttpProxyAuthenticator) >= 48)
3335 REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
3338 if (options->HttpsProxy) { /* parse it now */
3339 if (parse_addr_port(LOG_WARN, options->HttpsProxy, NULL,
3340 &options->HttpsProxyAddr, &options->HttpsProxyPort) <0)
3341 REJECT("HttpsProxy failed to parse or resolve. Please fix.");
3342 if (options->HttpsProxyPort == 0) { /* give it a default */
3343 options->HttpsProxyPort = 443;
3347 if (options->HttpsProxyAuthenticator) {
3348 if (strlen(options->HttpsProxyAuthenticator) >= 48)
3349 REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
3352 if (options->HashedControlPassword) {
3353 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3354 if (!sl) {
3355 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3356 } else {
3357 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3358 smartlist_free(sl);
3362 if (options->HashedControlSessionPassword) {
3363 smartlist_t *sl = decode_hashed_passwords(
3364 options->HashedControlSessionPassword);
3365 if (!sl) {
3366 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3367 } else {
3368 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3369 smartlist_free(sl);
3373 if (options->ControlListenAddress) {
3374 int all_are_local = 1;
3375 config_line_t *ln;
3376 for (ln = options->ControlListenAddress; ln; ln = ln->next) {
3377 if (strcmpstart(ln->value, "127."))
3378 all_are_local = 0;
3380 if (!all_are_local) {
3381 if (!options->HashedControlPassword &&
3382 !options->HashedControlSessionPassword &&
3383 !options->CookieAuthentication) {
3384 log_warn(LD_CONFIG,
3385 "You have a ControlListenAddress set to accept "
3386 "unauthenticated connections from a non-local address. "
3387 "This means that programs not running on your computer "
3388 "can reconfigure your Tor, without even having to guess a "
3389 "password. That's so bad that I'm closing your ControlPort "
3390 "for you. If you need to control your Tor remotely, try "
3391 "enabling authentication and using a tool like stunnel or "
3392 "ssh to encrypt remote access.");
3393 options->ControlPort = 0;
3394 } else {
3395 log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
3396 "connections from a non-local address. This means that "
3397 "programs not running on your computer can reconfigure your "
3398 "Tor. That's pretty bad, since the controller "
3399 "protocol isn't encrypted! Maybe you should just listen on "
3400 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
3401 "remote connections to your control port.");
3406 if (options->ControlPort && !options->HashedControlPassword &&
3407 !options->HashedControlSessionPassword &&
3408 !options->CookieAuthentication) {
3409 log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
3410 "has been configured. This means that any program on your "
3411 "computer can reconfigure your Tor. That's bad! You should "
3412 "upgrade your Tor controller as soon as possible.");
3415 if (options->UseEntryGuards && ! options->NumEntryGuards)
3416 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3418 if (check_nickname_list(options->MyFamily, "MyFamily", msg))
3419 return -1;
3420 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3421 if (check_nickname_list(cl->value, "NodeFamily", msg))
3422 return -1;
3425 if (validate_addr_policies(options, msg) < 0)
3426 return -1;
3428 if (validate_dir_authorities(options, old_options) < 0)
3429 REJECT("Directory authority line did not parse. See logs for details.");
3431 if (options->UseBridges && !options->Bridges)
3432 REJECT("If you set UseBridges, you must specify at least one bridge.");
3433 if (options->UseBridges && !options->TunnelDirConns)
3434 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3435 if (options->Bridges) {
3436 for (cl = options->Bridges; cl; cl = cl->next) {
3437 if (parse_bridge_line(cl->value, 1)<0)
3438 REJECT("Bridge line did not parse. See logs for details.");
3442 if (options->ConstrainedSockets) {
3443 /* If the user wants to constrain socket buffer use, make sure the desired
3444 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3445 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3446 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3447 options->ConstrainedSockSize % 1024) {
3448 r = tor_snprintf(buf, sizeof(buf),
3449 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3450 "in 1024 byte increments.",
3451 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3452 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3453 return -1;
3455 if (options->DirPort) {
3456 /* Providing cached directory entries while system TCP buffers are scarce
3457 * will exacerbate the socket errors. Suggest that this be disabled. */
3458 COMPLAIN("You have requested constrained socket buffers while also "
3459 "serving directory entries via DirPort. It is strongly "
3460 "suggested that you disable serving directory requests when "
3461 "system TCP buffer resources are scarce.");
3465 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3466 options->V3AuthVotingInterval/2) {
3467 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3468 "V3AuthVotingInterval");
3470 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
3471 REJECT("V3AuthVoteDelay is way too low.");
3472 if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
3473 REJECT("V3AuthDistDelay is way too low.");
3475 if (options->V3AuthNIntervalsValid < 2)
3476 REJECT("V3AuthNIntervalsValid must be at least 2.");
3478 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3479 REJECT("V3AuthVotingInterval is insanely low.");
3480 } else if (options->V3AuthVotingInterval > 24*60*60) {
3481 REJECT("V3AuthVotingInterval is insanely high.");
3482 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3483 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3486 if (rend_config_services(options, 1) < 0)
3487 REJECT("Failed to configure rendezvous options. See logs for details.");
3489 /* Parse client-side authorization for hidden services. */
3490 if (rend_parse_service_authorization(options, 1) < 0)
3491 REJECT("Failed to configure client authorization for hidden services. "
3492 "See logs for details.");
3494 if (parse_virtual_addr_network(options->VirtualAddrNetwork, 1, NULL)<0)
3495 return -1;
3497 if (options->PreferTunneledDirConns && !options->TunnelDirConns)
3498 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3500 if (options->AutomapHostsSuffixes) {
3501 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
3503 size_t len = strlen(suf);
3504 if (len && suf[len-1] == '.')
3505 suf[len-1] = '\0';
3509 if (options->TestingTorNetwork && !options->DirServers) {
3510 REJECT("TestingTorNetwork may only be configured in combination with "
3511 "a non-default set of DirServers.");
3514 /*XXXX022 checking for defaults manually like this is a bit fragile.*/
3516 /* Keep changes to hard-coded values synchronous to man page and default
3517 * values table. */
3518 if (options->TestingV3AuthInitialVotingInterval != 30*60 &&
3519 !options->TestingTorNetwork) {
3520 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
3521 "Tor networks!");
3522 } else if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
3523 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3524 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
3525 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3526 "30 minutes.");
3529 if (options->TestingV3AuthInitialVoteDelay != 5*60 &&
3530 !options->TestingTorNetwork) {
3531 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
3532 "Tor networks!");
3533 } else if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
3534 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3537 if (options->TestingV3AuthInitialDistDelay != 5*60 &&
3538 !options->TestingTorNetwork) {
3539 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
3540 "Tor networks!");
3541 } else if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
3542 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3545 if (options->TestingV3AuthInitialVoteDelay +
3546 options->TestingV3AuthInitialDistDelay >=
3547 options->TestingV3AuthInitialVotingInterval/2) {
3548 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3549 "must be less than half TestingV3AuthInitialVotingInterval");
3552 if (options->TestingAuthDirTimeToLearnReachability != 30*60 &&
3553 !options->TestingTorNetwork) {
3554 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
3555 "testing Tor networks!");
3556 } else if (options->TestingAuthDirTimeToLearnReachability < 0) {
3557 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3558 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
3559 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3562 if (options->TestingEstimatedDescriptorPropagationTime != 10*60 &&
3563 !options->TestingTorNetwork) {
3564 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
3565 "testing Tor networks!");
3566 } else if (options->TestingEstimatedDescriptorPropagationTime < 0) {
3567 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3568 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
3569 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3572 if (options->TestingTorNetwork) {
3573 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
3574 "almost unusable in the public Tor network, and is "
3575 "therefore only advised if you are building a "
3576 "testing Tor network!");
3579 return 0;
3580 #undef REJECT
3581 #undef COMPLAIN
3584 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3585 * equal strings. */
3586 static int
3587 opt_streq(const char *s1, const char *s2)
3589 if (!s1 && !s2)
3590 return 1;
3591 else if (s1 && s2 && !strcmp(s1,s2))
3592 return 1;
3593 else
3594 return 0;
3597 /** Check if any of the previous options have changed but aren't allowed to. */
3598 static int
3599 options_transition_allowed(or_options_t *old, or_options_t *new_val,
3600 char **msg)
3602 if (!old)
3603 return 0;
3605 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3606 *msg = tor_strdup("PidFile is not allowed to change.");
3607 return -1;
3610 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3611 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3612 "is not allowed.");
3613 return -1;
3616 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
3617 char buf[1024];
3618 int r = tor_snprintf(buf, sizeof(buf),
3619 "While Tor is running, changing DataDirectory "
3620 "(\"%s\"->\"%s\") is not allowed.",
3621 old->DataDirectory, new_val->DataDirectory);
3622 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3623 return -1;
3626 if (!opt_streq(old->User, new_val->User)) {
3627 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
3628 return -1;
3631 if (!opt_streq(old->Group, new_val->Group)) {
3632 *msg = tor_strdup("While Tor is running, changing Group is not allowed.");
3633 return -1;
3636 if (old->HardwareAccel != new_val->HardwareAccel) {
3637 *msg = tor_strdup("While Tor is running, changing HardwareAccel is "
3638 "not allowed.");
3639 return -1;
3642 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
3643 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
3644 "is not allowed.");
3645 return -1;
3648 return 0;
3651 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3652 * will require us to rotate the cpu and dns workers; else return 0. */
3653 static int
3654 options_transition_affects_workers(or_options_t *old_options,
3655 or_options_t *new_options)
3657 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3658 old_options->NumCpus != new_options->NumCpus ||
3659 old_options->ORPort != new_options->ORPort ||
3660 old_options->ServerDNSSearchDomains !=
3661 new_options->ServerDNSSearchDomains ||
3662 old_options->SafeLogging != new_options->SafeLogging ||
3663 old_options->ClientOnly != new_options->ClientOnly ||
3664 !config_lines_eq(old_options->Logs, new_options->Logs))
3665 return 1;
3667 /* Check whether log options match. */
3669 /* Nothing that changed matters. */
3670 return 0;
3673 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3674 * will require us to generate a new descriptor; else return 0. */
3675 static int
3676 options_transition_affects_descriptor(or_options_t *old_options,
3677 or_options_t *new_options)
3679 /* XXX We can be smarter here. If your DirPort isn't being
3680 * published and you just turned it off, no need to republish. If
3681 * you changed your bandwidthrate but maxadvertisedbandwidth still
3682 * trumps, no need to republish. Etc. */
3683 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3684 !opt_streq(old_options->Nickname,new_options->Nickname) ||
3685 !opt_streq(old_options->Address,new_options->Address) ||
3686 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
3687 old_options->ExitPolicyRejectPrivate !=
3688 new_options->ExitPolicyRejectPrivate ||
3689 old_options->ORPort != new_options->ORPort ||
3690 old_options->DirPort != new_options->DirPort ||
3691 old_options->ClientOnly != new_options->ClientOnly ||
3692 old_options->NoPublish != new_options->NoPublish ||
3693 old_options->_PublishServerDescriptor !=
3694 new_options->_PublishServerDescriptor ||
3695 old_options->BandwidthRate != new_options->BandwidthRate ||
3696 old_options->BandwidthBurst != new_options->BandwidthBurst ||
3697 old_options->MaxAdvertisedBandwidth !=
3698 new_options->MaxAdvertisedBandwidth ||
3699 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
3700 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
3701 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
3702 old_options->AccountingMax != new_options->AccountingMax)
3703 return 1;
3705 return 0;
3708 #ifdef MS_WINDOWS
3709 /** Return the directory on windows where we expect to find our application
3710 * data. */
3711 static char *
3712 get_windows_conf_root(void)
3714 static int is_set = 0;
3715 static char path[MAX_PATH+1];
3717 LPITEMIDLIST idl;
3718 IMalloc *m;
3719 HRESULT result;
3721 if (is_set)
3722 return path;
3724 /* Find X:\documents and settings\username\application data\ .
3725 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3727 #ifdef ENABLE_LOCAL_APPDATA
3728 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
3729 #else
3730 #define APPDATA_PATH CSIDL_APPDATA
3731 #endif
3732 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
3733 GetCurrentDirectory(MAX_PATH, path);
3734 is_set = 1;
3735 log_warn(LD_CONFIG,
3736 "I couldn't find your application data folder: are you "
3737 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3738 path);
3739 return path;
3741 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3742 result = SHGetPathFromIDList(idl, path);
3743 /* Now we need to free the */
3744 SHGetMalloc(&m);
3745 if (m) {
3746 m->lpVtbl->Free(m, idl);
3747 m->lpVtbl->Release(m);
3749 if (!SUCCEEDED(result)) {
3750 return NULL;
3752 strlcat(path,"\\tor",MAX_PATH);
3753 is_set = 1;
3754 return path;
3756 #endif
3758 /** Return the default location for our torrc file. */
3759 static const char *
3760 get_default_conf_file(void)
3762 #ifdef MS_WINDOWS
3763 static char path[MAX_PATH+1];
3764 strlcpy(path, get_windows_conf_root(), MAX_PATH);
3765 strlcat(path,"\\torrc",MAX_PATH);
3766 return path;
3767 #else
3768 return (CONFDIR "/torrc");
3769 #endif
3772 /** Verify whether lst is a string containing valid-looking comma-separated
3773 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3775 static int
3776 check_nickname_list(const char *lst, const char *name, char **msg)
3778 int r = 0;
3779 smartlist_t *sl;
3781 if (!lst)
3782 return 0;
3783 sl = smartlist_create();
3785 smartlist_split_string(sl, lst, ",",
3786 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
3788 SMARTLIST_FOREACH(sl, const char *, s,
3790 if (!is_legal_nickname_or_hexdigest(s)) {
3791 char buf[1024];
3792 int tmp = tor_snprintf(buf, sizeof(buf),
3793 "Invalid nickname '%s' in %s line", s, name);
3794 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
3795 r = -1;
3796 break;
3799 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
3800 smartlist_free(sl);
3801 return r;
3804 /** Learn config file name from command line arguments, or use the default */
3805 static char *
3806 find_torrc_filename(int argc, char **argv,
3807 int *using_default_torrc, int *ignore_missing_torrc)
3809 char *fname=NULL;
3810 int i;
3812 for (i = 1; i < argc; ++i) {
3813 if (i < argc-1 && !strcmp(argv[i],"-f")) {
3814 if (fname) {
3815 log(LOG_WARN, LD_CONFIG, "Duplicate -f options on command line.");
3816 tor_free(fname);
3818 #ifdef MS_WINDOWS
3819 /* XXX one day we might want to extend expand_filename to work
3820 * under Windows as well. */
3821 fname = tor_strdup(argv[i+1]);
3822 #else
3823 fname = expand_filename(argv[i+1]);
3824 #endif
3825 *using_default_torrc = 0;
3826 ++i;
3827 } else if (!strcmp(argv[i],"--ignore-missing-torrc")) {
3828 *ignore_missing_torrc = 1;
3832 if (*using_default_torrc) {
3833 /* didn't find one, try CONFDIR */
3834 const char *dflt = get_default_conf_file();
3835 if (dflt && file_status(dflt) == FN_FILE) {
3836 fname = tor_strdup(dflt);
3837 } else {
3838 #ifndef MS_WINDOWS
3839 char *fn;
3840 fn = expand_filename("~/.torrc");
3841 if (fn && file_status(fn) == FN_FILE) {
3842 fname = fn;
3843 } else {
3844 tor_free(fn);
3845 fname = tor_strdup(dflt);
3847 #else
3848 fname = tor_strdup(dflt);
3849 #endif
3852 return fname;
3855 /** Load torrc from disk, setting torrc_fname if successful */
3856 static char *
3857 load_torrc_from_disk(int argc, char **argv)
3859 char *fname=NULL;
3860 char *cf = NULL;
3861 int using_default_torrc = 1;
3862 int ignore_missing_torrc = 0;
3864 fname = find_torrc_filename(argc, argv,
3865 &using_default_torrc, &ignore_missing_torrc);
3866 tor_assert(fname);
3867 log(LOG_DEBUG, LD_CONFIG, "Opening config file \"%s\"", fname);
3869 tor_free(torrc_fname);
3870 torrc_fname = fname;
3872 /* Open config file */
3873 if (file_status(fname) != FN_FILE ||
3874 !(cf = read_file_to_str(fname,0,NULL))) {
3875 if (using_default_torrc == 1 || ignore_missing_torrc ) {
3876 log(LOG_NOTICE, LD_CONFIG, "Configuration file \"%s\" not present, "
3877 "using reasonable defaults.", fname);
3878 tor_free(fname); /* sets fname to NULL */
3879 torrc_fname = NULL;
3880 cf = tor_strdup("");
3881 } else {
3882 log(LOG_WARN, LD_CONFIG,
3883 "Unable to open configuration file \"%s\".", fname);
3884 goto err;
3888 return cf;
3889 err:
3890 tor_free(fname);
3891 torrc_fname = NULL;
3892 return NULL;
3895 /** Read a configuration file into <b>options</b>, finding the configuration
3896 * file location based on the command line. After loading the file
3897 * call options_init_from_string() to load the config.
3898 * Return 0 if success, -1 if failure. */
3900 options_init_from_torrc(int argc, char **argv)
3902 char *cf=NULL;
3903 int i, retval, command;
3904 static char **backup_argv;
3905 static int backup_argc;
3906 char *command_arg = NULL;
3907 char *errmsg=NULL;
3909 if (argv) { /* first time we're called. save commandline args */
3910 backup_argv = argv;
3911 backup_argc = argc;
3912 } else { /* we're reloading. need to clean up old options first. */
3913 argv = backup_argv;
3914 argc = backup_argc;
3916 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
3917 print_usage();
3918 exit(0);
3920 if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
3921 /* For documenting validating whether we've documented everything. */
3922 list_torrc_options();
3923 exit(0);
3926 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
3927 printf("Tor version %s.\n",get_version());
3928 exit(0);
3931 /* Go through command-line variables */
3932 if (!global_cmdline_options) {
3933 /* Or we could redo the list every time we pass this place.
3934 * It does not really matter */
3935 if (config_get_commandlines(argc, argv, &global_cmdline_options) < 0) {
3936 goto err;
3940 command = CMD_RUN_TOR;
3941 for (i = 1; i < argc; ++i) {
3942 if (!strcmp(argv[i],"--list-fingerprint")) {
3943 command = CMD_LIST_FINGERPRINT;
3944 } else if (!strcmp(argv[i],"--hash-password")) {
3945 command = CMD_HASH_PASSWORD;
3946 command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
3947 ++i;
3948 } else if (!strcmp(argv[i],"--verify-config")) {
3949 command = CMD_VERIFY_CONFIG;
3953 if (command == CMD_HASH_PASSWORD) {
3954 cf = tor_strdup("");
3955 } else {
3956 cf = load_torrc_from_disk(argc, argv);
3957 if (!cf)
3958 goto err;
3961 retval = options_init_from_string(cf, command, command_arg, &errmsg);
3962 tor_free(cf);
3963 if (retval < 0)
3964 goto err;
3966 return 0;
3968 err:
3969 if (errmsg) {
3970 log(LOG_WARN,LD_CONFIG,"%s", errmsg);
3971 tor_free(errmsg);
3973 return -1;
3976 /** Load the options from the configuration in <b>cf</b>, validate
3977 * them for consistency and take actions based on them.
3979 * Return 0 if success, negative on error:
3980 * * -1 for general errors.
3981 * * -2 for failure to parse/validate,
3982 * * -3 for transition not allowed
3983 * * -4 for error while setting the new options
3985 setopt_err_t
3986 options_init_from_string(const char *cf,
3987 int command, const char *command_arg,
3988 char **msg)
3990 or_options_t *oldoptions, *newoptions;
3991 config_line_t *cl;
3992 int retval;
3993 setopt_err_t err = SETOPT_ERR_MISC;
3994 tor_assert(msg);
3996 oldoptions = global_options; /* get_options unfortunately asserts if
3997 this is the first time we run*/
3999 newoptions = tor_malloc_zero(sizeof(or_options_t));
4000 newoptions->_magic = OR_OPTIONS_MAGIC;
4001 options_init(newoptions);
4002 newoptions->command = command;
4003 newoptions->command_arg = command_arg;
4005 /* get config lines, assign them */
4006 retval = config_get_lines(cf, &cl);
4007 if (retval < 0) {
4008 err = SETOPT_ERR_PARSE;
4009 goto err;
4011 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4012 config_free_lines(cl);
4013 if (retval < 0) {
4014 err = SETOPT_ERR_PARSE;
4015 goto err;
4018 /* Go through command-line variables too */
4019 retval = config_assign(&options_format, newoptions,
4020 global_cmdline_options, 0, 0, msg);
4021 if (retval < 0) {
4022 err = SETOPT_ERR_PARSE;
4023 goto err;
4026 /* If this is a testing network configuration, change defaults
4027 * for a list of dependent config options, re-initialize newoptions
4028 * with the new defaults, and assign all options to it second time. */
4029 if (newoptions->TestingTorNetwork) {
4030 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4031 * this? We could, for example, make the parsing algorithm do two passes
4032 * over the configuration. If it finds any "suite" options like
4033 * TestingTorNetwork, it could change the defaults before its second pass.
4034 * Not urgent so long as this seems to work, but at any sign of trouble,
4035 * let's clean it up. -NM */
4037 /* Change defaults. */
4038 int i;
4039 for (i = 0; testing_tor_network_defaults[i].name; ++i) {
4040 config_var_t *new_var = &testing_tor_network_defaults[i];
4041 config_var_t *old_var =
4042 config_find_option(&options_format, new_var->name);
4043 tor_assert(new_var);
4044 tor_assert(old_var);
4045 old_var->initvalue = new_var->initvalue;
4048 /* Clear newoptions and re-initialize them with new defaults. */
4049 config_free(&options_format, newoptions);
4050 newoptions = tor_malloc_zero(sizeof(or_options_t));
4051 newoptions->_magic = OR_OPTIONS_MAGIC;
4052 options_init(newoptions);
4053 newoptions->command = command;
4054 newoptions->command_arg = command_arg;
4056 /* Assign all options a second time. */
4057 retval = config_get_lines(cf, &cl);
4058 if (retval < 0) {
4059 err = SETOPT_ERR_PARSE;
4060 goto err;
4062 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4063 config_free_lines(cl);
4064 if (retval < 0) {
4065 err = SETOPT_ERR_PARSE;
4066 goto err;
4068 retval = config_assign(&options_format, newoptions,
4069 global_cmdline_options, 0, 0, msg);
4070 if (retval < 0) {
4071 err = SETOPT_ERR_PARSE;
4072 goto err;
4076 /* Validate newoptions */
4077 if (options_validate(oldoptions, newoptions, 0, msg) < 0) {
4078 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
4079 goto err;
4082 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
4083 err = SETOPT_ERR_TRANSITION;
4084 goto err;
4087 if (set_options(newoptions, msg)) {
4088 err = SETOPT_ERR_SETTING;
4089 goto err; /* frees and replaces old options */
4092 return SETOPT_OK;
4094 err:
4095 config_free(&options_format, newoptions);
4096 if (*msg) {
4097 int len = strlen(*msg)+256;
4098 char *newmsg = tor_malloc(len);
4100 tor_snprintf(newmsg, len, "Failed to parse/validate config: %s", *msg);
4101 tor_free(*msg);
4102 *msg = newmsg;
4104 return err;
4107 /** Return the location for our configuration file.
4109 const char *
4110 get_torrc_fname(void)
4112 if (torrc_fname)
4113 return torrc_fname;
4114 else
4115 return get_default_conf_file();
4118 /** Adjust the address map mased on the MapAddress elements in the
4119 * configuration <b>options</b>
4121 static void
4122 config_register_addressmaps(or_options_t *options)
4124 smartlist_t *elts;
4125 config_line_t *opt;
4126 char *from, *to;
4128 addressmap_clear_configured();
4129 elts = smartlist_create();
4130 for (opt = options->AddressMap; opt; opt = opt->next) {
4131 smartlist_split_string(elts, opt->value, NULL,
4132 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4133 if (smartlist_len(elts) >= 2) {
4134 from = smartlist_get(elts,0);
4135 to = smartlist_get(elts,1);
4136 if (address_is_invalid_destination(to, 1)) {
4137 log_warn(LD_CONFIG,
4138 "Skipping invalid argument '%s' to MapAddress", to);
4139 } else {
4140 addressmap_register(from, tor_strdup(to), 0, ADDRMAPSRC_TORRC);
4141 if (smartlist_len(elts)>2) {
4142 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
4145 } else {
4146 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
4147 opt->value);
4149 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4150 smartlist_clear(elts);
4152 smartlist_free(elts);
4156 * Initialize the logs based on the configuration file.
4158 static int
4159 options_init_logs(or_options_t *options, int validate_only)
4161 config_line_t *opt;
4162 int ok;
4163 smartlist_t *elts;
4164 int daemon =
4165 #ifdef MS_WINDOWS
4167 #else
4168 options->RunAsDaemon;
4169 #endif
4171 ok = 1;
4172 elts = smartlist_create();
4174 for (opt = options->Logs; opt; opt = opt->next) {
4175 log_severity_list_t *severity;
4176 const char *cfg = opt->value;
4177 severity = tor_malloc_zero(sizeof(log_severity_list_t));
4178 if (parse_log_severity_config(&cfg, severity) < 0) {
4179 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
4180 opt->value);
4181 ok = 0; goto cleanup;
4184 smartlist_split_string(elts, cfg, NULL,
4185 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4187 if (smartlist_len(elts) == 0)
4188 smartlist_add(elts, tor_strdup("stdout"));
4190 if (smartlist_len(elts) == 1 &&
4191 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
4192 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
4193 int err = smartlist_len(elts) &&
4194 !strcasecmp(smartlist_get(elts,0), "stderr");
4195 if (!validate_only) {
4196 if (daemon) {
4197 log_warn(LD_CONFIG,
4198 "Can't log to %s with RunAsDaemon set; skipping stdout",
4199 err?"stderr":"stdout");
4200 } else {
4201 add_stream_log(severity, err?"<stderr>":"<stdout>",
4202 fileno(err?stderr:stdout));
4205 goto cleanup;
4207 if (smartlist_len(elts) == 1 &&
4208 !strcasecmp(smartlist_get(elts,0), "syslog")) {
4209 #ifdef HAVE_SYSLOG_H
4210 if (!validate_only) {
4211 add_syslog_log(severity);
4213 #else
4214 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
4215 #endif
4216 goto cleanup;
4219 if (smartlist_len(elts) == 2 &&
4220 !strcasecmp(smartlist_get(elts,0), "file")) {
4221 if (!validate_only) {
4222 if (add_file_log(severity, smartlist_get(elts, 1)) < 0) {
4223 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
4224 opt->value, strerror(errno));
4225 ok = 0;
4228 goto cleanup;
4231 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
4232 opt->value);
4233 ok = 0; goto cleanup;
4235 cleanup:
4236 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4237 smartlist_clear(elts);
4238 tor_free(severity);
4240 smartlist_free(elts);
4242 return ok?0:-1;
4245 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4246 * if the line is well-formed, and -1 if it isn't. If
4247 * <b>validate_only</b> is 0, and the line is well-formed, then add
4248 * the bridge described in the line to our internal bridge list. */
4249 static int
4250 parse_bridge_line(const char *line, int validate_only)
4252 smartlist_t *items = NULL;
4253 int r;
4254 char *addrport=NULL, *fingerprint=NULL;
4255 tor_addr_t addr;
4256 uint16_t port = 0;
4257 char digest[DIGEST_LEN];
4259 items = smartlist_create();
4260 smartlist_split_string(items, line, NULL,
4261 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4262 if (smartlist_len(items) < 1) {
4263 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
4264 goto err;
4266 addrport = smartlist_get(items, 0);
4267 smartlist_del_keeporder(items, 0);
4268 if (tor_addr_port_parse(addrport, &addr, &port)<0) {
4269 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
4270 goto err;
4272 if (!port) {
4273 log_info(LD_CONFIG,
4274 "Bridge address '%s' has no port; using default port 443.",
4275 addrport);
4276 port = 443;
4279 if (smartlist_len(items)) {
4280 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4281 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4282 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
4283 goto err;
4285 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4286 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
4287 goto err;
4291 if (!validate_only) {
4292 log_debug(LD_DIR, "Bridge at %s:%d (%s)", fmt_addr(&addr),
4293 (int)port,
4294 fingerprint ? fingerprint : "no key listed");
4295 bridge_add_from_config(&addr, port, fingerprint ? digest : NULL);
4298 r = 0;
4299 goto done;
4301 err:
4302 r = -1;
4304 done:
4305 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4306 smartlist_free(items);
4307 tor_free(addrport);
4308 tor_free(fingerprint);
4309 return r;
4312 /** Read the contents of a DirServer line from <b>line</b>. If
4313 * <b>validate_only</b> is 0, and the line is well-formed, and it
4314 * shares any bits with <b>required_type</b> or <b>required_type</b>
4315 * is 0, then add the dirserver described in the line (minus whatever
4316 * bits it's missing) as a valid authority. Return 0 on success,
4317 * or -1 if the line isn't well-formed or if we can't add it. */
4318 static int
4319 parse_dir_server_line(const char *line, authority_type_t required_type,
4320 int validate_only)
4322 smartlist_t *items = NULL;
4323 int r;
4324 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
4325 uint16_t dir_port = 0, or_port = 0;
4326 char digest[DIGEST_LEN];
4327 char v3_digest[DIGEST_LEN];
4328 authority_type_t type = V2_AUTHORITY;
4329 int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
4331 items = smartlist_create();
4332 smartlist_split_string(items, line, NULL,
4333 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4334 if (smartlist_len(items) < 1) {
4335 log_warn(LD_CONFIG, "No arguments on DirServer line.");
4336 goto err;
4339 if (is_legal_nickname(smartlist_get(items, 0))) {
4340 nickname = smartlist_get(items, 0);
4341 smartlist_del_keeporder(items, 0);
4344 while (smartlist_len(items)) {
4345 char *flag = smartlist_get(items, 0);
4346 if (TOR_ISDIGIT(flag[0]))
4347 break;
4348 if (!strcasecmp(flag, "v1")) {
4349 type |= (V1_AUTHORITY | HIDSERV_AUTHORITY);
4350 } else if (!strcasecmp(flag, "hs")) {
4351 type |= HIDSERV_AUTHORITY;
4352 } else if (!strcasecmp(flag, "no-hs")) {
4353 is_not_hidserv_authority = 1;
4354 } else if (!strcasecmp(flag, "bridge")) {
4355 type |= BRIDGE_AUTHORITY;
4356 } else if (!strcasecmp(flag, "no-v2")) {
4357 is_not_v2_authority = 1;
4358 } else if (!strcasecmpstart(flag, "orport=")) {
4359 int ok;
4360 char *portstring = flag + strlen("orport=");
4361 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
4362 if (!ok)
4363 log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
4364 portstring);
4365 } else if (!strcasecmpstart(flag, "v3ident=")) {
4366 char *idstr = flag + strlen("v3ident=");
4367 if (strlen(idstr) != HEX_DIGEST_LEN ||
4368 base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
4369 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirServer line",
4370 flag);
4371 } else {
4372 type |= V3_AUTHORITY;
4374 } else {
4375 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
4376 flag);
4378 tor_free(flag);
4379 smartlist_del_keeporder(items, 0);
4381 if (is_not_hidserv_authority)
4382 type &= ~HIDSERV_AUTHORITY;
4383 if (is_not_v2_authority)
4384 type &= ~V2_AUTHORITY;
4386 if (smartlist_len(items) < 2) {
4387 log_warn(LD_CONFIG, "Too few arguments to DirServer line.");
4388 goto err;
4390 addrport = smartlist_get(items, 0);
4391 smartlist_del_keeporder(items, 0);
4392 if (parse_addr_port(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
4393 log_warn(LD_CONFIG, "Error parsing DirServer address '%s'", addrport);
4394 goto err;
4396 if (!dir_port) {
4397 log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
4398 goto err;
4401 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4402 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4403 log_warn(LD_CONFIG, "Key digest for DirServer is wrong length %d.",
4404 (int)strlen(fingerprint));
4405 goto err;
4407 if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4408 /* a known bad fingerprint. refuse to use it. We can remove this
4409 * clause once Tor 0.1.2.17 is obsolete. */
4410 log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
4411 "torrc file (%s), or reinstall Tor and use the default torrc.",
4412 get_torrc_fname());
4413 goto err;
4415 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4416 log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
4417 goto err;
4420 if (!validate_only && (!required_type || required_type & type)) {
4421 if (required_type)
4422 type &= required_type; /* pare down what we think of them as an
4423 * authority for. */
4424 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
4425 address, (int)dir_port, (char*)smartlist_get(items,0));
4426 if (!add_trusted_dir_server(nickname, address, dir_port, or_port,
4427 digest, v3_digest, type))
4428 goto err;
4431 r = 0;
4432 goto done;
4434 err:
4435 r = -1;
4437 done:
4438 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4439 smartlist_free(items);
4440 tor_free(addrport);
4441 tor_free(address);
4442 tor_free(nickname);
4443 tor_free(fingerprint);
4444 return r;
4447 /** Adjust the value of options->DataDirectory, or fill it in if it's
4448 * absent. Return 0 on success, -1 on failure. */
4449 static int
4450 normalize_data_directory(or_options_t *options)
4452 #ifdef MS_WINDOWS
4453 char *p;
4454 if (options->DataDirectory)
4455 return 0; /* all set */
4456 p = tor_malloc(MAX_PATH);
4457 strlcpy(p,get_windows_conf_root(),MAX_PATH);
4458 options->DataDirectory = p;
4459 return 0;
4460 #else
4461 const char *d = options->DataDirectory;
4462 if (!d)
4463 d = "~/.tor";
4465 if (strncmp(d,"~/",2) == 0) {
4466 char *fn = expand_filename(d);
4467 if (!fn) {
4468 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
4469 return -1;
4471 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
4472 /* If our homedir is /, we probably don't want to use it. */
4473 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4474 * want. */
4475 log_warn(LD_CONFIG,
4476 "Default DataDirectory is \"~/.tor\". This expands to "
4477 "\"%s\", which is probably not what you want. Using "
4478 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
4479 tor_free(fn);
4480 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
4482 tor_free(options->DataDirectory);
4483 options->DataDirectory = fn;
4485 return 0;
4486 #endif
4489 /** Check and normalize the value of options->DataDirectory; return 0 if it
4490 * sane, -1 otherwise. */
4491 static int
4492 validate_data_directory(or_options_t *options)
4494 if (normalize_data_directory(options) < 0)
4495 return -1;
4496 tor_assert(options->DataDirectory);
4497 if (strlen(options->DataDirectory) > (512-128)) {
4498 log_warn(LD_CONFIG, "DataDirectory is too long.");
4499 return -1;
4501 return 0;
4504 /** This string must remain the same forevermore. It is how we
4505 * recognize that the torrc file doesn't need to be backed up. */
4506 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4507 "if you edit it, comments will not be preserved"
4508 /** This string can change; it tries to give the reader an idea
4509 * that editing this file by hand is not a good plan. */
4510 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4511 "to torrc.orig.1 or similar, and Tor will ignore it"
4513 /** Save a configuration file for the configuration in <b>options</b>
4514 * into the file <b>fname</b>. If the file already exists, and
4515 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4516 * replace it. Return 0 on success, -1 on failure. */
4517 static int
4518 write_configuration_file(const char *fname, or_options_t *options)
4520 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4521 int rename_old = 0, r;
4522 size_t len;
4524 tor_assert(fname);
4526 switch (file_status(fname)) {
4527 case FN_FILE:
4528 old_val = read_file_to_str(fname, 0, NULL);
4529 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4530 rename_old = 1;
4532 tor_free(old_val);
4533 break;
4534 case FN_NOENT:
4535 break;
4536 case FN_ERROR:
4537 case FN_DIR:
4538 default:
4539 log_warn(LD_CONFIG,
4540 "Config file \"%s\" is not a file? Failing.", fname);
4541 return -1;
4544 if (!(new_conf = options_dump(options, 1))) {
4545 log_warn(LD_BUG, "Couldn't get configuration string");
4546 goto err;
4549 len = strlen(new_conf)+256;
4550 new_val = tor_malloc(len);
4551 tor_snprintf(new_val, len, "%s\n%s\n\n%s",
4552 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4554 if (rename_old) {
4555 int i = 1;
4556 size_t fn_tmp_len = strlen(fname)+32;
4557 char *fn_tmp;
4558 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4559 fn_tmp = tor_malloc(fn_tmp_len);
4560 while (1) {
4561 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4562 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4563 tor_free(fn_tmp);
4564 goto err;
4566 if (file_status(fn_tmp) == FN_NOENT)
4567 break;
4568 ++i;
4570 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4571 if (rename(fname, fn_tmp) < 0) {
4572 log_warn(LD_FS,
4573 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4574 fname, fn_tmp, strerror(errno));
4575 tor_free(fn_tmp);
4576 goto err;
4578 tor_free(fn_tmp);
4581 if (write_str_to_file(fname, new_val, 0) < 0)
4582 goto err;
4584 r = 0;
4585 goto done;
4586 err:
4587 r = -1;
4588 done:
4589 tor_free(new_val);
4590 tor_free(new_conf);
4591 return r;
4595 * Save the current configuration file value to disk. Return 0 on
4596 * success, -1 on failure.
4599 options_save_current(void)
4601 if (torrc_fname) {
4602 /* This fails if we can't write to our configuration file.
4604 * If we try falling back to datadirectory or something, we have a better
4605 * chance of saving the configuration, but a better chance of doing
4606 * something the user never expected. Let's just warn instead. */
4607 return write_configuration_file(torrc_fname, get_options());
4609 return write_configuration_file(get_default_conf_file(), get_options());
4612 /** Mapping from a unit name to a multiplier for converting that unit into a
4613 * base unit. */
4614 struct unit_table_t {
4615 const char *unit;
4616 uint64_t multiplier;
4619 /** Table to map the names of memory units to the number of bytes they
4620 * contain. */
4621 static struct unit_table_t memory_units[] = {
4622 { "", 1 },
4623 { "b", 1<< 0 },
4624 { "byte", 1<< 0 },
4625 { "bytes", 1<< 0 },
4626 { "kb", 1<<10 },
4627 { "kbyte", 1<<10 },
4628 { "kbytes", 1<<10 },
4629 { "kilobyte", 1<<10 },
4630 { "kilobytes", 1<<10 },
4631 { "m", 1<<20 },
4632 { "mb", 1<<20 },
4633 { "mbyte", 1<<20 },
4634 { "mbytes", 1<<20 },
4635 { "megabyte", 1<<20 },
4636 { "megabytes", 1<<20 },
4637 { "gb", 1<<30 },
4638 { "gbyte", 1<<30 },
4639 { "gbytes", 1<<30 },
4640 { "gigabyte", 1<<30 },
4641 { "gigabytes", 1<<30 },
4642 { "tb", U64_LITERAL(1)<<40 },
4643 { "terabyte", U64_LITERAL(1)<<40 },
4644 { "terabytes", U64_LITERAL(1)<<40 },
4645 { NULL, 0 },
4648 /** Table to map the names of time units to the number of seconds they
4649 * contain. */
4650 static struct unit_table_t time_units[] = {
4651 { "", 1 },
4652 { "second", 1 },
4653 { "seconds", 1 },
4654 { "minute", 60 },
4655 { "minutes", 60 },
4656 { "hour", 60*60 },
4657 { "hours", 60*60 },
4658 { "day", 24*60*60 },
4659 { "days", 24*60*60 },
4660 { "week", 7*24*60*60 },
4661 { "weeks", 7*24*60*60 },
4662 { NULL, 0 },
4665 /** Parse a string <b>val</b> containing a number, zero or more
4666 * spaces, and an optional unit string. If the unit appears in the
4667 * table <b>u</b>, then multiply the number by the unit multiplier.
4668 * On success, set *<b>ok</b> to 1 and return this product.
4669 * Otherwise, set *<b>ok</b> to 0.
4671 static uint64_t
4672 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4674 uint64_t v;
4675 char *cp;
4677 tor_assert(ok);
4679 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4680 if (!*ok)
4681 return 0;
4682 if (!cp) {
4683 *ok = 1;
4684 return v;
4686 while (TOR_ISSPACE(*cp))
4687 ++cp;
4688 for ( ;u->unit;++u) {
4689 if (!strcasecmp(u->unit, cp)) {
4690 v *= u->multiplier;
4691 *ok = 1;
4692 return v;
4695 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4696 *ok = 0;
4697 return 0;
4700 /** Parse a string in the format "number unit", where unit is a unit of
4701 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4702 * and return the number of bytes specified. Otherwise, set
4703 * *<b>ok</b> to false and return 0. */
4704 static uint64_t
4705 config_parse_memunit(const char *s, int *ok)
4707 return config_parse_units(s, memory_units, ok);
4710 /** Parse a string in the format "number unit", where unit is a unit of time.
4711 * On success, set *<b>ok</b> to true and return the number of seconds in
4712 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4714 static int
4715 config_parse_interval(const char *s, int *ok)
4717 uint64_t r;
4718 r = config_parse_units(s, time_units, ok);
4719 if (!ok)
4720 return -1;
4721 if (r > INT_MAX) {
4722 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4723 *ok = 0;
4724 return -1;
4726 return (int)r;
4729 /* This is what passes for version detection on OSX. We set
4730 * MACOSX_KQUEUE_IS_BROKEN to true iff we're on a version of OSX before
4731 * 10.4.0 (aka 1040). */
4732 #ifdef __APPLE__
4733 #ifdef __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__
4734 #define MACOSX_KQUEUE_IS_BROKEN \
4735 (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1040)
4736 #else
4737 #define MACOSX_KQUEUE_IS_BROKEN 0
4738 #endif
4739 #endif
4742 * Initialize the libevent library.
4744 static void
4745 init_libevent(void)
4747 configure_libevent_logging();
4748 /* If the kernel complains that some method (say, epoll) doesn't
4749 * exist, we don't care about it, since libevent will cope.
4751 suppress_libevent_log_msg("Function not implemented");
4752 #ifdef __APPLE__
4753 if (MACOSX_KQUEUE_IS_BROKEN ||
4754 decode_libevent_version(event_get_version(), NULL) < LE_11B) {
4755 setenv("EVENT_NOKQUEUE","1",1);
4757 #endif
4759 /* In libevent versions before 2.0, it's hard to keep binary compatibility
4760 * between upgrades, and unpleasant to detect when the version we compiled
4761 * against is unlike the version we have linked against. Here's how. */
4762 #if defined(_EVENT_VERSION) && defined(HAVE_EVENT_GET_VERSION)
4763 /* We have a header-file version and a function-call version. Easy. */
4764 if (strcmp(_EVENT_VERSION, event_get_version())) {
4765 int compat1 = -1, compat2 = -1;
4766 int verybad, prettybad ;
4767 decode_libevent_version(_EVENT_VERSION, &compat1);
4768 decode_libevent_version(event_get_version(), &compat2);
4769 verybad = compat1 != compat2;
4770 prettybad = (compat1 == -1 || compat2 == -1) && compat1 != compat2;
4772 log(verybad ? LOG_WARN : (prettybad ? LOG_NOTICE : LOG_INFO),
4773 LD_GENERAL, "We were compiled with headers from version %s "
4774 "of Libevent, but we're using a Libevent library that says it's "
4775 "version %s.", _EVENT_VERSION, event_get_version());
4776 if (verybad)
4777 log_warn(LD_GENERAL, "This will almost certainly make Tor crash.");
4778 else if (prettybad)
4779 log_notice(LD_GENERAL, "If Tor crashes, this might be why.");
4780 else
4781 log_info(LD_GENERAL, "I think these versions are binary-compatible.");
4783 #elif defined(HAVE_EVENT_GET_VERSION)
4784 /* event_get_version but no _EVENT_VERSION. We might be in 1.4.0-beta or
4785 earlier, where that's normal. To see whether we were compiled with an
4786 earlier version, let's see whether the struct event defines MIN_HEAP_IDX.
4788 #ifdef HAVE_STRUCT_EVENT_MIN_HEAP_IDX
4789 /* The header files are 1.4.0-beta or later. If the version is not
4790 * 1.4.0-beta, we are incompatible. */
4792 if (strcmp(event_get_version(), "1.4.0-beta")) {
4793 log_warn(LD_GENERAL, "It's a little hard to tell, but you seem to have "
4794 "Libevent 1.4.0-beta header files, whereas you have linked "
4795 "against Libevent %s. This will probably make Tor crash.",
4796 event_get_version());
4799 #else
4800 /* Our headers are 1.3e or earlier. If the library version is not 1.4.x or
4801 later, we're probably fine. */
4803 const char *v = event_get_version();
4804 if ((v[0] == '1' && v[2] == '.' && v[3] > '3') || v[0] > '1') {
4805 log_warn(LD_GENERAL, "It's a little hard to tell, but you seem to have "
4806 "Libevent header file from 1.3e or earlier, whereas you have "
4807 "linked against Libevent %s. This will probably make Tor "
4808 "crash.", event_get_version());
4811 #endif
4813 #elif defined(_EVENT_VERSION)
4814 #warn "_EVENT_VERSION is defined but not get_event_version(): Libevent is odd."
4815 #else
4816 /* Your libevent is ancient. */
4817 #endif
4819 event_init();
4820 suppress_libevent_log_msg(NULL);
4821 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4822 /* Making this a NOTICE for now so we can link bugs to a libevent versions
4823 * or methods better. */
4824 log(LOG_NOTICE, LD_GENERAL,
4825 "Initialized libevent version %s using method %s. Good.",
4826 event_get_version(), event_get_method());
4827 check_libevent_version(event_get_method(), get_options()->ORPort != 0);
4828 #else
4829 log(LOG_NOTICE, LD_GENERAL,
4830 "Initialized old libevent (version 1.0b or earlier).");
4831 log(LOG_WARN, LD_GENERAL,
4832 "You have a *VERY* old version of libevent. It is likely to be buggy; "
4833 "please build Tor with a more recent version.");
4834 #endif
4837 /** Table mapping return value of event_get_version() to le_version_t. */
4838 static const struct {
4839 const char *name; le_version_t version; int bincompat;
4840 } le_version_table[] = {
4841 /* earlier versions don't have get_version. */
4842 { "1.0c", LE_10C, 1},
4843 { "1.0d", LE_10D, 1},
4844 { "1.0e", LE_10E, 1},
4845 { "1.1", LE_11, 1 },
4846 { "1.1a", LE_11A, 1 },
4847 { "1.1b", LE_11B, 1 },
4848 { "1.2", LE_12, 1 },
4849 { "1.2a", LE_12A, 1 },
4850 { "1.3", LE_13, 1 },
4851 { "1.3a", LE_13A, 1 },
4852 { "1.3b", LE_13B, 1 },
4853 { "1.3c", LE_13C, 1 },
4854 { "1.3d", LE_13D, 1 },
4855 { "1.3e", LE_13E, 1 },
4856 { "1.4.0-beta", LE_140, 2 },
4857 { "1.4.1-beta", LE_141, 2 },
4858 { "1.4.2-rc", LE_142, 2 },
4859 { "1.4.3-stable", LE_143, 2 },
4860 { "1.4.4-stable", LE_144, 2 },
4861 { "1.4.5-stable", LE_145, 2 },
4862 { "1.4.6-stable", LE_146, 2 },
4863 { "1.4.7-stable", LE_147, 2 },
4864 { "1.4.8-stable", LE_148, 2 },
4865 { "1.4.99-trunk", LE_1499, 3 },
4866 { NULL, LE_OTHER, 0 }
4869 /** Return the le_version_t for the current version of libevent. If the
4870 * version is very new, return LE_OTHER. If the version is so old that it
4871 * doesn't support event_get_version(), return LE_OLD. */
4872 static le_version_t
4873 decode_libevent_version(const char *v, int *bincompat_out)
4875 int i;
4876 for (i=0; le_version_table[i].name; ++i) {
4877 if (!strcmp(le_version_table[i].name, v)) {
4878 if (bincompat_out)
4879 *bincompat_out = le_version_table[i].bincompat;
4880 return le_version_table[i].version;
4883 if (v[0] != '1' && bincompat_out)
4884 *bincompat_out = 100;
4885 else if (!strcmpstart(v, "1.4") && bincompat_out)
4886 *bincompat_out = 2;
4887 return LE_OTHER;
4890 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4892 * Compare the given libevent method and version to a list of versions
4893 * which are known not to work. Warn the user as appropriate.
4895 static void
4896 check_libevent_version(const char *m, int server)
4898 int buggy = 0, iffy = 0, slow = 0, thread_unsafe = 0;
4899 le_version_t version;
4900 const char *v = event_get_version();
4901 const char *badness = NULL;
4902 const char *sad_os = "";
4904 version = decode_libevent_version(v, NULL);
4906 /* XXX Would it be worthwhile disabling the methods that we know
4907 * are buggy, rather than just warning about them and then proceeding
4908 * to use them? If so, we should probably not wrap this whole thing
4909 * in HAVE_EVENT_GET_VERSION and HAVE_EVENT_GET_METHOD. -RD */
4910 /* XXXX The problem is that it's not trivial to get libevent to change it's
4911 * method once it's initialized, and it's not trivial to tell what method it
4912 * will use without initializing it. I guess we could preemptively disable
4913 * buggy libevent modes based on the version _before_ initializing it,
4914 * though, but then there's no good way (afaict) to warn "I would have used
4915 * kqueue, but instead I'm using select." -NM */
4916 if (!strcmp(m, "kqueue")) {
4917 if (version < LE_11B)
4918 buggy = 1;
4919 } else if (!strcmp(m, "epoll")) {
4920 if (version < LE_11)
4921 iffy = 1;
4922 } else if (!strcmp(m, "poll")) {
4923 if (version < LE_10E)
4924 buggy = 1;
4925 else if (version < LE_11)
4926 slow = 1;
4927 } else if (!strcmp(m, "select")) {
4928 if (version < LE_11)
4929 slow = 1;
4930 } else if (!strcmp(m, "win32")) {
4931 if (version < LE_11B)
4932 buggy = 1;
4935 /* Libevent versions before 1.3b do very badly on operating systems with
4936 * user-space threading implementations. */
4937 #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
4938 if (server && version < LE_13B) {
4939 thread_unsafe = 1;
4940 sad_os = "BSD variants";
4942 #elif defined(__APPLE__) || defined(__darwin__)
4943 if (server && version < LE_13B) {
4944 thread_unsafe = 1;
4945 sad_os = "Mac OS X";
4947 #endif
4949 if (thread_unsafe) {
4950 log(LOG_WARN, LD_GENERAL,
4951 "Libevent version %s often crashes when running a Tor server with %s. "
4952 "Please use the latest version of libevent (1.3b or later)",v,sad_os);
4953 badness = "BROKEN";
4954 } else if (buggy) {
4955 log(LOG_WARN, LD_GENERAL,
4956 "There are serious bugs in using %s with libevent %s. "
4957 "Please use the latest version of libevent.", m, v);
4958 badness = "BROKEN";
4959 } else if (iffy) {
4960 log(LOG_WARN, LD_GENERAL,
4961 "There are minor bugs in using %s with libevent %s. "
4962 "You may want to use the latest version of libevent.", m, v);
4963 badness = "BUGGY";
4964 } else if (slow && server) {
4965 log(LOG_WARN, LD_GENERAL,
4966 "libevent %s can be very slow with %s. "
4967 "When running a server, please use the latest version of libevent.",
4968 v,m);
4969 badness = "SLOW";
4971 if (badness) {
4972 control_event_general_status(LOG_WARN,
4973 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
4974 v, m, badness);
4978 #endif
4980 /** Return the persistent state struct for this Tor. */
4981 or_state_t *
4982 get_or_state(void)
4984 tor_assert(global_state);
4985 return global_state;
4988 /** Return a newly allocated string holding a filename relative to the data
4989 * directory. If <b>sub1</b> is present, it is the first path component after
4990 * the data directory. If <b>sub2</b> is also present, it is the second path
4991 * component after the data directory. If <b>suffix</b> is present, it
4992 * is appended to the filename.
4994 * Examples:
4995 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
4996 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
4997 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
4998 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
5000 * Note: Consider using the get_datadir_fname* macros in or.h.
5002 char *
5003 options_get_datadir_fname2_suffix(or_options_t *options,
5004 const char *sub1, const char *sub2,
5005 const char *suffix)
5007 char *fname = NULL;
5008 size_t len;
5009 tor_assert(options);
5010 tor_assert(options->DataDirectory);
5011 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
5012 len = strlen(options->DataDirectory);
5013 if (sub1) {
5014 len += strlen(sub1)+1;
5015 if (sub2)
5016 len += strlen(sub2)+1;
5018 if (suffix)
5019 len += strlen(suffix);
5020 len++;
5021 fname = tor_malloc(len);
5022 if (sub1) {
5023 if (sub2) {
5024 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
5025 options->DataDirectory, sub1, sub2);
5026 } else {
5027 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
5028 options->DataDirectory, sub1);
5030 } else {
5031 strlcpy(fname, options->DataDirectory, len);
5033 if (suffix)
5034 strlcat(fname, suffix, len);
5035 return fname;
5038 /** Return 0 if every setting in <b>state</b> is reasonable, and a
5039 * permissible transition from <b>old_state</b>. Else warn and return -1.
5040 * Should have no side effects, except for normalizing the contents of
5041 * <b>state</b>.
5043 /* XXX from_setconf is here because of bug 238 */
5044 static int
5045 or_state_validate(or_state_t *old_state, or_state_t *state,
5046 int from_setconf, char **msg)
5048 /* We don't use these; only options do. Still, we need to match that
5049 * signature. */
5050 (void) from_setconf;
5051 (void) old_state;
5053 if (entry_guards_parse_state(state, 0, msg)<0)
5054 return -1;
5056 return 0;
5059 /** Replace the current persistent state with <b>new_state</b> */
5060 static void
5061 or_state_set(or_state_t *new_state)
5063 char *err = NULL;
5064 tor_assert(new_state);
5065 if (global_state)
5066 config_free(&state_format, global_state);
5067 global_state = new_state;
5068 if (entry_guards_parse_state(global_state, 1, &err)<0) {
5069 log_warn(LD_GENERAL,"%s",err);
5070 tor_free(err);
5072 if (rep_hist_load_state(global_state, &err)<0) {
5073 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
5074 tor_free(err);
5078 /** Reload the persistent state from disk, generating a new state as needed.
5079 * Return 0 on success, less than 0 on failure.
5081 static int
5082 or_state_load(void)
5084 or_state_t *new_state = NULL;
5085 char *contents = NULL, *fname;
5086 char *errmsg = NULL;
5087 int r = -1, badstate = 0;
5089 fname = get_datadir_fname("state");
5090 switch (file_status(fname)) {
5091 case FN_FILE:
5092 if (!(contents = read_file_to_str(fname, 0, NULL))) {
5093 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
5094 goto done;
5096 break;
5097 case FN_NOENT:
5098 break;
5099 case FN_ERROR:
5100 case FN_DIR:
5101 default:
5102 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
5103 goto done;
5105 new_state = tor_malloc_zero(sizeof(or_state_t));
5106 new_state->_magic = OR_STATE_MAGIC;
5107 config_init(&state_format, new_state);
5108 if (contents) {
5109 config_line_t *lines=NULL;
5110 int assign_retval;
5111 if (config_get_lines(contents, &lines)<0)
5112 goto done;
5113 assign_retval = config_assign(&state_format, new_state,
5114 lines, 0, 0, &errmsg);
5115 config_free_lines(lines);
5116 if (assign_retval<0)
5117 badstate = 1;
5118 if (errmsg) {
5119 log_warn(LD_GENERAL, "%s", errmsg);
5120 tor_free(errmsg);
5124 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
5125 badstate = 1;
5127 if (errmsg) {
5128 log_warn(LD_GENERAL, "%s", errmsg);
5129 tor_free(errmsg);
5132 if (badstate && !contents) {
5133 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
5134 " This is a bug in Tor.");
5135 goto done;
5136 } else if (badstate && contents) {
5137 int i;
5138 file_status_t status;
5139 size_t len = strlen(fname)+16;
5140 char *fname2 = tor_malloc(len);
5141 for (i = 0; i < 100; ++i) {
5142 tor_snprintf(fname2, len, "%s.%d", fname, i);
5143 status = file_status(fname2);
5144 if (status == FN_NOENT)
5145 break;
5147 if (i == 100) {
5148 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
5149 "state files to move aside. Discarding the old state file.",
5150 fname);
5151 unlink(fname);
5152 } else {
5153 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
5154 "to \"%s\". This could be a bug in Tor; please tell "
5155 "the developers.", fname, fname2);
5156 if (rename(fname, fname2) < 0) {
5157 log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
5158 "OS gave an error of %s", strerror(errno));
5161 tor_free(fname2);
5162 tor_free(contents);
5163 config_free(&state_format, new_state);
5165 new_state = tor_malloc_zero(sizeof(or_state_t));
5166 new_state->_magic = OR_STATE_MAGIC;
5167 config_init(&state_format, new_state);
5168 } else if (contents) {
5169 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
5170 } else {
5171 log_info(LD_GENERAL, "Initialized state");
5173 or_state_set(new_state);
5174 new_state = NULL;
5175 if (!contents) {
5176 global_state->next_write = 0;
5177 or_state_save(time(NULL));
5179 r = 0;
5181 done:
5182 tor_free(fname);
5183 tor_free(contents);
5184 if (new_state)
5185 config_free(&state_format, new_state);
5187 return r;
5190 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
5192 or_state_save(time_t now)
5194 char *state, *contents;
5195 char tbuf[ISO_TIME_LEN+1];
5196 size_t len;
5197 char *fname;
5199 tor_assert(global_state);
5201 if (global_state->next_write > now)
5202 return 0;
5204 /* Call everything else that might dirty the state even more, in order
5205 * to avoid redundant writes. */
5206 entry_guards_update_state(global_state);
5207 rep_hist_update_state(global_state);
5208 if (accounting_is_enabled(get_options()))
5209 accounting_run_housekeeping(now);
5211 global_state->LastWritten = time(NULL);
5212 tor_free(global_state->TorVersion);
5213 len = strlen(get_version())+8;
5214 global_state->TorVersion = tor_malloc(len);
5215 tor_snprintf(global_state->TorVersion, len, "Tor %s", get_version());
5217 state = config_dump(&state_format, global_state, 1, 0);
5218 len = strlen(state)+256;
5219 contents = tor_malloc(len);
5220 format_local_iso_time(tbuf, time(NULL));
5221 tor_snprintf(contents, len,
5222 "# Tor state file last generated on %s local time\n"
5223 "# Other times below are in GMT\n"
5224 "# You *do not* need to edit this file.\n\n%s",
5225 tbuf, state);
5226 tor_free(state);
5227 fname = get_datadir_fname("state");
5228 if (write_str_to_file(fname, contents, 0)<0) {
5229 log_warn(LD_FS, "Unable to write state to file \"%s\"", fname);
5230 tor_free(fname);
5231 tor_free(contents);
5232 return -1;
5234 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
5235 tor_free(fname);
5236 tor_free(contents);
5238 global_state->next_write = TIME_MAX;
5239 return 0;
5242 /** Given a file name check to see whether the file exists but has not been
5243 * modified for a very long time. If so, remove it. */
5244 void
5245 remove_file_if_very_old(const char *fname, time_t now)
5247 #define VERY_OLD_FILE_AGE (28*24*60*60)
5248 struct stat st;
5250 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
5251 char buf[ISO_TIME_LEN+1];
5252 format_local_iso_time(buf, st.st_mtime);
5253 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
5254 "Removing it.", fname, buf);
5255 unlink(fname);
5259 /** Helper to implement GETINFO functions about configuration variables (not
5260 * their values). Given a "config/names" question, set *<b>answer</b> to a
5261 * new string describing the supported configuration variables and their
5262 * types. */
5264 getinfo_helper_config(control_connection_t *conn,
5265 const char *question, char **answer)
5267 (void) conn;
5268 if (!strcmp(question, "config/names")) {
5269 smartlist_t *sl = smartlist_create();
5270 int i;
5271 for (i = 0; _option_vars[i].name; ++i) {
5272 config_var_t *var = &_option_vars[i];
5273 const char *type, *desc;
5274 char *line;
5275 size_t len;
5276 desc = config_find_description(&options_format, var->name);
5277 switch (var->type) {
5278 case CONFIG_TYPE_STRING: type = "String"; break;
5279 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
5280 case CONFIG_TYPE_UINT: type = "Integer"; break;
5281 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
5282 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
5283 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
5284 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
5285 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
5286 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
5287 case CONFIG_TYPE_CSV: type = "CommaList"; break;
5288 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
5289 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
5290 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
5291 default:
5292 case CONFIG_TYPE_OBSOLETE:
5293 type = NULL; break;
5295 if (!type)
5296 continue;
5297 len = strlen(var->name)+strlen(type)+16;
5298 if (desc)
5299 len += strlen(desc);
5300 line = tor_malloc(len);
5301 if (desc)
5302 tor_snprintf(line, len, "%s %s %s\n",var->name,type,desc);
5303 else
5304 tor_snprintf(line, len, "%s %s\n",var->name,type);
5305 smartlist_add(sl, line);
5307 *answer = smartlist_join_strings(sl, "", 0, NULL);
5308 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
5309 smartlist_free(sl);
5311 return 0;