Now that FOO_free(NULL) always works, remove checks before calling it.
[tor.git] / src / or / config.c
blob416cbc130213d4c38e8ec29615313a08ceb0b857
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(CircuitStreamTimeout, INTERVAL, "0"),
170 V(ClientDNSRejectInternalAddresses, BOOL,"1"),
171 V(ClientOnly, BOOL, "0"),
172 V(ConsensusParams, STRING, NULL),
173 V(ConnLimit, UINT, "1000"),
174 V(ConstrainedSockets, BOOL, "0"),
175 V(ConstrainedSockSize, MEMUNIT, "8192"),
176 V(ContactInfo, STRING, NULL),
177 V(ControlListenAddress, LINELIST, NULL),
178 V(ControlPort, UINT, "0"),
179 V(ControlSocket, LINELIST, NULL),
180 V(CookieAuthentication, BOOL, "0"),
181 V(CookieAuthFileGroupReadable, BOOL, "0"),
182 V(CookieAuthFile, STRING, NULL),
183 V(DataDirectory, FILENAME, NULL),
184 OBSOLETE("DebugLogFile"),
185 V(DirAllowPrivateAddresses, BOOL, NULL),
186 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
187 V(DirListenAddress, LINELIST, NULL),
188 OBSOLETE("DirFetchPeriod"),
189 V(DirPolicy, LINELIST, NULL),
190 V(DirPort, UINT, "0"),
191 V(DirPortFrontPage, FILENAME, NULL),
192 OBSOLETE("DirPostPeriod"),
193 OBSOLETE("DirRecordUsageByCountry"),
194 OBSOLETE("DirRecordUsageGranularity"),
195 OBSOLETE("DirRecordUsageRetainIPs"),
196 OBSOLETE("DirRecordUsageSaveInterval"),
197 V(DirReqStatistics, BOOL, "0"),
198 VAR("DirServer", LINELIST, DirServers, NULL),
199 V(DisableAllSwap, BOOL, "0"),
200 V(DNSPort, UINT, "0"),
201 V(DNSListenAddress, LINELIST, NULL),
202 V(DownloadExtraInfo, BOOL, "0"),
203 V(EnforceDistinctSubnets, BOOL, "1"),
204 V(EntryNodes, ROUTERSET, NULL),
205 V(EntryStatistics, BOOL, "0"),
206 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
207 V(ExcludeNodes, ROUTERSET, NULL),
208 V(ExcludeExitNodes, ROUTERSET, NULL),
209 V(ExcludeSingleHopRelays, BOOL, "1"),
210 V(ExitNodes, ROUTERSET, NULL),
211 V(ExitPolicy, LINELIST, NULL),
212 V(ExitPolicyRejectPrivate, BOOL, "1"),
213 V(ExitPortStatistics, BOOL, "0"),
214 V(ExtraInfoStatistics, BOOL, "0"),
215 V(FallbackNetworkstatusFile, FILENAME,
216 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "fallback-consensus"),
217 V(FascistFirewall, BOOL, "0"),
218 V(FirewallPorts, CSV, ""),
219 V(FastFirstHopPK, BOOL, "1"),
220 V(FetchDirInfoEarly, BOOL, "0"),
221 V(FetchDirInfoExtraEarly, BOOL, "0"),
222 V(FetchServerDescriptors, BOOL, "1"),
223 V(FetchHidServDescriptors, BOOL, "1"),
224 V(FetchUselessDescriptors, BOOL, "0"),
225 #ifdef WIN32
226 V(GeoIPFile, FILENAME, "<default>"),
227 #else
228 V(GeoIPFile, FILENAME,
229 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
230 #endif
231 OBSOLETE("Group"),
232 V(HardwareAccel, BOOL, "0"),
233 V(AccelName, STRING, NULL),
234 V(AccelDir, FILENAME, NULL),
235 V(HashedControlPassword, LINELIST, NULL),
236 V(HidServDirectoryV2, BOOL, "1"),
237 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
238 OBSOLETE("HiddenServiceExcludeNodes"),
239 OBSOLETE("HiddenServiceNodes"),
240 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
241 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
242 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
243 VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
244 V(HidServAuth, LINELIST, NULL),
245 V(HSAuthoritativeDir, BOOL, "0"),
246 V(HSAuthorityRecordStats, BOOL, "0"),
247 V(HttpProxy, STRING, NULL),
248 V(HttpProxyAuthenticator, STRING, NULL),
249 V(HttpsProxy, STRING, NULL),
250 V(HttpsProxyAuthenticator, STRING, NULL),
251 V(Socks4Proxy, STRING, NULL),
252 V(Socks5Proxy, STRING, NULL),
253 V(Socks5ProxyUsername, STRING, NULL),
254 V(Socks5ProxyPassword, STRING, NULL),
255 OBSOLETE("IgnoreVersion"),
256 V(KeepalivePeriod, INTERVAL, "5 minutes"),
257 VAR("Log", LINELIST, Logs, NULL),
258 OBSOLETE("LinkPadding"),
259 OBSOLETE("LogLevel"),
260 OBSOLETE("LogFile"),
261 V(LongLivedPorts, CSV,
262 "21,22,706,1863,5050,5190,5222,5223,6667,6697,8300"),
263 VAR("MapAddress", LINELIST, AddressMap, NULL),
264 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
265 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
266 V(MaxOnionsPending, UINT, "100"),
267 OBSOLETE("MonthlyAccountingStart"),
268 V(MyFamily, STRING, NULL),
269 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
270 VAR("NamingAuthoritativeDirectory",BOOL, NamingAuthoritativeDir, "0"),
271 V(NatdListenAddress, LINELIST, NULL),
272 V(NatdPort, UINT, "0"),
273 V(Nickname, STRING, NULL),
274 V(NoPublish, BOOL, "0"),
275 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
276 V(NumCpus, UINT, "1"),
277 V(NumEntryGuards, UINT, "3"),
278 V(ORListenAddress, LINELIST, NULL),
279 V(ORPort, UINT, "0"),
280 V(OutboundBindAddress, STRING, NULL),
281 OBSOLETE("PathlenCoinWeight"),
282 V(PidFile, STRING, NULL),
283 V(TestingTorNetwork, BOOL, "0"),
284 V(PreferTunneledDirConns, BOOL, "1"),
285 V(ProtocolWarnings, BOOL, "0"),
286 V(PublishServerDescriptor, CSV, "1"),
287 V(PublishHidServDescriptors, BOOL, "1"),
288 V(ReachableAddresses, LINELIST, NULL),
289 V(ReachableDirAddresses, LINELIST, NULL),
290 V(ReachableORAddresses, LINELIST, NULL),
291 V(RecommendedVersions, LINELIST, NULL),
292 V(RecommendedClientVersions, LINELIST, NULL),
293 V(RecommendedServerVersions, LINELIST, NULL),
294 OBSOLETE("RedirectExit"),
295 V(RejectPlaintextPorts, CSV, ""),
296 V(RelayBandwidthBurst, MEMUNIT, "0"),
297 V(RelayBandwidthRate, MEMUNIT, "0"),
298 OBSOLETE("RendExcludeNodes"),
299 OBSOLETE("RendNodes"),
300 V(RendPostPeriod, INTERVAL, "1 hour"),
301 V(RephistTrackTime, INTERVAL, "24 hours"),
302 OBSOLETE("RouterFile"),
303 V(RunAsDaemon, BOOL, "0"),
304 V(RunTesting, BOOL, "0"),
305 V(SafeLogging, BOOL, "1"),
306 V(SafeSocks, BOOL, "0"),
307 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
308 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
309 V(ServerDNSDetectHijacking, BOOL, "1"),
310 V(ServerDNSRandomizeCase, BOOL, "1"),
311 V(ServerDNSResolvConfFile, STRING, NULL),
312 V(ServerDNSSearchDomains, BOOL, "0"),
313 V(ServerDNSTestAddresses, CSV,
314 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
315 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
316 V(SocksListenAddress, LINELIST, NULL),
317 V(SocksPolicy, LINELIST, NULL),
318 V(SocksPort, UINT, "9050"),
319 V(SocksTimeout, INTERVAL, "2 minutes"),
320 OBSOLETE("StatusFetchPeriod"),
321 V(StrictEntryNodes, BOOL, "0"),
322 V(StrictExitNodes, BOOL, "0"),
323 OBSOLETE("SysLog"),
324 V(TestSocks, BOOL, "0"),
325 OBSOLETE("TestVia"),
326 V(TrackHostExits, CSV, NULL),
327 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
328 OBSOLETE("TrafficShaping"),
329 V(TransListenAddress, LINELIST, NULL),
330 V(TransPort, UINT, "0"),
331 V(TunnelDirConns, BOOL, "1"),
332 V(UpdateBridgesFromAuthority, BOOL, "0"),
333 V(UseBridges, BOOL, "0"),
334 V(UseEntryGuards, BOOL, "1"),
335 V(User, STRING, NULL),
336 VAR("V1AuthoritativeDirectory",BOOL, V1AuthoritativeDir, "0"),
337 VAR("V2AuthoritativeDirectory",BOOL, V2AuthoritativeDir, "0"),
338 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
339 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
340 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
341 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
342 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
343 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
344 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
345 V(V3AuthNIntervalsValid, UINT, "3"),
346 V(V3AuthUseLegacyKey, BOOL, "0"),
347 V(V3BandwidthsFile, FILENAME, NULL),
348 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
349 V(VirtualAddrNetwork, STRING, "127.192.0.0/10"),
350 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
351 VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
352 VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
353 VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
354 VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
355 VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
356 NULL),
357 V(MinUptimeHidServDirectoryV2, INTERVAL, "24 hours"),
358 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
361 /** Override default values with these if the user sets the TestingTorNetwork
362 * option. */
363 static config_var_t testing_tor_network_defaults[] = {
364 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
365 V(DirAllowPrivateAddresses, BOOL, "1"),
366 V(EnforceDistinctSubnets, BOOL, "0"),
367 V(AssumeReachable, BOOL, "1"),
368 V(AuthDirMaxServersPerAddr, UINT, "0"),
369 V(AuthDirMaxServersPerAuthAddr,UINT, "0"),
370 V(ClientDNSRejectInternalAddresses, BOOL,"0"),
371 V(ExitPolicyRejectPrivate, BOOL, "0"),
372 V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
373 V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
374 V(V3AuthDistDelay, INTERVAL, "20 seconds"),
375 V(TestingV3AuthInitialVotingInterval, INTERVAL, "5 minutes"),
376 V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
377 V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
378 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
379 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
380 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
382 #undef VAR
384 #define VAR(name,conftype,member,initvalue) \
385 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
386 initvalue }
388 /** Array of "state" variables saved to the ~/.tor/state file. */
389 static config_var_t _state_vars[] = {
390 V(AccountingBytesReadInInterval, MEMUNIT, NULL),
391 V(AccountingBytesWrittenInInterval, MEMUNIT, NULL),
392 V(AccountingExpectedUsage, MEMUNIT, NULL),
393 V(AccountingIntervalStart, ISOTIME, NULL),
394 V(AccountingSecondsActive, INTERVAL, NULL),
396 VAR("EntryGuard", LINELIST_S, EntryGuards, NULL),
397 VAR("EntryGuardDownSince", LINELIST_S, EntryGuards, NULL),
398 VAR("EntryGuardUnlistedSince", LINELIST_S, EntryGuards, NULL),
399 VAR("EntryGuardAddedBy", LINELIST_S, EntryGuards, NULL),
400 V(EntryGuards, LINELIST_V, NULL),
402 V(BWHistoryReadEnds, ISOTIME, NULL),
403 V(BWHistoryReadInterval, UINT, "900"),
404 V(BWHistoryReadValues, CSV, ""),
405 V(BWHistoryWriteEnds, ISOTIME, NULL),
406 V(BWHistoryWriteInterval, UINT, "900"),
407 V(BWHistoryWriteValues, CSV, ""),
409 V(TorVersion, STRING, NULL),
411 V(LastRotatedOnionKey, ISOTIME, NULL),
412 V(LastWritten, ISOTIME, NULL),
414 V(TotalBuildTimes, UINT, NULL),
415 VAR("CircuitBuildTimeBin", LINELIST_S, BuildtimeHistogram, NULL),
416 VAR("BuildtimeHistogram", LINELIST_V, BuildtimeHistogram, NULL),
418 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
421 #undef VAR
422 #undef V
423 #undef OBSOLETE
425 /** Represents an English description of a configuration variable; used when
426 * generating configuration file comments. */
427 typedef struct config_var_description_t {
428 const char *name;
429 const char *description;
430 } config_var_description_t;
432 /** Descriptions of the configuration options, to be displayed by online
433 * option browsers */
434 /* XXXX022 did anybody want this? at all? If not, kill it.*/
435 static config_var_description_t options_description[] = {
436 /* ==== general options */
437 { "AvoidDiskWrites", "If non-zero, try to write to disk less frequently than"
438 " we would otherwise." },
439 { "BandwidthRate", "A token bucket limits the average incoming bandwidth on "
440 "this node to the specified number of bytes per second." },
441 { "BandwidthBurst", "Limit the maximum token buffer size (also known as "
442 "burst) to the given number of bytes." },
443 { "ConnLimit", "Minimum number of simultaneous sockets we must have." },
444 { "ConstrainedSockets", "Shrink tx and rx buffers for sockets to avoid "
445 "system limits on vservers and related environments. See man page for "
446 "more information regarding this option." },
447 { "ConstrainedSockSize", "Limit socket buffers to this size when "
448 "ConstrainedSockets is enabled." },
449 /* ControlListenAddress */
450 { "ControlPort", "If set, Tor will accept connections from the same machine "
451 "(localhost only) on this port, and allow those connections to control "
452 "the Tor process using the Tor Control Protocol (described in "
453 "control-spec.txt).", },
454 { "CookieAuthentication", "If this option is set to 1, don't allow any "
455 "connections to the control port except when the connecting process "
456 "can read a file that Tor creates in its data directory." },
457 { "DataDirectory", "Store working data, state, keys, and caches here." },
458 { "DirServer", "Tor only trusts directories signed with one of these "
459 "servers' keys. Used to override the standard list of directory "
460 "authorities." },
461 { "DisableAllSwap", "Tor will attempt a simple memory lock that "
462 "will prevent leaking of all information in memory to the swap file." },
463 /* { "FastFirstHopPK", "" }, */
464 /* FetchServerDescriptors, FetchHidServDescriptors,
465 * FetchUselessDescriptors */
466 { "HardwareAccel", "If set, Tor tries to use hardware crypto accelerators "
467 "when it can." },
468 { "AccelName", "If set, try to use hardware crypto accelerator with this "
469 "specific ID." },
470 { "AccelDir", "If set, look in this directory for the dynamic hardware "
471 "engine in addition to OpenSSL default path." },
472 /* HashedControlPassword */
473 { "HTTPProxy", "Force Tor to make all HTTP directory requests through this "
474 "host:port (or host:80 if port is not set)." },
475 { "HTTPProxyAuthenticator", "A username:password pair to be used with "
476 "HTTPProxy." },
477 { "HTTPSProxy", "Force Tor to make all TLS (SSL) connections through this "
478 "host:port (or host:80 if port is not set)." },
479 { "HTTPSProxyAuthenticator", "A username:password pair to be used with "
480 "HTTPSProxy." },
481 { "KeepalivePeriod", "Send a padding cell every N seconds to keep firewalls "
482 "from closing our connections while Tor is not in use." },
483 { "Log", "Where to send logging messages. Format is "
484 "minSeverity[-maxSeverity] (stderr|stdout|syslog|file FILENAME)." },
485 { "OutboundBindAddress", "Make all outbound connections originate from the "
486 "provided IP address (only useful for multiple network interfaces)." },
487 { "PIDFile", "On startup, write our PID to this file. On clean shutdown, "
488 "remove the file." },
489 { "PreferTunneledDirConns", "If non-zero, avoid directory servers that "
490 "don't support tunneled connections." },
491 /* PreferTunneledDirConns */
492 /* ProtocolWarnings */
493 /* RephistTrackTime */
494 { "RunAsDaemon", "If set, Tor forks and daemonizes to the background when "
495 "started. Unix only." },
496 { "SafeLogging", "If set to 0, Tor logs potentially sensitive strings "
497 "rather than replacing them with the string [scrubbed]." },
498 { "TunnelDirConns", "If non-zero, when a directory server we contact "
499 "supports it, we will build a one-hop circuit and make an encrypted "
500 "connection via its ORPort." },
501 { "User", "On startup, setuid to this user." },
503 /* ==== client options */
504 { "AllowInvalidNodes", "Where on our circuits should Tor allow servers "
505 "that the directory authorities haven't called \"valid\"?" },
506 { "AllowNonRFC953Hostnames", "If set to 1, we don't automatically reject "
507 "hostnames for having invalid characters." },
508 /* CircuitBuildTimeout, CircuitIdleTimeout */
509 { "ClientOnly", "If set to 1, Tor will under no circumstances run as a "
510 "server, even if ORPort is enabled." },
511 { "EntryNodes", "A list of preferred entry nodes to use for the first hop "
512 "in circuits, when possible." },
513 /* { "EnforceDistinctSubnets" , "" }, */
514 { "ExitNodes", "A list of preferred nodes to use for the last hop in "
515 "circuits, when possible." },
516 { "ExcludeNodes", "A list of nodes never to use when building a circuit." },
517 { "FascistFirewall", "If set, Tor will only create outgoing connections to "
518 "servers running on the ports listed in FirewallPorts." },
519 { "FirewallPorts", "A list of ports that we can connect to. Only used "
520 "when FascistFirewall is set." },
521 { "LongLivedPorts", "A list of ports for services that tend to require "
522 "high-uptime connections." },
523 { "MapAddress", "Force Tor to treat all requests for one address as if "
524 "they were for another." },
525 { "NewCircuitPeriod", "Force Tor to consider whether to build a new circuit "
526 "every NUM seconds." },
527 { "MaxCircuitDirtiness", "Do not attach new streams to a circuit that has "
528 "been used more than this many seconds ago." },
529 /* NatdPort, NatdListenAddress */
530 { "NodeFamily", "A list of servers that constitute a 'family' and should "
531 "never be used in the same circuit." },
532 { "NumEntryGuards", "How many entry guards should we keep at a time?" },
533 /* PathlenCoinWeight */
534 { "ReachableAddresses", "Addresses we can connect to, as IP/bits:port-port. "
535 "By default, we assume all addresses are reachable." },
536 /* reachablediraddresses, reachableoraddresses. */
537 /* SafeSOCKS */
538 { "SOCKSPort", "The port where we listen for SOCKS connections from "
539 "applications." },
540 { "SOCKSListenAddress", "Bind to this address to listen to connections from "
541 "SOCKS-speaking applications." },
542 { "SOCKSPolicy", "Set an entry policy to limit which addresses can connect "
543 "to the SOCKSPort." },
544 /* SocksTimeout */
545 { "StrictExitNodes", "If set, Tor will fail to operate when none of the "
546 "configured ExitNodes can be used." },
547 { "StrictEntryNodes", "If set, Tor will fail to operate when none of the "
548 "configured EntryNodes can be used." },
549 /* TestSocks */
550 { "TrackHostsExit", "Hosts and domains which should, if possible, be "
551 "accessed from the same exit node each time we connect to them." },
552 { "TrackHostsExitExpire", "Time after which we forget which exit we were "
553 "using to connect to hosts in TrackHostsExit." },
554 /* "TransPort", "TransListenAddress */
555 { "UseEntryGuards", "Set to 0 if we want to pick from the whole set of "
556 "servers for the first position in each circuit, rather than picking a "
557 "set of 'Guards' to prevent profiling attacks." },
559 /* === server options */
560 { "Address", "The advertised (external) address we should use." },
561 /* Accounting* options. */
562 /* AssumeReachable */
563 { "ContactInfo", "Administrative contact information to advertise for this "
564 "server." },
565 { "ExitPolicy", "Address/port ranges for which to accept or reject outgoing "
566 "connections on behalf of Tor users." },
567 /* { "ExitPolicyRejectPrivate, "" }, */
568 { "MaxAdvertisedBandwidth", "If set, we will not advertise more than this "
569 "amount of bandwidth for our bandwidth rate, regardless of how much "
570 "bandwidth we actually detect." },
571 { "MaxOnionsPending", "Reject new attempts to extend circuits when we "
572 "already have this many pending." },
573 { "MyFamily", "Declare a list of other servers as belonging to the same "
574 "family as this one, so that clients will not use two from the same "
575 "family in the same circuit." },
576 { "Nickname", "Set the server nickname." },
577 { "NoPublish", "{DEPRECATED}" },
578 { "NumCPUs", "How many processes to use at once for public-key crypto." },
579 { "ORPort", "Advertise this port to listen for connections from Tor clients "
580 "and servers." },
581 { "ORListenAddress", "Bind to this address to listen for connections from "
582 "clients and servers, instead of the default 0.0.0.0:ORPort." },
583 { "PublishServerDescriptor", "Set to 0 to keep the server from "
584 "uploading info to the directory authorities." },
585 /* ServerDNS: DetectHijacking, ResolvConfFile, SearchDomains */
586 { "ShutdownWaitLength", "Wait this long for clients to finish when "
587 "shutting down because of a SIGINT." },
589 /* === directory cache options */
590 { "DirPort", "Serve directory information from this port, and act as a "
591 "directory cache." },
592 { "DirPortFrontPage", "Serve a static html disclaimer on DirPort." },
593 { "DirListenAddress", "Bind to this address to listen for connections from "
594 "clients and servers, instead of the default 0.0.0.0:DirPort." },
595 { "DirPolicy", "Set a policy to limit who can connect to the directory "
596 "port." },
598 /* Authority options: AuthDirBadExit, AuthDirInvalid, AuthDirReject,
599 * AuthDirRejectUnlisted, AuthDirListBadExits, AuthoritativeDirectory,
600 * DirAllowPrivateAddresses, HSAuthoritativeDir,
601 * NamingAuthoritativeDirectory, RecommendedVersions,
602 * RecommendedClientVersions, RecommendedServerVersions, RendPostPeriod,
603 * RunTesting, V1AuthoritativeDirectory, VersioningAuthoritativeDirectory, */
605 /* Hidden service options: HiddenService: dir,excludenodes, nodes,
606 * options, port. PublishHidServDescriptor */
608 /* Circuit build time histogram options */
609 { "CircuitBuildTimeBin", "Histogram of recent circuit build times"},
610 { "TotalBuildTimes", "Total number of buildtimes in histogram"},
612 /* Nonpersistent options: __LeaveStreamsUnattached, __AllDirActionsPrivate */
613 { NULL, NULL },
616 /** Online description of state variables. */
617 static config_var_description_t state_description[] = {
618 { "AccountingBytesReadInInterval",
619 "How many bytes have we read in this accounting period?" },
620 { "AccountingBytesWrittenInInterval",
621 "How many bytes have we written in this accounting period?" },
622 { "AccountingExpectedUsage",
623 "How many bytes did we expect to use per minute? (0 for no estimate.)" },
624 { "AccountingIntervalStart", "When did this accounting period begin?" },
625 { "AccountingSecondsActive", "How long have we been awake in this period?" },
627 { "BWHistoryReadEnds", "When does the last-recorded read-interval end?" },
628 { "BWHistoryReadInterval", "How long is each read-interval (in seconds)?" },
629 { "BWHistoryReadValues", "Number of bytes read in each interval." },
630 { "BWHistoryWriteEnds", "When does the last-recorded write-interval end?" },
631 { "BWHistoryWriteInterval", "How long is each write-interval (in seconds)?"},
632 { "BWHistoryWriteValues", "Number of bytes written in each interval." },
634 { "EntryGuard", "One of the nodes we have chosen as a fixed entry" },
635 { "EntryGuardDownSince",
636 "The last entry guard has been unreachable since this time." },
637 { "EntryGuardUnlistedSince",
638 "The last entry guard has been unusable since this time." },
640 { "LastRotatedOnionKey",
641 "The last time at which we changed the medium-term private key used for "
642 "building circuits." },
643 { "LastWritten", "When was this state file last regenerated?" },
645 { "TorVersion", "Which version of Tor generated this state file?" },
646 { NULL, NULL },
649 /** Type of a callback to validate whether a given configuration is
650 * well-formed and consistent. See options_trial_assign() for documentation
651 * of arguments. */
652 typedef int (*validate_fn_t)(void*,void*,int,char**);
654 /** Information on the keys, value types, key-to-struct-member mappings,
655 * variable descriptions, validation functions, and abbreviations for a
656 * configuration or storage format. */
657 typedef struct {
658 size_t size; /**< Size of the struct that everything gets parsed into. */
659 uint32_t magic; /**< Required 'magic value' to make sure we have a struct
660 * of the right type. */
661 off_t magic_offset; /**< Offset of the magic value within the struct. */
662 config_abbrev_t *abbrevs; /**< List of abbreviations that we expand when
663 * parsing this format. */
664 config_var_t *vars; /**< List of variables we recognize, their default
665 * values, and where we stick them in the structure. */
666 validate_fn_t validate_fn; /**< Function to validate config. */
667 /** Documentation for configuration variables. */
668 config_var_description_t *descriptions;
669 /** If present, extra is a LINELIST variable for unrecognized
670 * lines. Otherwise, unrecognized lines are an error. */
671 config_var_t *extra;
672 } config_format_t;
674 /** Macro: assert that <b>cfg</b> has the right magic field for format
675 * <b>fmt</b>. */
676 #define CHECK(fmt, cfg) STMT_BEGIN \
677 tor_assert(fmt && cfg); \
678 tor_assert((fmt)->magic == \
679 *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
680 STMT_END
682 #ifdef MS_WINDOWS
683 static char *get_windows_conf_root(void);
684 #endif
685 static void config_line_append(config_line_t **lst,
686 const char *key, const char *val);
687 static void option_clear(config_format_t *fmt, or_options_t *options,
688 config_var_t *var);
689 static void option_reset(config_format_t *fmt, or_options_t *options,
690 config_var_t *var, int use_defaults);
691 static void config_free(config_format_t *fmt, void *options);
692 static int config_lines_eq(config_line_t *a, config_line_t *b);
693 static int option_is_same(config_format_t *fmt,
694 or_options_t *o1, or_options_t *o2,
695 const char *name);
696 static or_options_t *options_dup(config_format_t *fmt, or_options_t *old);
697 static int options_validate(or_options_t *old_options, or_options_t *options,
698 int from_setconf, char **msg);
699 static int options_act_reversible(or_options_t *old_options, char **msg);
700 static int options_act(or_options_t *old_options);
701 static int options_transition_allowed(or_options_t *old, or_options_t *new,
702 char **msg);
703 static int options_transition_affects_workers(or_options_t *old_options,
704 or_options_t *new_options);
705 static int options_transition_affects_descriptor(or_options_t *old_options,
706 or_options_t *new_options);
707 static int check_nickname_list(const char *lst, const char *name, char **msg);
708 static void config_register_addressmaps(or_options_t *options);
710 static int parse_bridge_line(const char *line, int validate_only);
711 static int parse_dir_server_line(const char *line,
712 authority_type_t required_type,
713 int validate_only);
714 static int validate_data_directory(or_options_t *options);
715 static int write_configuration_file(const char *fname, or_options_t *options);
716 static config_line_t *get_assigned_option(config_format_t *fmt,
717 void *options, const char *key,
718 int escape_val);
719 static void config_init(config_format_t *fmt, void *options);
720 static int or_state_validate(or_state_t *old_options, or_state_t *options,
721 int from_setconf, char **msg);
722 static int or_state_load(void);
723 static int options_init_logs(or_options_t *options, int validate_only);
725 static int is_listening_on_low_port(uint16_t port_option,
726 const config_line_t *listen_options);
728 static uint64_t config_parse_memunit(const char *s, int *ok);
729 static int config_parse_interval(const char *s, int *ok);
730 static void init_libevent(void);
731 static int opt_streq(const char *s1, const char *s2);
733 /** Magic value for or_options_t. */
734 #define OR_OPTIONS_MAGIC 9090909
736 /** Configuration format for or_options_t. */
737 static config_format_t options_format = {
738 sizeof(or_options_t),
739 OR_OPTIONS_MAGIC,
740 STRUCT_OFFSET(or_options_t, _magic),
741 _option_abbrevs,
742 _option_vars,
743 (validate_fn_t)options_validate,
744 options_description,
745 NULL
748 /** Magic value for or_state_t. */
749 #define OR_STATE_MAGIC 0x57A73f57
751 /** "Extra" variable in the state that receives lines we can't parse. This
752 * lets us preserve options from versions of Tor newer than us. */
753 static config_var_t state_extra_var = {
754 "__extra", CONFIG_TYPE_LINELIST, STRUCT_OFFSET(or_state_t, ExtraLines), NULL
757 /** Configuration format for or_state_t. */
758 static config_format_t state_format = {
759 sizeof(or_state_t),
760 OR_STATE_MAGIC,
761 STRUCT_OFFSET(or_state_t, _magic),
762 _state_abbrevs,
763 _state_vars,
764 (validate_fn_t)or_state_validate,
765 state_description,
766 &state_extra_var,
770 * Functions to read and write the global options pointer.
773 /** Command-line and config-file options. */
774 static or_options_t *global_options = NULL;
775 /** Name of most recently read torrc file. */
776 static char *torrc_fname = NULL;
777 /** Persistent serialized state. */
778 static or_state_t *global_state = NULL;
779 /** Configuration Options set by command line. */
780 static config_line_t *global_cmdline_options = NULL;
781 /** Contents of most recently read DirPortFrontPage file. */
782 static char *global_dirfrontpagecontents = NULL;
784 /** Return the contents of our frontpage string, or NULL if not configured. */
785 const char *
786 get_dirportfrontpage(void)
788 return global_dirfrontpagecontents;
791 /** Allocate an empty configuration object of a given format type. */
792 static void *
793 config_alloc(config_format_t *fmt)
795 void *opts = tor_malloc_zero(fmt->size);
796 *(uint32_t*)STRUCT_VAR_P(opts, fmt->magic_offset) = fmt->magic;
797 CHECK(fmt, opts);
798 return opts;
801 /** Return the currently configured options. */
802 or_options_t *
803 get_options(void)
805 tor_assert(global_options);
806 return global_options;
809 /** Change the current global options to contain <b>new_val</b> instead of
810 * their current value; take action based on the new value; free the old value
811 * as necessary. Returns 0 on success, -1 on failure.
814 set_options(or_options_t *new_val, char **msg)
816 or_options_t *old_options = global_options;
817 global_options = new_val;
818 /* Note that we pass the *old* options below, for comparison. It
819 * pulls the new options directly out of global_options. */
820 if (options_act_reversible(old_options, msg)<0) {
821 tor_assert(*msg);
822 global_options = old_options;
823 return -1;
825 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
826 log_err(LD_BUG,
827 "Acting on config options left us in a broken state. Dying.");
828 exit(1);
831 config_free(&options_format, old_options);
833 return 0;
836 extern const char tor_git_revision[]; /* from tor_main.c */
838 /** The version of this Tor process, as parsed. */
839 static char *_version = NULL;
841 /** Return the current Tor version. */
842 const char *
843 get_version(void)
845 if (_version == NULL) {
846 if (strlen(tor_git_revision)) {
847 size_t len = strlen(VERSION)+strlen(tor_git_revision)+16;
848 _version = tor_malloc(len);
849 tor_snprintf(_version, len, "%s (git-%s)", VERSION, tor_git_revision);
850 } else {
851 _version = tor_strdup(VERSION);
854 return _version;
857 /** Release additional memory allocated in options
859 static void
860 or_options_free(or_options_t *options)
862 if (!options)
863 return;
865 routerset_free(options->_ExcludeExitNodesUnion);
866 config_free(&options_format, options);
869 /** Release all memory and resources held by global configuration structures.
871 void
872 config_free_all(void)
874 or_options_free(global_options);
875 global_options = NULL;
877 config_free(&state_format, global_state);
878 global_state = NULL;
880 config_free_lines(global_cmdline_options);
881 global_cmdline_options = NULL;
883 tor_free(torrc_fname);
884 tor_free(_version);
885 tor_free(global_dirfrontpagecontents);
888 /** If options->SafeLogging is on, return a not very useful string,
889 * else return address.
891 const char *
892 safe_str(const char *address)
894 tor_assert(address);
895 if (get_options()->SafeLogging)
896 return "[scrubbed]";
897 else
898 return address;
901 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
902 * escaped(): don't use this outside the main thread, or twice in the same
903 * log statement. */
904 const char *
905 escaped_safe_str(const char *address)
907 if (get_options()->SafeLogging)
908 return "[scrubbed]";
909 else
910 return escaped(address);
913 /** Add the default directory authorities directly into the trusted dir list,
914 * but only add them insofar as they share bits with <b>type</b>. */
915 static void
916 add_default_trusted_dir_authorities(authority_type_t type)
918 int i;
919 const char *dirservers[] = {
920 "moria1 v1 orport=9001 v3ident=E2A2AF570166665D738736D0DD58169CC61D8A8B "
921 "128.31.0.39:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441",
922 "moria2 v1 orport=9002 128.31.0.34:9032 "
923 "719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF",
924 "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
925 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
926 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
927 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
928 "Tonga orport=443 bridge no-v2 82.94.251.203:80 "
929 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
930 "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
931 "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
932 "gabelmoo orport=443 no-v2 "
933 "v3ident=81349FC1F2DBA2C2C11B45CB9706637D480AB913 "
934 "80.190.246.100:80 6833 3D07 61BC F397 A587 A0C0 B963 E4A9 E99E C4D3",
935 "dannenberg orport=443 no-v2 "
936 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
937 "213.73.91.31:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
938 "urras orport=80 no-v2 v3ident=80550987E1D626E3EBA5E5E75A458DE0626D088C "
939 "208.83.223.34:443 0AD3 FA88 4D18 F89E EA2D 89C0 1937 9E0E 7FD9 4417",
940 NULL
942 for (i=0; dirservers[i]; i++) {
943 if (parse_dir_server_line(dirservers[i], type, 0)<0) {
944 log_err(LD_BUG, "Couldn't parse internal dirserver line %s",
945 dirservers[i]);
950 /** Look at all the config options for using alternate directory
951 * authorities, and make sure none of them are broken. Also, warn the
952 * user if we changed any dangerous ones.
954 static int
955 validate_dir_authorities(or_options_t *options, or_options_t *old_options)
957 config_line_t *cl;
959 if (options->DirServers &&
960 (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
961 options->AlternateHSAuthority)) {
962 log_warn(LD_CONFIG,
963 "You cannot set both DirServers and Alternate*Authority.");
964 return -1;
967 /* do we want to complain to the user about being partitionable? */
968 if ((options->DirServers &&
969 (!old_options ||
970 !config_lines_eq(options->DirServers, old_options->DirServers))) ||
971 (options->AlternateDirAuthority &&
972 (!old_options ||
973 !config_lines_eq(options->AlternateDirAuthority,
974 old_options->AlternateDirAuthority)))) {
975 log_warn(LD_CONFIG,
976 "You have used DirServer or AlternateDirAuthority to "
977 "specify alternate directory authorities in "
978 "your configuration. This is potentially dangerous: it can "
979 "make you look different from all other Tor users, and hurt "
980 "your anonymity. Even if you've specified the same "
981 "authorities as Tor uses by default, the defaults could "
982 "change in the future. Be sure you know what you're doing.");
985 /* Now go through the four ways you can configure an alternate
986 * set of directory authorities, and make sure none are broken. */
987 for (cl = options->DirServers; cl; cl = cl->next)
988 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
989 return -1;
990 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
991 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
992 return -1;
993 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
994 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
995 return -1;
996 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
997 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
998 return -1;
999 return 0;
1002 /** Look at all the config options and assign new dir authorities
1003 * as appropriate.
1005 static int
1006 consider_adding_dir_authorities(or_options_t *options,
1007 or_options_t *old_options)
1009 config_line_t *cl;
1010 int need_to_update =
1011 !smartlist_len(router_get_trusted_dir_servers()) || !old_options ||
1012 !config_lines_eq(options->DirServers, old_options->DirServers) ||
1013 !config_lines_eq(options->AlternateBridgeAuthority,
1014 old_options->AlternateBridgeAuthority) ||
1015 !config_lines_eq(options->AlternateDirAuthority,
1016 old_options->AlternateDirAuthority) ||
1017 !config_lines_eq(options->AlternateHSAuthority,
1018 old_options->AlternateHSAuthority);
1020 if (!need_to_update)
1021 return 0; /* all done */
1023 /* Start from a clean slate. */
1024 clear_trusted_dir_servers();
1026 if (!options->DirServers) {
1027 /* then we may want some of the defaults */
1028 authority_type_t type = NO_AUTHORITY;
1029 if (!options->AlternateBridgeAuthority)
1030 type |= BRIDGE_AUTHORITY;
1031 if (!options->AlternateDirAuthority)
1032 type |= V1_AUTHORITY | V2_AUTHORITY | V3_AUTHORITY;
1033 if (!options->AlternateHSAuthority)
1034 type |= HIDSERV_AUTHORITY;
1035 add_default_trusted_dir_authorities(type);
1038 for (cl = options->DirServers; cl; cl = cl->next)
1039 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1040 return -1;
1041 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1042 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1043 return -1;
1044 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1045 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1046 return -1;
1047 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
1048 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1049 return -1;
1050 return 0;
1053 /** Fetch the active option list, and take actions based on it. All of the
1054 * things we do should survive being done repeatedly. If present,
1055 * <b>old_options</b> contains the previous value of the options.
1057 * Return 0 if all goes well, return -1 if things went badly.
1059 static int
1060 options_act_reversible(or_options_t *old_options, char **msg)
1062 smartlist_t *new_listeners = smartlist_create();
1063 smartlist_t *replaced_listeners = smartlist_create();
1064 static int libevent_initialized = 0;
1065 or_options_t *options = get_options();
1066 int running_tor = options->command == CMD_RUN_TOR;
1067 int set_conn_limit = 0;
1068 int r = -1;
1069 int logs_marked = 0;
1071 /* Daemonize _first_, since we only want to open most of this stuff in
1072 * the subprocess. Libevent bases can't be reliably inherited across
1073 * processes. */
1074 if (running_tor && options->RunAsDaemon) {
1075 /* No need to roll back, since you can't change the value. */
1076 start_daemon();
1079 #ifndef HAVE_SYS_UN_H
1080 if (options->ControlSocket) {
1081 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported"
1082 " on this OS/with this build.");
1083 goto rollback;
1085 #endif
1087 if (running_tor) {
1088 /* We need to set the connection limit before we can open the listeners. */
1089 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1090 &options->_ConnLimit) < 0) {
1091 *msg = tor_strdup("Problem with ConnLimit value. See logs for details.");
1092 goto rollback;
1094 set_conn_limit = 1;
1096 /* Set up libevent. (We need to do this before we can register the
1097 * listeners as listeners.) */
1098 if (running_tor && !libevent_initialized) {
1099 init_libevent();
1100 libevent_initialized = 1;
1103 /* Launch the listeners. (We do this before we setuid, so we can bind to
1104 * ports under 1024.) */
1105 if (retry_all_listeners(replaced_listeners, new_listeners) < 0) {
1106 *msg = tor_strdup("Failed to bind one of the listener ports.");
1107 goto rollback;
1111 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1112 /* Open /dev/pf before dropping privileges. */
1113 if (options->TransPort) {
1114 if (get_pf_socket() < 0) {
1115 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1116 goto rollback;
1119 #endif
1121 /* Attempt to lock all current and future memory with mlockall() only once */
1122 if (options->DisableAllSwap) {
1123 if (tor_mlockall() == -1) {
1124 *msg = tor_strdup("DisableAllSwap failure. Do you have proper "
1125 "permissions?");
1126 goto done;
1130 /* Setuid/setgid as appropriate */
1131 if (options->User) {
1132 if (switch_id(options->User) != 0) {
1133 /* No need to roll back, since you can't change the value. */
1134 *msg = tor_strdup("Problem with User value. See logs for details.");
1135 goto done;
1139 /* Ensure data directory is private; create if possible. */
1140 if (check_private_dir(options->DataDirectory,
1141 running_tor ? CPD_CREATE : CPD_CHECK)<0) {
1142 char buf[1024];
1143 int tmp = tor_snprintf(buf, sizeof(buf),
1144 "Couldn't access/create private data directory \"%s\"",
1145 options->DataDirectory);
1146 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1147 goto done;
1148 /* No need to roll back, since you can't change the value. */
1151 if (directory_caches_v2_dir_info(options)) {
1152 size_t len = strlen(options->DataDirectory)+32;
1153 char *fn = tor_malloc(len);
1154 tor_snprintf(fn, len, "%s"PATH_SEPARATOR"cached-status",
1155 options->DataDirectory);
1156 if (check_private_dir(fn, running_tor ? CPD_CREATE : CPD_CHECK) < 0) {
1157 char buf[1024];
1158 int tmp = tor_snprintf(buf, sizeof(buf),
1159 "Couldn't access/create private data directory \"%s\"", fn);
1160 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1161 tor_free(fn);
1162 goto done;
1164 tor_free(fn);
1167 /* Bail out at this point if we're not going to be a client or server:
1168 * we don't run Tor itself. */
1169 if (!running_tor)
1170 goto commit;
1172 mark_logs_temp(); /* Close current logs once new logs are open. */
1173 logs_marked = 1;
1174 if (options_init_logs(options, 0)<0) { /* Configure the log(s) */
1175 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1176 goto rollback;
1179 commit:
1180 r = 0;
1181 if (logs_marked) {
1182 log_severity_list_t *severity =
1183 tor_malloc_zero(sizeof(log_severity_list_t));
1184 close_temp_logs();
1185 add_callback_log(severity, control_event_logmsg);
1186 control_adjust_event_log_severity();
1187 tor_free(severity);
1189 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1191 log_notice(LD_NET, "Closing old %s on %s:%d",
1192 conn_type_to_string(conn->type), conn->address, conn->port);
1193 connection_close_immediate(conn);
1194 connection_mark_for_close(conn);
1196 goto done;
1198 rollback:
1199 r = -1;
1200 tor_assert(*msg);
1202 if (logs_marked) {
1203 rollback_log_changes();
1204 control_adjust_event_log_severity();
1207 if (set_conn_limit && old_options)
1208 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1209 &options->_ConnLimit);
1211 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1213 log_notice(LD_NET, "Closing partially-constructed listener %s on %s:%d",
1214 conn_type_to_string(conn->type), conn->address, conn->port);
1215 connection_close_immediate(conn);
1216 connection_mark_for_close(conn);
1219 done:
1220 smartlist_free(new_listeners);
1221 smartlist_free(replaced_listeners);
1222 return r;
1225 /** If we need to have a GEOIP ip-to-country map to run with our configured
1226 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1228 options_need_geoip_info(or_options_t *options, const char **reason_out)
1230 int bridge_usage =
1231 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1232 int routerset_usage =
1233 routerset_needs_geoip(options->EntryNodes) ||
1234 routerset_needs_geoip(options->ExitNodes) ||
1235 routerset_needs_geoip(options->ExcludeExitNodes) ||
1236 routerset_needs_geoip(options->ExcludeNodes);
1238 if (routerset_usage && reason_out) {
1239 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1240 "countries, and we need GEOIP information to figure out which ones they "
1241 "are.";
1242 } else if (bridge_usage && reason_out) {
1243 *reason_out = "We've been configured to see which countries can access "
1244 "us as a bridge, and we need GEOIP information to tell which countries "
1245 "clients are in.";
1247 return bridge_usage || routerset_usage;
1250 /** Return the bandwidthrate that we are going to report to the authorities
1251 * based on the config options. */
1252 uint32_t
1253 get_effective_bwrate(or_options_t *options)
1255 uint64_t bw = options->BandwidthRate;
1256 if (bw > options->MaxAdvertisedBandwidth)
1257 bw = options->MaxAdvertisedBandwidth;
1258 if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1259 bw = options->RelayBandwidthRate;
1260 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1261 return (uint32_t)bw;
1264 /** Return the bandwidthburst that we are going to report to the authorities
1265 * based on the config options. */
1266 uint32_t
1267 get_effective_bwburst(or_options_t *options)
1269 uint64_t bw = options->BandwidthBurst;
1270 if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1271 bw = options->RelayBandwidthBurst;
1272 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1273 return (uint32_t)bw;
1276 /** Fetch the active option list, and take actions based on it. All of the
1277 * things we do should survive being done repeatedly. If present,
1278 * <b>old_options</b> contains the previous value of the options.
1280 * Return 0 if all goes well, return -1 if it's time to die.
1282 * Note: We haven't moved all the "act on new configuration" logic
1283 * here yet. Some is still in do_hup() and other places.
1285 static int
1286 options_act(or_options_t *old_options)
1288 config_line_t *cl;
1289 or_options_t *options = get_options();
1290 int running_tor = options->command == CMD_RUN_TOR;
1291 char *msg;
1293 if (running_tor && !have_lockfile()) {
1294 if (try_locking(options, 1) < 0)
1295 return -1;
1298 if (consider_adding_dir_authorities(options, old_options) < 0)
1299 return -1;
1301 if (options->Bridges) {
1302 clear_bridge_list();
1303 for (cl = options->Bridges; cl; cl = cl->next) {
1304 if (parse_bridge_line(cl->value, 0)<0) {
1305 log_warn(LD_BUG,
1306 "Previously validated Bridge line could not be added!");
1307 return -1;
1312 if (running_tor && rend_config_services(options, 0)<0) {
1313 log_warn(LD_BUG,
1314 "Previously validated hidden services line could not be added!");
1315 return -1;
1318 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1319 log_warn(LD_BUG, "Previously validated client authorization for "
1320 "hidden services could not be added!");
1321 return -1;
1324 /* Load state */
1325 if (! global_state && running_tor) {
1326 if (or_state_load())
1327 return -1;
1328 rep_hist_load_mtbf_data(time(NULL));
1331 /* Bail out at this point if we're not going to be a client or server:
1332 * we want to not fork, and to log stuff to stderr. */
1333 if (!running_tor)
1334 return 0;
1336 /* Finish backgrounding the process */
1337 if (options->RunAsDaemon) {
1338 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1339 finish_daemon(options->DataDirectory);
1342 /* Write our PID to the PID file. If we do not have write permissions we
1343 * will log a warning */
1344 if (options->PidFile)
1345 write_pidfile(options->PidFile);
1347 /* Register addressmap directives */
1348 config_register_addressmaps(options);
1349 parse_virtual_addr_network(options->VirtualAddrNetwork, 0, &msg);
1351 /* Update address policies. */
1352 if (policies_parse_from_options(options) < 0) {
1353 /* This should be impossible, but let's be sure. */
1354 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1355 return -1;
1358 if (init_cookie_authentication(options->CookieAuthentication) < 0) {
1359 log_warn(LD_CONFIG,"Error creating cookie authentication file.");
1360 return -1;
1363 /* reload keys as needed for rendezvous services. */
1364 if (rend_service_load_keys()<0) {
1365 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1366 return -1;
1369 /* Set up accounting */
1370 if (accounting_parse_options(options, 0)<0) {
1371 log_warn(LD_CONFIG,"Error in accounting options");
1372 return -1;
1374 if (accounting_is_enabled(options))
1375 configure_accounting(time(NULL));
1377 /* Check for transitions that need action. */
1378 if (old_options) {
1379 if (options->UseEntryGuards && !old_options->UseEntryGuards) {
1380 log_info(LD_CIRC,
1381 "Switching to entry guards; abandoning previous circuits");
1382 circuit_mark_all_unused_circs();
1383 circuit_expire_all_dirty_circs();
1386 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
1387 log_info(LD_GENERAL, "Bridge status changed. Forgetting GeoIP stats.");
1388 geoip_remove_old_clients(time(NULL)+(2*60*60));
1391 if (options_transition_affects_workers(old_options, options)) {
1392 log_info(LD_GENERAL,
1393 "Worker-related options changed. Rotating workers.");
1394 if (server_mode(options) && !server_mode(old_options)) {
1395 if (init_keys() < 0) {
1396 log_warn(LD_BUG,"Error initializing keys; exiting");
1397 return -1;
1399 ip_address_changed(0);
1400 if (has_completed_circuit || !any_predicted_circuits(time(NULL)))
1401 inform_testing_reachability();
1403 cpuworkers_rotate();
1404 if (dns_reset())
1405 return -1;
1406 } else {
1407 if (dns_reset())
1408 return -1;
1411 if (options->V3AuthoritativeDir && !old_options->V3AuthoritativeDir)
1412 init_keys();
1415 /* Maybe load geoip file */
1416 if (options->GeoIPFile &&
1417 ((!old_options || !opt_streq(old_options->GeoIPFile, options->GeoIPFile))
1418 || !geoip_is_loaded())) {
1419 /* XXXX Don't use this "<default>" junk; make our filename options
1420 * understand prefixes somehow. -NM */
1421 /* XXXX021 Reload GeoIPFile on SIGHUP. -NM */
1422 char *actual_fname = tor_strdup(options->GeoIPFile);
1423 #ifdef WIN32
1424 if (!strcmp(actual_fname, "<default>")) {
1425 const char *conf_root = get_windows_conf_root();
1426 size_t len = strlen(conf_root)+16;
1427 tor_free(actual_fname);
1428 actual_fname = tor_malloc(len+1);
1429 tor_snprintf(actual_fname, len, "%s\\geoip", conf_root);
1431 #endif
1432 geoip_load_file(actual_fname, options);
1433 tor_free(actual_fname);
1436 if (options->DirReqStatistics && !geoip_is_loaded()) {
1437 /* Check if GeoIP database could be loaded. */
1438 log_warn(LD_CONFIG, "Configured to measure directory request "
1439 "statistics, but no GeoIP database found!");
1440 return -1;
1443 if (options->EntryStatistics) {
1444 if (should_record_bridge_info(options)) {
1445 /* Don't allow measuring statistics on entry guards when configured
1446 * as bridge. */
1447 log_warn(LD_CONFIG, "Bridges cannot be configured to measure "
1448 "additional GeoIP statistics as entry guards.");
1449 return -1;
1450 } else if (!geoip_is_loaded()) {
1451 /* Check if GeoIP database could be loaded. */
1452 log_warn(LD_CONFIG, "Configured to measure entry node statistics, "
1453 "but no GeoIP database found!");
1454 return -1;
1458 /* Check if we need to parse and add the EntryNodes config option. */
1459 if (options->EntryNodes &&
1460 (!old_options ||
1461 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
1462 entry_nodes_should_be_added();
1464 /* Since our options changed, we might need to regenerate and upload our
1465 * server descriptor.
1467 if (!old_options ||
1468 options_transition_affects_descriptor(old_options, options))
1469 mark_my_descriptor_dirty();
1471 /* We may need to reschedule some directory stuff if our status changed. */
1472 if (old_options) {
1473 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1474 dirvote_recalculate_timing(options, time(NULL));
1475 if (!bool_eq(directory_fetches_dir_info_early(options),
1476 directory_fetches_dir_info_early(old_options)) ||
1477 !bool_eq(directory_fetches_dir_info_later(options),
1478 directory_fetches_dir_info_later(old_options))) {
1479 /* Make sure update_router_have_min_dir_info gets called. */
1480 router_dir_info_changed();
1481 /* We might need to download a new consensus status later or sooner than
1482 * we had expected. */
1483 update_consensus_networkstatus_fetch_time(time(NULL));
1487 /* Load the webpage we're going to serve every time someone asks for '/' on
1488 our DirPort. */
1489 tor_free(global_dirfrontpagecontents);
1490 if (options->DirPortFrontPage) {
1491 global_dirfrontpagecontents =
1492 read_file_to_str(options->DirPortFrontPage, 0, NULL);
1493 if (!global_dirfrontpagecontents) {
1494 log_warn(LD_CONFIG,
1495 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1496 options->DirPortFrontPage);
1500 return 0;
1504 * Functions to parse config options
1507 /** If <b>option</b> is an official abbreviation for a longer option,
1508 * return the longer option. Otherwise return <b>option</b>.
1509 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1510 * apply abbreviations that work for the config file and the command line.
1511 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1512 static const char *
1513 expand_abbrev(config_format_t *fmt, const char *option, int command_line,
1514 int warn_obsolete)
1516 int i;
1517 if (! fmt->abbrevs)
1518 return option;
1519 for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
1520 /* Abbreviations are case insensitive. */
1521 if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
1522 (command_line || !fmt->abbrevs[i].commandline_only)) {
1523 if (warn_obsolete && fmt->abbrevs[i].warn) {
1524 log_warn(LD_CONFIG,
1525 "The configuration option '%s' is deprecated; "
1526 "use '%s' instead.",
1527 fmt->abbrevs[i].abbreviated,
1528 fmt->abbrevs[i].full);
1530 /* Keep going through the list in case we want to rewrite it more.
1531 * (We could imagine recursing here, but I don't want to get the
1532 * user into an infinite loop if we craft our list wrong.) */
1533 option = fmt->abbrevs[i].full;
1536 return option;
1539 /** Helper: Read a list of configuration options from the command line.
1540 * If successful, put them in *<b>result</b> and return 0, and return
1541 * -1 and leave *<b>result</b> alone. */
1542 static int
1543 config_get_commandlines(int argc, char **argv, config_line_t **result)
1545 config_line_t *front = NULL;
1546 config_line_t **new = &front;
1547 char *s;
1548 int i = 1;
1550 while (i < argc) {
1551 if (!strcmp(argv[i],"-f") ||
1552 !strcmp(argv[i],"--hash-password")) {
1553 i += 2; /* command-line option with argument. ignore them. */
1554 continue;
1555 } else if (!strcmp(argv[i],"--list-fingerprint") ||
1556 !strcmp(argv[i],"--verify-config") ||
1557 !strcmp(argv[i],"--ignore-missing-torrc") ||
1558 !strcmp(argv[i],"--quiet") ||
1559 !strcmp(argv[i],"--hush")) {
1560 i += 1; /* command-line option. ignore it. */
1561 continue;
1562 } else if (!strcmp(argv[i],"--nt-service") ||
1563 !strcmp(argv[i],"-nt-service")) {
1564 i += 1;
1565 continue;
1568 if (i == argc-1) {
1569 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1570 argv[i]);
1571 config_free_lines(front);
1572 return -1;
1575 *new = tor_malloc_zero(sizeof(config_line_t));
1576 s = argv[i];
1578 while (*s == '-')
1579 s++;
1581 (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1, 1));
1582 (*new)->value = tor_strdup(argv[i+1]);
1583 (*new)->next = NULL;
1584 log(LOG_DEBUG, LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
1585 (*new)->key, (*new)->value);
1587 new = &((*new)->next);
1588 i += 2;
1590 *result = front;
1591 return 0;
1594 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1595 * append it to *<b>lst</b>. */
1596 static void
1597 config_line_append(config_line_t **lst,
1598 const char *key,
1599 const char *val)
1601 config_line_t *newline;
1603 newline = tor_malloc(sizeof(config_line_t));
1604 newline->key = tor_strdup(key);
1605 newline->value = tor_strdup(val);
1606 newline->next = NULL;
1607 while (*lst)
1608 lst = &((*lst)->next);
1610 (*lst) = newline;
1613 /** Helper: parse the config string and strdup into key/value
1614 * strings. Set *result to the list, or NULL if parsing the string
1615 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1616 * misformatted lines. */
1618 config_get_lines(const char *string, config_line_t **result)
1620 config_line_t *list = NULL, **next;
1621 char *k, *v;
1623 next = &list;
1624 do {
1625 k = v = NULL;
1626 string = parse_config_line_from_str(string, &k, &v);
1627 if (!string) {
1628 config_free_lines(list);
1629 tor_free(k);
1630 tor_free(v);
1631 return -1;
1633 if (k && v) {
1634 /* This list can get long, so we keep a pointer to the end of it
1635 * rather than using config_line_append over and over and getting
1636 * n^2 performance. */
1637 *next = tor_malloc(sizeof(config_line_t));
1638 (*next)->key = k;
1639 (*next)->value = v;
1640 (*next)->next = NULL;
1641 next = &((*next)->next);
1642 } else {
1643 tor_free(k);
1644 tor_free(v);
1646 } while (*string);
1648 *result = list;
1649 return 0;
1653 * Free all the configuration lines on the linked list <b>front</b>.
1655 void
1656 config_free_lines(config_line_t *front)
1658 config_line_t *tmp;
1660 while (front) {
1661 tmp = front;
1662 front = tmp->next;
1664 tor_free(tmp->key);
1665 tor_free(tmp->value);
1666 tor_free(tmp);
1670 /** Return the description for a given configuration variable, or NULL if no
1671 * description exists. */
1672 static const char *
1673 config_find_description(config_format_t *fmt, const char *name)
1675 int i;
1676 for (i=0; fmt->descriptions[i].name; ++i) {
1677 if (!strcasecmp(name, fmt->descriptions[i].name))
1678 return fmt->descriptions[i].description;
1680 return NULL;
1683 /** If <b>key</b> is a configuration option, return the corresponding
1684 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1685 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1687 static config_var_t *
1688 config_find_option(config_format_t *fmt, const char *key)
1690 int i;
1691 size_t keylen = strlen(key);
1692 if (!keylen)
1693 return NULL; /* if they say "--" on the command line, it's not an option */
1694 /* First, check for an exact (case-insensitive) match */
1695 for (i=0; fmt->vars[i].name; ++i) {
1696 if (!strcasecmp(key, fmt->vars[i].name)) {
1697 return &fmt->vars[i];
1700 /* If none, check for an abbreviated match */
1701 for (i=0; fmt->vars[i].name; ++i) {
1702 if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
1703 log_warn(LD_CONFIG, "The abbreviation '%s' is deprecated. "
1704 "Please use '%s' instead",
1705 key, fmt->vars[i].name);
1706 return &fmt->vars[i];
1709 /* Okay, unrecognized option */
1710 return NULL;
1714 * Functions to assign config options.
1717 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1718 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1720 * Called from config_assign_line() and option_reset().
1722 static int
1723 config_assign_value(config_format_t *fmt, or_options_t *options,
1724 config_line_t *c, char **msg)
1726 int i, r, ok;
1727 char buf[1024];
1728 config_var_t *var;
1729 void *lvalue;
1731 CHECK(fmt, options);
1733 var = config_find_option(fmt, c->key);
1734 tor_assert(var);
1736 lvalue = STRUCT_VAR_P(options, var->var_offset);
1738 switch (var->type) {
1740 case CONFIG_TYPE_UINT:
1741 i = (int)tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
1742 if (!ok) {
1743 r = tor_snprintf(buf, sizeof(buf),
1744 "Int keyword '%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;
1752 case CONFIG_TYPE_INTERVAL: {
1753 i = config_parse_interval(c->value, &ok);
1754 if (!ok) {
1755 r = tor_snprintf(buf, sizeof(buf),
1756 "Interval '%s %s' is malformed or out of bounds.",
1757 c->key, c->value);
1758 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1759 return -1;
1761 *(int *)lvalue = i;
1762 break;
1765 case CONFIG_TYPE_MEMUNIT: {
1766 uint64_t u64 = config_parse_memunit(c->value, &ok);
1767 if (!ok) {
1768 r = tor_snprintf(buf, sizeof(buf),
1769 "Value '%s %s' is malformed or out of bounds.",
1770 c->key, c->value);
1771 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1772 return -1;
1774 *(uint64_t *)lvalue = u64;
1775 break;
1778 case CONFIG_TYPE_BOOL:
1779 i = (int)tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
1780 if (!ok) {
1781 r = tor_snprintf(buf, sizeof(buf),
1782 "Boolean '%s %s' expects 0 or 1.",
1783 c->key, c->value);
1784 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1785 return -1;
1787 *(int *)lvalue = i;
1788 break;
1790 case CONFIG_TYPE_STRING:
1791 case CONFIG_TYPE_FILENAME:
1792 tor_free(*(char **)lvalue);
1793 *(char **)lvalue = tor_strdup(c->value);
1794 break;
1796 case CONFIG_TYPE_DOUBLE:
1797 *(double *)lvalue = atof(c->value);
1798 break;
1800 case CONFIG_TYPE_ISOTIME:
1801 if (parse_iso_time(c->value, (time_t *)lvalue)) {
1802 r = tor_snprintf(buf, sizeof(buf),
1803 "Invalid time '%s' for keyword '%s'", c->value, c->key);
1804 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1805 return -1;
1807 break;
1809 case CONFIG_TYPE_ROUTERSET:
1810 if (*(routerset_t**)lvalue) {
1811 routerset_free(*(routerset_t**)lvalue);
1813 *(routerset_t**)lvalue = routerset_new();
1814 if (routerset_parse(*(routerset_t**)lvalue, c->value, c->key)<0) {
1815 tor_snprintf(buf, sizeof(buf), "Invalid exit list '%s' for option '%s'",
1816 c->value, c->key);
1817 *msg = tor_strdup(buf);
1818 return -1;
1820 break;
1822 case CONFIG_TYPE_CSV:
1823 if (*(smartlist_t**)lvalue) {
1824 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
1825 smartlist_clear(*(smartlist_t**)lvalue);
1826 } else {
1827 *(smartlist_t**)lvalue = smartlist_create();
1830 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
1831 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1832 break;
1834 case CONFIG_TYPE_LINELIST:
1835 case CONFIG_TYPE_LINELIST_S:
1836 config_line_append((config_line_t**)lvalue, c->key, c->value);
1837 break;
1838 case CONFIG_TYPE_OBSOLETE:
1839 log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
1840 break;
1841 case CONFIG_TYPE_LINELIST_V:
1842 r = tor_snprintf(buf, sizeof(buf),
1843 "You may not provide a value for virtual option '%s'", c->key);
1844 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1845 return -1;
1846 default:
1847 tor_assert(0);
1848 break;
1850 return 0;
1853 /** If <b>c</b> is a syntactically valid configuration line, update
1854 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1855 * key, -2 for bad value.
1857 * If <b>clear_first</b> is set, clear the value first. Then if
1858 * <b>use_defaults</b> is set, set the value to the default.
1860 * Called from config_assign().
1862 static int
1863 config_assign_line(config_format_t *fmt, or_options_t *options,
1864 config_line_t *c, int use_defaults,
1865 int clear_first, char **msg)
1867 config_var_t *var;
1869 CHECK(fmt, options);
1871 var = config_find_option(fmt, c->key);
1872 if (!var) {
1873 if (fmt->extra) {
1874 void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
1875 log_info(LD_CONFIG,
1876 "Found unrecognized option '%s'; saving it.", c->key);
1877 config_line_append((config_line_t**)lvalue, c->key, c->value);
1878 return 0;
1879 } else {
1880 char buf[1024];
1881 int tmp = tor_snprintf(buf, sizeof(buf),
1882 "Unknown option '%s'. Failing.", c->key);
1883 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1884 return -1;
1887 /* Put keyword into canonical case. */
1888 if (strcmp(var->name, c->key)) {
1889 tor_free(c->key);
1890 c->key = tor_strdup(var->name);
1893 if (!strlen(c->value)) {
1894 /* reset or clear it, then return */
1895 if (!clear_first) {
1896 if (var->type == CONFIG_TYPE_LINELIST ||
1897 var->type == CONFIG_TYPE_LINELIST_S) {
1898 /* We got an empty linelist from the torrc or command line.
1899 As a special case, call this an error. Warn and ignore. */
1900 log_warn(LD_CONFIG,
1901 "Linelist option '%s' has no value. Skipping.", c->key);
1902 } else { /* not already cleared */
1903 option_reset(fmt, options, var, use_defaults);
1906 return 0;
1909 if (config_assign_value(fmt, options, c, msg) < 0)
1910 return -2;
1911 return 0;
1914 /** Restore the option named <b>key</b> in options to its default value.
1915 * Called from config_assign(). */
1916 static void
1917 config_reset_line(config_format_t *fmt, or_options_t *options,
1918 const char *key, int use_defaults)
1920 config_var_t *var;
1922 CHECK(fmt, options);
1924 var = config_find_option(fmt, key);
1925 if (!var)
1926 return; /* give error on next pass. */
1928 option_reset(fmt, options, var, use_defaults);
1931 /** Return true iff key is a valid configuration option. */
1933 option_is_recognized(const char *key)
1935 config_var_t *var = config_find_option(&options_format, key);
1936 return (var != NULL);
1939 /** Return the canonical name of a configuration option, or NULL
1940 * if no such option exists. */
1941 const char *
1942 option_get_canonical_name(const char *key)
1944 config_var_t *var = config_find_option(&options_format, key);
1945 return var ? var->name : NULL;
1948 /** Return a canonical list of the options assigned for key.
1950 config_line_t *
1951 option_get_assignment(or_options_t *options, const char *key)
1953 return get_assigned_option(&options_format, options, key, 1);
1956 /** Return true iff value needs to be quoted and escaped to be used in
1957 * a configuration file. */
1958 static int
1959 config_value_needs_escape(const char *value)
1961 if (*value == '\"')
1962 return 1;
1963 while (*value) {
1964 switch (*value)
1966 case '\r':
1967 case '\n':
1968 case '#':
1969 /* Note: quotes and backspaces need special handling when we are using
1970 * quotes, not otherwise, so they don't trigger escaping on their
1971 * own. */
1972 return 1;
1973 default:
1974 if (!TOR_ISPRINT(*value))
1975 return 1;
1977 ++value;
1979 return 0;
1982 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1983 static config_line_t *
1984 config_lines_dup(const config_line_t *inp)
1986 config_line_t *result = NULL;
1987 config_line_t **next_out = &result;
1988 while (inp) {
1989 *next_out = tor_malloc(sizeof(config_line_t));
1990 (*next_out)->key = tor_strdup(inp->key);
1991 (*next_out)->value = tor_strdup(inp->value);
1992 inp = inp->next;
1993 next_out = &((*next_out)->next);
1995 (*next_out) = NULL;
1996 return result;
1999 /** Return newly allocated line or lines corresponding to <b>key</b> in the
2000 * configuration <b>options</b>. If <b>escape_val</b> is true and a
2001 * value needs to be quoted before it's put in a config file, quote and
2002 * escape that value. Return NULL if no such key exists. */
2003 static config_line_t *
2004 get_assigned_option(config_format_t *fmt, void *options,
2005 const char *key, int escape_val)
2007 config_var_t *var;
2008 const void *value;
2009 char buf[32];
2010 config_line_t *result;
2011 tor_assert(options && key);
2013 CHECK(fmt, options);
2015 var = config_find_option(fmt, key);
2016 if (!var) {
2017 log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
2018 return NULL;
2020 value = STRUCT_VAR_P(options, var->var_offset);
2022 result = tor_malloc_zero(sizeof(config_line_t));
2023 result->key = tor_strdup(var->name);
2024 switch (var->type)
2026 case CONFIG_TYPE_STRING:
2027 case CONFIG_TYPE_FILENAME:
2028 if (*(char**)value) {
2029 result->value = tor_strdup(*(char**)value);
2030 } else {
2031 tor_free(result->key);
2032 tor_free(result);
2033 return NULL;
2035 break;
2036 case CONFIG_TYPE_ISOTIME:
2037 if (*(time_t*)value) {
2038 result->value = tor_malloc(ISO_TIME_LEN+1);
2039 format_iso_time(result->value, *(time_t*)value);
2040 } else {
2041 tor_free(result->key);
2042 tor_free(result);
2044 escape_val = 0; /* Can't need escape. */
2045 break;
2046 case CONFIG_TYPE_INTERVAL:
2047 case CONFIG_TYPE_UINT:
2048 /* This means every or_options_t uint or bool element
2049 * needs to be an int. Not, say, a uint16_t or char. */
2050 tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
2051 result->value = tor_strdup(buf);
2052 escape_val = 0; /* Can't need escape. */
2053 break;
2054 case CONFIG_TYPE_MEMUNIT:
2055 tor_snprintf(buf, sizeof(buf), U64_FORMAT,
2056 U64_PRINTF_ARG(*(uint64_t*)value));
2057 result->value = tor_strdup(buf);
2058 escape_val = 0; /* Can't need escape. */
2059 break;
2060 case CONFIG_TYPE_DOUBLE:
2061 tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
2062 result->value = tor_strdup(buf);
2063 escape_val = 0; /* Can't need escape. */
2064 break;
2065 case CONFIG_TYPE_BOOL:
2066 result->value = tor_strdup(*(int*)value ? "1" : "0");
2067 escape_val = 0; /* Can't need escape. */
2068 break;
2069 case CONFIG_TYPE_ROUTERSET:
2070 result->value = routerset_to_string(*(routerset_t**)value);
2071 break;
2072 case CONFIG_TYPE_CSV:
2073 if (*(smartlist_t**)value)
2074 result->value =
2075 smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
2076 else
2077 result->value = tor_strdup("");
2078 break;
2079 case CONFIG_TYPE_OBSOLETE:
2080 log_fn(LOG_PROTOCOL_WARN, LD_CONFIG,
2081 "You asked me for the value of an obsolete config option '%s'.",
2082 key);
2083 tor_free(result->key);
2084 tor_free(result);
2085 return NULL;
2086 case CONFIG_TYPE_LINELIST_S:
2087 log_warn(LD_CONFIG,
2088 "Can't return context-sensitive '%s' on its own", key);
2089 tor_free(result->key);
2090 tor_free(result);
2091 return NULL;
2092 case CONFIG_TYPE_LINELIST:
2093 case CONFIG_TYPE_LINELIST_V:
2094 tor_free(result->key);
2095 tor_free(result);
2096 result = config_lines_dup(*(const config_line_t**)value);
2097 break;
2098 default:
2099 tor_free(result->key);
2100 tor_free(result);
2101 log_warn(LD_BUG,"Unknown type %d for known key '%s'",
2102 var->type, key);
2103 return NULL;
2106 if (escape_val) {
2107 config_line_t *line;
2108 for (line = result; line; line = line->next) {
2109 if (line->value && config_value_needs_escape(line->value)) {
2110 char *newval = esc_for_log(line->value);
2111 tor_free(line->value);
2112 line->value = newval;
2117 return result;
2120 /** Iterate through the linked list of requested options <b>list</b>.
2121 * For each item, convert as appropriate and assign to <b>options</b>.
2122 * If an item is unrecognized, set *msg and return -1 immediately,
2123 * else return 0 for success.
2125 * If <b>clear_first</b>, interpret config options as replacing (not
2126 * extending) their previous values. If <b>clear_first</b> is set,
2127 * then <b>use_defaults</b> to decide if you set to defaults after
2128 * clearing, or make the value 0 or NULL.
2130 * Here are the use cases:
2131 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
2132 * if linelist, replaces current if csv.
2133 * 2. An empty AllowInvalid line in your torrc. Should clear it.
2134 * 3. "RESETCONF AllowInvalid" sets it to default.
2135 * 4. "SETCONF AllowInvalid" makes it NULL.
2136 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
2138 * Use_defaults Clear_first
2139 * 0 0 "append"
2140 * 1 0 undefined, don't use
2141 * 0 1 "set to null first"
2142 * 1 1 "set to defaults first"
2143 * Return 0 on success, -1 on bad key, -2 on bad value.
2145 * As an additional special case, if a LINELIST config option has
2146 * no value and clear_first is 0, then warn and ignore it.
2150 There are three call cases for config_assign() currently.
2152 Case one: Torrc entry
2153 options_init_from_torrc() calls config_assign(0, 0)
2154 calls config_assign_line(0, 0).
2155 if value is empty, calls option_reset(0) and returns.
2156 calls config_assign_value(), appends.
2158 Case two: setconf
2159 options_trial_assign() calls config_assign(0, 1)
2160 calls config_reset_line(0)
2161 calls option_reset(0)
2162 calls option_clear().
2163 calls config_assign_line(0, 1).
2164 if value is empty, returns.
2165 calls config_assign_value(), appends.
2167 Case three: resetconf
2168 options_trial_assign() calls config_assign(1, 1)
2169 calls config_reset_line(1)
2170 calls option_reset(1)
2171 calls option_clear().
2172 calls config_assign_value(default)
2173 calls config_assign_line(1, 1).
2174 returns.
2176 static int
2177 config_assign(config_format_t *fmt, void *options, config_line_t *list,
2178 int use_defaults, int clear_first, char **msg)
2180 config_line_t *p;
2182 CHECK(fmt, options);
2184 /* pass 1: normalize keys */
2185 for (p = list; p; p = p->next) {
2186 const char *full = expand_abbrev(fmt, p->key, 0, 1);
2187 if (strcmp(full,p->key)) {
2188 tor_free(p->key);
2189 p->key = tor_strdup(full);
2193 /* pass 2: if we're reading from a resetting source, clear all
2194 * mentioned config options, and maybe set to their defaults. */
2195 if (clear_first) {
2196 for (p = list; p; p = p->next)
2197 config_reset_line(fmt, options, p->key, use_defaults);
2200 /* pass 3: assign. */
2201 while (list) {
2202 int r;
2203 if ((r=config_assign_line(fmt, options, list, use_defaults,
2204 clear_first, msg)))
2205 return r;
2206 list = list->next;
2208 return 0;
2211 /** Try assigning <b>list</b> to the global options. You do this by duping
2212 * options, assigning list to the new one, then validating it. If it's
2213 * ok, then throw out the old one and stick with the new one. Else,
2214 * revert to old and return failure. Return SETOPT_OK on success, or
2215 * a setopt_err_t on failure.
2217 * If not success, point *<b>msg</b> to a newly allocated string describing
2218 * what went wrong.
2220 setopt_err_t
2221 options_trial_assign(config_line_t *list, int use_defaults,
2222 int clear_first, char **msg)
2224 int r;
2225 or_options_t *trial_options = options_dup(&options_format, get_options());
2227 if ((r=config_assign(&options_format, trial_options,
2228 list, use_defaults, clear_first, msg)) < 0) {
2229 config_free(&options_format, trial_options);
2230 return r;
2233 if (options_validate(get_options(), trial_options, 1, msg) < 0) {
2234 config_free(&options_format, trial_options);
2235 return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2238 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2239 config_free(&options_format, trial_options);
2240 return SETOPT_ERR_TRANSITION;
2243 if (set_options(trial_options, msg)<0) {
2244 config_free(&options_format, trial_options);
2245 return SETOPT_ERR_SETTING;
2248 /* we liked it. put it in place. */
2249 return SETOPT_OK;
2252 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2253 * Called from option_reset() and config_free(). */
2254 static void
2255 option_clear(config_format_t *fmt, or_options_t *options, config_var_t *var)
2257 void *lvalue = STRUCT_VAR_P(options, var->var_offset);
2258 (void)fmt; /* unused */
2259 switch (var->type) {
2260 case CONFIG_TYPE_STRING:
2261 case CONFIG_TYPE_FILENAME:
2262 tor_free(*(char**)lvalue);
2263 break;
2264 case CONFIG_TYPE_DOUBLE:
2265 *(double*)lvalue = 0.0;
2266 break;
2267 case CONFIG_TYPE_ISOTIME:
2268 *(time_t*)lvalue = 0;
2269 break;
2270 case CONFIG_TYPE_INTERVAL:
2271 case CONFIG_TYPE_UINT:
2272 case CONFIG_TYPE_BOOL:
2273 *(int*)lvalue = 0;
2274 break;
2275 case CONFIG_TYPE_MEMUNIT:
2276 *(uint64_t*)lvalue = 0;
2277 break;
2278 case CONFIG_TYPE_ROUTERSET:
2279 if (*(routerset_t**)lvalue) {
2280 routerset_free(*(routerset_t**)lvalue);
2281 *(routerset_t**)lvalue = NULL;
2283 break;
2284 case CONFIG_TYPE_CSV:
2285 if (*(smartlist_t**)lvalue) {
2286 SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
2287 smartlist_free(*(smartlist_t **)lvalue);
2288 *(smartlist_t **)lvalue = NULL;
2290 break;
2291 case CONFIG_TYPE_LINELIST:
2292 case CONFIG_TYPE_LINELIST_S:
2293 config_free_lines(*(config_line_t **)lvalue);
2294 *(config_line_t **)lvalue = NULL;
2295 break;
2296 case CONFIG_TYPE_LINELIST_V:
2297 /* handled by linelist_s. */
2298 break;
2299 case CONFIG_TYPE_OBSOLETE:
2300 break;
2304 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2305 * <b>use_defaults</b>, set it to its default value.
2306 * Called by config_init() and option_reset_line() and option_assign_line(). */
2307 static void
2308 option_reset(config_format_t *fmt, or_options_t *options,
2309 config_var_t *var, int use_defaults)
2311 config_line_t *c;
2312 char *msg = NULL;
2313 CHECK(fmt, options);
2314 option_clear(fmt, options, var); /* clear it first */
2315 if (!use_defaults)
2316 return; /* all done */
2317 if (var->initvalue) {
2318 c = tor_malloc_zero(sizeof(config_line_t));
2319 c->key = tor_strdup(var->name);
2320 c->value = tor_strdup(var->initvalue);
2321 if (config_assign_value(fmt, options, c, &msg) < 0) {
2322 log_warn(LD_BUG, "Failed to assign default: %s", msg);
2323 tor_free(msg); /* if this happens it's a bug */
2325 config_free_lines(c);
2329 /** Print a usage message for tor. */
2330 static void
2331 print_usage(void)
2333 printf(
2334 "Copyright (c) 2001-2004, Roger Dingledine\n"
2335 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2336 "Copyright (c) 2007-2009, The Tor Project, Inc.\n\n"
2337 "tor -f <torrc> [args]\n"
2338 "See man page for options, or https://www.torproject.org/ for "
2339 "documentation.\n");
2342 /** Print all non-obsolete torrc options. */
2343 static void
2344 list_torrc_options(void)
2346 int i;
2347 smartlist_t *lines = smartlist_create();
2348 for (i = 0; _option_vars[i].name; ++i) {
2349 config_var_t *var = &_option_vars[i];
2350 const char *desc;
2351 if (var->type == CONFIG_TYPE_OBSOLETE ||
2352 var->type == CONFIG_TYPE_LINELIST_V)
2353 continue;
2354 desc = config_find_description(&options_format, var->name);
2355 printf("%s\n", var->name);
2356 if (desc) {
2357 wrap_string(lines, desc, 76, " ", " ");
2358 SMARTLIST_FOREACH(lines, char *, cp, {
2359 printf("%s", cp);
2360 tor_free(cp);
2362 smartlist_clear(lines);
2365 smartlist_free(lines);
2368 /** Last value actually set by resolve_my_address. */
2369 static uint32_t last_resolved_addr = 0;
2371 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2372 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2373 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2374 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2375 * public IP address.
2378 resolve_my_address(int warn_severity, or_options_t *options,
2379 uint32_t *addr_out, char **hostname_out)
2381 struct in_addr in;
2382 struct hostent *rent;
2383 char hostname[256];
2384 int explicit_ip=1;
2385 int explicit_hostname=1;
2386 int from_interface=0;
2387 char tmpbuf[INET_NTOA_BUF_LEN];
2388 const char *address = options->Address;
2389 int notice_severity = warn_severity <= LOG_NOTICE ?
2390 LOG_NOTICE : warn_severity;
2392 tor_assert(addr_out);
2394 if (address && *address) {
2395 strlcpy(hostname, address, sizeof(hostname));
2396 } else { /* then we need to guess our address */
2397 explicit_ip = 0; /* it's implicit */
2398 explicit_hostname = 0; /* it's implicit */
2400 if (gethostname(hostname, sizeof(hostname)) < 0) {
2401 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2402 return -1;
2404 log_debug(LD_CONFIG,"Guessed local host name as '%s'",hostname);
2407 /* now we know hostname. resolve it and keep only the IP address */
2409 if (tor_inet_aton(hostname, &in) == 0) {
2410 /* then we have to resolve it */
2411 explicit_ip = 0;
2412 rent = (struct hostent *)gethostbyname(hostname);
2413 if (!rent) {
2414 uint32_t interface_ip;
2416 if (explicit_hostname) {
2417 log_fn(warn_severity, LD_CONFIG,
2418 "Could not resolve local Address '%s'. Failing.", hostname);
2419 return -1;
2421 log_fn(notice_severity, LD_CONFIG,
2422 "Could not resolve guessed local hostname '%s'. "
2423 "Trying something else.", hostname);
2424 if (get_interface_address(warn_severity, &interface_ip)) {
2425 log_fn(warn_severity, LD_CONFIG,
2426 "Could not get local interface IP address. Failing.");
2427 return -1;
2429 from_interface = 1;
2430 in.s_addr = htonl(interface_ip);
2431 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2432 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2433 "local interface. Using that.", tmpbuf);
2434 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2435 } else {
2436 tor_assert(rent->h_length == 4);
2437 memcpy(&in.s_addr, rent->h_addr, rent->h_length);
2439 if (!explicit_hostname &&
2440 is_internal_IP(ntohl(in.s_addr), 0)) {
2441 uint32_t interface_ip;
2443 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2444 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2445 "resolves to a private IP address (%s). Trying something "
2446 "else.", hostname, tmpbuf);
2448 if (get_interface_address(warn_severity, &interface_ip)) {
2449 log_fn(warn_severity, LD_CONFIG,
2450 "Could not get local interface IP address. Too bad.");
2451 } else if (is_internal_IP(interface_ip, 0)) {
2452 struct in_addr in2;
2453 in2.s_addr = htonl(interface_ip);
2454 tor_inet_ntoa(&in2,tmpbuf,sizeof(tmpbuf));
2455 log_fn(notice_severity, LD_CONFIG,
2456 "Interface IP address '%s' is a private address too. "
2457 "Ignoring.", tmpbuf);
2458 } else {
2459 from_interface = 1;
2460 in.s_addr = htonl(interface_ip);
2461 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2462 log_fn(notice_severity, LD_CONFIG,
2463 "Learned IP address '%s' for local interface."
2464 " Using that.", tmpbuf);
2465 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2471 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2472 if (is_internal_IP(ntohl(in.s_addr), 0) &&
2473 options->_PublishServerDescriptor) {
2474 /* make sure we're ok with publishing an internal IP */
2475 if (!options->DirServers && !options->AlternateDirAuthority) {
2476 /* if they are using the default dirservers, disallow internal IPs
2477 * always. */
2478 log_fn(warn_severity, LD_CONFIG,
2479 "Address '%s' resolves to private IP address '%s'. "
2480 "Tor servers that use the default DirServers must have public "
2481 "IP addresses.", hostname, tmpbuf);
2482 return -1;
2484 if (!explicit_ip) {
2485 /* even if they've set their own dirservers, require an explicit IP if
2486 * they're using an internal address. */
2487 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2488 "IP address '%s'. Please set the Address config option to be "
2489 "the IP address you want to use.", hostname, tmpbuf);
2490 return -1;
2494 log_debug(LD_CONFIG, "Resolved Address to '%s'.", tmpbuf);
2495 *addr_out = ntohl(in.s_addr);
2496 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2497 /* Leave this as a notice, regardless of the requested severity,
2498 * at least until dynamic IP address support becomes bulletproof. */
2499 log_notice(LD_NET,
2500 "Your IP address seems to have changed to %s. Updating.",
2501 tmpbuf);
2502 ip_address_changed(0);
2504 if (last_resolved_addr != *addr_out) {
2505 const char *method;
2506 const char *h = hostname;
2507 if (explicit_ip) {
2508 method = "CONFIGURED";
2509 h = NULL;
2510 } else if (explicit_hostname) {
2511 method = "RESOLVED";
2512 } else if (from_interface) {
2513 method = "INTERFACE";
2514 h = NULL;
2515 } else {
2516 method = "GETHOSTNAME";
2518 control_event_server_status(LOG_NOTICE,
2519 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2520 tmpbuf, method, h?"HOSTNAME=":"", h);
2522 last_resolved_addr = *addr_out;
2523 if (hostname_out)
2524 *hostname_out = tor_strdup(hostname);
2525 return 0;
2528 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2529 * on a private network.
2532 is_local_addr(const tor_addr_t *addr)
2534 if (tor_addr_is_internal(addr, 0))
2535 return 1;
2536 /* Check whether ip is on the same /24 as we are. */
2537 if (get_options()->EnforceDistinctSubnets == 0)
2538 return 0;
2539 if (tor_addr_family(addr) == AF_INET) {
2540 /*XXXX022 IP6 what corresponds to an /24? */
2541 uint32_t ip = tor_addr_to_ipv4h(addr);
2543 /* It's possible that this next check will hit before the first time
2544 * resolve_my_address actually succeeds. (For clients, it is likely that
2545 * resolve_my_address will never be called at all). In those cases,
2546 * last_resolved_addr will be 0, and so checking to see whether ip is on
2547 * the same /24 as last_resolved_addr will be the same as checking whether
2548 * it was on net 0, which is already done by is_internal_IP.
2550 if ((last_resolved_addr & (uint32_t)0xffffff00ul)
2551 == (ip & (uint32_t)0xffffff00ul))
2552 return 1;
2554 return 0;
2557 /** Called when we don't have a nickname set. Try to guess a good nickname
2558 * based on the hostname, and return it in a newly allocated string. If we
2559 * can't, return NULL and let the caller warn if it wants to. */
2560 static char *
2561 get_default_nickname(void)
2563 static const char * const bad_default_nicknames[] = {
2564 "localhost",
2565 NULL,
2567 char localhostname[256];
2568 char *cp, *out, *outp;
2569 int i;
2571 if (gethostname(localhostname, sizeof(localhostname)) < 0)
2572 return NULL;
2574 /* Put it in lowercase; stop at the first dot. */
2575 if ((cp = strchr(localhostname, '.')))
2576 *cp = '\0';
2577 tor_strlower(localhostname);
2579 /* Strip invalid characters. */
2580 cp = localhostname;
2581 out = outp = tor_malloc(strlen(localhostname) + 1);
2582 while (*cp) {
2583 if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
2584 *outp++ = *cp++;
2585 else
2586 cp++;
2588 *outp = '\0';
2590 /* Enforce length. */
2591 if (strlen(out) > MAX_NICKNAME_LEN)
2592 out[MAX_NICKNAME_LEN]='\0';
2594 /* Check for dumb names. */
2595 for (i = 0; bad_default_nicknames[i]; ++i) {
2596 if (!strcmp(out, bad_default_nicknames[i])) {
2597 tor_free(out);
2598 return NULL;
2602 return out;
2605 /** Release storage held by <b>options</b>. */
2606 static void
2607 config_free(config_format_t *fmt, void *options)
2609 int i;
2611 if (!options)
2612 return;
2614 tor_assert(fmt);
2616 for (i=0; fmt->vars[i].name; ++i)
2617 option_clear(fmt, options, &(fmt->vars[i]));
2618 if (fmt->extra) {
2619 config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
2620 config_free_lines(*linep);
2621 *linep = NULL;
2623 tor_free(options);
2626 /** Return true iff a and b contain identical keys and values in identical
2627 * order. */
2628 static int
2629 config_lines_eq(config_line_t *a, config_line_t *b)
2631 while (a && b) {
2632 if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
2633 return 0;
2634 a = a->next;
2635 b = b->next;
2637 if (a || b)
2638 return 0;
2639 return 1;
2642 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2643 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2645 static int
2646 option_is_same(config_format_t *fmt,
2647 or_options_t *o1, or_options_t *o2, const char *name)
2649 config_line_t *c1, *c2;
2650 int r = 1;
2651 CHECK(fmt, o1);
2652 CHECK(fmt, o2);
2654 c1 = get_assigned_option(fmt, o1, name, 0);
2655 c2 = get_assigned_option(fmt, o2, name, 0);
2656 r = config_lines_eq(c1, c2);
2657 config_free_lines(c1);
2658 config_free_lines(c2);
2659 return r;
2662 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2663 static or_options_t *
2664 options_dup(config_format_t *fmt, or_options_t *old)
2666 or_options_t *newopts;
2667 int i;
2668 config_line_t *line;
2670 newopts = config_alloc(fmt);
2671 for (i=0; fmt->vars[i].name; ++i) {
2672 if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2673 continue;
2674 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
2675 continue;
2676 line = get_assigned_option(fmt, old, fmt->vars[i].name, 0);
2677 if (line) {
2678 char *msg = NULL;
2679 if (config_assign(fmt, newopts, line, 0, 0, &msg) < 0) {
2680 log_err(LD_BUG, "Config_get_assigned_option() generated "
2681 "something we couldn't config_assign(): %s", msg);
2682 tor_free(msg);
2683 tor_assert(0);
2686 config_free_lines(line);
2688 return newopts;
2691 /** Return a new empty or_options_t. Used for testing. */
2692 or_options_t *
2693 options_new(void)
2695 return config_alloc(&options_format);
2698 /** Set <b>options</b> to hold reasonable defaults for most options.
2699 * Each option defaults to zero. */
2700 void
2701 options_init(or_options_t *options)
2703 config_init(&options_format, options);
2706 /* Check if the port number given in <b>port_option</b> in combination with
2707 * the specified port in <b>listen_options</b> will result in Tor actually
2708 * opening a low port (meaning a port lower than 1024). Return 1 if
2709 * it is, or 0 if it isn't or the concept of a low port isn't applicable for
2710 * the platform we're on. */
2711 static int
2712 is_listening_on_low_port(uint16_t port_option,
2713 const config_line_t *listen_options)
2715 #ifdef MS_WINDOWS
2716 (void) port_option;
2717 (void) listen_options;
2718 return 0; /* No port is too low for windows. */
2719 #else
2720 const config_line_t *l;
2721 uint16_t p;
2722 if (port_option == 0)
2723 return 0; /* We're not listening */
2724 if (listen_options == NULL)
2725 return (port_option < 1024);
2727 for (l = listen_options; l; l = l->next) {
2728 parse_addr_port(LOG_WARN, l->value, NULL, NULL, &p);
2729 if (p<1024) {
2730 return 1;
2733 return 0;
2734 #endif
2737 /** Set all vars in the configuration object <b>options</b> to their default
2738 * values. */
2739 static void
2740 config_init(config_format_t *fmt, void *options)
2742 int i;
2743 config_var_t *var;
2744 CHECK(fmt, options);
2746 for (i=0; fmt->vars[i].name; ++i) {
2747 var = &fmt->vars[i];
2748 if (!var->initvalue)
2749 continue; /* defaults to NULL or 0 */
2750 option_reset(fmt, options, var, 1);
2754 /** Allocate and return a new string holding the written-out values of the vars
2755 * in 'options'. If 'minimal', do not write out any default-valued vars.
2756 * Else, if comment_defaults, write default values as comments.
2758 static char *
2759 config_dump(config_format_t *fmt, void *options, int minimal,
2760 int comment_defaults)
2762 smartlist_t *elements;
2763 or_options_t *defaults;
2764 config_line_t *line, *assigned;
2765 char *result;
2766 int i;
2767 const char *desc;
2768 char *msg = NULL;
2770 defaults = config_alloc(fmt);
2771 config_init(fmt, defaults);
2773 /* XXX use a 1 here so we don't add a new log line while dumping */
2774 if (fmt->validate_fn(NULL,defaults, 1, &msg) < 0) {
2775 log_err(LD_BUG, "Failed to validate default config.");
2776 tor_free(msg);
2777 tor_assert(0);
2780 elements = smartlist_create();
2781 for (i=0; fmt->vars[i].name; ++i) {
2782 int comment_option = 0;
2783 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
2784 fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2785 continue;
2786 /* Don't save 'hidden' control variables. */
2787 if (!strcmpstart(fmt->vars[i].name, "__"))
2788 continue;
2789 if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
2790 continue;
2791 else if (comment_defaults &&
2792 option_is_same(fmt, options, defaults, fmt->vars[i].name))
2793 comment_option = 1;
2795 desc = config_find_description(fmt, fmt->vars[i].name);
2796 line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name, 1);
2798 if (line && desc) {
2799 /* Only dump the description if there's something to describe. */
2800 wrap_string(elements, desc, 78, "# ", "# ");
2803 for (; line; line = line->next) {
2804 size_t len = strlen(line->key) + strlen(line->value) + 5;
2805 char *tmp;
2806 tmp = tor_malloc(len);
2807 if (tor_snprintf(tmp, len, "%s%s %s\n",
2808 comment_option ? "# " : "",
2809 line->key, line->value)<0) {
2810 log_err(LD_BUG,"Internal error writing option value");
2811 tor_assert(0);
2813 smartlist_add(elements, tmp);
2815 config_free_lines(assigned);
2818 if (fmt->extra) {
2819 line = *(config_line_t**)STRUCT_VAR_P(options, fmt->extra->var_offset);
2820 for (; line; line = line->next) {
2821 size_t len = strlen(line->key) + strlen(line->value) + 3;
2822 char *tmp;
2823 tmp = tor_malloc(len);
2824 if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
2825 log_err(LD_BUG,"Internal error writing option value");
2826 tor_assert(0);
2828 smartlist_add(elements, tmp);
2832 result = smartlist_join_strings(elements, "", 0, NULL);
2833 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2834 smartlist_free(elements);
2835 config_free(fmt, defaults);
2836 return result;
2839 /** Return a string containing a possible configuration file that would give
2840 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2841 * include options that are the same as Tor's defaults.
2843 static char *
2844 options_dump(or_options_t *options, int minimal)
2846 return config_dump(&options_format, options, minimal, 0);
2849 /** Return 0 if every element of sl is a string holding a decimal
2850 * representation of a port number, or if sl is NULL.
2851 * Otherwise set *msg and return -1. */
2852 static int
2853 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2855 int i;
2856 char buf[1024];
2857 tor_assert(name);
2859 if (!sl)
2860 return 0;
2862 SMARTLIST_FOREACH(sl, const char *, cp,
2864 i = atoi(cp);
2865 if (i < 1 || i > 65535) {
2866 int r = tor_snprintf(buf, sizeof(buf),
2867 "Port '%s' out of range in %s", cp, name);
2868 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2869 return -1;
2872 return 0;
2875 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2876 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2877 * Else return 0.
2879 static int
2880 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2882 int r;
2883 char buf[1024];
2884 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2885 /* This handles an understandable special case where somebody says "2gb"
2886 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2887 --*value;
2889 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2890 r = tor_snprintf(buf, sizeof(buf), "%s ("U64_FORMAT") must be at most %d",
2891 desc, U64_PRINTF_ARG(*value),
2892 ROUTER_MAX_DECLARED_BANDWIDTH);
2893 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2894 return -1;
2896 return 0;
2899 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2900 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2901 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2902 * Treat "0" as "".
2903 * Return 0 on success or -1 if not a recognized authority type (in which
2904 * case the value of _PublishServerDescriptor is undefined). */
2905 static int
2906 compute_publishserverdescriptor(or_options_t *options)
2908 smartlist_t *list = options->PublishServerDescriptor;
2909 authority_type_t *auth = &options->_PublishServerDescriptor;
2910 *auth = NO_AUTHORITY;
2911 if (!list) /* empty list, answer is none */
2912 return 0;
2913 SMARTLIST_FOREACH(list, const char *, string, {
2914 if (!strcasecmp(string, "v1"))
2915 *auth |= V1_AUTHORITY;
2916 else if (!strcmp(string, "1"))
2917 if (options->BridgeRelay)
2918 *auth |= BRIDGE_AUTHORITY;
2919 else
2920 *auth |= V2_AUTHORITY | V3_AUTHORITY;
2921 else if (!strcasecmp(string, "v2"))
2922 *auth |= V2_AUTHORITY;
2923 else if (!strcasecmp(string, "v3"))
2924 *auth |= V3_AUTHORITY;
2925 else if (!strcasecmp(string, "bridge"))
2926 *auth |= BRIDGE_AUTHORITY;
2927 else if (!strcasecmp(string, "hidserv"))
2928 *auth |= HIDSERV_AUTHORITY;
2929 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2930 /* no authority */;
2931 else
2932 return -1;
2934 return 0;
2937 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2938 * services can overload the directory system. */
2939 #define MIN_REND_POST_PERIOD (10*60)
2941 /** Highest allowable value for RendPostPeriod. */
2942 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2944 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2945 * will generate too many circuits and potentially overload the network. */
2946 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2948 /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
2949 * will generate too many circuits and potentially overload the network. */
2950 #define MIN_CIRCUIT_STREAM_TIMEOUT 10
2952 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2953 * permissible transition from <b>old_options</b>. Else return -1.
2954 * Should have no side effects, except for normalizing the contents of
2955 * <b>options</b>.
2957 * On error, tor_strdup an error explanation into *<b>msg</b>.
2959 * XXX
2960 * If <b>from_setconf</b>, we were called by the controller, and our
2961 * Log line should stay empty. If it's 0, then give us a default log
2962 * if there are no logs defined.
2964 static int
2965 options_validate(or_options_t *old_options, or_options_t *options,
2966 int from_setconf, char **msg)
2968 int i, r;
2969 config_line_t *cl;
2970 const char *uname = get_uname();
2971 char buf[1024];
2972 #define REJECT(arg) \
2973 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2974 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2976 tor_assert(msg);
2977 *msg = NULL;
2979 if (options->ORPort < 0 || options->ORPort > 65535)
2980 REJECT("ORPort option out of bounds.");
2982 if (server_mode(options) &&
2983 (!strcmpstart(uname, "Windows 95") ||
2984 !strcmpstart(uname, "Windows 98") ||
2985 !strcmpstart(uname, "Windows Me"))) {
2986 log(LOG_WARN, LD_CONFIG, "Tor is running as a server, but you are "
2987 "running %s; this probably won't work. See "
2988 "https://wiki.torproject.org/TheOnionRouter/TorFAQ#ServerOS "
2989 "for details.", uname);
2992 if (options->ORPort == 0 && options->ORListenAddress != NULL)
2993 REJECT("ORPort must be defined if ORListenAddress is defined.");
2995 if (options->DirPort == 0 && options->DirListenAddress != NULL)
2996 REJECT("DirPort must be defined if DirListenAddress is defined.");
2998 if (options->DNSPort == 0 && options->DNSListenAddress != NULL)
2999 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
3001 if (options->ControlPort == 0 && options->ControlListenAddress != NULL)
3002 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
3004 if (options->TransPort == 0 && options->TransListenAddress != NULL)
3005 REJECT("TransPort must be defined if TransListenAddress is defined.");
3007 if (options->NatdPort == 0 && options->NatdListenAddress != NULL)
3008 REJECT("NatdPort must be defined if NatdListenAddress is defined.");
3010 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
3011 * configuration does this. */
3013 for (i = 0; i < 3; ++i) {
3014 int is_socks = i==0;
3015 int is_trans = i==1;
3016 config_line_t *line, *opt, *old;
3017 const char *tp;
3018 if (is_socks) {
3019 opt = options->SocksListenAddress;
3020 old = old_options ? old_options->SocksListenAddress : NULL;
3021 tp = "SOCKS proxy";
3022 } else if (is_trans) {
3023 opt = options->TransListenAddress;
3024 old = old_options ? old_options->TransListenAddress : NULL;
3025 tp = "transparent proxy";
3026 } else {
3027 opt = options->NatdListenAddress;
3028 old = old_options ? old_options->NatdListenAddress : NULL;
3029 tp = "natd proxy";
3032 for (line = opt; line; line = line->next) {
3033 char *address = NULL;
3034 uint16_t port;
3035 uint32_t addr;
3036 if (parse_addr_port(LOG_WARN, line->value, &address, &addr, &port)<0)
3037 continue; /* We'll warn about this later. */
3038 if (!is_internal_IP(addr, 1) &&
3039 (!old_options || !config_lines_eq(old, opt))) {
3040 log_warn(LD_CONFIG,
3041 "You specified a public address '%s' for a %s. Other "
3042 "people on the Internet might find your computer and use it as "
3043 "an open %s. Please don't allow this unless you have "
3044 "a good reason.", address, tp, tp);
3046 tor_free(address);
3050 if (validate_data_directory(options)<0)
3051 REJECT("Invalid DataDirectory");
3053 if (options->Nickname == NULL) {
3054 if (server_mode(options)) {
3055 if (!(options->Nickname = get_default_nickname())) {
3056 log_notice(LD_CONFIG, "Couldn't pick a nickname based on "
3057 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME);
3058 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
3059 } else {
3060 log_notice(LD_CONFIG, "Choosing default nickname '%s'",
3061 options->Nickname);
3064 } else {
3065 if (!is_legal_nickname(options->Nickname)) {
3066 r = tor_snprintf(buf, sizeof(buf),
3067 "Nickname '%s' is wrong length or contains illegal characters.",
3068 options->Nickname);
3069 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3070 return -1;
3074 if (server_mode(options) && !options->ContactInfo)
3075 log(LOG_NOTICE, LD_CONFIG, "Your ContactInfo config option is not set. "
3076 "Please consider setting it, so we can contact you if your server is "
3077 "misconfigured or something else goes wrong.");
3079 /* Special case on first boot if no Log options are given. */
3080 if (!options->Logs && !options->RunAsDaemon && !from_setconf)
3081 config_line_append(&options->Logs, "Log", "notice stdout");
3083 if (options_init_logs(options, 1)<0) /* Validate the log(s) */
3084 REJECT("Failed to validate Log options. See logs for details.");
3086 if (options->NoPublish) {
3087 log(LOG_WARN, LD_CONFIG,
3088 "NoPublish is obsolete. Use PublishServerDescriptor instead.");
3089 SMARTLIST_FOREACH(options->PublishServerDescriptor, char *, s,
3090 tor_free(s));
3091 smartlist_clear(options->PublishServerDescriptor);
3094 if (authdir_mode(options)) {
3095 /* confirm that our address isn't broken, so we can complain now */
3096 uint32_t tmp;
3097 if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
3098 REJECT("Failed to resolve/guess local address. See logs for details.");
3101 #ifndef MS_WINDOWS
3102 if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
3103 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
3104 #endif
3106 if (options->SocksPort < 0 || options->SocksPort > 65535)
3107 REJECT("SocksPort option out of bounds.");
3109 if (options->DNSPort < 0 || options->DNSPort > 65535)
3110 REJECT("DNSPort option out of bounds.");
3112 if (options->TransPort < 0 || options->TransPort > 65535)
3113 REJECT("TransPort option out of bounds.");
3115 if (options->NatdPort < 0 || options->NatdPort > 65535)
3116 REJECT("NatdPort option out of bounds.");
3118 if (options->SocksPort == 0 && options->TransPort == 0 &&
3119 options->NatdPort == 0 && options->ORPort == 0 &&
3120 options->DNSPort == 0 && !options->RendConfigLines)
3121 log(LOG_WARN, LD_CONFIG,
3122 "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
3123 "undefined, and there aren't any hidden services configured. "
3124 "Tor will still run, but probably won't do anything.");
3126 if (options->ControlPort < 0 || options->ControlPort > 65535)
3127 REJECT("ControlPort option out of bounds.");
3129 if (options->DirPort < 0 || options->DirPort > 65535)
3130 REJECT("DirPort option out of bounds.");
3132 #ifndef USE_TRANSPARENT
3133 if (options->TransPort || options->TransListenAddress)
3134 REJECT("TransPort and TransListenAddress are disabled in this build.");
3135 #endif
3137 if (options->AccountingMax &&
3138 (is_listening_on_low_port(options->ORPort, options->ORListenAddress) ||
3139 is_listening_on_low_port(options->DirPort, options->DirListenAddress)))
3141 log(LOG_WARN, LD_CONFIG,
3142 "You have set AccountingMax to use hibernation. You have also "
3143 "chosen a low DirPort or OrPort. This combination can make Tor stop "
3144 "working when it tries to re-attach the port after a period of "
3145 "hibernation. Please choose a different port or turn off "
3146 "hibernation unless you know this combination will work on your "
3147 "platform.");
3150 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3151 options->_ExcludeExitNodesUnion = routerset_new();
3152 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeExitNodes);
3153 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeNodes);
3156 if (options->StrictExitNodes &&
3157 (!options->ExitNodes) &&
3158 (!old_options ||
3159 (old_options->StrictExitNodes != options->StrictExitNodes) ||
3160 (!routerset_equal(old_options->ExitNodes,options->ExitNodes))))
3161 COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
3163 if (options->StrictEntryNodes &&
3164 (!options->EntryNodes) &&
3165 (!old_options ||
3166 (old_options->StrictEntryNodes != options->StrictEntryNodes) ||
3167 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
3168 COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
3170 if (options->EntryNodes && !routerset_is_list(options->EntryNodes)) {
3171 /* XXXX fix this; see entry_guards_prepend_from_config(). */
3172 REJECT("IPs or countries are not yet supported in EntryNodes.");
3175 if (options->AuthoritativeDir) {
3176 if (!options->ContactInfo && !options->TestingTorNetwork)
3177 REJECT("Authoritative directory servers must set ContactInfo");
3178 if (options->V1AuthoritativeDir && !options->RecommendedVersions)
3179 REJECT("V1 authoritative dir servers must set RecommendedVersions.");
3180 if (!options->RecommendedClientVersions)
3181 options->RecommendedClientVersions =
3182 config_lines_dup(options->RecommendedVersions);
3183 if (!options->RecommendedServerVersions)
3184 options->RecommendedServerVersions =
3185 config_lines_dup(options->RecommendedVersions);
3186 if (options->VersioningAuthoritativeDir &&
3187 (!options->RecommendedClientVersions ||
3188 !options->RecommendedServerVersions))
3189 REJECT("Versioning authoritative dir servers must set "
3190 "Recommended*Versions.");
3191 if (options->UseEntryGuards) {
3192 log_info(LD_CONFIG, "Authoritative directory servers can't set "
3193 "UseEntryGuards. Disabling.");
3194 options->UseEntryGuards = 0;
3196 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
3197 log_info(LD_CONFIG, "Authoritative directories always try to download "
3198 "extra-info documents. Setting DownloadExtraInfo.");
3199 options->DownloadExtraInfo = 1;
3201 if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
3202 options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
3203 options->V3AuthoritativeDir))
3204 REJECT("AuthoritativeDir is set, but none of "
3205 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
3206 /* If we have a v3bandwidthsfile and it's broken, complain on startup */
3207 if (options->V3BandwidthsFile && !old_options) {
3208 dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
3212 if (options->AuthoritativeDir && !options->DirPort)
3213 REJECT("Running as authoritative directory, but no DirPort set.");
3215 if (options->AuthoritativeDir && !options->ORPort)
3216 REJECT("Running as authoritative directory, but no ORPort set.");
3218 if (options->AuthoritativeDir && options->ClientOnly)
3219 REJECT("Running as authoritative directory, but ClientOnly also set.");
3221 if (options->HSAuthorityRecordStats && !options->HSAuthoritativeDir)
3222 REJECT("HSAuthorityRecordStats is set but we're not running as "
3223 "a hidden service authority.");
3225 if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
3226 REJECT("FetchDirInfoExtraEarly requires that you also set "
3227 "FetchDirInfoEarly");
3229 if (options->ConnLimit <= 0) {
3230 r = tor_snprintf(buf, sizeof(buf),
3231 "ConnLimit must be greater than 0, but was set to %d",
3232 options->ConnLimit);
3233 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3234 return -1;
3237 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3238 return -1;
3240 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3241 return -1;
3243 if (validate_ports_csv(options->RejectPlaintextPorts,
3244 "RejectPlaintextPorts", msg) < 0)
3245 return -1;
3247 if (validate_ports_csv(options->WarnPlaintextPorts,
3248 "WarnPlaintextPorts", msg) < 0)
3249 return -1;
3251 if (options->FascistFirewall && !options->ReachableAddresses) {
3252 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3253 /* We already have firewall ports set, so migrate them to
3254 * ReachableAddresses, which will set ReachableORAddresses and
3255 * ReachableDirAddresses if they aren't set explicitly. */
3256 smartlist_t *instead = smartlist_create();
3257 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3258 new_line->key = tor_strdup("ReachableAddresses");
3259 /* If we're configured with the old format, we need to prepend some
3260 * open ports. */
3261 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3263 int p = atoi(portno);
3264 char *s;
3265 if (p<0) continue;
3266 s = tor_malloc(16);
3267 tor_snprintf(s, 16, "*:%d", p);
3268 smartlist_add(instead, s);
3270 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3271 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3272 log(LOG_NOTICE, LD_CONFIG,
3273 "Converting FascistFirewall and FirewallPorts "
3274 "config options to new format: \"ReachableAddresses %s\"",
3275 new_line->value);
3276 options->ReachableAddresses = new_line;
3277 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3278 smartlist_free(instead);
3279 } else {
3280 /* We do not have FirewallPorts set, so add 80 to
3281 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3282 if (!options->ReachableDirAddresses) {
3283 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3284 new_line->key = tor_strdup("ReachableDirAddresses");
3285 new_line->value = tor_strdup("*:80");
3286 options->ReachableDirAddresses = new_line;
3287 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3288 "to new format: \"ReachableDirAddresses *:80\"");
3290 if (!options->ReachableORAddresses) {
3291 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3292 new_line->key = tor_strdup("ReachableORAddresses");
3293 new_line->value = tor_strdup("*:443");
3294 options->ReachableORAddresses = new_line;
3295 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3296 "to new format: \"ReachableORAddresses *:443\"");
3301 for (i=0; i<3; i++) {
3302 config_line_t **linep =
3303 (i==0) ? &options->ReachableAddresses :
3304 (i==1) ? &options->ReachableORAddresses :
3305 &options->ReachableDirAddresses;
3306 if (!*linep)
3307 continue;
3308 /* We need to end with a reject *:*, not an implicit accept *:* */
3309 for (;;) {
3310 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
3311 break;
3312 linep = &((*linep)->next);
3313 if (!*linep) {
3314 *linep = tor_malloc_zero(sizeof(config_line_t));
3315 (*linep)->key = tor_strdup(
3316 (i==0) ? "ReachableAddresses" :
3317 (i==1) ? "ReachableORAddresses" :
3318 "ReachableDirAddresses");
3319 (*linep)->value = tor_strdup("reject *:*");
3320 break;
3325 if ((options->ReachableAddresses ||
3326 options->ReachableORAddresses ||
3327 options->ReachableDirAddresses) &&
3328 server_mode(options))
3329 REJECT("Servers must be able to freely connect to the rest "
3330 "of the Internet, so they must not set Reachable*Addresses "
3331 "or FascistFirewall.");
3333 if (options->UseBridges &&
3334 server_mode(options))
3335 REJECT("Servers must be able to freely connect to the rest "
3336 "of the Internet, so they must not set UseBridges.");
3338 options->_AllowInvalid = 0;
3339 if (options->AllowInvalidNodes) {
3340 SMARTLIST_FOREACH(options->AllowInvalidNodes, const char *, cp, {
3341 if (!strcasecmp(cp, "entry"))
3342 options->_AllowInvalid |= ALLOW_INVALID_ENTRY;
3343 else if (!strcasecmp(cp, "exit"))
3344 options->_AllowInvalid |= ALLOW_INVALID_EXIT;
3345 else if (!strcasecmp(cp, "middle"))
3346 options->_AllowInvalid |= ALLOW_INVALID_MIDDLE;
3347 else if (!strcasecmp(cp, "introduction"))
3348 options->_AllowInvalid |= ALLOW_INVALID_INTRODUCTION;
3349 else if (!strcasecmp(cp, "rendezvous"))
3350 options->_AllowInvalid |= ALLOW_INVALID_RENDEZVOUS;
3351 else {
3352 r = tor_snprintf(buf, sizeof(buf),
3353 "Unrecognized value '%s' in AllowInvalidNodes", cp);
3354 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3355 return -1;
3360 if (compute_publishserverdescriptor(options) < 0) {
3361 r = tor_snprintf(buf, sizeof(buf),
3362 "Unrecognized value in PublishServerDescriptor");
3363 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3364 return -1;
3367 if ((options->BridgeRelay
3368 || options->_PublishServerDescriptor & BRIDGE_AUTHORITY)
3369 && (options->_PublishServerDescriptor
3370 & (V1_AUTHORITY|V2_AUTHORITY|V3_AUTHORITY))) {
3371 REJECT("Bridges are not supposed to publish router descriptors to the "
3372 "directory authorities. Please correct your "
3373 "PublishServerDescriptor line.");
3376 if (options->MinUptimeHidServDirectoryV2 < 0) {
3377 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3378 "least 0 seconds. Changing to 0.");
3379 options->MinUptimeHidServDirectoryV2 = 0;
3382 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
3383 log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
3384 "raising to %d seconds.", MIN_REND_POST_PERIOD);
3385 options->RendPostPeriod = MIN_REND_POST_PERIOD;
3388 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3389 log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3390 MAX_DIR_PERIOD);
3391 options->RendPostPeriod = MAX_DIR_PERIOD;
3394 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3395 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3396 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3397 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3400 if (options->CircuitStreamTimeout &&
3401 options->CircuitStreamTimeout < MIN_CIRCUIT_STREAM_TIMEOUT) {
3402 log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
3403 "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
3404 options->CircuitStreamTimeout = MIN_CIRCUIT_STREAM_TIMEOUT;
3407 if (options->KeepalivePeriod < 1)
3408 REJECT("KeepalivePeriod option must be positive.");
3410 if (ensure_bandwidth_cap(&options->BandwidthRate,
3411 "BandwidthRate", msg) < 0)
3412 return -1;
3413 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3414 "BandwidthBurst", msg) < 0)
3415 return -1;
3416 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3417 "MaxAdvertisedBandwidth", msg) < 0)
3418 return -1;
3419 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3420 "RelayBandwidthRate", msg) < 0)
3421 return -1;
3422 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3423 "RelayBandwidthBurst", msg) < 0)
3424 return -1;
3426 if (server_mode(options)) {
3427 if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3428 r = tor_snprintf(buf, sizeof(buf),
3429 "BandwidthRate is set to %d bytes/second. "
3430 "For servers, it must be at least %d.",
3431 (int)options->BandwidthRate,
3432 ROUTER_REQUIRED_MIN_BANDWIDTH);
3433 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3434 return -1;
3435 } else if (options->MaxAdvertisedBandwidth <
3436 ROUTER_REQUIRED_MIN_BANDWIDTH/2) {
3437 r = tor_snprintf(buf, sizeof(buf),
3438 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3439 "For servers, it must be at least %d.",
3440 (int)options->MaxAdvertisedBandwidth,
3441 ROUTER_REQUIRED_MIN_BANDWIDTH/2);
3442 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3443 return -1;
3445 if (options->RelayBandwidthRate &&
3446 options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3447 r = tor_snprintf(buf, sizeof(buf),
3448 "RelayBandwidthRate is set to %d bytes/second. "
3449 "For servers, it must be at least %d.",
3450 (int)options->RelayBandwidthRate,
3451 ROUTER_REQUIRED_MIN_BANDWIDTH);
3452 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3453 return -1;
3457 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3458 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3460 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3461 REJECT("RelayBandwidthBurst must be at least equal "
3462 "to RelayBandwidthRate.");
3464 if (options->BandwidthRate > options->BandwidthBurst)
3465 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3467 /* if they set relaybandwidth* really high but left bandwidth*
3468 * at the default, raise the defaults. */
3469 if (options->RelayBandwidthRate > options->BandwidthRate)
3470 options->BandwidthRate = options->RelayBandwidthRate;
3471 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3472 options->BandwidthBurst = options->RelayBandwidthBurst;
3474 if (accounting_parse_options(options, 1)<0)
3475 REJECT("Failed to parse accounting options. See logs for details.");
3477 if (options->HttpProxy) { /* parse it now */
3478 if (tor_addr_port_parse(options->HttpProxy,
3479 &options->HttpProxyAddr, &options->HttpProxyPort) < 0)
3480 REJECT("HttpProxy failed to parse or resolve. Please fix.");
3481 if (options->HttpProxyPort == 0) { /* give it a default */
3482 options->HttpProxyPort = 80;
3486 if (options->HttpProxyAuthenticator) {
3487 if (strlen(options->HttpProxyAuthenticator) >= 48)
3488 REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
3491 if (options->HttpsProxy) { /* parse it now */
3492 if (tor_addr_port_parse(options->HttpsProxy,
3493 &options->HttpsProxyAddr, &options->HttpsProxyPort) <0)
3494 REJECT("HttpsProxy failed to parse or resolve. Please fix.");
3495 if (options->HttpsProxyPort == 0) { /* give it a default */
3496 options->HttpsProxyPort = 443;
3500 if (options->HttpsProxyAuthenticator) {
3501 if (strlen(options->HttpsProxyAuthenticator) >= 48)
3502 REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
3505 if (options->Socks4Proxy) { /* parse it now */
3506 if (tor_addr_port_parse(options->Socks4Proxy,
3507 &options->Socks4ProxyAddr,
3508 &options->Socks4ProxyPort) <0)
3509 REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
3510 if (options->Socks4ProxyPort == 0) { /* give it a default */
3511 options->Socks4ProxyPort = 1080;
3515 if (options->Socks5Proxy) { /* parse it now */
3516 if (tor_addr_port_parse(options->Socks5Proxy,
3517 &options->Socks5ProxyAddr,
3518 &options->Socks5ProxyPort) <0)
3519 REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
3520 if (options->Socks5ProxyPort == 0) { /* give it a default */
3521 options->Socks5ProxyPort = 1080;
3525 if (options->Socks4Proxy && options->Socks5Proxy)
3526 REJECT("You cannot specify both Socks4Proxy and SOCKS5Proxy");
3528 if (options->Socks5ProxyUsername) {
3529 size_t len;
3531 len = strlen(options->Socks5ProxyUsername);
3532 if (len < 1 || len > 255)
3533 REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
3535 if (!options->Socks5ProxyPassword)
3536 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3538 len = strlen(options->Socks5ProxyPassword);
3539 if (len < 1 || len > 255)
3540 REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
3541 } else if (options->Socks5ProxyPassword)
3542 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3544 if (options->HashedControlPassword) {
3545 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3546 if (!sl) {
3547 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3548 } else {
3549 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3550 smartlist_free(sl);
3554 if (options->HashedControlSessionPassword) {
3555 smartlist_t *sl = decode_hashed_passwords(
3556 options->HashedControlSessionPassword);
3557 if (!sl) {
3558 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3559 } else {
3560 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3561 smartlist_free(sl);
3565 if (options->ControlListenAddress) {
3566 int all_are_local = 1;
3567 config_line_t *ln;
3568 for (ln = options->ControlListenAddress; ln; ln = ln->next) {
3569 if (strcmpstart(ln->value, "127."))
3570 all_are_local = 0;
3572 if (!all_are_local) {
3573 if (!options->HashedControlPassword &&
3574 !options->HashedControlSessionPassword &&
3575 !options->CookieAuthentication) {
3576 log_warn(LD_CONFIG,
3577 "You have a ControlListenAddress set to accept "
3578 "unauthenticated connections from a non-local address. "
3579 "This means that programs not running on your computer "
3580 "can reconfigure your Tor, without even having to guess a "
3581 "password. That's so bad that I'm closing your ControlPort "
3582 "for you. If you need to control your Tor remotely, try "
3583 "enabling authentication and using a tool like stunnel or "
3584 "ssh to encrypt remote access.");
3585 options->ControlPort = 0;
3586 } else {
3587 log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
3588 "connections from a non-local address. This means that "
3589 "programs not running on your computer can reconfigure your "
3590 "Tor. That's pretty bad, since the controller "
3591 "protocol isn't encrypted! Maybe you should just listen on "
3592 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
3593 "remote connections to your control port.");
3598 if (options->ControlPort && !options->HashedControlPassword &&
3599 !options->HashedControlSessionPassword &&
3600 !options->CookieAuthentication) {
3601 log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
3602 "has been configured. This means that any program on your "
3603 "computer can reconfigure your Tor. That's bad! You should "
3604 "upgrade your Tor controller as soon as possible.");
3607 if (options->UseEntryGuards && ! options->NumEntryGuards)
3608 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3610 if (check_nickname_list(options->MyFamily, "MyFamily", msg))
3611 return -1;
3612 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3613 if (check_nickname_list(cl->value, "NodeFamily", msg))
3614 return -1;
3617 if (validate_addr_policies(options, msg) < 0)
3618 return -1;
3620 if (validate_dir_authorities(options, old_options) < 0)
3621 REJECT("Directory authority line did not parse. See logs for details.");
3623 if (options->UseBridges && !options->Bridges)
3624 REJECT("If you set UseBridges, you must specify at least one bridge.");
3625 if (options->UseBridges && !options->TunnelDirConns)
3626 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3627 if (options->Bridges) {
3628 for (cl = options->Bridges; cl; cl = cl->next) {
3629 if (parse_bridge_line(cl->value, 1)<0)
3630 REJECT("Bridge line did not parse. See logs for details.");
3634 if (options->ConstrainedSockets) {
3635 /* If the user wants to constrain socket buffer use, make sure the desired
3636 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3637 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3638 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3639 options->ConstrainedSockSize % 1024) {
3640 r = tor_snprintf(buf, sizeof(buf),
3641 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3642 "in 1024 byte increments.",
3643 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3644 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3645 return -1;
3647 if (options->DirPort) {
3648 /* Providing cached directory entries while system TCP buffers are scarce
3649 * will exacerbate the socket errors. Suggest that this be disabled. */
3650 COMPLAIN("You have requested constrained socket buffers while also "
3651 "serving directory entries via DirPort. It is strongly "
3652 "suggested that you disable serving directory requests when "
3653 "system TCP buffer resources are scarce.");
3657 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3658 options->V3AuthVotingInterval/2) {
3659 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3660 "V3AuthVotingInterval");
3662 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
3663 REJECT("V3AuthVoteDelay is way too low.");
3664 if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
3665 REJECT("V3AuthDistDelay is way too low.");
3667 if (options->V3AuthNIntervalsValid < 2)
3668 REJECT("V3AuthNIntervalsValid must be at least 2.");
3670 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3671 REJECT("V3AuthVotingInterval is insanely low.");
3672 } else if (options->V3AuthVotingInterval > 24*60*60) {
3673 REJECT("V3AuthVotingInterval is insanely high.");
3674 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3675 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3678 if (rend_config_services(options, 1) < 0)
3679 REJECT("Failed to configure rendezvous options. See logs for details.");
3681 /* Parse client-side authorization for hidden services. */
3682 if (rend_parse_service_authorization(options, 1) < 0)
3683 REJECT("Failed to configure client authorization for hidden services. "
3684 "See logs for details.");
3686 if (parse_virtual_addr_network(options->VirtualAddrNetwork, 1, NULL)<0)
3687 return -1;
3689 if (options->PreferTunneledDirConns && !options->TunnelDirConns)
3690 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3692 if ((options->Socks4Proxy || options->Socks5Proxy) &&
3693 !options->HttpProxy && !options->PreferTunneledDirConns)
3694 REJECT("When Socks4Proxy or Socks5Proxy is configured, "
3695 "PreferTunneledDirConns and TunnelDirConns must both be "
3696 "set to 1, or HttpProxy must be configured.");
3698 if (options->AutomapHostsSuffixes) {
3699 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
3701 size_t len = strlen(suf);
3702 if (len && suf[len-1] == '.')
3703 suf[len-1] = '\0';
3707 if (options->TestingTorNetwork && !options->DirServers) {
3708 REJECT("TestingTorNetwork may only be configured in combination with "
3709 "a non-default set of DirServers.");
3712 /*XXXX022 checking for defaults manually like this is a bit fragile.*/
3714 /* Keep changes to hard-coded values synchronous to man page and default
3715 * values table. */
3716 if (options->TestingV3AuthInitialVotingInterval != 30*60 &&
3717 !options->TestingTorNetwork) {
3718 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
3719 "Tor networks!");
3720 } else if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
3721 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3722 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
3723 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3724 "30 minutes.");
3727 if (options->TestingV3AuthInitialVoteDelay != 5*60 &&
3728 !options->TestingTorNetwork) {
3729 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
3730 "Tor networks!");
3731 } else if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
3732 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3735 if (options->TestingV3AuthInitialDistDelay != 5*60 &&
3736 !options->TestingTorNetwork) {
3737 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
3738 "Tor networks!");
3739 } else if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
3740 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3743 if (options->TestingV3AuthInitialVoteDelay +
3744 options->TestingV3AuthInitialDistDelay >=
3745 options->TestingV3AuthInitialVotingInterval/2) {
3746 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3747 "must be less than half TestingV3AuthInitialVotingInterval");
3750 if (options->TestingAuthDirTimeToLearnReachability != 30*60 &&
3751 !options->TestingTorNetwork) {
3752 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
3753 "testing Tor networks!");
3754 } else if (options->TestingAuthDirTimeToLearnReachability < 0) {
3755 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3756 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
3757 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3760 if (options->TestingEstimatedDescriptorPropagationTime != 10*60 &&
3761 !options->TestingTorNetwork) {
3762 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
3763 "testing Tor networks!");
3764 } else if (options->TestingEstimatedDescriptorPropagationTime < 0) {
3765 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3766 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
3767 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3770 if (options->TestingTorNetwork) {
3771 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
3772 "almost unusable in the public Tor network, and is "
3773 "therefore only advised if you are building a "
3774 "testing Tor network!");
3777 if (options->AccelName && !options->HardwareAccel)
3778 options->HardwareAccel = 1;
3779 if (options->AccelDir && !options->AccelName)
3780 REJECT("Can't use hardware crypto accelerator dir without engine name.");
3782 return 0;
3783 #undef REJECT
3784 #undef COMPLAIN
3787 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3788 * equal strings. */
3789 static int
3790 opt_streq(const char *s1, const char *s2)
3792 if (!s1 && !s2)
3793 return 1;
3794 else if (s1 && s2 && !strcmp(s1,s2))
3795 return 1;
3796 else
3797 return 0;
3800 /** Check if any of the previous options have changed but aren't allowed to. */
3801 static int
3802 options_transition_allowed(or_options_t *old, or_options_t *new_val,
3803 char **msg)
3805 if (!old)
3806 return 0;
3808 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3809 *msg = tor_strdup("PidFile is not allowed to change.");
3810 return -1;
3813 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3814 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3815 "is not allowed.");
3816 return -1;
3819 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
3820 char buf[1024];
3821 int r = tor_snprintf(buf, sizeof(buf),
3822 "While Tor is running, changing DataDirectory "
3823 "(\"%s\"->\"%s\") is not allowed.",
3824 old->DataDirectory, new_val->DataDirectory);
3825 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3826 return -1;
3829 if (!opt_streq(old->User, new_val->User)) {
3830 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
3831 return -1;
3834 if (!opt_streq(old->Group, new_val->Group)) {
3835 *msg = tor_strdup("While Tor is running, changing Group is not allowed.");
3836 return -1;
3839 if ((old->HardwareAccel != new_val->HardwareAccel)
3840 || !opt_streq(old->AccelName, new_val->AccelName)
3841 || !opt_streq(old->AccelDir, new_val->AccelDir)) {
3842 *msg = tor_strdup("While Tor is running, changing OpenSSL hardware "
3843 "acceleration engine is not allowed.");
3844 return -1;
3847 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
3848 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
3849 "is not allowed.");
3850 return -1;
3853 if (old->CellStatistics != new_val->CellStatistics ||
3854 old->DirReqStatistics != new_val->DirReqStatistics ||
3855 old->EntryStatistics != new_val->EntryStatistics ||
3856 old->ExitPortStatistics != new_val->ExitPortStatistics) {
3857 *msg = tor_strdup("While Tor is running, changing either "
3858 "CellStatistics, DirReqStatistics, EntryStatistics, "
3859 "or ExitPortStatistics is not allowed.");
3860 return -1;
3863 if (old->DisableAllSwap != new_val->DisableAllSwap) {
3864 *msg = tor_strdup("While Tor is running, changing DisableAllSwap "
3865 "is not allowed.");
3866 return -1;
3869 return 0;
3872 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3873 * will require us to rotate the CPU and DNS workers; else return 0. */
3874 static int
3875 options_transition_affects_workers(or_options_t *old_options,
3876 or_options_t *new_options)
3878 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3879 old_options->NumCpus != new_options->NumCpus ||
3880 old_options->ORPort != new_options->ORPort ||
3881 old_options->ServerDNSSearchDomains !=
3882 new_options->ServerDNSSearchDomains ||
3883 old_options->SafeLogging != new_options->SafeLogging ||
3884 old_options->ClientOnly != new_options->ClientOnly ||
3885 !config_lines_eq(old_options->Logs, new_options->Logs))
3886 return 1;
3888 /* Check whether log options match. */
3890 /* Nothing that changed matters. */
3891 return 0;
3894 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3895 * will require us to generate a new descriptor; else return 0. */
3896 static int
3897 options_transition_affects_descriptor(or_options_t *old_options,
3898 or_options_t *new_options)
3900 /* XXX We can be smarter here. If your DirPort isn't being
3901 * published and you just turned it off, no need to republish. Etc. */
3902 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3903 !opt_streq(old_options->Nickname,new_options->Nickname) ||
3904 !opt_streq(old_options->Address,new_options->Address) ||
3905 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
3906 old_options->ExitPolicyRejectPrivate !=
3907 new_options->ExitPolicyRejectPrivate ||
3908 old_options->ORPort != new_options->ORPort ||
3909 old_options->DirPort != new_options->DirPort ||
3910 old_options->ClientOnly != new_options->ClientOnly ||
3911 old_options->NoPublish != new_options->NoPublish ||
3912 old_options->_PublishServerDescriptor !=
3913 new_options->_PublishServerDescriptor ||
3914 get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
3915 get_effective_bwburst(old_options) !=
3916 get_effective_bwburst(new_options) ||
3917 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
3918 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
3919 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
3920 old_options->AccountingMax != new_options->AccountingMax)
3921 return 1;
3923 return 0;
3926 #ifdef MS_WINDOWS
3927 /** Return the directory on windows where we expect to find our application
3928 * data. */
3929 static char *
3930 get_windows_conf_root(void)
3932 static int is_set = 0;
3933 static char path[MAX_PATH+1];
3935 LPITEMIDLIST idl;
3936 IMalloc *m;
3937 HRESULT result;
3939 if (is_set)
3940 return path;
3942 /* Find X:\documents and settings\username\application data\ .
3943 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3945 #ifdef ENABLE_LOCAL_APPDATA
3946 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
3947 #else
3948 #define APPDATA_PATH CSIDL_APPDATA
3949 #endif
3950 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
3951 GetCurrentDirectory(MAX_PATH, path);
3952 is_set = 1;
3953 log_warn(LD_CONFIG,
3954 "I couldn't find your application data folder: are you "
3955 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3956 path);
3957 return path;
3959 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3960 result = SHGetPathFromIDList(idl, path);
3961 /* Now we need to free the */
3962 SHGetMalloc(&m);
3963 if (m) {
3964 m->lpVtbl->Free(m, idl);
3965 m->lpVtbl->Release(m);
3967 if (!SUCCEEDED(result)) {
3968 return NULL;
3970 strlcat(path,"\\tor",MAX_PATH);
3971 is_set = 1;
3972 return path;
3974 #endif
3976 /** Return the default location for our torrc file. */
3977 static const char *
3978 get_default_conf_file(void)
3980 #ifdef MS_WINDOWS
3981 static char path[MAX_PATH+1];
3982 strlcpy(path, get_windows_conf_root(), MAX_PATH);
3983 strlcat(path,"\\torrc",MAX_PATH);
3984 return path;
3985 #else
3986 return (CONFDIR "/torrc");
3987 #endif
3990 /** Verify whether lst is a string containing valid-looking comma-separated
3991 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3993 static int
3994 check_nickname_list(const char *lst, const char *name, char **msg)
3996 int r = 0;
3997 smartlist_t *sl;
3999 if (!lst)
4000 return 0;
4001 sl = smartlist_create();
4003 smartlist_split_string(sl, lst, ",",
4004 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
4006 SMARTLIST_FOREACH(sl, const char *, s,
4008 if (!is_legal_nickname_or_hexdigest(s)) {
4009 char buf[1024];
4010 int tmp = tor_snprintf(buf, sizeof(buf),
4011 "Invalid nickname '%s' in %s line", s, name);
4012 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
4013 r = -1;
4014 break;
4017 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
4018 smartlist_free(sl);
4019 return r;
4022 /** Learn config file name from command line arguments, or use the default */
4023 static char *
4024 find_torrc_filename(int argc, char **argv,
4025 int *using_default_torrc, int *ignore_missing_torrc)
4027 char *fname=NULL;
4028 int i;
4030 for (i = 1; i < argc; ++i) {
4031 if (i < argc-1 && !strcmp(argv[i],"-f")) {
4032 if (fname) {
4033 log(LOG_WARN, LD_CONFIG, "Duplicate -f options on command line.");
4034 tor_free(fname);
4036 #ifdef MS_WINDOWS
4037 /* XXX one day we might want to extend expand_filename to work
4038 * under Windows as well. */
4039 fname = tor_strdup(argv[i+1]);
4040 #else
4041 fname = expand_filename(argv[i+1]);
4042 #endif
4043 *using_default_torrc = 0;
4044 ++i;
4045 } else if (!strcmp(argv[i],"--ignore-missing-torrc")) {
4046 *ignore_missing_torrc = 1;
4050 if (*using_default_torrc) {
4051 /* didn't find one, try CONFDIR */
4052 const char *dflt = get_default_conf_file();
4053 if (dflt && file_status(dflt) == FN_FILE) {
4054 fname = tor_strdup(dflt);
4055 } else {
4056 #ifndef MS_WINDOWS
4057 char *fn;
4058 fn = expand_filename("~/.torrc");
4059 if (fn && file_status(fn) == FN_FILE) {
4060 fname = fn;
4061 } else {
4062 tor_free(fn);
4063 fname = tor_strdup(dflt);
4065 #else
4066 fname = tor_strdup(dflt);
4067 #endif
4070 return fname;
4073 /** Load torrc from disk, setting torrc_fname if successful */
4074 static char *
4075 load_torrc_from_disk(int argc, char **argv)
4077 char *fname=NULL;
4078 char *cf = NULL;
4079 int using_default_torrc = 1;
4080 int ignore_missing_torrc = 0;
4082 fname = find_torrc_filename(argc, argv,
4083 &using_default_torrc, &ignore_missing_torrc);
4084 tor_assert(fname);
4085 log(LOG_DEBUG, LD_CONFIG, "Opening config file \"%s\"", fname);
4087 tor_free(torrc_fname);
4088 torrc_fname = fname;
4090 /* Open config file */
4091 if (file_status(fname) != FN_FILE ||
4092 !(cf = read_file_to_str(fname,0,NULL))) {
4093 if (using_default_torrc == 1 || ignore_missing_torrc ) {
4094 log(LOG_NOTICE, LD_CONFIG, "Configuration file \"%s\" not present, "
4095 "using reasonable defaults.", fname);
4096 tor_free(fname); /* sets fname to NULL */
4097 torrc_fname = NULL;
4098 cf = tor_strdup("");
4099 } else {
4100 log(LOG_WARN, LD_CONFIG,
4101 "Unable to open configuration file \"%s\".", fname);
4102 goto err;
4106 return cf;
4107 err:
4108 tor_free(fname);
4109 torrc_fname = NULL;
4110 return NULL;
4113 /** Read a configuration file into <b>options</b>, finding the configuration
4114 * file location based on the command line. After loading the file
4115 * call options_init_from_string() to load the config.
4116 * Return 0 if success, -1 if failure. */
4118 options_init_from_torrc(int argc, char **argv)
4120 char *cf=NULL;
4121 int i, retval, command;
4122 static char **backup_argv;
4123 static int backup_argc;
4124 char *command_arg = NULL;
4125 char *errmsg=NULL;
4127 if (argv) { /* first time we're called. save command line args */
4128 backup_argv = argv;
4129 backup_argc = argc;
4130 } else { /* we're reloading. need to clean up old options first. */
4131 argv = backup_argv;
4132 argc = backup_argc;
4134 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
4135 print_usage();
4136 exit(0);
4138 if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
4139 /* For documenting validating whether we've documented everything. */
4140 list_torrc_options();
4141 exit(0);
4144 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
4145 printf("Tor version %s.\n",get_version());
4146 exit(0);
4148 if (argc > 1 && (!strcmp(argv[1],"--digests"))) {
4149 printf("Tor version %s.\n",get_version());
4150 printf("%s", libor_get_digests());
4151 printf("%s", tor_get_digests());
4152 exit(0);
4155 /* Go through command-line variables */
4156 if (!global_cmdline_options) {
4157 /* Or we could redo the list every time we pass this place.
4158 * It does not really matter */
4159 if (config_get_commandlines(argc, argv, &global_cmdline_options) < 0) {
4160 goto err;
4164 command = CMD_RUN_TOR;
4165 for (i = 1; i < argc; ++i) {
4166 if (!strcmp(argv[i],"--list-fingerprint")) {
4167 command = CMD_LIST_FINGERPRINT;
4168 } else if (!strcmp(argv[i],"--hash-password")) {
4169 command = CMD_HASH_PASSWORD;
4170 command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
4171 ++i;
4172 } else if (!strcmp(argv[i],"--verify-config")) {
4173 command = CMD_VERIFY_CONFIG;
4177 if (command == CMD_HASH_PASSWORD) {
4178 cf = tor_strdup("");
4179 } else {
4180 cf = load_torrc_from_disk(argc, argv);
4181 if (!cf)
4182 goto err;
4185 retval = options_init_from_string(cf, command, command_arg, &errmsg);
4186 tor_free(cf);
4187 if (retval < 0)
4188 goto err;
4190 return 0;
4192 err:
4193 if (errmsg) {
4194 log(LOG_WARN,LD_CONFIG,"%s", errmsg);
4195 tor_free(errmsg);
4197 return -1;
4200 /** Load the options from the configuration in <b>cf</b>, validate
4201 * them for consistency and take actions based on them.
4203 * Return 0 if success, negative on error:
4204 * * -1 for general errors.
4205 * * -2 for failure to parse/validate,
4206 * * -3 for transition not allowed
4207 * * -4 for error while setting the new options
4209 setopt_err_t
4210 options_init_from_string(const char *cf,
4211 int command, const char *command_arg,
4212 char **msg)
4214 or_options_t *oldoptions, *newoptions;
4215 config_line_t *cl;
4216 int retval;
4217 setopt_err_t err = SETOPT_ERR_MISC;
4218 tor_assert(msg);
4220 oldoptions = global_options; /* get_options unfortunately asserts if
4221 this is the first time we run*/
4223 newoptions = tor_malloc_zero(sizeof(or_options_t));
4224 newoptions->_magic = OR_OPTIONS_MAGIC;
4225 options_init(newoptions);
4226 newoptions->command = command;
4227 newoptions->command_arg = command_arg;
4229 /* get config lines, assign them */
4230 retval = config_get_lines(cf, &cl);
4231 if (retval < 0) {
4232 err = SETOPT_ERR_PARSE;
4233 goto err;
4235 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4236 config_free_lines(cl);
4237 if (retval < 0) {
4238 err = SETOPT_ERR_PARSE;
4239 goto err;
4242 /* Go through command-line variables too */
4243 retval = config_assign(&options_format, newoptions,
4244 global_cmdline_options, 0, 0, msg);
4245 if (retval < 0) {
4246 err = SETOPT_ERR_PARSE;
4247 goto err;
4250 /* If this is a testing network configuration, change defaults
4251 * for a list of dependent config options, re-initialize newoptions
4252 * with the new defaults, and assign all options to it second time. */
4253 if (newoptions->TestingTorNetwork) {
4254 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4255 * this? We could, for example, make the parsing algorithm do two passes
4256 * over the configuration. If it finds any "suite" options like
4257 * TestingTorNetwork, it could change the defaults before its second pass.
4258 * Not urgent so long as this seems to work, but at any sign of trouble,
4259 * let's clean it up. -NM */
4261 /* Change defaults. */
4262 int i;
4263 for (i = 0; testing_tor_network_defaults[i].name; ++i) {
4264 config_var_t *new_var = &testing_tor_network_defaults[i];
4265 config_var_t *old_var =
4266 config_find_option(&options_format, new_var->name);
4267 tor_assert(new_var);
4268 tor_assert(old_var);
4269 old_var->initvalue = new_var->initvalue;
4272 /* Clear newoptions and re-initialize them with new defaults. */
4273 config_free(&options_format, newoptions);
4274 newoptions = tor_malloc_zero(sizeof(or_options_t));
4275 newoptions->_magic = OR_OPTIONS_MAGIC;
4276 options_init(newoptions);
4277 newoptions->command = command;
4278 newoptions->command_arg = command_arg;
4280 /* Assign all options a second time. */
4281 retval = config_get_lines(cf, &cl);
4282 if (retval < 0) {
4283 err = SETOPT_ERR_PARSE;
4284 goto err;
4286 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4287 config_free_lines(cl);
4288 if (retval < 0) {
4289 err = SETOPT_ERR_PARSE;
4290 goto err;
4292 retval = config_assign(&options_format, newoptions,
4293 global_cmdline_options, 0, 0, msg);
4294 if (retval < 0) {
4295 err = SETOPT_ERR_PARSE;
4296 goto err;
4300 /* Validate newoptions */
4301 if (options_validate(oldoptions, newoptions, 0, msg) < 0) {
4302 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
4303 goto err;
4306 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
4307 err = SETOPT_ERR_TRANSITION;
4308 goto err;
4311 if (set_options(newoptions, msg)) {
4312 err = SETOPT_ERR_SETTING;
4313 goto err; /* frees and replaces old options */
4316 return SETOPT_OK;
4318 err:
4319 config_free(&options_format, newoptions);
4320 if (*msg) {
4321 int len = (int)strlen(*msg)+256;
4322 char *newmsg = tor_malloc(len);
4324 tor_snprintf(newmsg, len, "Failed to parse/validate config: %s", *msg);
4325 tor_free(*msg);
4326 *msg = newmsg;
4328 return err;
4331 /** Return the location for our configuration file.
4333 const char *
4334 get_torrc_fname(void)
4336 if (torrc_fname)
4337 return torrc_fname;
4338 else
4339 return get_default_conf_file();
4342 /** Adjust the address map based on the MapAddress elements in the
4343 * configuration <b>options</b>
4345 static void
4346 config_register_addressmaps(or_options_t *options)
4348 smartlist_t *elts;
4349 config_line_t *opt;
4350 char *from, *to;
4352 addressmap_clear_configured();
4353 elts = smartlist_create();
4354 for (opt = options->AddressMap; opt; opt = opt->next) {
4355 smartlist_split_string(elts, opt->value, NULL,
4356 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4357 if (smartlist_len(elts) >= 2) {
4358 from = smartlist_get(elts,0);
4359 to = smartlist_get(elts,1);
4360 if (address_is_invalid_destination(to, 1)) {
4361 log_warn(LD_CONFIG,
4362 "Skipping invalid argument '%s' to MapAddress", to);
4363 } else {
4364 addressmap_register(from, tor_strdup(to), 0, ADDRMAPSRC_TORRC);
4365 if (smartlist_len(elts)>2) {
4366 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
4369 } else {
4370 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
4371 opt->value);
4373 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4374 smartlist_clear(elts);
4376 smartlist_free(elts);
4380 * Initialize the logs based on the configuration file.
4382 static int
4383 options_init_logs(or_options_t *options, int validate_only)
4385 config_line_t *opt;
4386 int ok;
4387 smartlist_t *elts;
4388 int daemon =
4389 #ifdef MS_WINDOWS
4391 #else
4392 options->RunAsDaemon;
4393 #endif
4395 ok = 1;
4396 elts = smartlist_create();
4398 for (opt = options->Logs; opt; opt = opt->next) {
4399 log_severity_list_t *severity;
4400 const char *cfg = opt->value;
4401 severity = tor_malloc_zero(sizeof(log_severity_list_t));
4402 if (parse_log_severity_config(&cfg, severity) < 0) {
4403 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
4404 opt->value);
4405 ok = 0; goto cleanup;
4408 smartlist_split_string(elts, cfg, NULL,
4409 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4411 if (smartlist_len(elts) == 0)
4412 smartlist_add(elts, tor_strdup("stdout"));
4414 if (smartlist_len(elts) == 1 &&
4415 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
4416 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
4417 int err = smartlist_len(elts) &&
4418 !strcasecmp(smartlist_get(elts,0), "stderr");
4419 if (!validate_only) {
4420 if (daemon) {
4421 log_warn(LD_CONFIG,
4422 "Can't log to %s with RunAsDaemon set; skipping stdout",
4423 err?"stderr":"stdout");
4424 } else {
4425 add_stream_log(severity, err?"<stderr>":"<stdout>",
4426 fileno(err?stderr:stdout));
4429 goto cleanup;
4431 if (smartlist_len(elts) == 1 &&
4432 !strcasecmp(smartlist_get(elts,0), "syslog")) {
4433 #ifdef HAVE_SYSLOG_H
4434 if (!validate_only) {
4435 add_syslog_log(severity);
4437 #else
4438 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
4439 #endif
4440 goto cleanup;
4443 if (smartlist_len(elts) == 2 &&
4444 !strcasecmp(smartlist_get(elts,0), "file")) {
4445 if (!validate_only) {
4446 if (add_file_log(severity, smartlist_get(elts, 1)) < 0) {
4447 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
4448 opt->value, strerror(errno));
4449 ok = 0;
4452 goto cleanup;
4455 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
4456 opt->value);
4457 ok = 0; goto cleanup;
4459 cleanup:
4460 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4461 smartlist_clear(elts);
4462 tor_free(severity);
4464 smartlist_free(elts);
4466 return ok?0:-1;
4469 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4470 * if the line is well-formed, and -1 if it isn't. If
4471 * <b>validate_only</b> is 0, and the line is well-formed, then add
4472 * the bridge described in the line to our internal bridge list. */
4473 static int
4474 parse_bridge_line(const char *line, int validate_only)
4476 smartlist_t *items = NULL;
4477 int r;
4478 char *addrport=NULL, *fingerprint=NULL;
4479 tor_addr_t addr;
4480 uint16_t port = 0;
4481 char digest[DIGEST_LEN];
4483 items = smartlist_create();
4484 smartlist_split_string(items, line, NULL,
4485 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4486 if (smartlist_len(items) < 1) {
4487 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
4488 goto err;
4490 addrport = smartlist_get(items, 0);
4491 smartlist_del_keeporder(items, 0);
4492 if (tor_addr_port_parse(addrport, &addr, &port)<0) {
4493 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
4494 goto err;
4496 if (!port) {
4497 log_info(LD_CONFIG,
4498 "Bridge address '%s' has no port; using default port 443.",
4499 addrport);
4500 port = 443;
4503 if (smartlist_len(items)) {
4504 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4505 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4506 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
4507 goto err;
4509 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4510 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
4511 goto err;
4515 if (!validate_only) {
4516 log_debug(LD_DIR, "Bridge at %s:%d (%s)", fmt_addr(&addr),
4517 (int)port,
4518 fingerprint ? fingerprint : "no key listed");
4519 bridge_add_from_config(&addr, port, fingerprint ? digest : NULL);
4522 r = 0;
4523 goto done;
4525 err:
4526 r = -1;
4528 done:
4529 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4530 smartlist_free(items);
4531 tor_free(addrport);
4532 tor_free(fingerprint);
4533 return r;
4536 /** Read the contents of a DirServer line from <b>line</b>. If
4537 * <b>validate_only</b> is 0, and the line is well-formed, and it
4538 * shares any bits with <b>required_type</b> or <b>required_type</b>
4539 * is 0, then add the dirserver described in the line (minus whatever
4540 * bits it's missing) as a valid authority. Return 0 on success,
4541 * or -1 if the line isn't well-formed or if we can't add it. */
4542 static int
4543 parse_dir_server_line(const char *line, authority_type_t required_type,
4544 int validate_only)
4546 smartlist_t *items = NULL;
4547 int r;
4548 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
4549 uint16_t dir_port = 0, or_port = 0;
4550 char digest[DIGEST_LEN];
4551 char v3_digest[DIGEST_LEN];
4552 authority_type_t type = V2_AUTHORITY;
4553 int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
4555 items = smartlist_create();
4556 smartlist_split_string(items, line, NULL,
4557 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4558 if (smartlist_len(items) < 1) {
4559 log_warn(LD_CONFIG, "No arguments on DirServer line.");
4560 goto err;
4563 if (is_legal_nickname(smartlist_get(items, 0))) {
4564 nickname = smartlist_get(items, 0);
4565 smartlist_del_keeporder(items, 0);
4568 while (smartlist_len(items)) {
4569 char *flag = smartlist_get(items, 0);
4570 if (TOR_ISDIGIT(flag[0]))
4571 break;
4572 if (!strcasecmp(flag, "v1")) {
4573 type |= (V1_AUTHORITY | HIDSERV_AUTHORITY);
4574 } else if (!strcasecmp(flag, "hs")) {
4575 type |= HIDSERV_AUTHORITY;
4576 } else if (!strcasecmp(flag, "no-hs")) {
4577 is_not_hidserv_authority = 1;
4578 } else if (!strcasecmp(flag, "bridge")) {
4579 type |= BRIDGE_AUTHORITY;
4580 } else if (!strcasecmp(flag, "no-v2")) {
4581 is_not_v2_authority = 1;
4582 } else if (!strcasecmpstart(flag, "orport=")) {
4583 int ok;
4584 char *portstring = flag + strlen("orport=");
4585 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
4586 if (!ok)
4587 log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
4588 portstring);
4589 } else if (!strcasecmpstart(flag, "v3ident=")) {
4590 char *idstr = flag + strlen("v3ident=");
4591 if (strlen(idstr) != HEX_DIGEST_LEN ||
4592 base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
4593 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirServer line",
4594 flag);
4595 } else {
4596 type |= V3_AUTHORITY;
4598 } else {
4599 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
4600 flag);
4602 tor_free(flag);
4603 smartlist_del_keeporder(items, 0);
4605 if (is_not_hidserv_authority)
4606 type &= ~HIDSERV_AUTHORITY;
4607 if (is_not_v2_authority)
4608 type &= ~V2_AUTHORITY;
4610 if (smartlist_len(items) < 2) {
4611 log_warn(LD_CONFIG, "Too few arguments to DirServer line.");
4612 goto err;
4614 addrport = smartlist_get(items, 0);
4615 smartlist_del_keeporder(items, 0);
4616 if (parse_addr_port(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
4617 log_warn(LD_CONFIG, "Error parsing DirServer address '%s'", addrport);
4618 goto err;
4620 if (!dir_port) {
4621 log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
4622 goto err;
4625 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4626 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4627 log_warn(LD_CONFIG, "Key digest for DirServer is wrong length %d.",
4628 (int)strlen(fingerprint));
4629 goto err;
4631 if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4632 /* a known bad fingerprint. refuse to use it. We can remove this
4633 * clause once Tor 0.1.2.17 is obsolete. */
4634 log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
4635 "torrc file (%s), or reinstall Tor and use the default torrc.",
4636 get_torrc_fname());
4637 goto err;
4639 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4640 log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
4641 goto err;
4644 if (!validate_only && (!required_type || required_type & type)) {
4645 if (required_type)
4646 type &= required_type; /* pare down what we think of them as an
4647 * authority for. */
4648 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
4649 address, (int)dir_port, (char*)smartlist_get(items,0));
4650 if (!add_trusted_dir_server(nickname, address, dir_port, or_port,
4651 digest, v3_digest, type))
4652 goto err;
4655 r = 0;
4656 goto done;
4658 err:
4659 r = -1;
4661 done:
4662 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4663 smartlist_free(items);
4664 tor_free(addrport);
4665 tor_free(address);
4666 tor_free(nickname);
4667 tor_free(fingerprint);
4668 return r;
4671 /** Adjust the value of options->DataDirectory, or fill it in if it's
4672 * absent. Return 0 on success, -1 on failure. */
4673 static int
4674 normalize_data_directory(or_options_t *options)
4676 #ifdef MS_WINDOWS
4677 char *p;
4678 if (options->DataDirectory)
4679 return 0; /* all set */
4680 p = tor_malloc(MAX_PATH);
4681 strlcpy(p,get_windows_conf_root(),MAX_PATH);
4682 options->DataDirectory = p;
4683 return 0;
4684 #else
4685 const char *d = options->DataDirectory;
4686 if (!d)
4687 d = "~/.tor";
4689 if (strncmp(d,"~/",2) == 0) {
4690 char *fn = expand_filename(d);
4691 if (!fn) {
4692 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
4693 return -1;
4695 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
4696 /* If our homedir is /, we probably don't want to use it. */
4697 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4698 * want. */
4699 log_warn(LD_CONFIG,
4700 "Default DataDirectory is \"~/.tor\". This expands to "
4701 "\"%s\", which is probably not what you want. Using "
4702 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
4703 tor_free(fn);
4704 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
4706 tor_free(options->DataDirectory);
4707 options->DataDirectory = fn;
4709 return 0;
4710 #endif
4713 /** Check and normalize the value of options->DataDirectory; return 0 if it
4714 * sane, -1 otherwise. */
4715 static int
4716 validate_data_directory(or_options_t *options)
4718 if (normalize_data_directory(options) < 0)
4719 return -1;
4720 tor_assert(options->DataDirectory);
4721 if (strlen(options->DataDirectory) > (512-128)) {
4722 log_warn(LD_CONFIG, "DataDirectory is too long.");
4723 return -1;
4725 return 0;
4728 /** This string must remain the same forevermore. It is how we
4729 * recognize that the torrc file doesn't need to be backed up. */
4730 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4731 "if you edit it, comments will not be preserved"
4732 /** This string can change; it tries to give the reader an idea
4733 * that editing this file by hand is not a good plan. */
4734 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4735 "to torrc.orig.1 or similar, and Tor will ignore it"
4737 /** Save a configuration file for the configuration in <b>options</b>
4738 * into the file <b>fname</b>. If the file already exists, and
4739 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4740 * replace it. Return 0 on success, -1 on failure. */
4741 static int
4742 write_configuration_file(const char *fname, or_options_t *options)
4744 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4745 int rename_old = 0, r;
4746 size_t len;
4748 tor_assert(fname);
4750 switch (file_status(fname)) {
4751 case FN_FILE:
4752 old_val = read_file_to_str(fname, 0, NULL);
4753 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4754 rename_old = 1;
4756 tor_free(old_val);
4757 break;
4758 case FN_NOENT:
4759 break;
4760 case FN_ERROR:
4761 case FN_DIR:
4762 default:
4763 log_warn(LD_CONFIG,
4764 "Config file \"%s\" is not a file? Failing.", fname);
4765 return -1;
4768 if (!(new_conf = options_dump(options, 1))) {
4769 log_warn(LD_BUG, "Couldn't get configuration string");
4770 goto err;
4773 len = strlen(new_conf)+256;
4774 new_val = tor_malloc(len);
4775 tor_snprintf(new_val, len, "%s\n%s\n\n%s",
4776 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4778 if (rename_old) {
4779 int i = 1;
4780 size_t fn_tmp_len = strlen(fname)+32;
4781 char *fn_tmp;
4782 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4783 fn_tmp = tor_malloc(fn_tmp_len);
4784 while (1) {
4785 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4786 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4787 tor_free(fn_tmp);
4788 goto err;
4790 if (file_status(fn_tmp) == FN_NOENT)
4791 break;
4792 ++i;
4794 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4795 if (rename(fname, fn_tmp) < 0) {
4796 log_warn(LD_FS,
4797 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4798 fname, fn_tmp, strerror(errno));
4799 tor_free(fn_tmp);
4800 goto err;
4802 tor_free(fn_tmp);
4805 if (write_str_to_file(fname, new_val, 0) < 0)
4806 goto err;
4808 r = 0;
4809 goto done;
4810 err:
4811 r = -1;
4812 done:
4813 tor_free(new_val);
4814 tor_free(new_conf);
4815 return r;
4819 * Save the current configuration file value to disk. Return 0 on
4820 * success, -1 on failure.
4823 options_save_current(void)
4825 if (torrc_fname) {
4826 /* This fails if we can't write to our configuration file.
4828 * If we try falling back to datadirectory or something, we have a better
4829 * chance of saving the configuration, but a better chance of doing
4830 * something the user never expected. Let's just warn instead. */
4831 return write_configuration_file(torrc_fname, get_options());
4833 return write_configuration_file(get_default_conf_file(), get_options());
4836 /** Mapping from a unit name to a multiplier for converting that unit into a
4837 * base unit. */
4838 struct unit_table_t {
4839 const char *unit;
4840 uint64_t multiplier;
4843 /** Table to map the names of memory units to the number of bytes they
4844 * contain. */
4845 static struct unit_table_t memory_units[] = {
4846 { "", 1 },
4847 { "b", 1<< 0 },
4848 { "byte", 1<< 0 },
4849 { "bytes", 1<< 0 },
4850 { "kb", 1<<10 },
4851 { "kbyte", 1<<10 },
4852 { "kbytes", 1<<10 },
4853 { "kilobyte", 1<<10 },
4854 { "kilobytes", 1<<10 },
4855 { "m", 1<<20 },
4856 { "mb", 1<<20 },
4857 { "mbyte", 1<<20 },
4858 { "mbytes", 1<<20 },
4859 { "megabyte", 1<<20 },
4860 { "megabytes", 1<<20 },
4861 { "gb", 1<<30 },
4862 { "gbyte", 1<<30 },
4863 { "gbytes", 1<<30 },
4864 { "gigabyte", 1<<30 },
4865 { "gigabytes", 1<<30 },
4866 { "tb", U64_LITERAL(1)<<40 },
4867 { "terabyte", U64_LITERAL(1)<<40 },
4868 { "terabytes", U64_LITERAL(1)<<40 },
4869 { NULL, 0 },
4872 /** Table to map the names of time units to the number of seconds they
4873 * contain. */
4874 static struct unit_table_t time_units[] = {
4875 { "", 1 },
4876 { "second", 1 },
4877 { "seconds", 1 },
4878 { "minute", 60 },
4879 { "minutes", 60 },
4880 { "hour", 60*60 },
4881 { "hours", 60*60 },
4882 { "day", 24*60*60 },
4883 { "days", 24*60*60 },
4884 { "week", 7*24*60*60 },
4885 { "weeks", 7*24*60*60 },
4886 { NULL, 0 },
4889 /** Parse a string <b>val</b> containing a number, zero or more
4890 * spaces, and an optional unit string. If the unit appears in the
4891 * table <b>u</b>, then multiply the number by the unit multiplier.
4892 * On success, set *<b>ok</b> to 1 and return this product.
4893 * Otherwise, set *<b>ok</b> to 0.
4895 static uint64_t
4896 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4898 uint64_t v = 0;
4899 double d = 0;
4900 int use_float = 0;
4901 char *cp;
4903 tor_assert(ok);
4905 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4906 if (!*ok || (cp && *cp == '.')) {
4907 d = tor_parse_double(val, 0, UINT64_MAX, ok, &cp);
4908 if (!*ok)
4909 goto done;
4910 use_float = 1;
4913 if (!cp) {
4914 *ok = 1;
4915 v = use_float ? DBL_TO_U64(d) : v;
4916 goto done;
4919 cp = (char*) eat_whitespace(cp);
4921 for ( ;u->unit;++u) {
4922 if (!strcasecmp(u->unit, cp)) {
4923 if (use_float)
4924 v = u->multiplier * d;
4925 else
4926 v *= u->multiplier;
4927 *ok = 1;
4928 goto done;
4931 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4932 *ok = 0;
4933 done:
4935 if (*ok)
4936 return v;
4937 else
4938 return 0;
4941 /** Parse a string in the format "number unit", where unit is a unit of
4942 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4943 * and return the number of bytes specified. Otherwise, set
4944 * *<b>ok</b> to false and return 0. */
4945 static uint64_t
4946 config_parse_memunit(const char *s, int *ok)
4948 uint64_t u = config_parse_units(s, memory_units, ok);
4949 return u;
4952 /** Parse a string in the format "number unit", where unit is a unit of time.
4953 * On success, set *<b>ok</b> to true and return the number of seconds in
4954 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4956 static int
4957 config_parse_interval(const char *s, int *ok)
4959 uint64_t r;
4960 r = config_parse_units(s, time_units, ok);
4961 if (!ok)
4962 return -1;
4963 if (r > INT_MAX) {
4964 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4965 *ok = 0;
4966 return -1;
4968 return (int)r;
4972 * Initialize the libevent library.
4974 static void
4975 init_libevent(void)
4977 const char *badness=NULL;
4979 configure_libevent_logging();
4980 /* If the kernel complains that some method (say, epoll) doesn't
4981 * exist, we don't care about it, since libevent will cope.
4983 suppress_libevent_log_msg("Function not implemented");
4985 tor_check_libevent_header_compatibility();
4987 tor_libevent_initialize();
4989 suppress_libevent_log_msg(NULL);
4991 tor_check_libevent_version(tor_libevent_get_method(),
4992 get_options()->ORPort != 0,
4993 &badness);
4994 if (badness) {
4995 const char *v = tor_libevent_get_version_str();
4996 const char *m = tor_libevent_get_method();
4997 control_event_general_status(LOG_WARN,
4998 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
4999 v, m, badness);
5003 /** Return the persistent state struct for this Tor. */
5004 or_state_t *
5005 get_or_state(void)
5007 tor_assert(global_state);
5008 return global_state;
5011 /** Return a newly allocated string holding a filename relative to the data
5012 * directory. If <b>sub1</b> is present, it is the first path component after
5013 * the data directory. If <b>sub2</b> is also present, it is the second path
5014 * component after the data directory. If <b>suffix</b> is present, it
5015 * is appended to the filename.
5017 * Examples:
5018 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
5019 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
5020 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
5021 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
5023 * Note: Consider using the get_datadir_fname* macros in or.h.
5025 char *
5026 options_get_datadir_fname2_suffix(or_options_t *options,
5027 const char *sub1, const char *sub2,
5028 const char *suffix)
5030 char *fname = NULL;
5031 size_t len;
5032 tor_assert(options);
5033 tor_assert(options->DataDirectory);
5034 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
5035 len = strlen(options->DataDirectory);
5036 if (sub1) {
5037 len += strlen(sub1)+1;
5038 if (sub2)
5039 len += strlen(sub2)+1;
5041 if (suffix)
5042 len += strlen(suffix);
5043 len++;
5044 fname = tor_malloc(len);
5045 if (sub1) {
5046 if (sub2) {
5047 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
5048 options->DataDirectory, sub1, sub2);
5049 } else {
5050 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
5051 options->DataDirectory, sub1);
5053 } else {
5054 strlcpy(fname, options->DataDirectory, len);
5056 if (suffix)
5057 strlcat(fname, suffix, len);
5058 return fname;
5061 /** Return 0 if every setting in <b>state</b> is reasonable, and a
5062 * permissible transition from <b>old_state</b>. Else warn and return -1.
5063 * Should have no side effects, except for normalizing the contents of
5064 * <b>state</b>.
5066 /* XXX from_setconf is here because of bug 238 */
5067 static int
5068 or_state_validate(or_state_t *old_state, or_state_t *state,
5069 int from_setconf, char **msg)
5071 /* We don't use these; only options do. Still, we need to match that
5072 * signature. */
5073 (void) from_setconf;
5074 (void) old_state;
5076 if (entry_guards_parse_state(state, 0, msg)<0)
5077 return -1;
5079 return 0;
5082 /** Replace the current persistent state with <b>new_state</b> */
5083 static void
5084 or_state_set(or_state_t *new_state)
5086 char *err = NULL;
5087 tor_assert(new_state);
5088 config_free(&state_format, global_state);
5089 global_state = new_state;
5090 if (entry_guards_parse_state(global_state, 1, &err)<0) {
5091 log_warn(LD_GENERAL,"%s",err);
5092 tor_free(err);
5094 if (rep_hist_load_state(global_state, &err)<0) {
5095 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
5096 tor_free(err);
5098 if (circuit_build_times_parse_state(&circ_times, global_state, &err) < 0) {
5099 log_warn(LD_GENERAL,"%s",err);
5100 tor_free(err);
5104 /** Reload the persistent state from disk, generating a new state as needed.
5105 * Return 0 on success, less than 0 on failure.
5107 static int
5108 or_state_load(void)
5110 or_state_t *new_state = NULL;
5111 char *contents = NULL, *fname;
5112 char *errmsg = NULL;
5113 int r = -1, badstate = 0;
5115 fname = get_datadir_fname("state");
5116 switch (file_status(fname)) {
5117 case FN_FILE:
5118 if (!(contents = read_file_to_str(fname, 0, NULL))) {
5119 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
5120 goto done;
5122 break;
5123 case FN_NOENT:
5124 break;
5125 case FN_ERROR:
5126 case FN_DIR:
5127 default:
5128 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
5129 goto done;
5131 new_state = tor_malloc_zero(sizeof(or_state_t));
5132 new_state->_magic = OR_STATE_MAGIC;
5133 config_init(&state_format, new_state);
5134 if (contents) {
5135 config_line_t *lines=NULL;
5136 int assign_retval;
5137 if (config_get_lines(contents, &lines)<0)
5138 goto done;
5139 assign_retval = config_assign(&state_format, new_state,
5140 lines, 0, 0, &errmsg);
5141 config_free_lines(lines);
5142 if (assign_retval<0)
5143 badstate = 1;
5144 if (errmsg) {
5145 log_warn(LD_GENERAL, "%s", errmsg);
5146 tor_free(errmsg);
5150 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
5151 badstate = 1;
5153 if (errmsg) {
5154 log_warn(LD_GENERAL, "%s", errmsg);
5155 tor_free(errmsg);
5158 if (badstate && !contents) {
5159 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
5160 " This is a bug in Tor.");
5161 goto done;
5162 } else if (badstate && contents) {
5163 int i;
5164 file_status_t status;
5165 size_t len = strlen(fname)+16;
5166 char *fname2 = tor_malloc(len);
5167 for (i = 0; i < 100; ++i) {
5168 tor_snprintf(fname2, len, "%s.%d", fname, i);
5169 status = file_status(fname2);
5170 if (status == FN_NOENT)
5171 break;
5173 if (i == 100) {
5174 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
5175 "state files to move aside. Discarding the old state file.",
5176 fname);
5177 unlink(fname);
5178 } else {
5179 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
5180 "to \"%s\". This could be a bug in Tor; please tell "
5181 "the developers.", fname, fname2);
5182 if (rename(fname, fname2) < 0) {
5183 log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
5184 "OS gave an error of %s", strerror(errno));
5187 tor_free(fname2);
5188 tor_free(contents);
5189 config_free(&state_format, new_state);
5191 new_state = tor_malloc_zero(sizeof(or_state_t));
5192 new_state->_magic = OR_STATE_MAGIC;
5193 config_init(&state_format, new_state);
5194 } else if (contents) {
5195 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
5196 } else {
5197 log_info(LD_GENERAL, "Initialized state");
5199 or_state_set(new_state);
5200 new_state = NULL;
5201 if (!contents) {
5202 global_state->next_write = 0;
5203 or_state_save(time(NULL));
5205 r = 0;
5207 done:
5208 tor_free(fname);
5209 tor_free(contents);
5210 if (new_state)
5211 config_free(&state_format, new_state);
5213 return r;
5216 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
5218 or_state_save(time_t now)
5220 char *state, *contents;
5221 char tbuf[ISO_TIME_LEN+1];
5222 size_t len;
5223 char *fname;
5225 tor_assert(global_state);
5227 if (global_state->next_write > now)
5228 return 0;
5230 /* Call everything else that might dirty the state even more, in order
5231 * to avoid redundant writes. */
5232 entry_guards_update_state(global_state);
5233 rep_hist_update_state(global_state);
5234 circuit_build_times_update_state(&circ_times, global_state);
5235 if (accounting_is_enabled(get_options()))
5236 accounting_run_housekeeping(now);
5238 global_state->LastWritten = time(NULL);
5239 tor_free(global_state->TorVersion);
5240 len = strlen(get_version())+8;
5241 global_state->TorVersion = tor_malloc(len);
5242 tor_snprintf(global_state->TorVersion, len, "Tor %s", get_version());
5244 state = config_dump(&state_format, global_state, 1, 0);
5245 len = strlen(state)+256;
5246 contents = tor_malloc(len);
5247 format_local_iso_time(tbuf, time(NULL));
5248 tor_snprintf(contents, len,
5249 "# Tor state file last generated on %s local time\n"
5250 "# Other times below are in GMT\n"
5251 "# You *do not* need to edit this file.\n\n%s",
5252 tbuf, state);
5253 tor_free(state);
5254 fname = get_datadir_fname("state");
5255 if (write_str_to_file(fname, contents, 0)<0) {
5256 log_warn(LD_FS, "Unable to write state to file \"%s\"", fname);
5257 tor_free(fname);
5258 tor_free(contents);
5259 return -1;
5261 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
5262 tor_free(fname);
5263 tor_free(contents);
5265 global_state->next_write = TIME_MAX;
5266 return 0;
5269 /** Given a file name check to see whether the file exists but has not been
5270 * modified for a very long time. If so, remove it. */
5271 void
5272 remove_file_if_very_old(const char *fname, time_t now)
5274 #define VERY_OLD_FILE_AGE (28*24*60*60)
5275 struct stat st;
5277 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
5278 char buf[ISO_TIME_LEN+1];
5279 format_local_iso_time(buf, st.st_mtime);
5280 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
5281 "Removing it.", fname, buf);
5282 unlink(fname);
5286 /** Helper to implement GETINFO functions about configuration variables (not
5287 * their values). Given a "config/names" question, set *<b>answer</b> to a
5288 * new string describing the supported configuration variables and their
5289 * types. */
5291 getinfo_helper_config(control_connection_t *conn,
5292 const char *question, char **answer)
5294 (void) conn;
5295 if (!strcmp(question, "config/names")) {
5296 smartlist_t *sl = smartlist_create();
5297 int i;
5298 for (i = 0; _option_vars[i].name; ++i) {
5299 config_var_t *var = &_option_vars[i];
5300 const char *type, *desc;
5301 char *line;
5302 size_t len;
5303 desc = config_find_description(&options_format, var->name);
5304 switch (var->type) {
5305 case CONFIG_TYPE_STRING: type = "String"; break;
5306 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
5307 case CONFIG_TYPE_UINT: type = "Integer"; break;
5308 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
5309 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
5310 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
5311 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
5312 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
5313 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
5314 case CONFIG_TYPE_CSV: type = "CommaList"; break;
5315 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
5316 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
5317 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
5318 default:
5319 case CONFIG_TYPE_OBSOLETE:
5320 type = NULL; break;
5322 if (!type)
5323 continue;
5324 len = strlen(var->name)+strlen(type)+16;
5325 if (desc)
5326 len += strlen(desc);
5327 line = tor_malloc(len);
5328 if (desc)
5329 tor_snprintf(line, len, "%s %s %s\n",var->name,type,desc);
5330 else
5331 tor_snprintf(line, len, "%s %s\n",var->name,type);
5332 smartlist_add(sl, line);
5334 *answer = smartlist_join_strings(sl, "", 0, NULL);
5335 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
5336 smartlist_free(sl);
5338 return 0;