Move dizum to an alternate IP address.
[tor.git] / src / or / config.c
blob84fe80350b8cc8fa42848ecd1c2fd862cbd550c1
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2009, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file config.c
9 * \brief Code to parse and interpret configuration files.
10 **/
12 #define CONFIG_PRIVATE
14 #include "or.h"
15 #ifdef MS_WINDOWS
16 #include <shlobj.h>
17 #endif
19 /** Enumeration of types which option values can take */
20 typedef enum config_type_t {
21 CONFIG_TYPE_STRING = 0, /**< An arbitrary string. */
22 CONFIG_TYPE_FILENAME, /**< A filename: some prefixes get expanded. */
23 CONFIG_TYPE_UINT, /**< A non-negative integer less than MAX_INT */
24 CONFIG_TYPE_INTERVAL, /**< A number of seconds, with optional units*/
25 CONFIG_TYPE_MEMUNIT, /**< A number of bytes, with optional units*/
26 CONFIG_TYPE_DOUBLE, /**< A floating-point value */
27 CONFIG_TYPE_BOOL, /**< A boolean value, expressed as 0 or 1. */
28 CONFIG_TYPE_ISOTIME, /**< An ISO-formatted time relative to GMT. */
29 CONFIG_TYPE_CSV, /**< A list of strings, separated by commas and
30 * optional whitespace. */
31 CONFIG_TYPE_LINELIST, /**< Uninterpreted config lines */
32 CONFIG_TYPE_LINELIST_S, /**< Uninterpreted, context-sensitive config lines,
33 * mixed with other keywords. */
34 CONFIG_TYPE_LINELIST_V, /**< Catch-all "virtual" option to summarize
35 * context-sensitive config lines when fetching.
37 CONFIG_TYPE_ROUTERSET, /**< A list of router names, addrs, and fps,
38 * parsed into a routerset_t. */
39 CONFIG_TYPE_OBSOLETE, /**< Obsolete (ignored) option. */
40 } config_type_t;
42 /** An abbreviation for a configuration option allowed on the command line. */
43 typedef struct config_abbrev_t {
44 const char *abbreviated;
45 const char *full;
46 int commandline_only;
47 int warn;
48 } config_abbrev_t;
50 /* Handy macro for declaring "In the config file or on the command line,
51 * you can abbreviate <b>tok</b>s as <b>tok</b>". */
52 #define PLURAL(tok) { #tok, #tok "s", 0, 0 }
54 /** A list of abbreviations and aliases to map command-line options, obsolete
55 * option names, or alternative option names, to their current values. */
56 static config_abbrev_t _option_abbrevs[] = {
57 PLURAL(ExitNode),
58 PLURAL(EntryNode),
59 PLURAL(ExcludeNode),
60 PLURAL(FirewallPort),
61 PLURAL(LongLivedPort),
62 PLURAL(HiddenServiceNode),
63 PLURAL(HiddenServiceExcludeNode),
64 PLURAL(NumCpu),
65 PLURAL(RendNode),
66 PLURAL(RendExcludeNode),
67 PLURAL(StrictEntryNode),
68 PLURAL(StrictExitNode),
69 { "l", "Log", 1, 0},
70 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
71 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
72 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
73 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
74 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
75 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
76 { "MaxConn", "ConnLimit", 0, 1},
77 { "ORBindAddress", "ORListenAddress", 0, 0},
78 { "DirBindAddress", "DirListenAddress", 0, 0},
79 { "SocksBindAddress", "SocksListenAddress", 0, 0},
80 { "UseHelperNodes", "UseEntryGuards", 0, 0},
81 { "NumHelperNodes", "NumEntryGuards", 0, 0},
82 { "UseEntryNodes", "UseEntryGuards", 0, 0},
83 { "NumEntryNodes", "NumEntryGuards", 0, 0},
84 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
85 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
86 { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0 },
87 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
88 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
89 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
90 { NULL, NULL, 0, 0},
93 /** A list of state-file "abbreviations," for compatibility. */
94 static config_abbrev_t _state_abbrevs[] = {
95 { "AccountingBytesReadInterval", "AccountingBytesReadInInterval", 0, 0 },
96 { "HelperNode", "EntryGuard", 0, 0 },
97 { "HelperNodeDownSince", "EntryGuardDownSince", 0, 0 },
98 { "HelperNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
99 { "EntryNode", "EntryGuard", 0, 0 },
100 { "EntryNodeDownSince", "EntryGuardDownSince", 0, 0 },
101 { "EntryNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
102 { NULL, NULL, 0, 0},
104 #undef PLURAL
106 /** A variable allowed in the configuration file or on the command line. */
107 typedef struct config_var_t {
108 const char *name; /**< The full keyword (case insensitive). */
109 config_type_t type; /**< How to interpret the type and turn it into a
110 * value. */
111 off_t var_offset; /**< Offset of the corresponding member of or_options_t. */
112 const char *initvalue; /**< String (or null) describing initial value. */
113 } config_var_t;
115 /** An entry for config_vars: "The option <b>name</b> has type
116 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
117 * or_options_t.<b>member</b>"
119 #define VAR(name,conftype,member,initvalue) \
120 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
121 initvalue }
122 /** As VAR, but the option name and member name are the same. */
123 #define V(member,conftype,initvalue) \
124 VAR(#member, conftype, member, initvalue)
125 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
126 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
128 /** Array of configuration options. Until we disallow nonstandard
129 * abbreviations, order is significant, since the first matching option will
130 * be chosen first.
132 static config_var_t _option_vars[] = {
133 OBSOLETE("AccountingMaxKB"),
134 V(AccountingMax, MEMUNIT, "0 bytes"),
135 V(AccountingStart, STRING, NULL),
136 V(Address, STRING, NULL),
137 V(AllowDotExit, BOOL, "0"),
138 V(AllowInvalidNodes, CSV, "middle,rendezvous"),
139 V(AllowNonRFC953Hostnames, BOOL, "0"),
140 V(AllowSingleHopCircuits, BOOL, "0"),
141 V(AllowSingleHopExits, BOOL, "0"),
142 V(AlternateBridgeAuthority, LINELIST, NULL),
143 V(AlternateDirAuthority, LINELIST, NULL),
144 V(AlternateHSAuthority, LINELIST, NULL),
145 V(AssumeReachable, BOOL, "0"),
146 V(AuthDirBadDir, LINELIST, NULL),
147 V(AuthDirBadExit, LINELIST, NULL),
148 V(AuthDirInvalid, LINELIST, NULL),
149 V(AuthDirReject, LINELIST, NULL),
150 V(AuthDirRejectUnlisted, BOOL, "0"),
151 V(AuthDirListBadDirs, BOOL, "0"),
152 V(AuthDirListBadExits, BOOL, "0"),
153 V(AuthDirMaxServersPerAddr, UINT, "2"),
154 V(AuthDirMaxServersPerAuthAddr,UINT, "5"),
155 VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
156 V(AutomapHostsOnResolve, BOOL, "0"),
157 V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
158 V(AvoidDiskWrites, BOOL, "0"),
159 V(BandwidthBurst, MEMUNIT, "10 MB"),
160 V(BandwidthRate, MEMUNIT, "5 MB"),
161 V(BridgeAuthoritativeDir, BOOL, "0"),
162 VAR("Bridge", LINELIST, Bridges, NULL),
163 V(BridgePassword, STRING, NULL),
164 V(BridgeRecordUsageByCountry, BOOL, "1"),
165 V(BridgeRelay, BOOL, "0"),
166 V(CellStatistics, BOOL, "0"),
167 V(CircuitBuildTimeout, INTERVAL, "0"),
168 V(CircuitIdleTimeout, INTERVAL, "1 hour"),
169 V(ClientDNSRejectInternalAddresses, BOOL,"1"),
170 V(ClientOnly, BOOL, "0"),
171 V(ConsensusParams, STRING, NULL),
172 V(ConnLimit, UINT, "1000"),
173 V(ConstrainedSockets, BOOL, "0"),
174 V(ConstrainedSockSize, MEMUNIT, "8192"),
175 V(ContactInfo, STRING, NULL),
176 V(ControlListenAddress, LINELIST, NULL),
177 V(ControlPort, UINT, "0"),
178 V(ControlSocket, LINELIST, NULL),
179 V(CookieAuthentication, BOOL, "0"),
180 V(CookieAuthFileGroupReadable, BOOL, "0"),
181 V(CookieAuthFile, STRING, NULL),
182 V(DataDirectory, FILENAME, NULL),
183 OBSOLETE("DebugLogFile"),
184 V(DirAllowPrivateAddresses, BOOL, NULL),
185 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
186 V(DirListenAddress, LINELIST, NULL),
187 OBSOLETE("DirFetchPeriod"),
188 V(DirPolicy, LINELIST, NULL),
189 V(DirPort, UINT, "0"),
190 V(DirPortFrontPage, FILENAME, NULL),
191 OBSOLETE("DirPostPeriod"),
192 OBSOLETE("DirRecordUsageByCountry"),
193 OBSOLETE("DirRecordUsageGranularity"),
194 OBSOLETE("DirRecordUsageRetainIPs"),
195 OBSOLETE("DirRecordUsageSaveInterval"),
196 V(DirReqStatistics, BOOL, "0"),
197 VAR("DirServer", LINELIST, DirServers, NULL),
198 V(DNSPort, UINT, "0"),
199 V(DNSListenAddress, LINELIST, NULL),
200 V(DownloadExtraInfo, BOOL, "0"),
201 V(EnforceDistinctSubnets, BOOL, "1"),
202 V(EntryNodes, ROUTERSET, NULL),
203 V(EntryStatistics, BOOL, "0"),
204 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
205 V(ExcludeNodes, ROUTERSET, NULL),
206 V(ExcludeExitNodes, ROUTERSET, NULL),
207 V(ExcludeSingleHopRelays, BOOL, "1"),
208 V(ExitNodes, ROUTERSET, NULL),
209 V(ExitPolicy, LINELIST, NULL),
210 V(ExitPolicyRejectPrivate, BOOL, "1"),
211 V(ExitPortStatistics, BOOL, "0"),
212 V(ExtraInfoStatistics, BOOL, "0"),
213 V(FallbackNetworkstatusFile, FILENAME,
214 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "fallback-consensus"),
215 V(FascistFirewall, BOOL, "0"),
216 V(FirewallPorts, CSV, ""),
217 V(FastFirstHopPK, BOOL, "1"),
218 V(FetchDirInfoEarly, BOOL, "0"),
219 V(FetchDirInfoExtraEarly, BOOL, "0"),
220 V(FetchServerDescriptors, BOOL, "1"),
221 V(FetchHidServDescriptors, BOOL, "1"),
222 V(FetchUselessDescriptors, BOOL, "0"),
223 #ifdef WIN32
224 V(GeoIPFile, FILENAME, "<default>"),
225 #else
226 V(GeoIPFile, FILENAME,
227 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
228 #endif
229 OBSOLETE("Group"),
230 V(HardwareAccel, BOOL, "0"),
231 V(AccelName, STRING, NULL),
232 V(AccelDir, FILENAME, NULL),
233 V(HashedControlPassword, LINELIST, NULL),
234 V(HidServDirectoryV2, BOOL, "1"),
235 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
236 OBSOLETE("HiddenServiceExcludeNodes"),
237 OBSOLETE("HiddenServiceNodes"),
238 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
239 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
240 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
241 VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
242 V(HidServAuth, LINELIST, NULL),
243 V(HSAuthoritativeDir, BOOL, "0"),
244 V(HSAuthorityRecordStats, BOOL, "0"),
245 V(HttpProxy, STRING, NULL),
246 V(HttpProxyAuthenticator, STRING, NULL),
247 V(HttpsProxy, STRING, NULL),
248 V(HttpsProxyAuthenticator, STRING, NULL),
249 V(Socks4Proxy, STRING, NULL),
250 V(Socks5Proxy, STRING, NULL),
251 V(Socks5ProxyUsername, STRING, NULL),
252 V(Socks5ProxyPassword, STRING, NULL),
253 OBSOLETE("IgnoreVersion"),
254 V(KeepalivePeriod, INTERVAL, "5 minutes"),
255 VAR("Log", LINELIST, Logs, NULL),
256 OBSOLETE("LinkPadding"),
257 OBSOLETE("LogLevel"),
258 OBSOLETE("LogFile"),
259 V(LongLivedPorts, CSV,
260 "21,22,706,1863,5050,5190,5222,5223,6667,6697,8300"),
261 VAR("MapAddress", LINELIST, AddressMap, NULL),
262 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
263 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
264 V(MaxOnionsPending, UINT, "100"),
265 OBSOLETE("MonthlyAccountingStart"),
266 V(MyFamily, STRING, NULL),
267 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
268 VAR("NamingAuthoritativeDirectory",BOOL, NamingAuthoritativeDir, "0"),
269 V(NatdListenAddress, LINELIST, NULL),
270 V(NatdPort, UINT, "0"),
271 V(Nickname, STRING, NULL),
272 V(NoPublish, BOOL, "0"),
273 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
274 V(NumCpus, UINT, "1"),
275 V(NumEntryGuards, UINT, "3"),
276 V(ORListenAddress, LINELIST, NULL),
277 V(ORPort, UINT, "0"),
278 V(OutboundBindAddress, STRING, NULL),
279 OBSOLETE("PathlenCoinWeight"),
280 V(PidFile, STRING, NULL),
281 V(TestingTorNetwork, BOOL, "0"),
282 V(PreferTunneledDirConns, BOOL, "1"),
283 V(ProtocolWarnings, BOOL, "0"),
284 V(PublishServerDescriptor, CSV, "1"),
285 V(PublishHidServDescriptors, BOOL, "1"),
286 V(ReachableAddresses, LINELIST, NULL),
287 V(ReachableDirAddresses, LINELIST, NULL),
288 V(ReachableORAddresses, LINELIST, NULL),
289 V(RecommendedVersions, LINELIST, NULL),
290 V(RecommendedClientVersions, LINELIST, NULL),
291 V(RecommendedServerVersions, LINELIST, NULL),
292 OBSOLETE("RedirectExit"),
293 V(RejectPlaintextPorts, CSV, ""),
294 V(RelayBandwidthBurst, MEMUNIT, "0"),
295 V(RelayBandwidthRate, MEMUNIT, "0"),
296 OBSOLETE("RendExcludeNodes"),
297 OBSOLETE("RendNodes"),
298 V(RendPostPeriod, INTERVAL, "1 hour"),
299 V(RephistTrackTime, INTERVAL, "24 hours"),
300 OBSOLETE("RouterFile"),
301 V(RunAsDaemon, BOOL, "0"),
302 V(RunTesting, BOOL, "0"),
303 V(SafeLogging, BOOL, "1"),
304 V(SafeSocks, BOOL, "0"),
305 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
306 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
307 V(ServerDNSDetectHijacking, BOOL, "1"),
308 V(ServerDNSRandomizeCase, BOOL, "1"),
309 V(ServerDNSResolvConfFile, STRING, NULL),
310 V(ServerDNSSearchDomains, BOOL, "0"),
311 V(ServerDNSTestAddresses, CSV,
312 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
313 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
314 V(SocksListenAddress, LINELIST, NULL),
315 V(SocksPolicy, LINELIST, NULL),
316 V(SocksPort, UINT, "9050"),
317 V(SocksTimeout, INTERVAL, "2 minutes"),
318 OBSOLETE("StatusFetchPeriod"),
319 V(StrictEntryNodes, BOOL, "0"),
320 V(StrictExitNodes, BOOL, "0"),
321 OBSOLETE("SysLog"),
322 V(TestSocks, BOOL, "0"),
323 OBSOLETE("TestVia"),
324 V(TrackHostExits, CSV, NULL),
325 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
326 OBSOLETE("TrafficShaping"),
327 V(TransListenAddress, LINELIST, NULL),
328 V(TransPort, UINT, "0"),
329 V(TunnelDirConns, BOOL, "1"),
330 V(UpdateBridgesFromAuthority, BOOL, "0"),
331 V(UseBridges, BOOL, "0"),
332 V(UseEntryGuards, BOOL, "1"),
333 V(User, STRING, NULL),
334 VAR("V1AuthoritativeDirectory",BOOL, V1AuthoritativeDir, "0"),
335 VAR("V2AuthoritativeDirectory",BOOL, V2AuthoritativeDir, "0"),
336 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
337 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
338 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
339 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
340 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
341 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
342 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
343 V(V3AuthNIntervalsValid, UINT, "3"),
344 V(V3AuthUseLegacyKey, BOOL, "0"),
345 V(V3BandwidthsFile, FILENAME, NULL),
346 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
347 V(VirtualAddrNetwork, STRING, "127.192.0.0/10"),
348 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
349 VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
350 VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
351 VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
352 VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
353 VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
354 NULL),
355 V(MinUptimeHidServDirectoryV2, INTERVAL, "24 hours"),
356 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
359 /** Override default values with these if the user sets the TestingTorNetwork
360 * option. */
361 static config_var_t testing_tor_network_defaults[] = {
362 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
363 V(DirAllowPrivateAddresses, BOOL, "1"),
364 V(EnforceDistinctSubnets, BOOL, "0"),
365 V(AssumeReachable, BOOL, "1"),
366 V(AuthDirMaxServersPerAddr, UINT, "0"),
367 V(AuthDirMaxServersPerAuthAddr,UINT, "0"),
368 V(ClientDNSRejectInternalAddresses, BOOL,"0"),
369 V(ExitPolicyRejectPrivate, BOOL, "0"),
370 V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
371 V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
372 V(V3AuthDistDelay, INTERVAL, "20 seconds"),
373 V(TestingV3AuthInitialVotingInterval, INTERVAL, "5 minutes"),
374 V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
375 V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
376 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
377 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
378 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
380 #undef VAR
382 #define VAR(name,conftype,member,initvalue) \
383 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
384 initvalue }
386 /** Array of "state" variables saved to the ~/.tor/state file. */
387 static config_var_t _state_vars[] = {
388 V(AccountingBytesReadInInterval, MEMUNIT, NULL),
389 V(AccountingBytesWrittenInInterval, MEMUNIT, NULL),
390 V(AccountingExpectedUsage, MEMUNIT, NULL),
391 V(AccountingIntervalStart, ISOTIME, NULL),
392 V(AccountingSecondsActive, INTERVAL, NULL),
394 VAR("EntryGuard", LINELIST_S, EntryGuards, NULL),
395 VAR("EntryGuardDownSince", LINELIST_S, EntryGuards, NULL),
396 VAR("EntryGuardUnlistedSince", LINELIST_S, EntryGuards, NULL),
397 VAR("EntryGuardAddedBy", LINELIST_S, EntryGuards, NULL),
398 V(EntryGuards, LINELIST_V, NULL),
400 V(BWHistoryReadEnds, ISOTIME, NULL),
401 V(BWHistoryReadInterval, UINT, "900"),
402 V(BWHistoryReadValues, CSV, ""),
403 V(BWHistoryWriteEnds, ISOTIME, NULL),
404 V(BWHistoryWriteInterval, UINT, "900"),
405 V(BWHistoryWriteValues, CSV, ""),
407 V(TorVersion, STRING, NULL),
409 V(LastRotatedOnionKey, ISOTIME, NULL),
410 V(LastWritten, ISOTIME, NULL),
412 V(TotalBuildTimes, UINT, NULL),
413 VAR("CircuitBuildTimeBin", LINELIST_S, BuildtimeHistogram, NULL),
414 VAR("BuildtimeHistogram", LINELIST_V, BuildtimeHistogram, NULL),
416 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
419 #undef VAR
420 #undef V
421 #undef OBSOLETE
423 /** Represents an English description of a configuration variable; used when
424 * generating configuration file comments. */
425 typedef struct config_var_description_t {
426 const char *name;
427 const char *description;
428 } config_var_description_t;
430 /** Descriptions of the configuration options, to be displayed by online
431 * option browsers */
432 /* XXXX022 did anybody want this? at all? If not, kill it.*/
433 static config_var_description_t options_description[] = {
434 /* ==== general options */
435 { "AvoidDiskWrites", "If non-zero, try to write to disk less frequently than"
436 " we would otherwise." },
437 { "BandwidthRate", "A token bucket limits the average incoming bandwidth on "
438 "this node to the specified number of bytes per second." },
439 { "BandwidthBurst", "Limit the maximum token buffer size (also known as "
440 "burst) to the given number of bytes." },
441 { "ConnLimit", "Minimum number of simultaneous sockets we must have." },
442 { "ConstrainedSockets", "Shrink tx and rx buffers for sockets to avoid "
443 "system limits on vservers and related environments. See man page for "
444 "more information regarding this option." },
445 { "ConstrainedSockSize", "Limit socket buffers to this size when "
446 "ConstrainedSockets is enabled." },
447 /* ControlListenAddress */
448 { "ControlPort", "If set, Tor will accept connections from the same machine "
449 "(localhost only) on this port, and allow those connections to control "
450 "the Tor process using the Tor Control Protocol (described in "
451 "control-spec.txt).", },
452 { "CookieAuthentication", "If this option is set to 1, don't allow any "
453 "connections to the control port except when the connecting process "
454 "can read a file that Tor creates in its data directory." },
455 { "DataDirectory", "Store working data, state, keys, and caches here." },
456 { "DirServer", "Tor only trusts directories signed with one of these "
457 "servers' keys. Used to override the standard list of directory "
458 "authorities." },
459 /* { "FastFirstHopPK", "" }, */
460 /* FetchServerDescriptors, FetchHidServDescriptors,
461 * FetchUselessDescriptors */
462 { "HardwareAccel", "If set, Tor tries to use hardware crypto accelerators "
463 "when it can." },
464 { "AccelName", "If set, try to use hardware crypto accelerator with this "
465 "specific ID." },
466 { "AccelDir", "If set, look in this directory for the dynamic hardware "
467 "engine in addition to OpenSSL default path." },
468 /* HashedControlPassword */
469 { "HTTPProxy", "Force Tor to make all HTTP directory requests through this "
470 "host:port (or host:80 if port is not set)." },
471 { "HTTPProxyAuthenticator", "A username:password pair to be used with "
472 "HTTPProxy." },
473 { "HTTPSProxy", "Force Tor to make all TLS (SSL) connections through this "
474 "host:port (or host:80 if port is not set)." },
475 { "HTTPSProxyAuthenticator", "A username:password pair to be used with "
476 "HTTPSProxy." },
477 { "KeepalivePeriod", "Send a padding cell every N seconds to keep firewalls "
478 "from closing our connections while Tor is not in use." },
479 { "Log", "Where to send logging messages. Format is "
480 "minSeverity[-maxSeverity] (stderr|stdout|syslog|file FILENAME)." },
481 { "OutboundBindAddress", "Make all outbound connections originate from the "
482 "provided IP address (only useful for multiple network interfaces)." },
483 { "PIDFile", "On startup, write our PID to this file. On clean shutdown, "
484 "remove the file." },
485 { "PreferTunneledDirConns", "If non-zero, avoid directory servers that "
486 "don't support tunneled connections." },
487 /* PreferTunneledDirConns */
488 /* ProtocolWarnings */
489 /* RephistTrackTime */
490 { "RunAsDaemon", "If set, Tor forks and daemonizes to the background when "
491 "started. Unix only." },
492 { "SafeLogging", "If set to 0, Tor logs potentially sensitive strings "
493 "rather than replacing them with the string [scrubbed]." },
494 { "TunnelDirConns", "If non-zero, when a directory server we contact "
495 "supports it, we will build a one-hop circuit and make an encrypted "
496 "connection via its ORPort." },
497 { "User", "On startup, setuid to this user." },
499 /* ==== client options */
500 { "AllowInvalidNodes", "Where on our circuits should Tor allow servers "
501 "that the directory authorities haven't called \"valid\"?" },
502 { "AllowNonRFC953Hostnames", "If set to 1, we don't automatically reject "
503 "hostnames for having invalid characters." },
504 /* CircuitBuildTimeout, CircuitIdleTimeout */
505 { "ClientOnly", "If set to 1, Tor will under no circumstances run as a "
506 "server, even if ORPort is enabled." },
507 { "EntryNodes", "A list of preferred entry nodes to use for the first hop "
508 "in circuits, when possible." },
509 /* { "EnforceDistinctSubnets" , "" }, */
510 { "ExitNodes", "A list of preferred nodes to use for the last hop in "
511 "circuits, when possible." },
512 { "ExcludeNodes", "A list of nodes never to use when building a circuit." },
513 { "FascistFirewall", "If set, Tor will only create outgoing connections to "
514 "servers running on the ports listed in FirewallPorts." },
515 { "FirewallPorts", "A list of ports that we can connect to. Only used "
516 "when FascistFirewall is set." },
517 { "LongLivedPorts", "A list of ports for services that tend to require "
518 "high-uptime connections." },
519 { "MapAddress", "Force Tor to treat all requests for one address as if "
520 "they were for another." },
521 { "NewCircuitPeriod", "Force Tor to consider whether to build a new circuit "
522 "every NUM seconds." },
523 { "MaxCircuitDirtiness", "Do not attach new streams to a circuit that has "
524 "been used more than this many seconds ago." },
525 /* NatdPort, NatdListenAddress */
526 { "NodeFamily", "A list of servers that constitute a 'family' and should "
527 "never be used in the same circuit." },
528 { "NumEntryGuards", "How many entry guards should we keep at a time?" },
529 /* PathlenCoinWeight */
530 { "ReachableAddresses", "Addresses we can connect to, as IP/bits:port-port. "
531 "By default, we assume all addresses are reachable." },
532 /* reachablediraddresses, reachableoraddresses. */
533 /* SafeSOCKS */
534 { "SOCKSPort", "The port where we listen for SOCKS connections from "
535 "applications." },
536 { "SOCKSListenAddress", "Bind to this address to listen to connections from "
537 "SOCKS-speaking applications." },
538 { "SOCKSPolicy", "Set an entry policy to limit which addresses can connect "
539 "to the SOCKSPort." },
540 /* SocksTimeout */
541 { "StrictExitNodes", "If set, Tor will fail to operate when none of the "
542 "configured ExitNodes can be used." },
543 { "StrictEntryNodes", "If set, Tor will fail to operate when none of the "
544 "configured EntryNodes can be used." },
545 /* TestSocks */
546 { "TrackHostsExit", "Hosts and domains which should, if possible, be "
547 "accessed from the same exit node each time we connect to them." },
548 { "TrackHostsExitExpire", "Time after which we forget which exit we were "
549 "using to connect to hosts in TrackHostsExit." },
550 /* "TransPort", "TransListenAddress */
551 { "UseEntryGuards", "Set to 0 if we want to pick from the whole set of "
552 "servers for the first position in each circuit, rather than picking a "
553 "set of 'Guards' to prevent profiling attacks." },
555 /* === server options */
556 { "Address", "The advertised (external) address we should use." },
557 /* Accounting* options. */
558 /* AssumeReachable */
559 { "ContactInfo", "Administrative contact information to advertise for this "
560 "server." },
561 { "ExitPolicy", "Address/port ranges for which to accept or reject outgoing "
562 "connections on behalf of Tor users." },
563 /* { "ExitPolicyRejectPrivate, "" }, */
564 { "MaxAdvertisedBandwidth", "If set, we will not advertise more than this "
565 "amount of bandwidth for our bandwidth rate, regardless of how much "
566 "bandwidth we actually detect." },
567 { "MaxOnionsPending", "Reject new attempts to extend circuits when we "
568 "already have this many pending." },
569 { "MyFamily", "Declare a list of other servers as belonging to the same "
570 "family as this one, so that clients will not use two from the same "
571 "family in the same circuit." },
572 { "Nickname", "Set the server nickname." },
573 { "NoPublish", "{DEPRECATED}" },
574 { "NumCPUs", "How many processes to use at once for public-key crypto." },
575 { "ORPort", "Advertise this port to listen for connections from Tor clients "
576 "and servers." },
577 { "ORListenAddress", "Bind to this address to listen for connections from "
578 "clients and servers, instead of the default 0.0.0.0:ORPort." },
579 { "PublishServerDescriptor", "Set to 0 to keep the server from "
580 "uploading info to the directory authorities." },
581 /* ServerDNS: DetectHijacking, ResolvConfFile, SearchDomains */
582 { "ShutdownWaitLength", "Wait this long for clients to finish when "
583 "shutting down because of a SIGINT." },
585 /* === directory cache options */
586 { "DirPort", "Serve directory information from this port, and act as a "
587 "directory cache." },
588 { "DirPortFrontPage", "Serve a static html disclaimer on DirPort." },
589 { "DirListenAddress", "Bind to this address to listen for connections from "
590 "clients and servers, instead of the default 0.0.0.0:DirPort." },
591 { "DirPolicy", "Set a policy to limit who can connect to the directory "
592 "port." },
594 /* Authority options: AuthDirBadExit, AuthDirInvalid, AuthDirReject,
595 * AuthDirRejectUnlisted, AuthDirListBadExits, AuthoritativeDirectory,
596 * DirAllowPrivateAddresses, HSAuthoritativeDir,
597 * NamingAuthoritativeDirectory, RecommendedVersions,
598 * RecommendedClientVersions, RecommendedServerVersions, RendPostPeriod,
599 * RunTesting, V1AuthoritativeDirectory, VersioningAuthoritativeDirectory, */
601 /* Hidden service options: HiddenService: dir,excludenodes, nodes,
602 * options, port. PublishHidServDescriptor */
604 /* Circuit build time histogram options */
605 { "CircuitBuildTimeBin", "Histogram of recent circuit build times"},
606 { "TotalBuildTimes", "Total number of buildtimes in histogram"},
608 /* Nonpersistent options: __LeaveStreamsUnattached, __AllDirActionsPrivate */
609 { NULL, NULL },
612 /** Online description of state variables. */
613 static config_var_description_t state_description[] = {
614 { "AccountingBytesReadInInterval",
615 "How many bytes have we read in this accounting period?" },
616 { "AccountingBytesWrittenInInterval",
617 "How many bytes have we written in this accounting period?" },
618 { "AccountingExpectedUsage",
619 "How many bytes did we expect to use per minute? (0 for no estimate.)" },
620 { "AccountingIntervalStart", "When did this accounting period begin?" },
621 { "AccountingSecondsActive", "How long have we been awake in this period?" },
623 { "BWHistoryReadEnds", "When does the last-recorded read-interval end?" },
624 { "BWHistoryReadInterval", "How long is each read-interval (in seconds)?" },
625 { "BWHistoryReadValues", "Number of bytes read in each interval." },
626 { "BWHistoryWriteEnds", "When does the last-recorded write-interval end?" },
627 { "BWHistoryWriteInterval", "How long is each write-interval (in seconds)?"},
628 { "BWHistoryWriteValues", "Number of bytes written in each interval." },
630 { "EntryGuard", "One of the nodes we have chosen as a fixed entry" },
631 { "EntryGuardDownSince",
632 "The last entry guard has been unreachable since this time." },
633 { "EntryGuardUnlistedSince",
634 "The last entry guard has been unusable since this time." },
636 { "LastRotatedOnionKey",
637 "The last time at which we changed the medium-term private key used for "
638 "building circuits." },
639 { "LastWritten", "When was this state file last regenerated?" },
641 { "TorVersion", "Which version of Tor generated this state file?" },
642 { NULL, NULL },
645 /** Type of a callback to validate whether a given configuration is
646 * well-formed and consistent. See options_trial_assign() for documentation
647 * of arguments. */
648 typedef int (*validate_fn_t)(void*,void*,int,char**);
650 /** Information on the keys, value types, key-to-struct-member mappings,
651 * variable descriptions, validation functions, and abbreviations for a
652 * configuration or storage format. */
653 typedef struct {
654 size_t size; /**< Size of the struct that everything gets parsed into. */
655 uint32_t magic; /**< Required 'magic value' to make sure we have a struct
656 * of the right type. */
657 off_t magic_offset; /**< Offset of the magic value within the struct. */
658 config_abbrev_t *abbrevs; /**< List of abbreviations that we expand when
659 * parsing this format. */
660 config_var_t *vars; /**< List of variables we recognize, their default
661 * values, and where we stick them in the structure. */
662 validate_fn_t validate_fn; /**< Function to validate config. */
663 /** Documentation for configuration variables. */
664 config_var_description_t *descriptions;
665 /** If present, extra is a LINELIST variable for unrecognized
666 * lines. Otherwise, unrecognized lines are an error. */
667 config_var_t *extra;
668 } config_format_t;
670 /** Macro: assert that <b>cfg</b> has the right magic field for format
671 * <b>fmt</b>. */
672 #define CHECK(fmt, cfg) STMT_BEGIN \
673 tor_assert(fmt && cfg); \
674 tor_assert((fmt)->magic == \
675 *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
676 STMT_END
678 #ifdef MS_WINDOWS
679 static char *get_windows_conf_root(void);
680 #endif
681 static void config_line_append(config_line_t **lst,
682 const char *key, const char *val);
683 static void option_clear(config_format_t *fmt, or_options_t *options,
684 config_var_t *var);
685 static void option_reset(config_format_t *fmt, or_options_t *options,
686 config_var_t *var, int use_defaults);
687 static void config_free(config_format_t *fmt, void *options);
688 static int config_lines_eq(config_line_t *a, config_line_t *b);
689 static int option_is_same(config_format_t *fmt,
690 or_options_t *o1, or_options_t *o2,
691 const char *name);
692 static or_options_t *options_dup(config_format_t *fmt, or_options_t *old);
693 static int options_validate(or_options_t *old_options, or_options_t *options,
694 int from_setconf, char **msg);
695 static int options_act_reversible(or_options_t *old_options, char **msg);
696 static int options_act(or_options_t *old_options);
697 static int options_transition_allowed(or_options_t *old, or_options_t *new,
698 char **msg);
699 static int options_transition_affects_workers(or_options_t *old_options,
700 or_options_t *new_options);
701 static int options_transition_affects_descriptor(or_options_t *old_options,
702 or_options_t *new_options);
703 static int check_nickname_list(const char *lst, const char *name, char **msg);
704 static void config_register_addressmaps(or_options_t *options);
706 static int parse_bridge_line(const char *line, int validate_only);
707 static int parse_dir_server_line(const char *line,
708 authority_type_t required_type,
709 int validate_only);
710 static int validate_data_directory(or_options_t *options);
711 static int write_configuration_file(const char *fname, or_options_t *options);
712 static config_line_t *get_assigned_option(config_format_t *fmt,
713 void *options, const char *key,
714 int escape_val);
715 static void config_init(config_format_t *fmt, void *options);
716 static int or_state_validate(or_state_t *old_options, or_state_t *options,
717 int from_setconf, char **msg);
718 static int or_state_load(void);
719 static int options_init_logs(or_options_t *options, int validate_only);
721 static int is_listening_on_low_port(uint16_t port_option,
722 const config_line_t *listen_options);
724 static uint64_t config_parse_memunit(const char *s, int *ok);
725 static int config_parse_interval(const char *s, int *ok);
726 static void init_libevent(void);
727 static int opt_streq(const char *s1, const char *s2);
729 /** Magic value for or_options_t. */
730 #define OR_OPTIONS_MAGIC 9090909
732 /** Configuration format for or_options_t. */
733 static config_format_t options_format = {
734 sizeof(or_options_t),
735 OR_OPTIONS_MAGIC,
736 STRUCT_OFFSET(or_options_t, _magic),
737 _option_abbrevs,
738 _option_vars,
739 (validate_fn_t)options_validate,
740 options_description,
741 NULL
744 /** Magic value for or_state_t. */
745 #define OR_STATE_MAGIC 0x57A73f57
747 /** "Extra" variable in the state that receives lines we can't parse. This
748 * lets us preserve options from versions of Tor newer than us. */
749 static config_var_t state_extra_var = {
750 "__extra", CONFIG_TYPE_LINELIST, STRUCT_OFFSET(or_state_t, ExtraLines), NULL
753 /** Configuration format for or_state_t. */
754 static config_format_t state_format = {
755 sizeof(or_state_t),
756 OR_STATE_MAGIC,
757 STRUCT_OFFSET(or_state_t, _magic),
758 _state_abbrevs,
759 _state_vars,
760 (validate_fn_t)or_state_validate,
761 state_description,
762 &state_extra_var,
766 * Functions to read and write the global options pointer.
769 /** Command-line and config-file options. */
770 static or_options_t *global_options = NULL;
771 /** Name of most recently read torrc file. */
772 static char *torrc_fname = NULL;
773 /** Persistent serialized state. */
774 static or_state_t *global_state = NULL;
775 /** Configuration Options set by command line. */
776 static config_line_t *global_cmdline_options = NULL;
777 /** Contents of most recently read DirPortFrontPage file. */
778 static char *global_dirfrontpagecontents = NULL;
780 /** Return the contents of our frontpage string, or NULL if not configured. */
781 const char *
782 get_dirportfrontpage(void)
784 return global_dirfrontpagecontents;
787 /** Allocate an empty configuration object of a given format type. */
788 static void *
789 config_alloc(config_format_t *fmt)
791 void *opts = tor_malloc_zero(fmt->size);
792 *(uint32_t*)STRUCT_VAR_P(opts, fmt->magic_offset) = fmt->magic;
793 CHECK(fmt, opts);
794 return opts;
797 /** Return the currently configured options. */
798 or_options_t *
799 get_options(void)
801 tor_assert(global_options);
802 return global_options;
805 /** Change the current global options to contain <b>new_val</b> instead of
806 * their current value; take action based on the new value; free the old value
807 * as necessary. Returns 0 on success, -1 on failure.
810 set_options(or_options_t *new_val, char **msg)
812 or_options_t *old_options = global_options;
813 global_options = new_val;
814 /* Note that we pass the *old* options below, for comparison. It
815 * pulls the new options directly out of global_options. */
816 if (options_act_reversible(old_options, msg)<0) {
817 tor_assert(*msg);
818 global_options = old_options;
819 return -1;
821 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
822 log_err(LD_BUG,
823 "Acting on config options left us in a broken state. Dying.");
824 exit(1);
826 if (old_options)
827 config_free(&options_format, old_options);
829 return 0;
832 extern const char tor_git_revision[]; /* from tor_main.c */
834 /** The version of this Tor process, as parsed. */
835 static char *_version = NULL;
837 /** Return the current Tor version. */
838 const char *
839 get_version(void)
841 if (_version == NULL) {
842 if (strlen(tor_git_revision)) {
843 size_t len = strlen(VERSION)+strlen(tor_git_revision)+16;
844 _version = tor_malloc(len);
845 tor_snprintf(_version, len, "%s (git-%s)", VERSION, tor_git_revision);
846 } else {
847 _version = tor_strdup(VERSION);
850 return _version;
853 /** Release additional memory allocated in options
855 static void
856 or_options_free(or_options_t *options)
858 if (options->_ExcludeExitNodesUnion)
859 routerset_free(options->_ExcludeExitNodesUnion);
860 config_free(&options_format, options);
863 /** Release all memory and resources held by global configuration structures.
865 void
866 config_free_all(void)
868 if (global_options) {
869 or_options_free(global_options);
870 global_options = NULL;
872 if (global_state) {
873 config_free(&state_format, global_state);
874 global_state = NULL;
876 if (global_cmdline_options) {
877 config_free_lines(global_cmdline_options);
878 global_cmdline_options = NULL;
880 tor_free(torrc_fname);
881 tor_free(_version);
882 tor_free(global_dirfrontpagecontents);
885 /** If options->SafeLogging is on, return a not very useful string,
886 * else return address.
888 const char *
889 safe_str(const char *address)
891 tor_assert(address);
892 if (get_options()->SafeLogging)
893 return "[scrubbed]";
894 else
895 return address;
898 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
899 * escaped(): don't use this outside the main thread, or twice in the same
900 * log statement. */
901 const char *
902 escaped_safe_str(const char *address)
904 if (get_options()->SafeLogging)
905 return "[scrubbed]";
906 else
907 return escaped(address);
910 /** Add the default directory authorities directly into the trusted dir list,
911 * but only add them insofar as they share bits with <b>type</b>. */
912 static void
913 add_default_trusted_dir_authorities(authority_type_t type)
915 int i;
916 const char *dirservers[] = {
917 "moria1 v1 orport=9001 v3ident=E2A2AF570166665D738736D0DD58169CC61D8A8B "
918 "128.31.0.39:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441",
919 "moria2 v1 orport=9002 128.31.0.34:9032 "
920 "719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF",
921 "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
922 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
923 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
924 "194.109.206.214:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
925 "Tonga orport=443 bridge no-v2 82.94.251.203:80 "
926 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
927 "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
928 "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
929 "gabelmoo orport=443 no-v2 "
930 "v3ident=81349FC1F2DBA2C2C11B45CB9706637D480AB913 "
931 "80.190.246.100:80 6833 3D07 61BC F397 A587 A0C0 B963 E4A9 E99E C4D3",
932 "dannenberg orport=443 no-v2 "
933 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
934 "213.73.91.31:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
935 "urras orport=80 no-v2 v3ident=80550987E1D626E3EBA5E5E75A458DE0626D088C "
936 "208.83.223.34:443 0AD3 FA88 4D18 F89E EA2D 89C0 1937 9E0E 7FD9 4417",
937 NULL
939 for (i=0; dirservers[i]; i++) {
940 if (parse_dir_server_line(dirservers[i], type, 0)<0) {
941 log_err(LD_BUG, "Couldn't parse internal dirserver line %s",
942 dirservers[i]);
947 /** Look at all the config options for using alternate directory
948 * authorities, and make sure none of them are broken. Also, warn the
949 * user if we changed any dangerous ones.
951 static int
952 validate_dir_authorities(or_options_t *options, or_options_t *old_options)
954 config_line_t *cl;
956 if (options->DirServers &&
957 (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
958 options->AlternateHSAuthority)) {
959 log_warn(LD_CONFIG,
960 "You cannot set both DirServers and Alternate*Authority.");
961 return -1;
964 /* do we want to complain to the user about being partitionable? */
965 if ((options->DirServers &&
966 (!old_options ||
967 !config_lines_eq(options->DirServers, old_options->DirServers))) ||
968 (options->AlternateDirAuthority &&
969 (!old_options ||
970 !config_lines_eq(options->AlternateDirAuthority,
971 old_options->AlternateDirAuthority)))) {
972 log_warn(LD_CONFIG,
973 "You have used DirServer or AlternateDirAuthority to "
974 "specify alternate directory authorities in "
975 "your configuration. This is potentially dangerous: it can "
976 "make you look different from all other Tor users, and hurt "
977 "your anonymity. Even if you've specified the same "
978 "authorities as Tor uses by default, the defaults could "
979 "change in the future. Be sure you know what you're doing.");
982 /* Now go through the four ways you can configure an alternate
983 * set of directory authorities, and make sure none are broken. */
984 for (cl = options->DirServers; cl; cl = cl->next)
985 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
986 return -1;
987 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
988 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
989 return -1;
990 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
991 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
992 return -1;
993 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
994 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
995 return -1;
996 return 0;
999 /** Look at all the config options and assign new dir authorities
1000 * as appropriate.
1002 static int
1003 consider_adding_dir_authorities(or_options_t *options,
1004 or_options_t *old_options)
1006 config_line_t *cl;
1007 int need_to_update =
1008 !smartlist_len(router_get_trusted_dir_servers()) || !old_options ||
1009 !config_lines_eq(options->DirServers, old_options->DirServers) ||
1010 !config_lines_eq(options->AlternateBridgeAuthority,
1011 old_options->AlternateBridgeAuthority) ||
1012 !config_lines_eq(options->AlternateDirAuthority,
1013 old_options->AlternateDirAuthority) ||
1014 !config_lines_eq(options->AlternateHSAuthority,
1015 old_options->AlternateHSAuthority);
1017 if (!need_to_update)
1018 return 0; /* all done */
1020 /* Start from a clean slate. */
1021 clear_trusted_dir_servers();
1023 if (!options->DirServers) {
1024 /* then we may want some of the defaults */
1025 authority_type_t type = NO_AUTHORITY;
1026 if (!options->AlternateBridgeAuthority)
1027 type |= BRIDGE_AUTHORITY;
1028 if (!options->AlternateDirAuthority)
1029 type |= V1_AUTHORITY | V2_AUTHORITY | V3_AUTHORITY;
1030 if (!options->AlternateHSAuthority)
1031 type |= HIDSERV_AUTHORITY;
1032 add_default_trusted_dir_authorities(type);
1035 for (cl = options->DirServers; cl; cl = cl->next)
1036 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1037 return -1;
1038 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1039 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1040 return -1;
1041 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1042 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1043 return -1;
1044 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
1045 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1046 return -1;
1047 return 0;
1050 /** Fetch the active option list, and take actions based on it. All of the
1051 * things we do should survive being done repeatedly. If present,
1052 * <b>old_options</b> contains the previous value of the options.
1054 * Return 0 if all goes well, return -1 if things went badly.
1056 static int
1057 options_act_reversible(or_options_t *old_options, char **msg)
1059 smartlist_t *new_listeners = smartlist_create();
1060 smartlist_t *replaced_listeners = smartlist_create();
1061 static int libevent_initialized = 0;
1062 or_options_t *options = get_options();
1063 int running_tor = options->command == CMD_RUN_TOR;
1064 int set_conn_limit = 0;
1065 int r = -1;
1066 int logs_marked = 0;
1068 /* Daemonize _first_, since we only want to open most of this stuff in
1069 * the subprocess. Libevent bases can't be reliably inherited across
1070 * processes. */
1071 if (running_tor && options->RunAsDaemon) {
1072 /* No need to roll back, since you can't change the value. */
1073 start_daemon();
1076 #ifndef HAVE_SYS_UN_H
1077 if (options->ControlSocket) {
1078 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported"
1079 " on this OS/with this build.");
1080 goto rollback;
1082 #endif
1084 if (running_tor) {
1085 /* We need to set the connection limit before we can open the listeners. */
1086 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1087 &options->_ConnLimit) < 0) {
1088 *msg = tor_strdup("Problem with ConnLimit value. See logs for details.");
1089 goto rollback;
1091 set_conn_limit = 1;
1093 /* Set up libevent. (We need to do this before we can register the
1094 * listeners as listeners.) */
1095 if (running_tor && !libevent_initialized) {
1096 init_libevent();
1097 libevent_initialized = 1;
1100 /* Launch the listeners. (We do this before we setuid, so we can bind to
1101 * ports under 1024.) */
1102 if (retry_all_listeners(replaced_listeners, new_listeners) < 0) {
1103 *msg = tor_strdup("Failed to bind one of the listener ports.");
1104 goto rollback;
1108 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1109 /* Open /dev/pf before dropping privileges. */
1110 if (options->TransPort) {
1111 if (get_pf_socket() < 0) {
1112 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1113 goto rollback;
1116 #endif
1118 /* Setuid/setgid as appropriate */
1119 if (options->User) {
1120 if (switch_id(options->User) != 0) {
1121 /* No need to roll back, since you can't change the value. */
1122 *msg = tor_strdup("Problem with User value. See logs for details.");
1123 goto done;
1127 /* Ensure data directory is private; create if possible. */
1128 if (check_private_dir(options->DataDirectory,
1129 running_tor ? CPD_CREATE : CPD_CHECK)<0) {
1130 char buf[1024];
1131 int tmp = tor_snprintf(buf, sizeof(buf),
1132 "Couldn't access/create private data directory \"%s\"",
1133 options->DataDirectory);
1134 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1135 goto done;
1136 /* No need to roll back, since you can't change the value. */
1139 if (directory_caches_v2_dir_info(options)) {
1140 size_t len = strlen(options->DataDirectory)+32;
1141 char *fn = tor_malloc(len);
1142 tor_snprintf(fn, len, "%s"PATH_SEPARATOR"cached-status",
1143 options->DataDirectory);
1144 if (check_private_dir(fn, running_tor ? CPD_CREATE : CPD_CHECK) < 0) {
1145 char buf[1024];
1146 int tmp = tor_snprintf(buf, sizeof(buf),
1147 "Couldn't access/create private data directory \"%s\"", fn);
1148 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1149 tor_free(fn);
1150 goto done;
1152 tor_free(fn);
1155 /* Bail out at this point if we're not going to be a client or server:
1156 * we don't run Tor itself. */
1157 if (!running_tor)
1158 goto commit;
1160 mark_logs_temp(); /* Close current logs once new logs are open. */
1161 logs_marked = 1;
1162 if (options_init_logs(options, 0)<0) { /* Configure the log(s) */
1163 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1164 goto rollback;
1167 commit:
1168 r = 0;
1169 if (logs_marked) {
1170 log_severity_list_t *severity =
1171 tor_malloc_zero(sizeof(log_severity_list_t));
1172 close_temp_logs();
1173 add_callback_log(severity, control_event_logmsg);
1174 control_adjust_event_log_severity();
1175 tor_free(severity);
1177 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1179 log_notice(LD_NET, "Closing old %s on %s:%d",
1180 conn_type_to_string(conn->type), conn->address, conn->port);
1181 connection_close_immediate(conn);
1182 connection_mark_for_close(conn);
1184 goto done;
1186 rollback:
1187 r = -1;
1188 tor_assert(*msg);
1190 if (logs_marked) {
1191 rollback_log_changes();
1192 control_adjust_event_log_severity();
1195 if (set_conn_limit && old_options)
1196 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1197 &options->_ConnLimit);
1199 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1201 log_notice(LD_NET, "Closing partially-constructed listener %s on %s:%d",
1202 conn_type_to_string(conn->type), conn->address, conn->port);
1203 connection_close_immediate(conn);
1204 connection_mark_for_close(conn);
1207 done:
1208 smartlist_free(new_listeners);
1209 smartlist_free(replaced_listeners);
1210 return r;
1213 /** If we need to have a GEOIP ip-to-country map to run with our configured
1214 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1216 options_need_geoip_info(or_options_t *options, const char **reason_out)
1218 int bridge_usage =
1219 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1220 int routerset_usage =
1221 routerset_needs_geoip(options->EntryNodes) ||
1222 routerset_needs_geoip(options->ExitNodes) ||
1223 routerset_needs_geoip(options->ExcludeExitNodes) ||
1224 routerset_needs_geoip(options->ExcludeNodes);
1226 if (routerset_usage && reason_out) {
1227 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1228 "countries, and we need GEOIP information to figure out which ones they "
1229 "are.";
1230 } else if (bridge_usage && reason_out) {
1231 *reason_out = "We've been configured to see which countries can access "
1232 "us as a bridge, and we need GEOIP information to tell which countries "
1233 "clients are in.";
1235 return bridge_usage || routerset_usage;
1238 /** Return the bandwidthrate that we are going to report to the authorities
1239 * based on the config options. */
1240 uint32_t
1241 get_effective_bwrate(or_options_t *options)
1243 uint64_t bw = options->BandwidthRate;
1244 if (bw > options->MaxAdvertisedBandwidth)
1245 bw = options->MaxAdvertisedBandwidth;
1246 if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1247 bw = options->RelayBandwidthRate;
1248 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1249 return (uint32_t)bw;
1252 /** Return the bandwidthburst that we are going to report to the authorities
1253 * based on the config options. */
1254 uint32_t
1255 get_effective_bwburst(or_options_t *options)
1257 uint64_t bw = options->BandwidthBurst;
1258 if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1259 bw = options->RelayBandwidthBurst;
1260 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1261 return (uint32_t)bw;
1264 /** Fetch the active option list, and take actions based on it. All of the
1265 * things we do should survive being done repeatedly. If present,
1266 * <b>old_options</b> contains the previous value of the options.
1268 * Return 0 if all goes well, return -1 if it's time to die.
1270 * Note: We haven't moved all the "act on new configuration" logic
1271 * here yet. Some is still in do_hup() and other places.
1273 static int
1274 options_act(or_options_t *old_options)
1276 config_line_t *cl;
1277 or_options_t *options = get_options();
1278 int running_tor = options->command == CMD_RUN_TOR;
1279 char *msg;
1281 if (running_tor && !have_lockfile()) {
1282 if (try_locking(options, 1) < 0)
1283 return -1;
1286 if (consider_adding_dir_authorities(options, old_options) < 0)
1287 return -1;
1289 if (options->Bridges) {
1290 clear_bridge_list();
1291 for (cl = options->Bridges; cl; cl = cl->next) {
1292 if (parse_bridge_line(cl->value, 0)<0) {
1293 log_warn(LD_BUG,
1294 "Previously validated Bridge line could not be added!");
1295 return -1;
1300 if (running_tor && rend_config_services(options, 0)<0) {
1301 log_warn(LD_BUG,
1302 "Previously validated hidden services line could not be added!");
1303 return -1;
1306 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1307 log_warn(LD_BUG, "Previously validated client authorization for "
1308 "hidden services could not be added!");
1309 return -1;
1312 /* Load state */
1313 if (! global_state && running_tor) {
1314 if (or_state_load())
1315 return -1;
1316 rep_hist_load_mtbf_data(time(NULL));
1319 /* Bail out at this point if we're not going to be a client or server:
1320 * we want to not fork, and to log stuff to stderr. */
1321 if (!running_tor)
1322 return 0;
1324 /* Finish backgrounding the process */
1325 if (options->RunAsDaemon) {
1326 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1327 finish_daemon(options->DataDirectory);
1330 /* Write our PID to the PID file. If we do not have write permissions we
1331 * will log a warning */
1332 if (options->PidFile)
1333 write_pidfile(options->PidFile);
1335 /* Register addressmap directives */
1336 config_register_addressmaps(options);
1337 parse_virtual_addr_network(options->VirtualAddrNetwork, 0, &msg);
1339 /* Update address policies. */
1340 if (policies_parse_from_options(options) < 0) {
1341 /* This should be impossible, but let's be sure. */
1342 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1343 return -1;
1346 if (init_cookie_authentication(options->CookieAuthentication) < 0) {
1347 log_warn(LD_CONFIG,"Error creating cookie authentication file.");
1348 return -1;
1351 /* reload keys as needed for rendezvous services. */
1352 if (rend_service_load_keys()<0) {
1353 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1354 return -1;
1357 /* Set up accounting */
1358 if (accounting_parse_options(options, 0)<0) {
1359 log_warn(LD_CONFIG,"Error in accounting options");
1360 return -1;
1362 if (accounting_is_enabled(options))
1363 configure_accounting(time(NULL));
1365 /* Check for transitions that need action. */
1366 if (old_options) {
1367 if (options->UseEntryGuards && !old_options->UseEntryGuards) {
1368 log_info(LD_CIRC,
1369 "Switching to entry guards; abandoning previous circuits");
1370 circuit_mark_all_unused_circs();
1371 circuit_expire_all_dirty_circs();
1374 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
1375 log_info(LD_GENERAL, "Bridge status changed. Forgetting GeoIP stats.");
1376 geoip_remove_old_clients(time(NULL)+(2*60*60));
1379 if (options_transition_affects_workers(old_options, options)) {
1380 log_info(LD_GENERAL,
1381 "Worker-related options changed. Rotating workers.");
1382 if (server_mode(options) && !server_mode(old_options)) {
1383 if (init_keys() < 0) {
1384 log_warn(LD_BUG,"Error initializing keys; exiting");
1385 return -1;
1387 ip_address_changed(0);
1388 if (has_completed_circuit || !any_predicted_circuits(time(NULL)))
1389 inform_testing_reachability();
1391 cpuworkers_rotate();
1392 if (dns_reset())
1393 return -1;
1394 } else {
1395 if (dns_reset())
1396 return -1;
1399 if (options->V3AuthoritativeDir && !old_options->V3AuthoritativeDir)
1400 init_keys();
1403 /* Maybe load geoip file */
1404 if (options->GeoIPFile &&
1405 ((!old_options || !opt_streq(old_options->GeoIPFile, options->GeoIPFile))
1406 || !geoip_is_loaded())) {
1407 /* XXXX Don't use this "<default>" junk; make our filename options
1408 * understand prefixes somehow. -NM */
1409 /* XXXX021 Reload GeoIPFile on SIGHUP. -NM */
1410 char *actual_fname = tor_strdup(options->GeoIPFile);
1411 #ifdef WIN32
1412 if (!strcmp(actual_fname, "<default>")) {
1413 const char *conf_root = get_windows_conf_root();
1414 size_t len = strlen(conf_root)+16;
1415 tor_free(actual_fname);
1416 actual_fname = tor_malloc(len+1);
1417 tor_snprintf(actual_fname, len, "%s\\geoip", conf_root);
1419 #endif
1420 geoip_load_file(actual_fname, options);
1421 tor_free(actual_fname);
1424 if (options->DirReqStatistics && !geoip_is_loaded()) {
1425 /* Check if GeoIP database could be loaded. */
1426 log_warn(LD_CONFIG, "Configured to measure directory request "
1427 "statistics, but no GeoIP database found!");
1428 return -1;
1431 if (options->EntryStatistics) {
1432 if (should_record_bridge_info(options)) {
1433 /* Don't allow measuring statistics on entry guards when configured
1434 * as bridge. */
1435 log_warn(LD_CONFIG, "Bridges cannot be configured to measure "
1436 "additional GeoIP statistics as entry guards.");
1437 return -1;
1438 } else if (!geoip_is_loaded()) {
1439 /* Check if GeoIP database could be loaded. */
1440 log_warn(LD_CONFIG, "Configured to measure entry node statistics, "
1441 "but no GeoIP database found!");
1442 return -1;
1446 /* Check if we need to parse and add the EntryNodes config option. */
1447 if (options->EntryNodes &&
1448 (!old_options ||
1449 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
1450 entry_nodes_should_be_added();
1452 /* Since our options changed, we might need to regenerate and upload our
1453 * server descriptor.
1455 if (!old_options ||
1456 options_transition_affects_descriptor(old_options, options))
1457 mark_my_descriptor_dirty();
1459 /* We may need to reschedule some directory stuff if our status changed. */
1460 if (old_options) {
1461 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1462 dirvote_recalculate_timing(options, time(NULL));
1463 if (!bool_eq(directory_fetches_dir_info_early(options),
1464 directory_fetches_dir_info_early(old_options)) ||
1465 !bool_eq(directory_fetches_dir_info_later(options),
1466 directory_fetches_dir_info_later(old_options))) {
1467 /* Make sure update_router_have_min_dir_info gets called. */
1468 router_dir_info_changed();
1469 /* We might need to download a new consensus status later or sooner than
1470 * we had expected. */
1471 update_consensus_networkstatus_fetch_time(time(NULL));
1475 /* Load the webpage we're going to serve every time someone asks for '/' on
1476 our DirPort. */
1477 tor_free(global_dirfrontpagecontents);
1478 if (options->DirPortFrontPage) {
1479 global_dirfrontpagecontents =
1480 read_file_to_str(options->DirPortFrontPage, 0, NULL);
1481 if (!global_dirfrontpagecontents) {
1482 log_warn(LD_CONFIG,
1483 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1484 options->DirPortFrontPage);
1488 return 0;
1492 * Functions to parse config options
1495 /** If <b>option</b> is an official abbreviation for a longer option,
1496 * return the longer option. Otherwise return <b>option</b>.
1497 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1498 * apply abbreviations that work for the config file and the command line.
1499 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1500 static const char *
1501 expand_abbrev(config_format_t *fmt, const char *option, int command_line,
1502 int warn_obsolete)
1504 int i;
1505 if (! fmt->abbrevs)
1506 return option;
1507 for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
1508 /* Abbreviations are case insensitive. */
1509 if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
1510 (command_line || !fmt->abbrevs[i].commandline_only)) {
1511 if (warn_obsolete && fmt->abbrevs[i].warn) {
1512 log_warn(LD_CONFIG,
1513 "The configuration option '%s' is deprecated; "
1514 "use '%s' instead.",
1515 fmt->abbrevs[i].abbreviated,
1516 fmt->abbrevs[i].full);
1518 /* Keep going through the list in case we want to rewrite it more.
1519 * (We could imagine recursing here, but I don't want to get the
1520 * user into an infinite loop if we craft our list wrong.) */
1521 option = fmt->abbrevs[i].full;
1524 return option;
1527 /** Helper: Read a list of configuration options from the command line.
1528 * If successful, put them in *<b>result</b> and return 0, and return
1529 * -1 and leave *<b>result</b> alone. */
1530 static int
1531 config_get_commandlines(int argc, char **argv, config_line_t **result)
1533 config_line_t *front = NULL;
1534 config_line_t **new = &front;
1535 char *s;
1536 int i = 1;
1538 while (i < argc) {
1539 if (!strcmp(argv[i],"-f") ||
1540 !strcmp(argv[i],"--hash-password")) {
1541 i += 2; /* command-line option with argument. ignore them. */
1542 continue;
1543 } else if (!strcmp(argv[i],"--list-fingerprint") ||
1544 !strcmp(argv[i],"--verify-config") ||
1545 !strcmp(argv[i],"--ignore-missing-torrc") ||
1546 !strcmp(argv[i],"--quiet") ||
1547 !strcmp(argv[i],"--hush")) {
1548 i += 1; /* command-line option. ignore it. */
1549 continue;
1550 } else if (!strcmp(argv[i],"--nt-service") ||
1551 !strcmp(argv[i],"-nt-service")) {
1552 i += 1;
1553 continue;
1556 if (i == argc-1) {
1557 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1558 argv[i]);
1559 config_free_lines(front);
1560 return -1;
1563 *new = tor_malloc_zero(sizeof(config_line_t));
1564 s = argv[i];
1566 while (*s == '-')
1567 s++;
1569 (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1, 1));
1570 (*new)->value = tor_strdup(argv[i+1]);
1571 (*new)->next = NULL;
1572 log(LOG_DEBUG, LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
1573 (*new)->key, (*new)->value);
1575 new = &((*new)->next);
1576 i += 2;
1578 *result = front;
1579 return 0;
1582 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1583 * append it to *<b>lst</b>. */
1584 static void
1585 config_line_append(config_line_t **lst,
1586 const char *key,
1587 const char *val)
1589 config_line_t *newline;
1591 newline = tor_malloc(sizeof(config_line_t));
1592 newline->key = tor_strdup(key);
1593 newline->value = tor_strdup(val);
1594 newline->next = NULL;
1595 while (*lst)
1596 lst = &((*lst)->next);
1598 (*lst) = newline;
1601 /** Helper: parse the config string and strdup into key/value
1602 * strings. Set *result to the list, or NULL if parsing the string
1603 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1604 * misformatted lines. */
1606 config_get_lines(const char *string, config_line_t **result)
1608 config_line_t *list = NULL, **next;
1609 char *k, *v;
1611 next = &list;
1612 do {
1613 k = v = NULL;
1614 string = parse_config_line_from_str(string, &k, &v);
1615 if (!string) {
1616 config_free_lines(list);
1617 tor_free(k);
1618 tor_free(v);
1619 return -1;
1621 if (k && v) {
1622 /* This list can get long, so we keep a pointer to the end of it
1623 * rather than using config_line_append over and over and getting
1624 * n^2 performance. */
1625 *next = tor_malloc(sizeof(config_line_t));
1626 (*next)->key = k;
1627 (*next)->value = v;
1628 (*next)->next = NULL;
1629 next = &((*next)->next);
1630 } else {
1631 tor_free(k);
1632 tor_free(v);
1634 } while (*string);
1636 *result = list;
1637 return 0;
1641 * Free all the configuration lines on the linked list <b>front</b>.
1643 void
1644 config_free_lines(config_line_t *front)
1646 config_line_t *tmp;
1648 while (front) {
1649 tmp = front;
1650 front = tmp->next;
1652 tor_free(tmp->key);
1653 tor_free(tmp->value);
1654 tor_free(tmp);
1658 /** Return the description for a given configuration variable, or NULL if no
1659 * description exists. */
1660 static const char *
1661 config_find_description(config_format_t *fmt, const char *name)
1663 int i;
1664 for (i=0; fmt->descriptions[i].name; ++i) {
1665 if (!strcasecmp(name, fmt->descriptions[i].name))
1666 return fmt->descriptions[i].description;
1668 return NULL;
1671 /** If <b>key</b> is a configuration option, return the corresponding
1672 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1673 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1675 static config_var_t *
1676 config_find_option(config_format_t *fmt, const char *key)
1678 int i;
1679 size_t keylen = strlen(key);
1680 if (!keylen)
1681 return NULL; /* if they say "--" on the command line, it's not an option */
1682 /* First, check for an exact (case-insensitive) match */
1683 for (i=0; fmt->vars[i].name; ++i) {
1684 if (!strcasecmp(key, fmt->vars[i].name)) {
1685 return &fmt->vars[i];
1688 /* If none, check for an abbreviated match */
1689 for (i=0; fmt->vars[i].name; ++i) {
1690 if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
1691 log_warn(LD_CONFIG, "The abbreviation '%s' is deprecated. "
1692 "Please use '%s' instead",
1693 key, fmt->vars[i].name);
1694 return &fmt->vars[i];
1697 /* Okay, unrecognized option */
1698 return NULL;
1702 * Functions to assign config options.
1705 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1706 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1708 * Called from config_assign_line() and option_reset().
1710 static int
1711 config_assign_value(config_format_t *fmt, or_options_t *options,
1712 config_line_t *c, char **msg)
1714 int i, r, ok;
1715 char buf[1024];
1716 config_var_t *var;
1717 void *lvalue;
1719 CHECK(fmt, options);
1721 var = config_find_option(fmt, c->key);
1722 tor_assert(var);
1724 lvalue = STRUCT_VAR_P(options, var->var_offset);
1726 switch (var->type) {
1728 case CONFIG_TYPE_UINT:
1729 i = (int)tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
1730 if (!ok) {
1731 r = tor_snprintf(buf, sizeof(buf),
1732 "Int keyword '%s %s' is malformed or out of bounds.",
1733 c->key, c->value);
1734 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1735 return -1;
1737 *(int *)lvalue = i;
1738 break;
1740 case CONFIG_TYPE_INTERVAL: {
1741 i = config_parse_interval(c->value, &ok);
1742 if (!ok) {
1743 r = tor_snprintf(buf, sizeof(buf),
1744 "Interval '%s %s' is malformed or out of bounds.",
1745 c->key, c->value);
1746 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1747 return -1;
1749 *(int *)lvalue = i;
1750 break;
1753 case CONFIG_TYPE_MEMUNIT: {
1754 uint64_t u64 = config_parse_memunit(c->value, &ok);
1755 if (!ok) {
1756 r = tor_snprintf(buf, sizeof(buf),
1757 "Value '%s %s' is malformed or out of bounds.",
1758 c->key, c->value);
1759 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1760 return -1;
1762 *(uint64_t *)lvalue = u64;
1763 break;
1766 case CONFIG_TYPE_BOOL:
1767 i = (int)tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
1768 if (!ok) {
1769 r = tor_snprintf(buf, sizeof(buf),
1770 "Boolean '%s %s' expects 0 or 1.",
1771 c->key, c->value);
1772 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1773 return -1;
1775 *(int *)lvalue = i;
1776 break;
1778 case CONFIG_TYPE_STRING:
1779 case CONFIG_TYPE_FILENAME:
1780 tor_free(*(char **)lvalue);
1781 *(char **)lvalue = tor_strdup(c->value);
1782 break;
1784 case CONFIG_TYPE_DOUBLE:
1785 *(double *)lvalue = atof(c->value);
1786 break;
1788 case CONFIG_TYPE_ISOTIME:
1789 if (parse_iso_time(c->value, (time_t *)lvalue)) {
1790 r = tor_snprintf(buf, sizeof(buf),
1791 "Invalid time '%s' for keyword '%s'", c->value, c->key);
1792 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1793 return -1;
1795 break;
1797 case CONFIG_TYPE_ROUTERSET:
1798 if (*(routerset_t**)lvalue) {
1799 routerset_free(*(routerset_t**)lvalue);
1801 *(routerset_t**)lvalue = routerset_new();
1802 if (routerset_parse(*(routerset_t**)lvalue, c->value, c->key)<0) {
1803 tor_snprintf(buf, sizeof(buf), "Invalid exit list '%s' for option '%s'",
1804 c->value, c->key);
1805 *msg = tor_strdup(buf);
1806 return -1;
1808 break;
1810 case CONFIG_TYPE_CSV:
1811 if (*(smartlist_t**)lvalue) {
1812 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
1813 smartlist_clear(*(smartlist_t**)lvalue);
1814 } else {
1815 *(smartlist_t**)lvalue = smartlist_create();
1818 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
1819 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1820 break;
1822 case CONFIG_TYPE_LINELIST:
1823 case CONFIG_TYPE_LINELIST_S:
1824 config_line_append((config_line_t**)lvalue, c->key, c->value);
1825 break;
1826 case CONFIG_TYPE_OBSOLETE:
1827 log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
1828 break;
1829 case CONFIG_TYPE_LINELIST_V:
1830 r = tor_snprintf(buf, sizeof(buf),
1831 "You may not provide a value for virtual option '%s'", c->key);
1832 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1833 return -1;
1834 default:
1835 tor_assert(0);
1836 break;
1838 return 0;
1841 /** If <b>c</b> is a syntactically valid configuration line, update
1842 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1843 * key, -2 for bad value.
1845 * If <b>clear_first</b> is set, clear the value first. Then if
1846 * <b>use_defaults</b> is set, set the value to the default.
1848 * Called from config_assign().
1850 static int
1851 config_assign_line(config_format_t *fmt, or_options_t *options,
1852 config_line_t *c, int use_defaults,
1853 int clear_first, char **msg)
1855 config_var_t *var;
1857 CHECK(fmt, options);
1859 var = config_find_option(fmt, c->key);
1860 if (!var) {
1861 if (fmt->extra) {
1862 void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
1863 log_info(LD_CONFIG,
1864 "Found unrecognized option '%s'; saving it.", c->key);
1865 config_line_append((config_line_t**)lvalue, c->key, c->value);
1866 return 0;
1867 } else {
1868 char buf[1024];
1869 int tmp = tor_snprintf(buf, sizeof(buf),
1870 "Unknown option '%s'. Failing.", c->key);
1871 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1872 return -1;
1875 /* Put keyword into canonical case. */
1876 if (strcmp(var->name, c->key)) {
1877 tor_free(c->key);
1878 c->key = tor_strdup(var->name);
1881 if (!strlen(c->value)) {
1882 /* reset or clear it, then return */
1883 if (!clear_first) {
1884 if (var->type == CONFIG_TYPE_LINELIST ||
1885 var->type == CONFIG_TYPE_LINELIST_S) {
1886 /* We got an empty linelist from the torrc or command line.
1887 As a special case, call this an error. Warn and ignore. */
1888 log_warn(LD_CONFIG,
1889 "Linelist option '%s' has no value. Skipping.", c->key);
1890 } else { /* not already cleared */
1891 option_reset(fmt, options, var, use_defaults);
1894 return 0;
1897 if (config_assign_value(fmt, options, c, msg) < 0)
1898 return -2;
1899 return 0;
1902 /** Restore the option named <b>key</b> in options to its default value.
1903 * Called from config_assign(). */
1904 static void
1905 config_reset_line(config_format_t *fmt, or_options_t *options,
1906 const char *key, int use_defaults)
1908 config_var_t *var;
1910 CHECK(fmt, options);
1912 var = config_find_option(fmt, key);
1913 if (!var)
1914 return; /* give error on next pass. */
1916 option_reset(fmt, options, var, use_defaults);
1919 /** Return true iff key is a valid configuration option. */
1921 option_is_recognized(const char *key)
1923 config_var_t *var = config_find_option(&options_format, key);
1924 return (var != NULL);
1927 /** Return the canonical name of a configuration option, or NULL
1928 * if no such option exists. */
1929 const char *
1930 option_get_canonical_name(const char *key)
1932 config_var_t *var = config_find_option(&options_format, key);
1933 return var ? var->name : NULL;
1936 /** Return a canonical list of the options assigned for key.
1938 config_line_t *
1939 option_get_assignment(or_options_t *options, const char *key)
1941 return get_assigned_option(&options_format, options, key, 1);
1944 /** Return true iff value needs to be quoted and escaped to be used in
1945 * a configuration file. */
1946 static int
1947 config_value_needs_escape(const char *value)
1949 if (*value == '\"')
1950 return 1;
1951 while (*value) {
1952 switch (*value)
1954 case '\r':
1955 case '\n':
1956 case '#':
1957 /* Note: quotes and backspaces need special handling when we are using
1958 * quotes, not otherwise, so they don't trigger escaping on their
1959 * own. */
1960 return 1;
1961 default:
1962 if (!TOR_ISPRINT(*value))
1963 return 1;
1965 ++value;
1967 return 0;
1970 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1971 static config_line_t *
1972 config_lines_dup(const config_line_t *inp)
1974 config_line_t *result = NULL;
1975 config_line_t **next_out = &result;
1976 while (inp) {
1977 *next_out = tor_malloc(sizeof(config_line_t));
1978 (*next_out)->key = tor_strdup(inp->key);
1979 (*next_out)->value = tor_strdup(inp->value);
1980 inp = inp->next;
1981 next_out = &((*next_out)->next);
1983 (*next_out) = NULL;
1984 return result;
1987 /** Return newly allocated line or lines corresponding to <b>key</b> in the
1988 * configuration <b>options</b>. If <b>escape_val</b> is true and a
1989 * value needs to be quoted before it's put in a config file, quote and
1990 * escape that value. Return NULL if no such key exists. */
1991 static config_line_t *
1992 get_assigned_option(config_format_t *fmt, void *options,
1993 const char *key, int escape_val)
1995 config_var_t *var;
1996 const void *value;
1997 char buf[32];
1998 config_line_t *result;
1999 tor_assert(options && key);
2001 CHECK(fmt, options);
2003 var = config_find_option(fmt, key);
2004 if (!var) {
2005 log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
2006 return NULL;
2008 value = STRUCT_VAR_P(options, var->var_offset);
2010 result = tor_malloc_zero(sizeof(config_line_t));
2011 result->key = tor_strdup(var->name);
2012 switch (var->type)
2014 case CONFIG_TYPE_STRING:
2015 case CONFIG_TYPE_FILENAME:
2016 if (*(char**)value) {
2017 result->value = tor_strdup(*(char**)value);
2018 } else {
2019 tor_free(result->key);
2020 tor_free(result);
2021 return NULL;
2023 break;
2024 case CONFIG_TYPE_ISOTIME:
2025 if (*(time_t*)value) {
2026 result->value = tor_malloc(ISO_TIME_LEN+1);
2027 format_iso_time(result->value, *(time_t*)value);
2028 } else {
2029 tor_free(result->key);
2030 tor_free(result);
2032 escape_val = 0; /* Can't need escape. */
2033 break;
2034 case CONFIG_TYPE_INTERVAL:
2035 case CONFIG_TYPE_UINT:
2036 /* This means every or_options_t uint or bool element
2037 * needs to be an int. Not, say, a uint16_t or char. */
2038 tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
2039 result->value = tor_strdup(buf);
2040 escape_val = 0; /* Can't need escape. */
2041 break;
2042 case CONFIG_TYPE_MEMUNIT:
2043 tor_snprintf(buf, sizeof(buf), U64_FORMAT,
2044 U64_PRINTF_ARG(*(uint64_t*)value));
2045 result->value = tor_strdup(buf);
2046 escape_val = 0; /* Can't need escape. */
2047 break;
2048 case CONFIG_TYPE_DOUBLE:
2049 tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
2050 result->value = tor_strdup(buf);
2051 escape_val = 0; /* Can't need escape. */
2052 break;
2053 case CONFIG_TYPE_BOOL:
2054 result->value = tor_strdup(*(int*)value ? "1" : "0");
2055 escape_val = 0; /* Can't need escape. */
2056 break;
2057 case CONFIG_TYPE_ROUTERSET:
2058 result->value = routerset_to_string(*(routerset_t**)value);
2059 break;
2060 case CONFIG_TYPE_CSV:
2061 if (*(smartlist_t**)value)
2062 result->value =
2063 smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
2064 else
2065 result->value = tor_strdup("");
2066 break;
2067 case CONFIG_TYPE_OBSOLETE:
2068 log_fn(LOG_PROTOCOL_WARN, LD_CONFIG,
2069 "You asked me for the value of an obsolete config option '%s'.",
2070 key);
2071 tor_free(result->key);
2072 tor_free(result);
2073 return NULL;
2074 case CONFIG_TYPE_LINELIST_S:
2075 log_warn(LD_CONFIG,
2076 "Can't return context-sensitive '%s' on its own", key);
2077 tor_free(result->key);
2078 tor_free(result);
2079 return NULL;
2080 case CONFIG_TYPE_LINELIST:
2081 case CONFIG_TYPE_LINELIST_V:
2082 tor_free(result->key);
2083 tor_free(result);
2084 result = config_lines_dup(*(const config_line_t**)value);
2085 break;
2086 default:
2087 tor_free(result->key);
2088 tor_free(result);
2089 log_warn(LD_BUG,"Unknown type %d for known key '%s'",
2090 var->type, key);
2091 return NULL;
2094 if (escape_val) {
2095 config_line_t *line;
2096 for (line = result; line; line = line->next) {
2097 if (line->value && config_value_needs_escape(line->value)) {
2098 char *newval = esc_for_log(line->value);
2099 tor_free(line->value);
2100 line->value = newval;
2105 return result;
2108 /** Iterate through the linked list of requested options <b>list</b>.
2109 * For each item, convert as appropriate and assign to <b>options</b>.
2110 * If an item is unrecognized, set *msg and return -1 immediately,
2111 * else return 0 for success.
2113 * If <b>clear_first</b>, interpret config options as replacing (not
2114 * extending) their previous values. If <b>clear_first</b> is set,
2115 * then <b>use_defaults</b> to decide if you set to defaults after
2116 * clearing, or make the value 0 or NULL.
2118 * Here are the use cases:
2119 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
2120 * if linelist, replaces current if csv.
2121 * 2. An empty AllowInvalid line in your torrc. Should clear it.
2122 * 3. "RESETCONF AllowInvalid" sets it to default.
2123 * 4. "SETCONF AllowInvalid" makes it NULL.
2124 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
2126 * Use_defaults Clear_first
2127 * 0 0 "append"
2128 * 1 0 undefined, don't use
2129 * 0 1 "set to null first"
2130 * 1 1 "set to defaults first"
2131 * Return 0 on success, -1 on bad key, -2 on bad value.
2133 * As an additional special case, if a LINELIST config option has
2134 * no value and clear_first is 0, then warn and ignore it.
2138 There are three call cases for config_assign() currently.
2140 Case one: Torrc entry
2141 options_init_from_torrc() calls config_assign(0, 0)
2142 calls config_assign_line(0, 0).
2143 if value is empty, calls option_reset(0) and returns.
2144 calls config_assign_value(), appends.
2146 Case two: setconf
2147 options_trial_assign() calls config_assign(0, 1)
2148 calls config_reset_line(0)
2149 calls option_reset(0)
2150 calls option_clear().
2151 calls config_assign_line(0, 1).
2152 if value is empty, returns.
2153 calls config_assign_value(), appends.
2155 Case three: resetconf
2156 options_trial_assign() calls config_assign(1, 1)
2157 calls config_reset_line(1)
2158 calls option_reset(1)
2159 calls option_clear().
2160 calls config_assign_value(default)
2161 calls config_assign_line(1, 1).
2162 returns.
2164 static int
2165 config_assign(config_format_t *fmt, void *options, config_line_t *list,
2166 int use_defaults, int clear_first, char **msg)
2168 config_line_t *p;
2170 CHECK(fmt, options);
2172 /* pass 1: normalize keys */
2173 for (p = list; p; p = p->next) {
2174 const char *full = expand_abbrev(fmt, p->key, 0, 1);
2175 if (strcmp(full,p->key)) {
2176 tor_free(p->key);
2177 p->key = tor_strdup(full);
2181 /* pass 2: if we're reading from a resetting source, clear all
2182 * mentioned config options, and maybe set to their defaults. */
2183 if (clear_first) {
2184 for (p = list; p; p = p->next)
2185 config_reset_line(fmt, options, p->key, use_defaults);
2188 /* pass 3: assign. */
2189 while (list) {
2190 int r;
2191 if ((r=config_assign_line(fmt, options, list, use_defaults,
2192 clear_first, msg)))
2193 return r;
2194 list = list->next;
2196 return 0;
2199 /** Try assigning <b>list</b> to the global options. You do this by duping
2200 * options, assigning list to the new one, then validating it. If it's
2201 * ok, then throw out the old one and stick with the new one. Else,
2202 * revert to old and return failure. Return SETOPT_OK on success, or
2203 * a setopt_err_t on failure.
2205 * If not success, point *<b>msg</b> to a newly allocated string describing
2206 * what went wrong.
2208 setopt_err_t
2209 options_trial_assign(config_line_t *list, int use_defaults,
2210 int clear_first, char **msg)
2212 int r;
2213 or_options_t *trial_options = options_dup(&options_format, get_options());
2215 if ((r=config_assign(&options_format, trial_options,
2216 list, use_defaults, clear_first, msg)) < 0) {
2217 config_free(&options_format, trial_options);
2218 return r;
2221 if (options_validate(get_options(), trial_options, 1, msg) < 0) {
2222 config_free(&options_format, trial_options);
2223 return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2226 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2227 config_free(&options_format, trial_options);
2228 return SETOPT_ERR_TRANSITION;
2231 if (set_options(trial_options, msg)<0) {
2232 config_free(&options_format, trial_options);
2233 return SETOPT_ERR_SETTING;
2236 /* we liked it. put it in place. */
2237 return SETOPT_OK;
2240 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2241 * Called from option_reset() and config_free(). */
2242 static void
2243 option_clear(config_format_t *fmt, or_options_t *options, config_var_t *var)
2245 void *lvalue = STRUCT_VAR_P(options, var->var_offset);
2246 (void)fmt; /* unused */
2247 switch (var->type) {
2248 case CONFIG_TYPE_STRING:
2249 case CONFIG_TYPE_FILENAME:
2250 tor_free(*(char**)lvalue);
2251 break;
2252 case CONFIG_TYPE_DOUBLE:
2253 *(double*)lvalue = 0.0;
2254 break;
2255 case CONFIG_TYPE_ISOTIME:
2256 *(time_t*)lvalue = 0;
2257 case CONFIG_TYPE_INTERVAL:
2258 case CONFIG_TYPE_UINT:
2259 case CONFIG_TYPE_BOOL:
2260 *(int*)lvalue = 0;
2261 break;
2262 case CONFIG_TYPE_MEMUNIT:
2263 *(uint64_t*)lvalue = 0;
2264 break;
2265 case CONFIG_TYPE_ROUTERSET:
2266 if (*(routerset_t**)lvalue) {
2267 routerset_free(*(routerset_t**)lvalue);
2268 *(routerset_t**)lvalue = NULL;
2270 case CONFIG_TYPE_CSV:
2271 if (*(smartlist_t**)lvalue) {
2272 SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
2273 smartlist_free(*(smartlist_t **)lvalue);
2274 *(smartlist_t **)lvalue = NULL;
2276 break;
2277 case CONFIG_TYPE_LINELIST:
2278 case CONFIG_TYPE_LINELIST_S:
2279 config_free_lines(*(config_line_t **)lvalue);
2280 *(config_line_t **)lvalue = NULL;
2281 break;
2282 case CONFIG_TYPE_LINELIST_V:
2283 /* handled by linelist_s. */
2284 break;
2285 case CONFIG_TYPE_OBSOLETE:
2286 break;
2290 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2291 * <b>use_defaults</b>, set it to its default value.
2292 * Called by config_init() and option_reset_line() and option_assign_line(). */
2293 static void
2294 option_reset(config_format_t *fmt, or_options_t *options,
2295 config_var_t *var, int use_defaults)
2297 config_line_t *c;
2298 char *msg = NULL;
2299 CHECK(fmt, options);
2300 option_clear(fmt, options, var); /* clear it first */
2301 if (!use_defaults)
2302 return; /* all done */
2303 if (var->initvalue) {
2304 c = tor_malloc_zero(sizeof(config_line_t));
2305 c->key = tor_strdup(var->name);
2306 c->value = tor_strdup(var->initvalue);
2307 if (config_assign_value(fmt, options, c, &msg) < 0) {
2308 log_warn(LD_BUG, "Failed to assign default: %s", msg);
2309 tor_free(msg); /* if this happens it's a bug */
2311 config_free_lines(c);
2315 /** Print a usage message for tor. */
2316 static void
2317 print_usage(void)
2319 printf(
2320 "Copyright (c) 2001-2004, Roger Dingledine\n"
2321 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2322 "Copyright (c) 2007-2009, The Tor Project, Inc.\n\n"
2323 "tor -f <torrc> [args]\n"
2324 "See man page for options, or https://www.torproject.org/ for "
2325 "documentation.\n");
2328 /** Print all non-obsolete torrc options. */
2329 static void
2330 list_torrc_options(void)
2332 int i;
2333 smartlist_t *lines = smartlist_create();
2334 for (i = 0; _option_vars[i].name; ++i) {
2335 config_var_t *var = &_option_vars[i];
2336 const char *desc;
2337 if (var->type == CONFIG_TYPE_OBSOLETE ||
2338 var->type == CONFIG_TYPE_LINELIST_V)
2339 continue;
2340 desc = config_find_description(&options_format, var->name);
2341 printf("%s\n", var->name);
2342 if (desc) {
2343 wrap_string(lines, desc, 76, " ", " ");
2344 SMARTLIST_FOREACH(lines, char *, cp, {
2345 printf("%s", cp);
2346 tor_free(cp);
2348 smartlist_clear(lines);
2351 smartlist_free(lines);
2354 /** Last value actually set by resolve_my_address. */
2355 static uint32_t last_resolved_addr = 0;
2357 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2358 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2359 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2360 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2361 * public IP address.
2364 resolve_my_address(int warn_severity, or_options_t *options,
2365 uint32_t *addr_out, char **hostname_out)
2367 struct in_addr in;
2368 struct hostent *rent;
2369 char hostname[256];
2370 int explicit_ip=1;
2371 int explicit_hostname=1;
2372 int from_interface=0;
2373 char tmpbuf[INET_NTOA_BUF_LEN];
2374 const char *address = options->Address;
2375 int notice_severity = warn_severity <= LOG_NOTICE ?
2376 LOG_NOTICE : warn_severity;
2378 tor_assert(addr_out);
2380 if (address && *address) {
2381 strlcpy(hostname, address, sizeof(hostname));
2382 } else { /* then we need to guess our address */
2383 explicit_ip = 0; /* it's implicit */
2384 explicit_hostname = 0; /* it's implicit */
2386 if (gethostname(hostname, sizeof(hostname)) < 0) {
2387 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2388 return -1;
2390 log_debug(LD_CONFIG,"Guessed local host name as '%s'",hostname);
2393 /* now we know hostname. resolve it and keep only the IP address */
2395 if (tor_inet_aton(hostname, &in) == 0) {
2396 /* then we have to resolve it */
2397 explicit_ip = 0;
2398 rent = (struct hostent *)gethostbyname(hostname);
2399 if (!rent) {
2400 uint32_t interface_ip;
2402 if (explicit_hostname) {
2403 log_fn(warn_severity, LD_CONFIG,
2404 "Could not resolve local Address '%s'. Failing.", hostname);
2405 return -1;
2407 log_fn(notice_severity, LD_CONFIG,
2408 "Could not resolve guessed local hostname '%s'. "
2409 "Trying something else.", hostname);
2410 if (get_interface_address(warn_severity, &interface_ip)) {
2411 log_fn(warn_severity, LD_CONFIG,
2412 "Could not get local interface IP address. Failing.");
2413 return -1;
2415 from_interface = 1;
2416 in.s_addr = htonl(interface_ip);
2417 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2418 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2419 "local interface. Using that.", tmpbuf);
2420 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2421 } else {
2422 tor_assert(rent->h_length == 4);
2423 memcpy(&in.s_addr, rent->h_addr, rent->h_length);
2425 if (!explicit_hostname &&
2426 is_internal_IP(ntohl(in.s_addr), 0)) {
2427 uint32_t interface_ip;
2429 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2430 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2431 "resolves to a private IP address (%s). Trying something "
2432 "else.", hostname, tmpbuf);
2434 if (get_interface_address(warn_severity, &interface_ip)) {
2435 log_fn(warn_severity, LD_CONFIG,
2436 "Could not get local interface IP address. Too bad.");
2437 } else if (is_internal_IP(interface_ip, 0)) {
2438 struct in_addr in2;
2439 in2.s_addr = htonl(interface_ip);
2440 tor_inet_ntoa(&in2,tmpbuf,sizeof(tmpbuf));
2441 log_fn(notice_severity, LD_CONFIG,
2442 "Interface IP address '%s' is a private address too. "
2443 "Ignoring.", tmpbuf);
2444 } else {
2445 from_interface = 1;
2446 in.s_addr = htonl(interface_ip);
2447 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2448 log_fn(notice_severity, LD_CONFIG,
2449 "Learned IP address '%s' for local interface."
2450 " Using that.", tmpbuf);
2451 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2457 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2458 if (is_internal_IP(ntohl(in.s_addr), 0) &&
2459 options->_PublishServerDescriptor) {
2460 /* make sure we're ok with publishing an internal IP */
2461 if (!options->DirServers && !options->AlternateDirAuthority) {
2462 /* if they are using the default dirservers, disallow internal IPs
2463 * always. */
2464 log_fn(warn_severity, LD_CONFIG,
2465 "Address '%s' resolves to private IP address '%s'. "
2466 "Tor servers that use the default DirServers must have public "
2467 "IP addresses.", hostname, tmpbuf);
2468 return -1;
2470 if (!explicit_ip) {
2471 /* even if they've set their own dirservers, require an explicit IP if
2472 * they're using an internal address. */
2473 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2474 "IP address '%s'. Please set the Address config option to be "
2475 "the IP address you want to use.", hostname, tmpbuf);
2476 return -1;
2480 log_debug(LD_CONFIG, "Resolved Address to '%s'.", tmpbuf);
2481 *addr_out = ntohl(in.s_addr);
2482 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2483 /* Leave this as a notice, regardless of the requested severity,
2484 * at least until dynamic IP address support becomes bulletproof. */
2485 log_notice(LD_NET,
2486 "Your IP address seems to have changed to %s. Updating.",
2487 tmpbuf);
2488 ip_address_changed(0);
2490 if (last_resolved_addr != *addr_out) {
2491 const char *method;
2492 const char *h = hostname;
2493 if (explicit_ip) {
2494 method = "CONFIGURED";
2495 h = NULL;
2496 } else if (explicit_hostname) {
2497 method = "RESOLVED";
2498 } else if (from_interface) {
2499 method = "INTERFACE";
2500 h = NULL;
2501 } else {
2502 method = "GETHOSTNAME";
2504 control_event_server_status(LOG_NOTICE,
2505 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2506 tmpbuf, method, h?"HOSTNAME=":"", h);
2508 last_resolved_addr = *addr_out;
2509 if (hostname_out)
2510 *hostname_out = tor_strdup(hostname);
2511 return 0;
2514 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2515 * on a private network.
2518 is_local_addr(const tor_addr_t *addr)
2520 if (tor_addr_is_internal(addr, 0))
2521 return 1;
2522 /* Check whether ip is on the same /24 as we are. */
2523 if (get_options()->EnforceDistinctSubnets == 0)
2524 return 0;
2525 if (tor_addr_family(addr) == AF_INET) {
2526 /*XXXX022 IP6 what corresponds to an /24? */
2527 uint32_t ip = tor_addr_to_ipv4h(addr);
2529 /* It's possible that this next check will hit before the first time
2530 * resolve_my_address actually succeeds. (For clients, it is likely that
2531 * resolve_my_address will never be called at all). In those cases,
2532 * last_resolved_addr will be 0, and so checking to see whether ip is on
2533 * the same /24 as last_resolved_addr will be the same as checking whether
2534 * it was on net 0, which is already done by is_internal_IP.
2536 if ((last_resolved_addr & (uint32_t)0xffffff00ul)
2537 == (ip & (uint32_t)0xffffff00ul))
2538 return 1;
2540 return 0;
2543 /** Called when we don't have a nickname set. Try to guess a good nickname
2544 * based on the hostname, and return it in a newly allocated string. If we
2545 * can't, return NULL and let the caller warn if it wants to. */
2546 static char *
2547 get_default_nickname(void)
2549 static const char * const bad_default_nicknames[] = {
2550 "localhost",
2551 NULL,
2553 char localhostname[256];
2554 char *cp, *out, *outp;
2555 int i;
2557 if (gethostname(localhostname, sizeof(localhostname)) < 0)
2558 return NULL;
2560 /* Put it in lowercase; stop at the first dot. */
2561 if ((cp = strchr(localhostname, '.')))
2562 *cp = '\0';
2563 tor_strlower(localhostname);
2565 /* Strip invalid characters. */
2566 cp = localhostname;
2567 out = outp = tor_malloc(strlen(localhostname) + 1);
2568 while (*cp) {
2569 if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
2570 *outp++ = *cp++;
2571 else
2572 cp++;
2574 *outp = '\0';
2576 /* Enforce length. */
2577 if (strlen(out) > MAX_NICKNAME_LEN)
2578 out[MAX_NICKNAME_LEN]='\0';
2580 /* Check for dumb names. */
2581 for (i = 0; bad_default_nicknames[i]; ++i) {
2582 if (!strcmp(out, bad_default_nicknames[i])) {
2583 tor_free(out);
2584 return NULL;
2588 return out;
2591 /** Release storage held by <b>options</b>. */
2592 static void
2593 config_free(config_format_t *fmt, void *options)
2595 int i;
2597 tor_assert(options);
2599 for (i=0; fmt->vars[i].name; ++i)
2600 option_clear(fmt, options, &(fmt->vars[i]));
2601 if (fmt->extra) {
2602 config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
2603 config_free_lines(*linep);
2604 *linep = NULL;
2606 tor_free(options);
2609 /** Return true iff a and b contain identical keys and values in identical
2610 * order. */
2611 static int
2612 config_lines_eq(config_line_t *a, config_line_t *b)
2614 while (a && b) {
2615 if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
2616 return 0;
2617 a = a->next;
2618 b = b->next;
2620 if (a || b)
2621 return 0;
2622 return 1;
2625 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2626 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2628 static int
2629 option_is_same(config_format_t *fmt,
2630 or_options_t *o1, or_options_t *o2, const char *name)
2632 config_line_t *c1, *c2;
2633 int r = 1;
2634 CHECK(fmt, o1);
2635 CHECK(fmt, o2);
2637 c1 = get_assigned_option(fmt, o1, name, 0);
2638 c2 = get_assigned_option(fmt, o2, name, 0);
2639 r = config_lines_eq(c1, c2);
2640 config_free_lines(c1);
2641 config_free_lines(c2);
2642 return r;
2645 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2646 static or_options_t *
2647 options_dup(config_format_t *fmt, or_options_t *old)
2649 or_options_t *newopts;
2650 int i;
2651 config_line_t *line;
2653 newopts = config_alloc(fmt);
2654 for (i=0; fmt->vars[i].name; ++i) {
2655 if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2656 continue;
2657 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
2658 continue;
2659 line = get_assigned_option(fmt, old, fmt->vars[i].name, 0);
2660 if (line) {
2661 char *msg = NULL;
2662 if (config_assign(fmt, newopts, line, 0, 0, &msg) < 0) {
2663 log_err(LD_BUG, "Config_get_assigned_option() generated "
2664 "something we couldn't config_assign(): %s", msg);
2665 tor_free(msg);
2666 tor_assert(0);
2669 config_free_lines(line);
2671 return newopts;
2674 /** Return a new empty or_options_t. Used for testing. */
2675 or_options_t *
2676 options_new(void)
2678 return config_alloc(&options_format);
2681 /** Set <b>options</b> to hold reasonable defaults for most options.
2682 * Each option defaults to zero. */
2683 void
2684 options_init(or_options_t *options)
2686 config_init(&options_format, options);
2689 /* Check if the port number given in <b>port_option</b> in combination with
2690 * the specified port in <b>listen_options</b> will result in Tor actually
2691 * opening a low port (meaning a port lower than 1024). Return 1 if
2692 * it is, or 0 if it isn't or the concept of a low port isn't applicable for
2693 * the platform we're on. */
2694 static int
2695 is_listening_on_low_port(uint16_t port_option,
2696 const config_line_t *listen_options)
2698 #ifdef MS_WINDOWS
2699 (void) port_option;
2700 (void) listen_options;
2701 return 0; /* No port is too low for windows. */
2702 #else
2703 const config_line_t *l;
2704 uint16_t p;
2705 if (port_option == 0)
2706 return 0; /* We're not listening */
2707 if (listen_options == NULL)
2708 return (port_option < 1024);
2710 for (l = listen_options; l; l = l->next) {
2711 parse_addr_port(LOG_WARN, l->value, NULL, NULL, &p);
2712 if (p<1024) {
2713 return 1;
2716 return 0;
2717 #endif
2720 /** Set all vars in the configuration object <b>options</b> to their default
2721 * values. */
2722 static void
2723 config_init(config_format_t *fmt, void *options)
2725 int i;
2726 config_var_t *var;
2727 CHECK(fmt, options);
2729 for (i=0; fmt->vars[i].name; ++i) {
2730 var = &fmt->vars[i];
2731 if (!var->initvalue)
2732 continue; /* defaults to NULL or 0 */
2733 option_reset(fmt, options, var, 1);
2737 /** Allocate and return a new string holding the written-out values of the vars
2738 * in 'options'. If 'minimal', do not write out any default-valued vars.
2739 * Else, if comment_defaults, write default values as comments.
2741 static char *
2742 config_dump(config_format_t *fmt, void *options, int minimal,
2743 int comment_defaults)
2745 smartlist_t *elements;
2746 or_options_t *defaults;
2747 config_line_t *line, *assigned;
2748 char *result;
2749 int i;
2750 const char *desc;
2751 char *msg = NULL;
2753 defaults = config_alloc(fmt);
2754 config_init(fmt, defaults);
2756 /* XXX use a 1 here so we don't add a new log line while dumping */
2757 if (fmt->validate_fn(NULL,defaults, 1, &msg) < 0) {
2758 log_err(LD_BUG, "Failed to validate default config.");
2759 tor_free(msg);
2760 tor_assert(0);
2763 elements = smartlist_create();
2764 for (i=0; fmt->vars[i].name; ++i) {
2765 int comment_option = 0;
2766 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
2767 fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2768 continue;
2769 /* Don't save 'hidden' control variables. */
2770 if (!strcmpstart(fmt->vars[i].name, "__"))
2771 continue;
2772 if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
2773 continue;
2774 else if (comment_defaults &&
2775 option_is_same(fmt, options, defaults, fmt->vars[i].name))
2776 comment_option = 1;
2778 desc = config_find_description(fmt, fmt->vars[i].name);
2779 line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name, 1);
2781 if (line && desc) {
2782 /* Only dump the description if there's something to describe. */
2783 wrap_string(elements, desc, 78, "# ", "# ");
2786 for (; line; line = line->next) {
2787 size_t len = strlen(line->key) + strlen(line->value) + 5;
2788 char *tmp;
2789 tmp = tor_malloc(len);
2790 if (tor_snprintf(tmp, len, "%s%s %s\n",
2791 comment_option ? "# " : "",
2792 line->key, line->value)<0) {
2793 log_err(LD_BUG,"Internal error writing option value");
2794 tor_assert(0);
2796 smartlist_add(elements, tmp);
2798 config_free_lines(assigned);
2801 if (fmt->extra) {
2802 line = *(config_line_t**)STRUCT_VAR_P(options, fmt->extra->var_offset);
2803 for (; line; line = line->next) {
2804 size_t len = strlen(line->key) + strlen(line->value) + 3;
2805 char *tmp;
2806 tmp = tor_malloc(len);
2807 if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
2808 log_err(LD_BUG,"Internal error writing option value");
2809 tor_assert(0);
2811 smartlist_add(elements, tmp);
2815 result = smartlist_join_strings(elements, "", 0, NULL);
2816 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2817 smartlist_free(elements);
2818 config_free(fmt, defaults);
2819 return result;
2822 /** Return a string containing a possible configuration file that would give
2823 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2824 * include options that are the same as Tor's defaults.
2826 static char *
2827 options_dump(or_options_t *options, int minimal)
2829 return config_dump(&options_format, options, minimal, 0);
2832 /** Return 0 if every element of sl is a string holding a decimal
2833 * representation of a port number, or if sl is NULL.
2834 * Otherwise set *msg and return -1. */
2835 static int
2836 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2838 int i;
2839 char buf[1024];
2840 tor_assert(name);
2842 if (!sl)
2843 return 0;
2845 SMARTLIST_FOREACH(sl, const char *, cp,
2847 i = atoi(cp);
2848 if (i < 1 || i > 65535) {
2849 int r = tor_snprintf(buf, sizeof(buf),
2850 "Port '%s' out of range in %s", cp, name);
2851 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2852 return -1;
2855 return 0;
2858 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2859 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2860 * Else return 0.
2862 static int
2863 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2865 int r;
2866 char buf[1024];
2867 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2868 /* This handles an understandable special case where somebody says "2gb"
2869 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2870 --*value;
2872 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2873 r = tor_snprintf(buf, sizeof(buf), "%s ("U64_FORMAT") must be at most %d",
2874 desc, U64_PRINTF_ARG(*value),
2875 ROUTER_MAX_DECLARED_BANDWIDTH);
2876 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2877 return -1;
2879 return 0;
2882 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2883 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2884 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2885 * Treat "0" as "".
2886 * Return 0 on success or -1 if not a recognized authority type (in which
2887 * case the value of _PublishServerDescriptor is undefined). */
2888 static int
2889 compute_publishserverdescriptor(or_options_t *options)
2891 smartlist_t *list = options->PublishServerDescriptor;
2892 authority_type_t *auth = &options->_PublishServerDescriptor;
2893 *auth = NO_AUTHORITY;
2894 if (!list) /* empty list, answer is none */
2895 return 0;
2896 SMARTLIST_FOREACH(list, const char *, string, {
2897 if (!strcasecmp(string, "v1"))
2898 *auth |= V1_AUTHORITY;
2899 else if (!strcmp(string, "1"))
2900 if (options->BridgeRelay)
2901 *auth |= BRIDGE_AUTHORITY;
2902 else
2903 *auth |= V2_AUTHORITY | V3_AUTHORITY;
2904 else if (!strcasecmp(string, "v2"))
2905 *auth |= V2_AUTHORITY;
2906 else if (!strcasecmp(string, "v3"))
2907 *auth |= V3_AUTHORITY;
2908 else if (!strcasecmp(string, "bridge"))
2909 *auth |= BRIDGE_AUTHORITY;
2910 else if (!strcasecmp(string, "hidserv"))
2911 *auth |= HIDSERV_AUTHORITY;
2912 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2913 /* no authority */;
2914 else
2915 return -1;
2917 return 0;
2920 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2921 * services can overload the directory system. */
2922 #define MIN_REND_POST_PERIOD (10*60)
2924 /** Highest allowable value for RendPostPeriod. */
2925 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2927 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2928 * will generate too many circuits and potentially overload the network. */
2929 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2931 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2932 * permissible transition from <b>old_options</b>. Else return -1.
2933 * Should have no side effects, except for normalizing the contents of
2934 * <b>options</b>.
2936 * On error, tor_strdup an error explanation into *<b>msg</b>.
2938 * XXX
2939 * If <b>from_setconf</b>, we were called by the controller, and our
2940 * Log line should stay empty. If it's 0, then give us a default log
2941 * if there are no logs defined.
2943 static int
2944 options_validate(or_options_t *old_options, or_options_t *options,
2945 int from_setconf, char **msg)
2947 int i, r;
2948 config_line_t *cl;
2949 const char *uname = get_uname();
2950 char buf[1024];
2951 #define REJECT(arg) \
2952 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2953 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2955 tor_assert(msg);
2956 *msg = NULL;
2958 if (options->ORPort < 0 || options->ORPort > 65535)
2959 REJECT("ORPort option out of bounds.");
2961 if (server_mode(options) &&
2962 (!strcmpstart(uname, "Windows 95") ||
2963 !strcmpstart(uname, "Windows 98") ||
2964 !strcmpstart(uname, "Windows Me"))) {
2965 log(LOG_WARN, LD_CONFIG, "Tor is running as a server, but you are "
2966 "running %s; this probably won't work. See "
2967 "https://wiki.torproject.org/TheOnionRouter/TorFAQ#ServerOS "
2968 "for details.", uname);
2971 if (options->ORPort == 0 && options->ORListenAddress != NULL)
2972 REJECT("ORPort must be defined if ORListenAddress is defined.");
2974 if (options->DirPort == 0 && options->DirListenAddress != NULL)
2975 REJECT("DirPort must be defined if DirListenAddress is defined.");
2977 if (options->DNSPort == 0 && options->DNSListenAddress != NULL)
2978 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
2980 if (options->ControlPort == 0 && options->ControlListenAddress != NULL)
2981 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
2983 if (options->TransPort == 0 && options->TransListenAddress != NULL)
2984 REJECT("TransPort must be defined if TransListenAddress is defined.");
2986 if (options->NatdPort == 0 && options->NatdListenAddress != NULL)
2987 REJECT("NatdPort must be defined if NatdListenAddress is defined.");
2989 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
2990 * configuration does this. */
2992 for (i = 0; i < 3; ++i) {
2993 int is_socks = i==0;
2994 int is_trans = i==1;
2995 config_line_t *line, *opt, *old;
2996 const char *tp;
2997 if (is_socks) {
2998 opt = options->SocksListenAddress;
2999 old = old_options ? old_options->SocksListenAddress : NULL;
3000 tp = "SOCKS proxy";
3001 } else if (is_trans) {
3002 opt = options->TransListenAddress;
3003 old = old_options ? old_options->TransListenAddress : NULL;
3004 tp = "transparent proxy";
3005 } else {
3006 opt = options->NatdListenAddress;
3007 old = old_options ? old_options->NatdListenAddress : NULL;
3008 tp = "natd proxy";
3011 for (line = opt; line; line = line->next) {
3012 char *address = NULL;
3013 uint16_t port;
3014 uint32_t addr;
3015 if (parse_addr_port(LOG_WARN, line->value, &address, &addr, &port)<0)
3016 continue; /* We'll warn about this later. */
3017 if (!is_internal_IP(addr, 1) &&
3018 (!old_options || !config_lines_eq(old, opt))) {
3019 log_warn(LD_CONFIG,
3020 "You specified a public address '%s' for a %s. Other "
3021 "people on the Internet might find your computer and use it as "
3022 "an open %s. Please don't allow this unless you have "
3023 "a good reason.", address, tp, tp);
3025 tor_free(address);
3029 if (validate_data_directory(options)<0)
3030 REJECT("Invalid DataDirectory");
3032 if (options->Nickname == NULL) {
3033 if (server_mode(options)) {
3034 if (!(options->Nickname = get_default_nickname())) {
3035 log_notice(LD_CONFIG, "Couldn't pick a nickname based on "
3036 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME);
3037 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
3038 } else {
3039 log_notice(LD_CONFIG, "Choosing default nickname '%s'",
3040 options->Nickname);
3043 } else {
3044 if (!is_legal_nickname(options->Nickname)) {
3045 r = tor_snprintf(buf, sizeof(buf),
3046 "Nickname '%s' is wrong length or contains illegal characters.",
3047 options->Nickname);
3048 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3049 return -1;
3053 if (server_mode(options) && !options->ContactInfo)
3054 log(LOG_NOTICE, LD_CONFIG, "Your ContactInfo config option is not set. "
3055 "Please consider setting it, so we can contact you if your server is "
3056 "misconfigured or something else goes wrong.");
3058 /* Special case on first boot if no Log options are given. */
3059 if (!options->Logs && !options->RunAsDaemon && !from_setconf)
3060 config_line_append(&options->Logs, "Log", "notice stdout");
3062 if (options_init_logs(options, 1)<0) /* Validate the log(s) */
3063 REJECT("Failed to validate Log options. See logs for details.");
3065 if (options->NoPublish) {
3066 log(LOG_WARN, LD_CONFIG,
3067 "NoPublish is obsolete. Use PublishServerDescriptor instead.");
3068 SMARTLIST_FOREACH(options->PublishServerDescriptor, char *, s,
3069 tor_free(s));
3070 smartlist_clear(options->PublishServerDescriptor);
3073 if (authdir_mode(options)) {
3074 /* confirm that our address isn't broken, so we can complain now */
3075 uint32_t tmp;
3076 if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
3077 REJECT("Failed to resolve/guess local address. See logs for details.");
3080 #ifndef MS_WINDOWS
3081 if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
3082 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
3083 #endif
3085 if (options->SocksPort < 0 || options->SocksPort > 65535)
3086 REJECT("SocksPort option out of bounds.");
3088 if (options->DNSPort < 0 || options->DNSPort > 65535)
3089 REJECT("DNSPort option out of bounds.");
3091 if (options->TransPort < 0 || options->TransPort > 65535)
3092 REJECT("TransPort option out of bounds.");
3094 if (options->NatdPort < 0 || options->NatdPort > 65535)
3095 REJECT("NatdPort option out of bounds.");
3097 if (options->SocksPort == 0 && options->TransPort == 0 &&
3098 options->NatdPort == 0 && options->ORPort == 0 &&
3099 options->DNSPort == 0 && !options->RendConfigLines)
3100 log(LOG_WARN, LD_CONFIG,
3101 "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
3102 "undefined, and there aren't any hidden services configured. "
3103 "Tor will still run, but probably won't do anything.");
3105 if (options->ControlPort < 0 || options->ControlPort > 65535)
3106 REJECT("ControlPort option out of bounds.");
3108 if (options->DirPort < 0 || options->DirPort > 65535)
3109 REJECT("DirPort option out of bounds.");
3111 #ifndef USE_TRANSPARENT
3112 if (options->TransPort || options->TransListenAddress)
3113 REJECT("TransPort and TransListenAddress are disabled in this build.");
3114 #endif
3116 if (options->AccountingMax &&
3117 (is_listening_on_low_port(options->ORPort, options->ORListenAddress) ||
3118 is_listening_on_low_port(options->DirPort, options->DirListenAddress)))
3120 log(LOG_WARN, LD_CONFIG,
3121 "You have set AccountingMax to use hibernation. You have also "
3122 "chosen a low DirPort or OrPort. This combination can make Tor stop "
3123 "working when it tries to re-attach the port after a period of "
3124 "hibernation. Please choose a different port or turn off "
3125 "hibernation unless you know this combination will work on your "
3126 "platform.");
3129 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3130 options->_ExcludeExitNodesUnion = routerset_new();
3131 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeExitNodes);
3132 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeNodes);
3135 if (options->StrictExitNodes &&
3136 (!options->ExitNodes) &&
3137 (!old_options ||
3138 (old_options->StrictExitNodes != options->StrictExitNodes) ||
3139 (!routerset_equal(old_options->ExitNodes,options->ExitNodes))))
3140 COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
3142 if (options->StrictEntryNodes &&
3143 (!options->EntryNodes) &&
3144 (!old_options ||
3145 (old_options->StrictEntryNodes != options->StrictEntryNodes) ||
3146 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
3147 COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
3149 if (options->EntryNodes && !routerset_is_list(options->EntryNodes)) {
3150 /* XXXX fix this; see entry_guards_prepend_from_config(). */
3151 REJECT("IPs or countries are not yet supported in EntryNodes.");
3154 if (options->AuthoritativeDir) {
3155 if (!options->ContactInfo && !options->TestingTorNetwork)
3156 REJECT("Authoritative directory servers must set ContactInfo");
3157 if (options->V1AuthoritativeDir && !options->RecommendedVersions)
3158 REJECT("V1 authoritative dir servers must set RecommendedVersions.");
3159 if (!options->RecommendedClientVersions)
3160 options->RecommendedClientVersions =
3161 config_lines_dup(options->RecommendedVersions);
3162 if (!options->RecommendedServerVersions)
3163 options->RecommendedServerVersions =
3164 config_lines_dup(options->RecommendedVersions);
3165 if (options->VersioningAuthoritativeDir &&
3166 (!options->RecommendedClientVersions ||
3167 !options->RecommendedServerVersions))
3168 REJECT("Versioning authoritative dir servers must set "
3169 "Recommended*Versions.");
3170 if (options->UseEntryGuards) {
3171 log_info(LD_CONFIG, "Authoritative directory servers can't set "
3172 "UseEntryGuards. Disabling.");
3173 options->UseEntryGuards = 0;
3175 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
3176 log_info(LD_CONFIG, "Authoritative directories always try to download "
3177 "extra-info documents. Setting DownloadExtraInfo.");
3178 options->DownloadExtraInfo = 1;
3180 if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
3181 options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
3182 options->V3AuthoritativeDir))
3183 REJECT("AuthoritativeDir is set, but none of "
3184 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
3185 /* If we have a v3bandwidthsfile and it's broken, complain on startup */
3186 if (options->V3BandwidthsFile && !old_options) {
3187 dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
3191 if (options->AuthoritativeDir && !options->DirPort)
3192 REJECT("Running as authoritative directory, but no DirPort set.");
3194 if (options->AuthoritativeDir && !options->ORPort)
3195 REJECT("Running as authoritative directory, but no ORPort set.");
3197 if (options->AuthoritativeDir && options->ClientOnly)
3198 REJECT("Running as authoritative directory, but ClientOnly also set.");
3200 if (options->HSAuthorityRecordStats && !options->HSAuthoritativeDir)
3201 REJECT("HSAuthorityRecordStats is set but we're not running as "
3202 "a hidden service authority.");
3204 if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
3205 REJECT("FetchDirInfoExtraEarly requires that you also set "
3206 "FetchDirInfoEarly");
3208 if (options->ConnLimit <= 0) {
3209 r = tor_snprintf(buf, sizeof(buf),
3210 "ConnLimit must be greater than 0, but was set to %d",
3211 options->ConnLimit);
3212 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3213 return -1;
3216 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3217 return -1;
3219 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3220 return -1;
3222 if (validate_ports_csv(options->RejectPlaintextPorts,
3223 "RejectPlaintextPorts", msg) < 0)
3224 return -1;
3226 if (validate_ports_csv(options->WarnPlaintextPorts,
3227 "WarnPlaintextPorts", msg) < 0)
3228 return -1;
3230 if (options->FascistFirewall && !options->ReachableAddresses) {
3231 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3232 /* We already have firewall ports set, so migrate them to
3233 * ReachableAddresses, which will set ReachableORAddresses and
3234 * ReachableDirAddresses if they aren't set explicitly. */
3235 smartlist_t *instead = smartlist_create();
3236 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3237 new_line->key = tor_strdup("ReachableAddresses");
3238 /* If we're configured with the old format, we need to prepend some
3239 * open ports. */
3240 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3242 int p = atoi(portno);
3243 char *s;
3244 if (p<0) continue;
3245 s = tor_malloc(16);
3246 tor_snprintf(s, 16, "*:%d", p);
3247 smartlist_add(instead, s);
3249 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3250 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3251 log(LOG_NOTICE, LD_CONFIG,
3252 "Converting FascistFirewall and FirewallPorts "
3253 "config options to new format: \"ReachableAddresses %s\"",
3254 new_line->value);
3255 options->ReachableAddresses = new_line;
3256 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3257 smartlist_free(instead);
3258 } else {
3259 /* We do not have FirewallPorts set, so add 80 to
3260 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3261 if (!options->ReachableDirAddresses) {
3262 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3263 new_line->key = tor_strdup("ReachableDirAddresses");
3264 new_line->value = tor_strdup("*:80");
3265 options->ReachableDirAddresses = new_line;
3266 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3267 "to new format: \"ReachableDirAddresses *:80\"");
3269 if (!options->ReachableORAddresses) {
3270 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3271 new_line->key = tor_strdup("ReachableORAddresses");
3272 new_line->value = tor_strdup("*:443");
3273 options->ReachableORAddresses = new_line;
3274 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3275 "to new format: \"ReachableORAddresses *:443\"");
3280 for (i=0; i<3; i++) {
3281 config_line_t **linep =
3282 (i==0) ? &options->ReachableAddresses :
3283 (i==1) ? &options->ReachableORAddresses :
3284 &options->ReachableDirAddresses;
3285 if (!*linep)
3286 continue;
3287 /* We need to end with a reject *:*, not an implicit accept *:* */
3288 for (;;) {
3289 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
3290 break;
3291 linep = &((*linep)->next);
3292 if (!*linep) {
3293 *linep = tor_malloc_zero(sizeof(config_line_t));
3294 (*linep)->key = tor_strdup(
3295 (i==0) ? "ReachableAddresses" :
3296 (i==1) ? "ReachableORAddresses" :
3297 "ReachableDirAddresses");
3298 (*linep)->value = tor_strdup("reject *:*");
3299 break;
3304 if ((options->ReachableAddresses ||
3305 options->ReachableORAddresses ||
3306 options->ReachableDirAddresses) &&
3307 server_mode(options))
3308 REJECT("Servers must be able to freely connect to the rest "
3309 "of the Internet, so they must not set Reachable*Addresses "
3310 "or FascistFirewall.");
3312 if (options->UseBridges &&
3313 server_mode(options))
3314 REJECT("Servers must be able to freely connect to the rest "
3315 "of the Internet, so they must not set UseBridges.");
3317 options->_AllowInvalid = 0;
3318 if (options->AllowInvalidNodes) {
3319 SMARTLIST_FOREACH(options->AllowInvalidNodes, const char *, cp, {
3320 if (!strcasecmp(cp, "entry"))
3321 options->_AllowInvalid |= ALLOW_INVALID_ENTRY;
3322 else if (!strcasecmp(cp, "exit"))
3323 options->_AllowInvalid |= ALLOW_INVALID_EXIT;
3324 else if (!strcasecmp(cp, "middle"))
3325 options->_AllowInvalid |= ALLOW_INVALID_MIDDLE;
3326 else if (!strcasecmp(cp, "introduction"))
3327 options->_AllowInvalid |= ALLOW_INVALID_INTRODUCTION;
3328 else if (!strcasecmp(cp, "rendezvous"))
3329 options->_AllowInvalid |= ALLOW_INVALID_RENDEZVOUS;
3330 else {
3331 r = tor_snprintf(buf, sizeof(buf),
3332 "Unrecognized value '%s' in AllowInvalidNodes", cp);
3333 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3334 return -1;
3339 if (compute_publishserverdescriptor(options) < 0) {
3340 r = tor_snprintf(buf, sizeof(buf),
3341 "Unrecognized value in PublishServerDescriptor");
3342 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3343 return -1;
3346 if ((options->BridgeRelay
3347 || options->_PublishServerDescriptor & BRIDGE_AUTHORITY)
3348 && (options->_PublishServerDescriptor
3349 & (V1_AUTHORITY|V2_AUTHORITY|V3_AUTHORITY))) {
3350 REJECT("Bridges are not supposed to publish router descriptors to the "
3351 "directory authorities. Please correct your "
3352 "PublishServerDescriptor line.");
3355 if (options->MinUptimeHidServDirectoryV2 < 0) {
3356 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3357 "least 0 seconds. Changing to 0.");
3358 options->MinUptimeHidServDirectoryV2 = 0;
3361 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
3362 log(LOG_WARN,LD_CONFIG,"RendPostPeriod option is too short; "
3363 "raising to %d seconds.", MIN_REND_POST_PERIOD);
3364 options->RendPostPeriod = MIN_REND_POST_PERIOD;
3367 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3368 log(LOG_WARN, LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3369 MAX_DIR_PERIOD);
3370 options->RendPostPeriod = MAX_DIR_PERIOD;
3373 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3374 log(LOG_WARN, LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3375 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3376 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3379 if (options->KeepalivePeriod < 1)
3380 REJECT("KeepalivePeriod option must be positive.");
3382 if (ensure_bandwidth_cap(&options->BandwidthRate,
3383 "BandwidthRate", msg) < 0)
3384 return -1;
3385 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3386 "BandwidthBurst", msg) < 0)
3387 return -1;
3388 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3389 "MaxAdvertisedBandwidth", msg) < 0)
3390 return -1;
3391 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3392 "RelayBandwidthRate", msg) < 0)
3393 return -1;
3394 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3395 "RelayBandwidthBurst", msg) < 0)
3396 return -1;
3398 if (server_mode(options)) {
3399 if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3400 r = tor_snprintf(buf, sizeof(buf),
3401 "BandwidthRate is set to %d bytes/second. "
3402 "For servers, it must be at least %d.",
3403 (int)options->BandwidthRate,
3404 ROUTER_REQUIRED_MIN_BANDWIDTH);
3405 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3406 return -1;
3407 } else if (options->MaxAdvertisedBandwidth <
3408 ROUTER_REQUIRED_MIN_BANDWIDTH/2) {
3409 r = tor_snprintf(buf, sizeof(buf),
3410 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3411 "For servers, it must be at least %d.",
3412 (int)options->MaxAdvertisedBandwidth,
3413 ROUTER_REQUIRED_MIN_BANDWIDTH/2);
3414 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3415 return -1;
3417 if (options->RelayBandwidthRate &&
3418 options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3419 r = tor_snprintf(buf, sizeof(buf),
3420 "RelayBandwidthRate is set to %d bytes/second. "
3421 "For servers, it must be at least %d.",
3422 (int)options->RelayBandwidthRate,
3423 ROUTER_REQUIRED_MIN_BANDWIDTH);
3424 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3425 return -1;
3429 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3430 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3432 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3433 REJECT("RelayBandwidthBurst must be at least equal "
3434 "to RelayBandwidthRate.");
3436 if (options->BandwidthRate > options->BandwidthBurst)
3437 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3439 /* if they set relaybandwidth* really high but left bandwidth*
3440 * at the default, raise the defaults. */
3441 if (options->RelayBandwidthRate > options->BandwidthRate)
3442 options->BandwidthRate = options->RelayBandwidthRate;
3443 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3444 options->BandwidthBurst = options->RelayBandwidthBurst;
3446 if (accounting_parse_options(options, 1)<0)
3447 REJECT("Failed to parse accounting options. See logs for details.");
3449 if (options->HttpProxy) { /* parse it now */
3450 if (tor_addr_port_parse(options->HttpProxy,
3451 &options->HttpProxyAddr, &options->HttpProxyPort) < 0)
3452 REJECT("HttpProxy failed to parse or resolve. Please fix.");
3453 if (options->HttpProxyPort == 0) { /* give it a default */
3454 options->HttpProxyPort = 80;
3458 if (options->HttpProxyAuthenticator) {
3459 if (strlen(options->HttpProxyAuthenticator) >= 48)
3460 REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
3463 if (options->HttpsProxy) { /* parse it now */
3464 if (tor_addr_port_parse(options->HttpsProxy,
3465 &options->HttpsProxyAddr, &options->HttpsProxyPort) <0)
3466 REJECT("HttpsProxy failed to parse or resolve. Please fix.");
3467 if (options->HttpsProxyPort == 0) { /* give it a default */
3468 options->HttpsProxyPort = 443;
3472 if (options->HttpsProxyAuthenticator) {
3473 if (strlen(options->HttpsProxyAuthenticator) >= 48)
3474 REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
3477 if (options->Socks4Proxy) { /* parse it now */
3478 if (tor_addr_port_parse(options->Socks4Proxy,
3479 &options->Socks4ProxyAddr,
3480 &options->Socks4ProxyPort) <0)
3481 REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
3482 if (options->Socks4ProxyPort == 0) { /* give it a default */
3483 options->Socks4ProxyPort = 1080;
3487 if (options->Socks5Proxy) { /* parse it now */
3488 if (tor_addr_port_parse(options->Socks5Proxy,
3489 &options->Socks5ProxyAddr,
3490 &options->Socks5ProxyPort) <0)
3491 REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
3492 if (options->Socks5ProxyPort == 0) { /* give it a default */
3493 options->Socks5ProxyPort = 1080;
3497 if (options->Socks4Proxy && options->Socks5Proxy)
3498 REJECT("You cannot specify both Socks4Proxy and SOCKS5Proxy");
3500 if (options->Socks5ProxyUsername) {
3501 size_t len;
3503 len = strlen(options->Socks5ProxyUsername);
3504 if (len < 1 || len > 255)
3505 REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
3507 if (!options->Socks5ProxyPassword)
3508 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3510 len = strlen(options->Socks5ProxyPassword);
3511 if (len < 1 || len > 255)
3512 REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
3513 } else if (options->Socks5ProxyPassword)
3514 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3516 if (options->HashedControlPassword) {
3517 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3518 if (!sl) {
3519 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3520 } else {
3521 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3522 smartlist_free(sl);
3526 if (options->HashedControlSessionPassword) {
3527 smartlist_t *sl = decode_hashed_passwords(
3528 options->HashedControlSessionPassword);
3529 if (!sl) {
3530 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3531 } else {
3532 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3533 smartlist_free(sl);
3537 if (options->ControlListenAddress) {
3538 int all_are_local = 1;
3539 config_line_t *ln;
3540 for (ln = options->ControlListenAddress; ln; ln = ln->next) {
3541 if (strcmpstart(ln->value, "127."))
3542 all_are_local = 0;
3544 if (!all_are_local) {
3545 if (!options->HashedControlPassword &&
3546 !options->HashedControlSessionPassword &&
3547 !options->CookieAuthentication) {
3548 log_warn(LD_CONFIG,
3549 "You have a ControlListenAddress set to accept "
3550 "unauthenticated connections from a non-local address. "
3551 "This means that programs not running on your computer "
3552 "can reconfigure your Tor, without even having to guess a "
3553 "password. That's so bad that I'm closing your ControlPort "
3554 "for you. If you need to control your Tor remotely, try "
3555 "enabling authentication and using a tool like stunnel or "
3556 "ssh to encrypt remote access.");
3557 options->ControlPort = 0;
3558 } else {
3559 log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
3560 "connections from a non-local address. This means that "
3561 "programs not running on your computer can reconfigure your "
3562 "Tor. That's pretty bad, since the controller "
3563 "protocol isn't encrypted! Maybe you should just listen on "
3564 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
3565 "remote connections to your control port.");
3570 if (options->ControlPort && !options->HashedControlPassword &&
3571 !options->HashedControlSessionPassword &&
3572 !options->CookieAuthentication) {
3573 log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
3574 "has been configured. This means that any program on your "
3575 "computer can reconfigure your Tor. That's bad! You should "
3576 "upgrade your Tor controller as soon as possible.");
3579 if (options->UseEntryGuards && ! options->NumEntryGuards)
3580 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3582 if (check_nickname_list(options->MyFamily, "MyFamily", msg))
3583 return -1;
3584 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3585 if (check_nickname_list(cl->value, "NodeFamily", msg))
3586 return -1;
3589 if (validate_addr_policies(options, msg) < 0)
3590 return -1;
3592 if (validate_dir_authorities(options, old_options) < 0)
3593 REJECT("Directory authority line did not parse. See logs for details.");
3595 if (options->UseBridges && !options->Bridges)
3596 REJECT("If you set UseBridges, you must specify at least one bridge.");
3597 if (options->UseBridges && !options->TunnelDirConns)
3598 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3599 if (options->Bridges) {
3600 for (cl = options->Bridges; cl; cl = cl->next) {
3601 if (parse_bridge_line(cl->value, 1)<0)
3602 REJECT("Bridge line did not parse. See logs for details.");
3606 if (options->ConstrainedSockets) {
3607 /* If the user wants to constrain socket buffer use, make sure the desired
3608 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3609 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3610 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3611 options->ConstrainedSockSize % 1024) {
3612 r = tor_snprintf(buf, sizeof(buf),
3613 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3614 "in 1024 byte increments.",
3615 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3616 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3617 return -1;
3619 if (options->DirPort) {
3620 /* Providing cached directory entries while system TCP buffers are scarce
3621 * will exacerbate the socket errors. Suggest that this be disabled. */
3622 COMPLAIN("You have requested constrained socket buffers while also "
3623 "serving directory entries via DirPort. It is strongly "
3624 "suggested that you disable serving directory requests when "
3625 "system TCP buffer resources are scarce.");
3629 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3630 options->V3AuthVotingInterval/2) {
3631 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3632 "V3AuthVotingInterval");
3634 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
3635 REJECT("V3AuthVoteDelay is way too low.");
3636 if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
3637 REJECT("V3AuthDistDelay is way too low.");
3639 if (options->V3AuthNIntervalsValid < 2)
3640 REJECT("V3AuthNIntervalsValid must be at least 2.");
3642 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3643 REJECT("V3AuthVotingInterval is insanely low.");
3644 } else if (options->V3AuthVotingInterval > 24*60*60) {
3645 REJECT("V3AuthVotingInterval is insanely high.");
3646 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3647 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3650 if (rend_config_services(options, 1) < 0)
3651 REJECT("Failed to configure rendezvous options. See logs for details.");
3653 /* Parse client-side authorization for hidden services. */
3654 if (rend_parse_service_authorization(options, 1) < 0)
3655 REJECT("Failed to configure client authorization for hidden services. "
3656 "See logs for details.");
3658 if (parse_virtual_addr_network(options->VirtualAddrNetwork, 1, NULL)<0)
3659 return -1;
3661 if (options->PreferTunneledDirConns && !options->TunnelDirConns)
3662 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3664 if ((options->Socks4Proxy || options->Socks5Proxy) &&
3665 !options->HttpProxy && !options->PreferTunneledDirConns)
3666 REJECT("When Socks4Proxy or Socks5Proxy is configured, "
3667 "PreferTunneledDirConns and TunnelDirConns must both be "
3668 "set to 1, or HttpProxy must be configured.");
3670 if (options->AutomapHostsSuffixes) {
3671 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
3673 size_t len = strlen(suf);
3674 if (len && suf[len-1] == '.')
3675 suf[len-1] = '\0';
3679 if (options->TestingTorNetwork && !options->DirServers) {
3680 REJECT("TestingTorNetwork may only be configured in combination with "
3681 "a non-default set of DirServers.");
3684 /*XXXX022 checking for defaults manually like this is a bit fragile.*/
3686 /* Keep changes to hard-coded values synchronous to man page and default
3687 * values table. */
3688 if (options->TestingV3AuthInitialVotingInterval != 30*60 &&
3689 !options->TestingTorNetwork) {
3690 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
3691 "Tor networks!");
3692 } else if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
3693 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3694 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
3695 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3696 "30 minutes.");
3699 if (options->TestingV3AuthInitialVoteDelay != 5*60 &&
3700 !options->TestingTorNetwork) {
3701 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
3702 "Tor networks!");
3703 } else if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
3704 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3707 if (options->TestingV3AuthInitialDistDelay != 5*60 &&
3708 !options->TestingTorNetwork) {
3709 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
3710 "Tor networks!");
3711 } else if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
3712 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3715 if (options->TestingV3AuthInitialVoteDelay +
3716 options->TestingV3AuthInitialDistDelay >=
3717 options->TestingV3AuthInitialVotingInterval/2) {
3718 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3719 "must be less than half TestingV3AuthInitialVotingInterval");
3722 if (options->TestingAuthDirTimeToLearnReachability != 30*60 &&
3723 !options->TestingTorNetwork) {
3724 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
3725 "testing Tor networks!");
3726 } else if (options->TestingAuthDirTimeToLearnReachability < 0) {
3727 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3728 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
3729 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3732 if (options->TestingEstimatedDescriptorPropagationTime != 10*60 &&
3733 !options->TestingTorNetwork) {
3734 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
3735 "testing Tor networks!");
3736 } else if (options->TestingEstimatedDescriptorPropagationTime < 0) {
3737 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3738 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
3739 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3742 if (options->TestingTorNetwork) {
3743 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
3744 "almost unusable in the public Tor network, and is "
3745 "therefore only advised if you are building a "
3746 "testing Tor network!");
3749 if (options->AccelName && !options->HardwareAccel)
3750 options->HardwareAccel = 1;
3751 if (options->AccelDir && !options->AccelName)
3752 REJECT("Can't use hardware crypto accelerator dir without engine name.");
3754 return 0;
3755 #undef REJECT
3756 #undef COMPLAIN
3759 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3760 * equal strings. */
3761 static int
3762 opt_streq(const char *s1, const char *s2)
3764 if (!s1 && !s2)
3765 return 1;
3766 else if (s1 && s2 && !strcmp(s1,s2))
3767 return 1;
3768 else
3769 return 0;
3772 /** Check if any of the previous options have changed but aren't allowed to. */
3773 static int
3774 options_transition_allowed(or_options_t *old, or_options_t *new_val,
3775 char **msg)
3777 if (!old)
3778 return 0;
3780 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3781 *msg = tor_strdup("PidFile is not allowed to change.");
3782 return -1;
3785 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3786 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3787 "is not allowed.");
3788 return -1;
3791 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
3792 char buf[1024];
3793 int r = tor_snprintf(buf, sizeof(buf),
3794 "While Tor is running, changing DataDirectory "
3795 "(\"%s\"->\"%s\") is not allowed.",
3796 old->DataDirectory, new_val->DataDirectory);
3797 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3798 return -1;
3801 if (!opt_streq(old->User, new_val->User)) {
3802 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
3803 return -1;
3806 if (!opt_streq(old->Group, new_val->Group)) {
3807 *msg = tor_strdup("While Tor is running, changing Group is not allowed.");
3808 return -1;
3811 if ((old->HardwareAccel != new_val->HardwareAccel)
3812 || !opt_streq(old->AccelName, new_val->AccelName)
3813 || !opt_streq(old->AccelDir, new_val->AccelDir)) {
3814 *msg = tor_strdup("While Tor is running, changing OpenSSL hardware "
3815 "acceleration engine is not allowed.");
3816 return -1;
3819 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
3820 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
3821 "is not allowed.");
3822 return -1;
3825 if (old->CellStatistics != new_val->CellStatistics ||
3826 old->DirReqStatistics != new_val->DirReqStatistics ||
3827 old->EntryStatistics != new_val->EntryStatistics ||
3828 old->ExitPortStatistics != new_val->ExitPortStatistics) {
3829 *msg = tor_strdup("While Tor is running, changing either "
3830 "CellStatistics, DirReqStatistics, EntryStatistics, "
3831 "or ExitPortStatistics is not allowed.");
3832 return -1;
3835 return 0;
3838 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3839 * will require us to rotate the CPU and DNS workers; else return 0. */
3840 static int
3841 options_transition_affects_workers(or_options_t *old_options,
3842 or_options_t *new_options)
3844 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3845 old_options->NumCpus != new_options->NumCpus ||
3846 old_options->ORPort != new_options->ORPort ||
3847 old_options->ServerDNSSearchDomains !=
3848 new_options->ServerDNSSearchDomains ||
3849 old_options->SafeLogging != new_options->SafeLogging ||
3850 old_options->ClientOnly != new_options->ClientOnly ||
3851 !config_lines_eq(old_options->Logs, new_options->Logs))
3852 return 1;
3854 /* Check whether log options match. */
3856 /* Nothing that changed matters. */
3857 return 0;
3860 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3861 * will require us to generate a new descriptor; else return 0. */
3862 static int
3863 options_transition_affects_descriptor(or_options_t *old_options,
3864 or_options_t *new_options)
3866 /* XXX We can be smarter here. If your DirPort isn't being
3867 * published and you just turned it off, no need to republish. Etc. */
3868 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3869 !opt_streq(old_options->Nickname,new_options->Nickname) ||
3870 !opt_streq(old_options->Address,new_options->Address) ||
3871 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
3872 old_options->ExitPolicyRejectPrivate !=
3873 new_options->ExitPolicyRejectPrivate ||
3874 old_options->ORPort != new_options->ORPort ||
3875 old_options->DirPort != new_options->DirPort ||
3876 old_options->ClientOnly != new_options->ClientOnly ||
3877 old_options->NoPublish != new_options->NoPublish ||
3878 old_options->_PublishServerDescriptor !=
3879 new_options->_PublishServerDescriptor ||
3880 get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
3881 get_effective_bwburst(old_options) !=
3882 get_effective_bwburst(new_options) ||
3883 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
3884 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
3885 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
3886 old_options->AccountingMax != new_options->AccountingMax)
3887 return 1;
3889 return 0;
3892 #ifdef MS_WINDOWS
3893 /** Return the directory on windows where we expect to find our application
3894 * data. */
3895 static char *
3896 get_windows_conf_root(void)
3898 static int is_set = 0;
3899 static char path[MAX_PATH+1];
3901 LPITEMIDLIST idl;
3902 IMalloc *m;
3903 HRESULT result;
3905 if (is_set)
3906 return path;
3908 /* Find X:\documents and settings\username\application data\ .
3909 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3911 #ifdef ENABLE_LOCAL_APPDATA
3912 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
3913 #else
3914 #define APPDATA_PATH CSIDL_APPDATA
3915 #endif
3916 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
3917 GetCurrentDirectory(MAX_PATH, path);
3918 is_set = 1;
3919 log_warn(LD_CONFIG,
3920 "I couldn't find your application data folder: are you "
3921 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3922 path);
3923 return path;
3925 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3926 result = SHGetPathFromIDList(idl, path);
3927 /* Now we need to free the */
3928 SHGetMalloc(&m);
3929 if (m) {
3930 m->lpVtbl->Free(m, idl);
3931 m->lpVtbl->Release(m);
3933 if (!SUCCEEDED(result)) {
3934 return NULL;
3936 strlcat(path,"\\tor",MAX_PATH);
3937 is_set = 1;
3938 return path;
3940 #endif
3942 /** Return the default location for our torrc file. */
3943 static const char *
3944 get_default_conf_file(void)
3946 #ifdef MS_WINDOWS
3947 static char path[MAX_PATH+1];
3948 strlcpy(path, get_windows_conf_root(), MAX_PATH);
3949 strlcat(path,"\\torrc",MAX_PATH);
3950 return path;
3951 #else
3952 return (CONFDIR "/torrc");
3953 #endif
3956 /** Verify whether lst is a string containing valid-looking comma-separated
3957 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3959 static int
3960 check_nickname_list(const char *lst, const char *name, char **msg)
3962 int r = 0;
3963 smartlist_t *sl;
3965 if (!lst)
3966 return 0;
3967 sl = smartlist_create();
3969 smartlist_split_string(sl, lst, ",",
3970 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
3972 SMARTLIST_FOREACH(sl, const char *, s,
3974 if (!is_legal_nickname_or_hexdigest(s)) {
3975 char buf[1024];
3976 int tmp = tor_snprintf(buf, sizeof(buf),
3977 "Invalid nickname '%s' in %s line", s, name);
3978 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
3979 r = -1;
3980 break;
3983 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
3984 smartlist_free(sl);
3985 return r;
3988 /** Learn config file name from command line arguments, or use the default */
3989 static char *
3990 find_torrc_filename(int argc, char **argv,
3991 int *using_default_torrc, int *ignore_missing_torrc)
3993 char *fname=NULL;
3994 int i;
3996 for (i = 1; i < argc; ++i) {
3997 if (i < argc-1 && !strcmp(argv[i],"-f")) {
3998 if (fname) {
3999 log(LOG_WARN, LD_CONFIG, "Duplicate -f options on command line.");
4000 tor_free(fname);
4002 #ifdef MS_WINDOWS
4003 /* XXX one day we might want to extend expand_filename to work
4004 * under Windows as well. */
4005 fname = tor_strdup(argv[i+1]);
4006 #else
4007 fname = expand_filename(argv[i+1]);
4008 #endif
4009 *using_default_torrc = 0;
4010 ++i;
4011 } else if (!strcmp(argv[i],"--ignore-missing-torrc")) {
4012 *ignore_missing_torrc = 1;
4016 if (*using_default_torrc) {
4017 /* didn't find one, try CONFDIR */
4018 const char *dflt = get_default_conf_file();
4019 if (dflt && file_status(dflt) == FN_FILE) {
4020 fname = tor_strdup(dflt);
4021 } else {
4022 #ifndef MS_WINDOWS
4023 char *fn;
4024 fn = expand_filename("~/.torrc");
4025 if (fn && file_status(fn) == FN_FILE) {
4026 fname = fn;
4027 } else {
4028 tor_free(fn);
4029 fname = tor_strdup(dflt);
4031 #else
4032 fname = tor_strdup(dflt);
4033 #endif
4036 return fname;
4039 /** Load torrc from disk, setting torrc_fname if successful */
4040 static char *
4041 load_torrc_from_disk(int argc, char **argv)
4043 char *fname=NULL;
4044 char *cf = NULL;
4045 int using_default_torrc = 1;
4046 int ignore_missing_torrc = 0;
4048 fname = find_torrc_filename(argc, argv,
4049 &using_default_torrc, &ignore_missing_torrc);
4050 tor_assert(fname);
4051 log(LOG_DEBUG, LD_CONFIG, "Opening config file \"%s\"", fname);
4053 tor_free(torrc_fname);
4054 torrc_fname = fname;
4056 /* Open config file */
4057 if (file_status(fname) != FN_FILE ||
4058 !(cf = read_file_to_str(fname,0,NULL))) {
4059 if (using_default_torrc == 1 || ignore_missing_torrc ) {
4060 log(LOG_NOTICE, LD_CONFIG, "Configuration file \"%s\" not present, "
4061 "using reasonable defaults.", fname);
4062 tor_free(fname); /* sets fname to NULL */
4063 torrc_fname = NULL;
4064 cf = tor_strdup("");
4065 } else {
4066 log(LOG_WARN, LD_CONFIG,
4067 "Unable to open configuration file \"%s\".", fname);
4068 goto err;
4072 return cf;
4073 err:
4074 tor_free(fname);
4075 torrc_fname = NULL;
4076 return NULL;
4079 /** Read a configuration file into <b>options</b>, finding the configuration
4080 * file location based on the command line. After loading the file
4081 * call options_init_from_string() to load the config.
4082 * Return 0 if success, -1 if failure. */
4084 options_init_from_torrc(int argc, char **argv)
4086 char *cf=NULL;
4087 int i, retval, command;
4088 static char **backup_argv;
4089 static int backup_argc;
4090 char *command_arg = NULL;
4091 char *errmsg=NULL;
4093 if (argv) { /* first time we're called. save command line args */
4094 backup_argv = argv;
4095 backup_argc = argc;
4096 } else { /* we're reloading. need to clean up old options first. */
4097 argv = backup_argv;
4098 argc = backup_argc;
4100 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
4101 print_usage();
4102 exit(0);
4104 if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
4105 /* For documenting validating whether we've documented everything. */
4106 list_torrc_options();
4107 exit(0);
4110 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
4111 printf("Tor version %s.\n",get_version());
4112 exit(0);
4114 if (argc > 1 && (!strcmp(argv[1],"--digests"))) {
4115 printf("Tor version %s.\n",get_version());
4116 printf("%s", libor_get_digests());
4117 printf("%s", tor_get_digests());
4118 exit(0);
4121 /* Go through command-line variables */
4122 if (!global_cmdline_options) {
4123 /* Or we could redo the list every time we pass this place.
4124 * It does not really matter */
4125 if (config_get_commandlines(argc, argv, &global_cmdline_options) < 0) {
4126 goto err;
4130 command = CMD_RUN_TOR;
4131 for (i = 1; i < argc; ++i) {
4132 if (!strcmp(argv[i],"--list-fingerprint")) {
4133 command = CMD_LIST_FINGERPRINT;
4134 } else if (!strcmp(argv[i],"--hash-password")) {
4135 command = CMD_HASH_PASSWORD;
4136 command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
4137 ++i;
4138 } else if (!strcmp(argv[i],"--verify-config")) {
4139 command = CMD_VERIFY_CONFIG;
4143 if (command == CMD_HASH_PASSWORD) {
4144 cf = tor_strdup("");
4145 } else {
4146 cf = load_torrc_from_disk(argc, argv);
4147 if (!cf)
4148 goto err;
4151 retval = options_init_from_string(cf, command, command_arg, &errmsg);
4152 tor_free(cf);
4153 if (retval < 0)
4154 goto err;
4156 return 0;
4158 err:
4159 if (errmsg) {
4160 log(LOG_WARN,LD_CONFIG,"%s", errmsg);
4161 tor_free(errmsg);
4163 return -1;
4166 /** Load the options from the configuration in <b>cf</b>, validate
4167 * them for consistency and take actions based on them.
4169 * Return 0 if success, negative on error:
4170 * * -1 for general errors.
4171 * * -2 for failure to parse/validate,
4172 * * -3 for transition not allowed
4173 * * -4 for error while setting the new options
4175 setopt_err_t
4176 options_init_from_string(const char *cf,
4177 int command, const char *command_arg,
4178 char **msg)
4180 or_options_t *oldoptions, *newoptions;
4181 config_line_t *cl;
4182 int retval;
4183 setopt_err_t err = SETOPT_ERR_MISC;
4184 tor_assert(msg);
4186 oldoptions = global_options; /* get_options unfortunately asserts if
4187 this is the first time we run*/
4189 newoptions = tor_malloc_zero(sizeof(or_options_t));
4190 newoptions->_magic = OR_OPTIONS_MAGIC;
4191 options_init(newoptions);
4192 newoptions->command = command;
4193 newoptions->command_arg = command_arg;
4195 /* get config lines, assign them */
4196 retval = config_get_lines(cf, &cl);
4197 if (retval < 0) {
4198 err = SETOPT_ERR_PARSE;
4199 goto err;
4201 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4202 config_free_lines(cl);
4203 if (retval < 0) {
4204 err = SETOPT_ERR_PARSE;
4205 goto err;
4208 /* Go through command-line variables too */
4209 retval = config_assign(&options_format, newoptions,
4210 global_cmdline_options, 0, 0, msg);
4211 if (retval < 0) {
4212 err = SETOPT_ERR_PARSE;
4213 goto err;
4216 /* If this is a testing network configuration, change defaults
4217 * for a list of dependent config options, re-initialize newoptions
4218 * with the new defaults, and assign all options to it second time. */
4219 if (newoptions->TestingTorNetwork) {
4220 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4221 * this? We could, for example, make the parsing algorithm do two passes
4222 * over the configuration. If it finds any "suite" options like
4223 * TestingTorNetwork, it could change the defaults before its second pass.
4224 * Not urgent so long as this seems to work, but at any sign of trouble,
4225 * let's clean it up. -NM */
4227 /* Change defaults. */
4228 int i;
4229 for (i = 0; testing_tor_network_defaults[i].name; ++i) {
4230 config_var_t *new_var = &testing_tor_network_defaults[i];
4231 config_var_t *old_var =
4232 config_find_option(&options_format, new_var->name);
4233 tor_assert(new_var);
4234 tor_assert(old_var);
4235 old_var->initvalue = new_var->initvalue;
4238 /* Clear newoptions and re-initialize them with new defaults. */
4239 config_free(&options_format, newoptions);
4240 newoptions = tor_malloc_zero(sizeof(or_options_t));
4241 newoptions->_magic = OR_OPTIONS_MAGIC;
4242 options_init(newoptions);
4243 newoptions->command = command;
4244 newoptions->command_arg = command_arg;
4246 /* Assign all options a second time. */
4247 retval = config_get_lines(cf, &cl);
4248 if (retval < 0) {
4249 err = SETOPT_ERR_PARSE;
4250 goto err;
4252 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4253 config_free_lines(cl);
4254 if (retval < 0) {
4255 err = SETOPT_ERR_PARSE;
4256 goto err;
4258 retval = config_assign(&options_format, newoptions,
4259 global_cmdline_options, 0, 0, msg);
4260 if (retval < 0) {
4261 err = SETOPT_ERR_PARSE;
4262 goto err;
4266 /* Validate newoptions */
4267 if (options_validate(oldoptions, newoptions, 0, msg) < 0) {
4268 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
4269 goto err;
4272 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
4273 err = SETOPT_ERR_TRANSITION;
4274 goto err;
4277 if (set_options(newoptions, msg)) {
4278 err = SETOPT_ERR_SETTING;
4279 goto err; /* frees and replaces old options */
4282 return SETOPT_OK;
4284 err:
4285 config_free(&options_format, newoptions);
4286 if (*msg) {
4287 int len = (int)strlen(*msg)+256;
4288 char *newmsg = tor_malloc(len);
4290 tor_snprintf(newmsg, len, "Failed to parse/validate config: %s", *msg);
4291 tor_free(*msg);
4292 *msg = newmsg;
4294 return err;
4297 /** Return the location for our configuration file.
4299 const char *
4300 get_torrc_fname(void)
4302 if (torrc_fname)
4303 return torrc_fname;
4304 else
4305 return get_default_conf_file();
4308 /** Adjust the address map based on the MapAddress elements in the
4309 * configuration <b>options</b>
4311 static void
4312 config_register_addressmaps(or_options_t *options)
4314 smartlist_t *elts;
4315 config_line_t *opt;
4316 char *from, *to;
4318 addressmap_clear_configured();
4319 elts = smartlist_create();
4320 for (opt = options->AddressMap; opt; opt = opt->next) {
4321 smartlist_split_string(elts, opt->value, NULL,
4322 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4323 if (smartlist_len(elts) >= 2) {
4324 from = smartlist_get(elts,0);
4325 to = smartlist_get(elts,1);
4326 if (address_is_invalid_destination(to, 1)) {
4327 log_warn(LD_CONFIG,
4328 "Skipping invalid argument '%s' to MapAddress", to);
4329 } else {
4330 addressmap_register(from, tor_strdup(to), 0, ADDRMAPSRC_TORRC);
4331 if (smartlist_len(elts)>2) {
4332 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
4335 } else {
4336 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
4337 opt->value);
4339 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4340 smartlist_clear(elts);
4342 smartlist_free(elts);
4346 * Initialize the logs based on the configuration file.
4348 static int
4349 options_init_logs(or_options_t *options, int validate_only)
4351 config_line_t *opt;
4352 int ok;
4353 smartlist_t *elts;
4354 int daemon =
4355 #ifdef MS_WINDOWS
4357 #else
4358 options->RunAsDaemon;
4359 #endif
4361 ok = 1;
4362 elts = smartlist_create();
4364 for (opt = options->Logs; opt; opt = opt->next) {
4365 log_severity_list_t *severity;
4366 const char *cfg = opt->value;
4367 severity = tor_malloc_zero(sizeof(log_severity_list_t));
4368 if (parse_log_severity_config(&cfg, severity) < 0) {
4369 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
4370 opt->value);
4371 ok = 0; goto cleanup;
4374 smartlist_split_string(elts, cfg, NULL,
4375 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4377 if (smartlist_len(elts) == 0)
4378 smartlist_add(elts, tor_strdup("stdout"));
4380 if (smartlist_len(elts) == 1 &&
4381 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
4382 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
4383 int err = smartlist_len(elts) &&
4384 !strcasecmp(smartlist_get(elts,0), "stderr");
4385 if (!validate_only) {
4386 if (daemon) {
4387 log_warn(LD_CONFIG,
4388 "Can't log to %s with RunAsDaemon set; skipping stdout",
4389 err?"stderr":"stdout");
4390 } else {
4391 add_stream_log(severity, err?"<stderr>":"<stdout>",
4392 fileno(err?stderr:stdout));
4395 goto cleanup;
4397 if (smartlist_len(elts) == 1 &&
4398 !strcasecmp(smartlist_get(elts,0), "syslog")) {
4399 #ifdef HAVE_SYSLOG_H
4400 if (!validate_only) {
4401 add_syslog_log(severity);
4403 #else
4404 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
4405 #endif
4406 goto cleanup;
4409 if (smartlist_len(elts) == 2 &&
4410 !strcasecmp(smartlist_get(elts,0), "file")) {
4411 if (!validate_only) {
4412 if (add_file_log(severity, smartlist_get(elts, 1)) < 0) {
4413 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
4414 opt->value, strerror(errno));
4415 ok = 0;
4418 goto cleanup;
4421 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
4422 opt->value);
4423 ok = 0; goto cleanup;
4425 cleanup:
4426 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4427 smartlist_clear(elts);
4428 tor_free(severity);
4430 smartlist_free(elts);
4432 return ok?0:-1;
4435 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4436 * if the line is well-formed, and -1 if it isn't. If
4437 * <b>validate_only</b> is 0, and the line is well-formed, then add
4438 * the bridge described in the line to our internal bridge list. */
4439 static int
4440 parse_bridge_line(const char *line, int validate_only)
4442 smartlist_t *items = NULL;
4443 int r;
4444 char *addrport=NULL, *fingerprint=NULL;
4445 tor_addr_t addr;
4446 uint16_t port = 0;
4447 char digest[DIGEST_LEN];
4449 items = smartlist_create();
4450 smartlist_split_string(items, line, NULL,
4451 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4452 if (smartlist_len(items) < 1) {
4453 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
4454 goto err;
4456 addrport = smartlist_get(items, 0);
4457 smartlist_del_keeporder(items, 0);
4458 if (tor_addr_port_parse(addrport, &addr, &port)<0) {
4459 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
4460 goto err;
4462 if (!port) {
4463 log_info(LD_CONFIG,
4464 "Bridge address '%s' has no port; using default port 443.",
4465 addrport);
4466 port = 443;
4469 if (smartlist_len(items)) {
4470 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4471 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4472 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
4473 goto err;
4475 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4476 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
4477 goto err;
4481 if (!validate_only) {
4482 log_debug(LD_DIR, "Bridge at %s:%d (%s)", fmt_addr(&addr),
4483 (int)port,
4484 fingerprint ? fingerprint : "no key listed");
4485 bridge_add_from_config(&addr, port, fingerprint ? digest : NULL);
4488 r = 0;
4489 goto done;
4491 err:
4492 r = -1;
4494 done:
4495 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4496 smartlist_free(items);
4497 tor_free(addrport);
4498 tor_free(fingerprint);
4499 return r;
4502 /** Read the contents of a DirServer line from <b>line</b>. If
4503 * <b>validate_only</b> is 0, and the line is well-formed, and it
4504 * shares any bits with <b>required_type</b> or <b>required_type</b>
4505 * is 0, then add the dirserver described in the line (minus whatever
4506 * bits it's missing) as a valid authority. Return 0 on success,
4507 * or -1 if the line isn't well-formed or if we can't add it. */
4508 static int
4509 parse_dir_server_line(const char *line, authority_type_t required_type,
4510 int validate_only)
4512 smartlist_t *items = NULL;
4513 int r;
4514 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
4515 uint16_t dir_port = 0, or_port = 0;
4516 char digest[DIGEST_LEN];
4517 char v3_digest[DIGEST_LEN];
4518 authority_type_t type = V2_AUTHORITY;
4519 int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
4521 items = smartlist_create();
4522 smartlist_split_string(items, line, NULL,
4523 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4524 if (smartlist_len(items) < 1) {
4525 log_warn(LD_CONFIG, "No arguments on DirServer line.");
4526 goto err;
4529 if (is_legal_nickname(smartlist_get(items, 0))) {
4530 nickname = smartlist_get(items, 0);
4531 smartlist_del_keeporder(items, 0);
4534 while (smartlist_len(items)) {
4535 char *flag = smartlist_get(items, 0);
4536 if (TOR_ISDIGIT(flag[0]))
4537 break;
4538 if (!strcasecmp(flag, "v1")) {
4539 type |= (V1_AUTHORITY | HIDSERV_AUTHORITY);
4540 } else if (!strcasecmp(flag, "hs")) {
4541 type |= HIDSERV_AUTHORITY;
4542 } else if (!strcasecmp(flag, "no-hs")) {
4543 is_not_hidserv_authority = 1;
4544 } else if (!strcasecmp(flag, "bridge")) {
4545 type |= BRIDGE_AUTHORITY;
4546 } else if (!strcasecmp(flag, "no-v2")) {
4547 is_not_v2_authority = 1;
4548 } else if (!strcasecmpstart(flag, "orport=")) {
4549 int ok;
4550 char *portstring = flag + strlen("orport=");
4551 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
4552 if (!ok)
4553 log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
4554 portstring);
4555 } else if (!strcasecmpstart(flag, "v3ident=")) {
4556 char *idstr = flag + strlen("v3ident=");
4557 if (strlen(idstr) != HEX_DIGEST_LEN ||
4558 base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
4559 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirServer line",
4560 flag);
4561 } else {
4562 type |= V3_AUTHORITY;
4564 } else {
4565 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
4566 flag);
4568 tor_free(flag);
4569 smartlist_del_keeporder(items, 0);
4571 if (is_not_hidserv_authority)
4572 type &= ~HIDSERV_AUTHORITY;
4573 if (is_not_v2_authority)
4574 type &= ~V2_AUTHORITY;
4576 if (smartlist_len(items) < 2) {
4577 log_warn(LD_CONFIG, "Too few arguments to DirServer line.");
4578 goto err;
4580 addrport = smartlist_get(items, 0);
4581 smartlist_del_keeporder(items, 0);
4582 if (parse_addr_port(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
4583 log_warn(LD_CONFIG, "Error parsing DirServer address '%s'", addrport);
4584 goto err;
4586 if (!dir_port) {
4587 log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
4588 goto err;
4591 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4592 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4593 log_warn(LD_CONFIG, "Key digest for DirServer is wrong length %d.",
4594 (int)strlen(fingerprint));
4595 goto err;
4597 if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4598 /* a known bad fingerprint. refuse to use it. We can remove this
4599 * clause once Tor 0.1.2.17 is obsolete. */
4600 log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
4601 "torrc file (%s), or reinstall Tor and use the default torrc.",
4602 get_torrc_fname());
4603 goto err;
4605 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4606 log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
4607 goto err;
4610 if (!validate_only && (!required_type || required_type & type)) {
4611 if (required_type)
4612 type &= required_type; /* pare down what we think of them as an
4613 * authority for. */
4614 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
4615 address, (int)dir_port, (char*)smartlist_get(items,0));
4616 if (!add_trusted_dir_server(nickname, address, dir_port, or_port,
4617 digest, v3_digest, type))
4618 goto err;
4621 r = 0;
4622 goto done;
4624 err:
4625 r = -1;
4627 done:
4628 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4629 smartlist_free(items);
4630 tor_free(addrport);
4631 tor_free(address);
4632 tor_free(nickname);
4633 tor_free(fingerprint);
4634 return r;
4637 /** Adjust the value of options->DataDirectory, or fill it in if it's
4638 * absent. Return 0 on success, -1 on failure. */
4639 static int
4640 normalize_data_directory(or_options_t *options)
4642 #ifdef MS_WINDOWS
4643 char *p;
4644 if (options->DataDirectory)
4645 return 0; /* all set */
4646 p = tor_malloc(MAX_PATH);
4647 strlcpy(p,get_windows_conf_root(),MAX_PATH);
4648 options->DataDirectory = p;
4649 return 0;
4650 #else
4651 const char *d = options->DataDirectory;
4652 if (!d)
4653 d = "~/.tor";
4655 if (strncmp(d,"~/",2) == 0) {
4656 char *fn = expand_filename(d);
4657 if (!fn) {
4658 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
4659 return -1;
4661 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
4662 /* If our homedir is /, we probably don't want to use it. */
4663 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4664 * want. */
4665 log_warn(LD_CONFIG,
4666 "Default DataDirectory is \"~/.tor\". This expands to "
4667 "\"%s\", which is probably not what you want. Using "
4668 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
4669 tor_free(fn);
4670 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
4672 tor_free(options->DataDirectory);
4673 options->DataDirectory = fn;
4675 return 0;
4676 #endif
4679 /** Check and normalize the value of options->DataDirectory; return 0 if it
4680 * sane, -1 otherwise. */
4681 static int
4682 validate_data_directory(or_options_t *options)
4684 if (normalize_data_directory(options) < 0)
4685 return -1;
4686 tor_assert(options->DataDirectory);
4687 if (strlen(options->DataDirectory) > (512-128)) {
4688 log_warn(LD_CONFIG, "DataDirectory is too long.");
4689 return -1;
4691 return 0;
4694 /** This string must remain the same forevermore. It is how we
4695 * recognize that the torrc file doesn't need to be backed up. */
4696 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4697 "if you edit it, comments will not be preserved"
4698 /** This string can change; it tries to give the reader an idea
4699 * that editing this file by hand is not a good plan. */
4700 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4701 "to torrc.orig.1 or similar, and Tor will ignore it"
4703 /** Save a configuration file for the configuration in <b>options</b>
4704 * into the file <b>fname</b>. If the file already exists, and
4705 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4706 * replace it. Return 0 on success, -1 on failure. */
4707 static int
4708 write_configuration_file(const char *fname, or_options_t *options)
4710 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4711 int rename_old = 0, r;
4712 size_t len;
4714 tor_assert(fname);
4716 switch (file_status(fname)) {
4717 case FN_FILE:
4718 old_val = read_file_to_str(fname, 0, NULL);
4719 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4720 rename_old = 1;
4722 tor_free(old_val);
4723 break;
4724 case FN_NOENT:
4725 break;
4726 case FN_ERROR:
4727 case FN_DIR:
4728 default:
4729 log_warn(LD_CONFIG,
4730 "Config file \"%s\" is not a file? Failing.", fname);
4731 return -1;
4734 if (!(new_conf = options_dump(options, 1))) {
4735 log_warn(LD_BUG, "Couldn't get configuration string");
4736 goto err;
4739 len = strlen(new_conf)+256;
4740 new_val = tor_malloc(len);
4741 tor_snprintf(new_val, len, "%s\n%s\n\n%s",
4742 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4744 if (rename_old) {
4745 int i = 1;
4746 size_t fn_tmp_len = strlen(fname)+32;
4747 char *fn_tmp;
4748 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4749 fn_tmp = tor_malloc(fn_tmp_len);
4750 while (1) {
4751 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4752 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4753 tor_free(fn_tmp);
4754 goto err;
4756 if (file_status(fn_tmp) == FN_NOENT)
4757 break;
4758 ++i;
4760 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4761 if (rename(fname, fn_tmp) < 0) {
4762 log_warn(LD_FS,
4763 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4764 fname, fn_tmp, strerror(errno));
4765 tor_free(fn_tmp);
4766 goto err;
4768 tor_free(fn_tmp);
4771 if (write_str_to_file(fname, new_val, 0) < 0)
4772 goto err;
4774 r = 0;
4775 goto done;
4776 err:
4777 r = -1;
4778 done:
4779 tor_free(new_val);
4780 tor_free(new_conf);
4781 return r;
4785 * Save the current configuration file value to disk. Return 0 on
4786 * success, -1 on failure.
4789 options_save_current(void)
4791 if (torrc_fname) {
4792 /* This fails if we can't write to our configuration file.
4794 * If we try falling back to datadirectory or something, we have a better
4795 * chance of saving the configuration, but a better chance of doing
4796 * something the user never expected. Let's just warn instead. */
4797 return write_configuration_file(torrc_fname, get_options());
4799 return write_configuration_file(get_default_conf_file(), get_options());
4802 /** Mapping from a unit name to a multiplier for converting that unit into a
4803 * base unit. */
4804 struct unit_table_t {
4805 const char *unit;
4806 uint64_t multiplier;
4809 /** Table to map the names of memory units to the number of bytes they
4810 * contain. */
4811 static struct unit_table_t memory_units[] = {
4812 { "", 1 },
4813 { "b", 1<< 0 },
4814 { "byte", 1<< 0 },
4815 { "bytes", 1<< 0 },
4816 { "kb", 1<<10 },
4817 { "kbyte", 1<<10 },
4818 { "kbytes", 1<<10 },
4819 { "kilobyte", 1<<10 },
4820 { "kilobytes", 1<<10 },
4821 { "m", 1<<20 },
4822 { "mb", 1<<20 },
4823 { "mbyte", 1<<20 },
4824 { "mbytes", 1<<20 },
4825 { "megabyte", 1<<20 },
4826 { "megabytes", 1<<20 },
4827 { "gb", 1<<30 },
4828 { "gbyte", 1<<30 },
4829 { "gbytes", 1<<30 },
4830 { "gigabyte", 1<<30 },
4831 { "gigabytes", 1<<30 },
4832 { "tb", U64_LITERAL(1)<<40 },
4833 { "terabyte", U64_LITERAL(1)<<40 },
4834 { "terabytes", U64_LITERAL(1)<<40 },
4835 { NULL, 0 },
4838 /** Table to map the names of time units to the number of seconds they
4839 * contain. */
4840 static struct unit_table_t time_units[] = {
4841 { "", 1 },
4842 { "second", 1 },
4843 { "seconds", 1 },
4844 { "minute", 60 },
4845 { "minutes", 60 },
4846 { "hour", 60*60 },
4847 { "hours", 60*60 },
4848 { "day", 24*60*60 },
4849 { "days", 24*60*60 },
4850 { "week", 7*24*60*60 },
4851 { "weeks", 7*24*60*60 },
4852 { NULL, 0 },
4855 /** Parse a string <b>val</b> containing a number, zero or more
4856 * spaces, and an optional unit string. If the unit appears in the
4857 * table <b>u</b>, then multiply the number by the unit multiplier.
4858 * On success, set *<b>ok</b> to 1 and return this product.
4859 * Otherwise, set *<b>ok</b> to 0.
4861 static uint64_t
4862 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4864 uint64_t v = 0;
4865 double d = 0;
4866 int use_float = 0;
4867 char *cp;
4869 tor_assert(ok);
4871 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4872 if (!*ok || (cp && *cp == '.')) {
4873 d = tor_parse_double(val, 0, UINT64_MAX, ok, &cp);
4874 if (!*ok)
4875 goto done;
4876 use_float = 1;
4879 if (!cp) {
4880 *ok = 1;
4881 v = use_float ? DBL_TO_U64(d) : v;
4882 goto done;
4885 cp = (char*) eat_whitespace(cp);
4887 for ( ;u->unit;++u) {
4888 if (!strcasecmp(u->unit, cp)) {
4889 if (use_float)
4890 v = u->multiplier * d;
4891 else
4892 v *= u->multiplier;
4893 *ok = 1;
4894 goto done;
4897 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4898 *ok = 0;
4899 done:
4901 if (*ok)
4902 return v;
4903 else
4904 return 0;
4907 /** Parse a string in the format "number unit", where unit is a unit of
4908 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4909 * and return the number of bytes specified. Otherwise, set
4910 * *<b>ok</b> to false and return 0. */
4911 static uint64_t
4912 config_parse_memunit(const char *s, int *ok)
4914 uint64_t u = config_parse_units(s, memory_units, ok);
4915 return u;
4918 /** Parse a string in the format "number unit", where unit is a unit of time.
4919 * On success, set *<b>ok</b> to true and return the number of seconds in
4920 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4922 static int
4923 config_parse_interval(const char *s, int *ok)
4925 uint64_t r;
4926 r = config_parse_units(s, time_units, ok);
4927 if (!ok)
4928 return -1;
4929 if (r > INT_MAX) {
4930 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4931 *ok = 0;
4932 return -1;
4934 return (int)r;
4938 * Initialize the libevent library.
4940 static void
4941 init_libevent(void)
4943 const char *badness=NULL;
4945 configure_libevent_logging();
4946 /* If the kernel complains that some method (say, epoll) doesn't
4947 * exist, we don't care about it, since libevent will cope.
4949 suppress_libevent_log_msg("Function not implemented");
4951 tor_check_libevent_header_compatibility();
4953 tor_libevent_initialize();
4955 suppress_libevent_log_msg(NULL);
4957 tor_check_libevent_version(tor_libevent_get_method(),
4958 get_options()->ORPort != 0,
4959 &badness);
4960 if (badness) {
4961 const char *v = tor_libevent_get_version_str();
4962 const char *m = tor_libevent_get_method();
4963 control_event_general_status(LOG_WARN,
4964 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
4965 v, m, badness);
4969 /** Return the persistent state struct for this Tor. */
4970 or_state_t *
4971 get_or_state(void)
4973 tor_assert(global_state);
4974 return global_state;
4977 /** Return a newly allocated string holding a filename relative to the data
4978 * directory. If <b>sub1</b> is present, it is the first path component after
4979 * the data directory. If <b>sub2</b> is also present, it is the second path
4980 * component after the data directory. If <b>suffix</b> is present, it
4981 * is appended to the filename.
4983 * Examples:
4984 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
4985 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
4986 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
4987 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
4989 * Note: Consider using the get_datadir_fname* macros in or.h.
4991 char *
4992 options_get_datadir_fname2_suffix(or_options_t *options,
4993 const char *sub1, const char *sub2,
4994 const char *suffix)
4996 char *fname = NULL;
4997 size_t len;
4998 tor_assert(options);
4999 tor_assert(options->DataDirectory);
5000 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
5001 len = strlen(options->DataDirectory);
5002 if (sub1) {
5003 len += strlen(sub1)+1;
5004 if (sub2)
5005 len += strlen(sub2)+1;
5007 if (suffix)
5008 len += strlen(suffix);
5009 len++;
5010 fname = tor_malloc(len);
5011 if (sub1) {
5012 if (sub2) {
5013 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
5014 options->DataDirectory, sub1, sub2);
5015 } else {
5016 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
5017 options->DataDirectory, sub1);
5019 } else {
5020 strlcpy(fname, options->DataDirectory, len);
5022 if (suffix)
5023 strlcat(fname, suffix, len);
5024 return fname;
5027 /** Return 0 if every setting in <b>state</b> is reasonable, and a
5028 * permissible transition from <b>old_state</b>. Else warn and return -1.
5029 * Should have no side effects, except for normalizing the contents of
5030 * <b>state</b>.
5032 /* XXX from_setconf is here because of bug 238 */
5033 static int
5034 or_state_validate(or_state_t *old_state, or_state_t *state,
5035 int from_setconf, char **msg)
5037 /* We don't use these; only options do. Still, we need to match that
5038 * signature. */
5039 (void) from_setconf;
5040 (void) old_state;
5042 if (entry_guards_parse_state(state, 0, msg)<0)
5043 return -1;
5045 return 0;
5048 /** Replace the current persistent state with <b>new_state</b> */
5049 static void
5050 or_state_set(or_state_t *new_state)
5052 char *err = NULL;
5053 tor_assert(new_state);
5054 if (global_state)
5055 config_free(&state_format, global_state);
5056 global_state = new_state;
5057 if (entry_guards_parse_state(global_state, 1, &err)<0) {
5058 log_warn(LD_GENERAL,"%s",err);
5059 tor_free(err);
5061 if (rep_hist_load_state(global_state, &err)<0) {
5062 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
5063 tor_free(err);
5065 if (circuit_build_times_parse_state(&circ_times, global_state, &err) < 0) {
5066 log_warn(LD_GENERAL,"%s",err);
5067 tor_free(err);
5071 /** Reload the persistent state from disk, generating a new state as needed.
5072 * Return 0 on success, less than 0 on failure.
5074 static int
5075 or_state_load(void)
5077 or_state_t *new_state = NULL;
5078 char *contents = NULL, *fname;
5079 char *errmsg = NULL;
5080 int r = -1, badstate = 0;
5082 fname = get_datadir_fname("state");
5083 switch (file_status(fname)) {
5084 case FN_FILE:
5085 if (!(contents = read_file_to_str(fname, 0, NULL))) {
5086 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
5087 goto done;
5089 break;
5090 case FN_NOENT:
5091 break;
5092 case FN_ERROR:
5093 case FN_DIR:
5094 default:
5095 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
5096 goto done;
5098 new_state = tor_malloc_zero(sizeof(or_state_t));
5099 new_state->_magic = OR_STATE_MAGIC;
5100 config_init(&state_format, new_state);
5101 if (contents) {
5102 config_line_t *lines=NULL;
5103 int assign_retval;
5104 if (config_get_lines(contents, &lines)<0)
5105 goto done;
5106 assign_retval = config_assign(&state_format, new_state,
5107 lines, 0, 0, &errmsg);
5108 config_free_lines(lines);
5109 if (assign_retval<0)
5110 badstate = 1;
5111 if (errmsg) {
5112 log_warn(LD_GENERAL, "%s", errmsg);
5113 tor_free(errmsg);
5117 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
5118 badstate = 1;
5120 if (errmsg) {
5121 log_warn(LD_GENERAL, "%s", errmsg);
5122 tor_free(errmsg);
5125 if (badstate && !contents) {
5126 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
5127 " This is a bug in Tor.");
5128 goto done;
5129 } else if (badstate && contents) {
5130 int i;
5131 file_status_t status;
5132 size_t len = strlen(fname)+16;
5133 char *fname2 = tor_malloc(len);
5134 for (i = 0; i < 100; ++i) {
5135 tor_snprintf(fname2, len, "%s.%d", fname, i);
5136 status = file_status(fname2);
5137 if (status == FN_NOENT)
5138 break;
5140 if (i == 100) {
5141 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
5142 "state files to move aside. Discarding the old state file.",
5143 fname);
5144 unlink(fname);
5145 } else {
5146 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
5147 "to \"%s\". This could be a bug in Tor; please tell "
5148 "the developers.", fname, fname2);
5149 if (rename(fname, fname2) < 0) {
5150 log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
5151 "OS gave an error of %s", strerror(errno));
5154 tor_free(fname2);
5155 tor_free(contents);
5156 config_free(&state_format, new_state);
5158 new_state = tor_malloc_zero(sizeof(or_state_t));
5159 new_state->_magic = OR_STATE_MAGIC;
5160 config_init(&state_format, new_state);
5161 } else if (contents) {
5162 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
5163 } else {
5164 log_info(LD_GENERAL, "Initialized state");
5166 or_state_set(new_state);
5167 new_state = NULL;
5168 if (!contents) {
5169 global_state->next_write = 0;
5170 or_state_save(time(NULL));
5172 r = 0;
5174 done:
5175 tor_free(fname);
5176 tor_free(contents);
5177 if (new_state)
5178 config_free(&state_format, new_state);
5180 return r;
5183 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
5185 or_state_save(time_t now)
5187 char *state, *contents;
5188 char tbuf[ISO_TIME_LEN+1];
5189 size_t len;
5190 char *fname;
5192 tor_assert(global_state);
5194 if (global_state->next_write > now)
5195 return 0;
5197 /* Call everything else that might dirty the state even more, in order
5198 * to avoid redundant writes. */
5199 entry_guards_update_state(global_state);
5200 rep_hist_update_state(global_state);
5201 circuit_build_times_update_state(&circ_times, global_state);
5202 if (accounting_is_enabled(get_options()))
5203 accounting_run_housekeeping(now);
5205 global_state->LastWritten = time(NULL);
5206 tor_free(global_state->TorVersion);
5207 len = strlen(get_version())+8;
5208 global_state->TorVersion = tor_malloc(len);
5209 tor_snprintf(global_state->TorVersion, len, "Tor %s", get_version());
5211 state = config_dump(&state_format, global_state, 1, 0);
5212 len = strlen(state)+256;
5213 contents = tor_malloc(len);
5214 format_local_iso_time(tbuf, time(NULL));
5215 tor_snprintf(contents, len,
5216 "# Tor state file last generated on %s local time\n"
5217 "# Other times below are in GMT\n"
5218 "# You *do not* need to edit this file.\n\n%s",
5219 tbuf, state);
5220 tor_free(state);
5221 fname = get_datadir_fname("state");
5222 if (write_str_to_file(fname, contents, 0)<0) {
5223 log_warn(LD_FS, "Unable to write state to file \"%s\"", fname);
5224 tor_free(fname);
5225 tor_free(contents);
5226 return -1;
5228 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
5229 tor_free(fname);
5230 tor_free(contents);
5232 global_state->next_write = TIME_MAX;
5233 return 0;
5236 /** Given a file name check to see whether the file exists but has not been
5237 * modified for a very long time. If so, remove it. */
5238 void
5239 remove_file_if_very_old(const char *fname, time_t now)
5241 #define VERY_OLD_FILE_AGE (28*24*60*60)
5242 struct stat st;
5244 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
5245 char buf[ISO_TIME_LEN+1];
5246 format_local_iso_time(buf, st.st_mtime);
5247 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
5248 "Removing it.", fname, buf);
5249 unlink(fname);
5253 /** Helper to implement GETINFO functions about configuration variables (not
5254 * their values). Given a "config/names" question, set *<b>answer</b> to a
5255 * new string describing the supported configuration variables and their
5256 * types. */
5258 getinfo_helper_config(control_connection_t *conn,
5259 const char *question, char **answer)
5261 (void) conn;
5262 if (!strcmp(question, "config/names")) {
5263 smartlist_t *sl = smartlist_create();
5264 int i;
5265 for (i = 0; _option_vars[i].name; ++i) {
5266 config_var_t *var = &_option_vars[i];
5267 const char *type, *desc;
5268 char *line;
5269 size_t len;
5270 desc = config_find_description(&options_format, var->name);
5271 switch (var->type) {
5272 case CONFIG_TYPE_STRING: type = "String"; break;
5273 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
5274 case CONFIG_TYPE_UINT: type = "Integer"; break;
5275 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
5276 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
5277 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
5278 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
5279 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
5280 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
5281 case CONFIG_TYPE_CSV: type = "CommaList"; break;
5282 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
5283 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
5284 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
5285 default:
5286 case CONFIG_TYPE_OBSOLETE:
5287 type = NULL; break;
5289 if (!type)
5290 continue;
5291 len = strlen(var->name)+strlen(type)+16;
5292 if (desc)
5293 len += strlen(desc);
5294 line = tor_malloc(len);
5295 if (desc)
5296 tor_snprintf(line, len, "%s %s %s\n",var->name,type,desc);
5297 else
5298 tor_snprintf(line, len, "%s %s\n",var->name,type);
5299 smartlist_add(sl, line);
5301 *answer = smartlist_join_strings(sl, "", 0, NULL);
5302 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
5303 smartlist_free(sl);
5305 return 0;