Favor quiet circuits when choosing which order to relay cells in.
[tor.git] / src / or / config.c
blobfe5fe9f7eea007d8751ca21d7687fa3d29001de5
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"),
359 /* Options for EWMA selection of circuit to write from */
360 VAR("EWMASignificance", DOUBLE, EWMASignificance, "-1.0"),
361 VAR("EWMAInterval", DOUBLE, EWMAInterval, "-1.0"),
363 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
366 /** Override default values with these if the user sets the TestingTorNetwork
367 * option. */
368 static config_var_t testing_tor_network_defaults[] = {
369 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
370 V(DirAllowPrivateAddresses, BOOL, "1"),
371 V(EnforceDistinctSubnets, BOOL, "0"),
372 V(AssumeReachable, BOOL, "1"),
373 V(AuthDirMaxServersPerAddr, UINT, "0"),
374 V(AuthDirMaxServersPerAuthAddr,UINT, "0"),
375 V(ClientDNSRejectInternalAddresses, BOOL,"0"),
376 V(ExitPolicyRejectPrivate, BOOL, "0"),
377 V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
378 V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
379 V(V3AuthDistDelay, INTERVAL, "20 seconds"),
380 V(TestingV3AuthInitialVotingInterval, INTERVAL, "5 minutes"),
381 V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
382 V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
383 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
384 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
385 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
387 #undef VAR
389 #define VAR(name,conftype,member,initvalue) \
390 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
391 initvalue }
393 /** Array of "state" variables saved to the ~/.tor/state file. */
394 static config_var_t _state_vars[] = {
395 V(AccountingBytesReadInInterval, MEMUNIT, NULL),
396 V(AccountingBytesWrittenInInterval, MEMUNIT, NULL),
397 V(AccountingExpectedUsage, MEMUNIT, NULL),
398 V(AccountingIntervalStart, ISOTIME, NULL),
399 V(AccountingSecondsActive, INTERVAL, NULL),
401 VAR("EntryGuard", LINELIST_S, EntryGuards, NULL),
402 VAR("EntryGuardDownSince", LINELIST_S, EntryGuards, NULL),
403 VAR("EntryGuardUnlistedSince", LINELIST_S, EntryGuards, NULL),
404 VAR("EntryGuardAddedBy", LINELIST_S, EntryGuards, NULL),
405 V(EntryGuards, LINELIST_V, NULL),
407 V(BWHistoryReadEnds, ISOTIME, NULL),
408 V(BWHistoryReadInterval, UINT, "900"),
409 V(BWHistoryReadValues, CSV, ""),
410 V(BWHistoryWriteEnds, ISOTIME, NULL),
411 V(BWHistoryWriteInterval, UINT, "900"),
412 V(BWHistoryWriteValues, CSV, ""),
414 V(TorVersion, STRING, NULL),
416 V(LastRotatedOnionKey, ISOTIME, NULL),
417 V(LastWritten, ISOTIME, NULL),
419 V(TotalBuildTimes, UINT, NULL),
420 VAR("CircuitBuildTimeBin", LINELIST_S, BuildtimeHistogram, NULL),
421 VAR("BuildtimeHistogram", LINELIST_V, BuildtimeHistogram, NULL),
423 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
426 #undef VAR
427 #undef V
428 #undef OBSOLETE
430 /** Represents an English description of a configuration variable; used when
431 * generating configuration file comments. */
432 typedef struct config_var_description_t {
433 const char *name;
434 const char *description;
435 } config_var_description_t;
437 /** Descriptions of the configuration options, to be displayed by online
438 * option browsers */
439 /* XXXX022 did anybody want this? at all? If not, kill it.*/
440 static config_var_description_t options_description[] = {
441 /* ==== general options */
442 { "AvoidDiskWrites", "If non-zero, try to write to disk less frequently than"
443 " we would otherwise." },
444 { "BandwidthRate", "A token bucket limits the average incoming bandwidth on "
445 "this node to the specified number of bytes per second." },
446 { "BandwidthBurst", "Limit the maximum token buffer size (also known as "
447 "burst) to the given number of bytes." },
448 { "ConnLimit", "Minimum number of simultaneous sockets we must have." },
449 { "ConstrainedSockets", "Shrink tx and rx buffers for sockets to avoid "
450 "system limits on vservers and related environments. See man page for "
451 "more information regarding this option." },
452 { "ConstrainedSockSize", "Limit socket buffers to this size when "
453 "ConstrainedSockets is enabled." },
454 /* ControlListenAddress */
455 { "ControlPort", "If set, Tor will accept connections from the same machine "
456 "(localhost only) on this port, and allow those connections to control "
457 "the Tor process using the Tor Control Protocol (described in "
458 "control-spec.txt).", },
459 { "CookieAuthentication", "If this option is set to 1, don't allow any "
460 "connections to the control port except when the connecting process "
461 "can read a file that Tor creates in its data directory." },
462 { "DataDirectory", "Store working data, state, keys, and caches here." },
463 { "DirServer", "Tor only trusts directories signed with one of these "
464 "servers' keys. Used to override the standard list of directory "
465 "authorities." },
466 { "DisableAllSwap", "Tor will attempt a simple memory lock that "
467 "will prevent leaking of all information in memory to the swap file." },
468 /* { "FastFirstHopPK", "" }, */
469 /* FetchServerDescriptors, FetchHidServDescriptors,
470 * FetchUselessDescriptors */
471 { "HardwareAccel", "If set, Tor tries to use hardware crypto accelerators "
472 "when it can." },
473 { "AccelName", "If set, try to use hardware crypto accelerator with this "
474 "specific ID." },
475 { "AccelDir", "If set, look in this directory for the dynamic hardware "
476 "engine in addition to OpenSSL default path." },
477 /* HashedControlPassword */
478 { "HTTPProxy", "Force Tor to make all HTTP directory requests through this "
479 "host:port (or host:80 if port is not set)." },
480 { "HTTPProxyAuthenticator", "A username:password pair to be used with "
481 "HTTPProxy." },
482 { "HTTPSProxy", "Force Tor to make all TLS (SSL) connections through this "
483 "host:port (or host:80 if port is not set)." },
484 { "HTTPSProxyAuthenticator", "A username:password pair to be used with "
485 "HTTPSProxy." },
486 { "KeepalivePeriod", "Send a padding cell every N seconds to keep firewalls "
487 "from closing our connections while Tor is not in use." },
488 { "Log", "Where to send logging messages. Format is "
489 "minSeverity[-maxSeverity] (stderr|stdout|syslog|file FILENAME)." },
490 { "OutboundBindAddress", "Make all outbound connections originate from the "
491 "provided IP address (only useful for multiple network interfaces)." },
492 { "PIDFile", "On startup, write our PID to this file. On clean shutdown, "
493 "remove the file." },
494 { "PreferTunneledDirConns", "If non-zero, avoid directory servers that "
495 "don't support tunneled connections." },
496 /* PreferTunneledDirConns */
497 /* ProtocolWarnings */
498 /* RephistTrackTime */
499 { "RunAsDaemon", "If set, Tor forks and daemonizes to the background when "
500 "started. Unix only." },
501 { "SafeLogging", "If set to 0, Tor logs potentially sensitive strings "
502 "rather than replacing them with the string [scrubbed]." },
503 { "TunnelDirConns", "If non-zero, when a directory server we contact "
504 "supports it, we will build a one-hop circuit and make an encrypted "
505 "connection via its ORPort." },
506 { "User", "On startup, setuid to this user." },
508 /* ==== client options */
509 { "AllowInvalidNodes", "Where on our circuits should Tor allow servers "
510 "that the directory authorities haven't called \"valid\"?" },
511 { "AllowNonRFC953Hostnames", "If set to 1, we don't automatically reject "
512 "hostnames for having invalid characters." },
513 /* CircuitBuildTimeout, CircuitIdleTimeout */
514 { "ClientOnly", "If set to 1, Tor will under no circumstances run as a "
515 "server, even if ORPort is enabled." },
516 { "EntryNodes", "A list of preferred entry nodes to use for the first hop "
517 "in circuits, when possible." },
518 /* { "EnforceDistinctSubnets" , "" }, */
519 { "ExitNodes", "A list of preferred nodes to use for the last hop in "
520 "circuits, when possible." },
521 { "ExcludeNodes", "A list of nodes never to use when building a circuit." },
522 { "FascistFirewall", "If set, Tor will only create outgoing connections to "
523 "servers running on the ports listed in FirewallPorts." },
524 { "FirewallPorts", "A list of ports that we can connect to. Only used "
525 "when FascistFirewall is set." },
526 { "LongLivedPorts", "A list of ports for services that tend to require "
527 "high-uptime connections." },
528 { "MapAddress", "Force Tor to treat all requests for one address as if "
529 "they were for another." },
530 { "NewCircuitPeriod", "Force Tor to consider whether to build a new circuit "
531 "every NUM seconds." },
532 { "MaxCircuitDirtiness", "Do not attach new streams to a circuit that has "
533 "been used more than this many seconds ago." },
534 /* NatdPort, NatdListenAddress */
535 { "NodeFamily", "A list of servers that constitute a 'family' and should "
536 "never be used in the same circuit." },
537 { "NumEntryGuards", "How many entry guards should we keep at a time?" },
538 /* PathlenCoinWeight */
539 { "ReachableAddresses", "Addresses we can connect to, as IP/bits:port-port. "
540 "By default, we assume all addresses are reachable." },
541 /* reachablediraddresses, reachableoraddresses. */
542 /* SafeSOCKS */
543 { "SOCKSPort", "The port where we listen for SOCKS connections from "
544 "applications." },
545 { "SOCKSListenAddress", "Bind to this address to listen to connections from "
546 "SOCKS-speaking applications." },
547 { "SOCKSPolicy", "Set an entry policy to limit which addresses can connect "
548 "to the SOCKSPort." },
549 /* SocksTimeout */
550 { "StrictExitNodes", "If set, Tor will fail to operate when none of the "
551 "configured ExitNodes can be used." },
552 { "StrictEntryNodes", "If set, Tor will fail to operate when none of the "
553 "configured EntryNodes can be used." },
554 /* TestSocks */
555 { "TrackHostsExit", "Hosts and domains which should, if possible, be "
556 "accessed from the same exit node each time we connect to them." },
557 { "TrackHostsExitExpire", "Time after which we forget which exit we were "
558 "using to connect to hosts in TrackHostsExit." },
559 /* "TransPort", "TransListenAddress */
560 { "UseEntryGuards", "Set to 0 if we want to pick from the whole set of "
561 "servers for the first position in each circuit, rather than picking a "
562 "set of 'Guards' to prevent profiling attacks." },
564 /* === server options */
565 { "Address", "The advertised (external) address we should use." },
566 /* Accounting* options. */
567 /* AssumeReachable */
568 { "ContactInfo", "Administrative contact information to advertise for this "
569 "server." },
570 { "ExitPolicy", "Address/port ranges for which to accept or reject outgoing "
571 "connections on behalf of Tor users." },
572 /* { "ExitPolicyRejectPrivate, "" }, */
573 { "MaxAdvertisedBandwidth", "If set, we will not advertise more than this "
574 "amount of bandwidth for our bandwidth rate, regardless of how much "
575 "bandwidth we actually detect." },
576 { "MaxOnionsPending", "Reject new attempts to extend circuits when we "
577 "already have this many pending." },
578 { "MyFamily", "Declare a list of other servers as belonging to the same "
579 "family as this one, so that clients will not use two from the same "
580 "family in the same circuit." },
581 { "Nickname", "Set the server nickname." },
582 { "NoPublish", "{DEPRECATED}" },
583 { "NumCPUs", "How many processes to use at once for public-key crypto." },
584 { "ORPort", "Advertise this port to listen for connections from Tor clients "
585 "and servers." },
586 { "ORListenAddress", "Bind to this address to listen for connections from "
587 "clients and servers, instead of the default 0.0.0.0:ORPort." },
588 { "PublishServerDescriptor", "Set to 0 to keep the server from "
589 "uploading info to the directory authorities." },
590 /* ServerDNS: DetectHijacking, ResolvConfFile, SearchDomains */
591 { "ShutdownWaitLength", "Wait this long for clients to finish when "
592 "shutting down because of a SIGINT." },
594 /* === directory cache options */
595 { "DirPort", "Serve directory information from this port, and act as a "
596 "directory cache." },
597 { "DirPortFrontPage", "Serve a static html disclaimer on DirPort." },
598 { "DirListenAddress", "Bind to this address to listen for connections from "
599 "clients and servers, instead of the default 0.0.0.0:DirPort." },
600 { "DirPolicy", "Set a policy to limit who can connect to the directory "
601 "port." },
603 /* Authority options: AuthDirBadExit, AuthDirInvalid, AuthDirReject,
604 * AuthDirRejectUnlisted, AuthDirListBadExits, AuthoritativeDirectory,
605 * DirAllowPrivateAddresses, HSAuthoritativeDir,
606 * NamingAuthoritativeDirectory, RecommendedVersions,
607 * RecommendedClientVersions, RecommendedServerVersions, RendPostPeriod,
608 * RunTesting, V1AuthoritativeDirectory, VersioningAuthoritativeDirectory, */
610 /* Hidden service options: HiddenService: dir,excludenodes, nodes,
611 * options, port. PublishHidServDescriptor */
613 /* Circuit build time histogram options */
614 { "CircuitBuildTimeBin", "Histogram of recent circuit build times"},
615 { "TotalBuildTimes", "Total number of buildtimes in histogram"},
617 /* Nonpersistent options: __LeaveStreamsUnattached, __AllDirActionsPrivate */
618 { NULL, NULL },
621 /** Online description of state variables. */
622 static config_var_description_t state_description[] = {
623 { "AccountingBytesReadInInterval",
624 "How many bytes have we read in this accounting period?" },
625 { "AccountingBytesWrittenInInterval",
626 "How many bytes have we written in this accounting period?" },
627 { "AccountingExpectedUsage",
628 "How many bytes did we expect to use per minute? (0 for no estimate.)" },
629 { "AccountingIntervalStart", "When did this accounting period begin?" },
630 { "AccountingSecondsActive", "How long have we been awake in this period?" },
632 { "BWHistoryReadEnds", "When does the last-recorded read-interval end?" },
633 { "BWHistoryReadInterval", "How long is each read-interval (in seconds)?" },
634 { "BWHistoryReadValues", "Number of bytes read in each interval." },
635 { "BWHistoryWriteEnds", "When does the last-recorded write-interval end?" },
636 { "BWHistoryWriteInterval", "How long is each write-interval (in seconds)?"},
637 { "BWHistoryWriteValues", "Number of bytes written in each interval." },
639 { "EntryGuard", "One of the nodes we have chosen as a fixed entry" },
640 { "EntryGuardDownSince",
641 "The last entry guard has been unreachable since this time." },
642 { "EntryGuardUnlistedSince",
643 "The last entry guard has been unusable since this time." },
645 { "LastRotatedOnionKey",
646 "The last time at which we changed the medium-term private key used for "
647 "building circuits." },
648 { "LastWritten", "When was this state file last regenerated?" },
650 { "TorVersion", "Which version of Tor generated this state file?" },
651 { NULL, NULL },
654 /** Type of a callback to validate whether a given configuration is
655 * well-formed and consistent. See options_trial_assign() for documentation
656 * of arguments. */
657 typedef int (*validate_fn_t)(void*,void*,int,char**);
659 /** Information on the keys, value types, key-to-struct-member mappings,
660 * variable descriptions, validation functions, and abbreviations for a
661 * configuration or storage format. */
662 typedef struct {
663 size_t size; /**< Size of the struct that everything gets parsed into. */
664 uint32_t magic; /**< Required 'magic value' to make sure we have a struct
665 * of the right type. */
666 off_t magic_offset; /**< Offset of the magic value within the struct. */
667 config_abbrev_t *abbrevs; /**< List of abbreviations that we expand when
668 * parsing this format. */
669 config_var_t *vars; /**< List of variables we recognize, their default
670 * values, and where we stick them in the structure. */
671 validate_fn_t validate_fn; /**< Function to validate config. */
672 /** Documentation for configuration variables. */
673 config_var_description_t *descriptions;
674 /** If present, extra is a LINELIST variable for unrecognized
675 * lines. Otherwise, unrecognized lines are an error. */
676 config_var_t *extra;
677 } config_format_t;
679 /** Macro: assert that <b>cfg</b> has the right magic field for format
680 * <b>fmt</b>. */
681 #define CHECK(fmt, cfg) STMT_BEGIN \
682 tor_assert(fmt && cfg); \
683 tor_assert((fmt)->magic == \
684 *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
685 STMT_END
687 #ifdef MS_WINDOWS
688 static char *get_windows_conf_root(void);
689 #endif
690 static void config_line_append(config_line_t **lst,
691 const char *key, const char *val);
692 static void option_clear(config_format_t *fmt, or_options_t *options,
693 config_var_t *var);
694 static void option_reset(config_format_t *fmt, or_options_t *options,
695 config_var_t *var, int use_defaults);
696 static void config_free(config_format_t *fmt, void *options);
697 static int config_lines_eq(config_line_t *a, config_line_t *b);
698 static int option_is_same(config_format_t *fmt,
699 or_options_t *o1, or_options_t *o2,
700 const char *name);
701 static or_options_t *options_dup(config_format_t *fmt, or_options_t *old);
702 static int options_validate(or_options_t *old_options, or_options_t *options,
703 int from_setconf, char **msg);
704 static int options_act_reversible(or_options_t *old_options, char **msg);
705 static int options_act(or_options_t *old_options);
706 static int options_transition_allowed(or_options_t *old, or_options_t *new,
707 char **msg);
708 static int options_transition_affects_workers(or_options_t *old_options,
709 or_options_t *new_options);
710 static int options_transition_affects_descriptor(or_options_t *old_options,
711 or_options_t *new_options);
712 static int check_nickname_list(const char *lst, const char *name, char **msg);
713 static void config_register_addressmaps(or_options_t *options);
715 static int parse_bridge_line(const char *line, int validate_only);
716 static int parse_dir_server_line(const char *line,
717 authority_type_t required_type,
718 int validate_only);
719 static int validate_data_directory(or_options_t *options);
720 static int write_configuration_file(const char *fname, or_options_t *options);
721 static config_line_t *get_assigned_option(config_format_t *fmt,
722 void *options, const char *key,
723 int escape_val);
724 static void config_init(config_format_t *fmt, void *options);
725 static int or_state_validate(or_state_t *old_options, or_state_t *options,
726 int from_setconf, char **msg);
727 static int or_state_load(void);
728 static int options_init_logs(or_options_t *options, int validate_only);
730 static int is_listening_on_low_port(uint16_t port_option,
731 const config_line_t *listen_options);
733 static uint64_t config_parse_memunit(const char *s, int *ok);
734 static int config_parse_interval(const char *s, int *ok);
735 static void init_libevent(void);
736 static int opt_streq(const char *s1, const char *s2);
738 /** Magic value for or_options_t. */
739 #define OR_OPTIONS_MAGIC 9090909
741 /** Configuration format for or_options_t. */
742 static config_format_t options_format = {
743 sizeof(or_options_t),
744 OR_OPTIONS_MAGIC,
745 STRUCT_OFFSET(or_options_t, _magic),
746 _option_abbrevs,
747 _option_vars,
748 (validate_fn_t)options_validate,
749 options_description,
750 NULL
753 /** Magic value for or_state_t. */
754 #define OR_STATE_MAGIC 0x57A73f57
756 /** "Extra" variable in the state that receives lines we can't parse. This
757 * lets us preserve options from versions of Tor newer than us. */
758 static config_var_t state_extra_var = {
759 "__extra", CONFIG_TYPE_LINELIST, STRUCT_OFFSET(or_state_t, ExtraLines), NULL
762 /** Configuration format for or_state_t. */
763 static config_format_t state_format = {
764 sizeof(or_state_t),
765 OR_STATE_MAGIC,
766 STRUCT_OFFSET(or_state_t, _magic),
767 _state_abbrevs,
768 _state_vars,
769 (validate_fn_t)or_state_validate,
770 state_description,
771 &state_extra_var,
775 * Functions to read and write the global options pointer.
778 /** Command-line and config-file options. */
779 static or_options_t *global_options = NULL;
780 /** Name of most recently read torrc file. */
781 static char *torrc_fname = NULL;
782 /** Persistent serialized state. */
783 static or_state_t *global_state = NULL;
784 /** Configuration Options set by command line. */
785 static config_line_t *global_cmdline_options = NULL;
786 /** Contents of most recently read DirPortFrontPage file. */
787 static char *global_dirfrontpagecontents = NULL;
789 /** Return the contents of our frontpage string, or NULL if not configured. */
790 const char *
791 get_dirportfrontpage(void)
793 return global_dirfrontpagecontents;
796 /** Allocate an empty configuration object of a given format type. */
797 static void *
798 config_alloc(config_format_t *fmt)
800 void *opts = tor_malloc_zero(fmt->size);
801 *(uint32_t*)STRUCT_VAR_P(opts, fmt->magic_offset) = fmt->magic;
802 CHECK(fmt, opts);
803 return opts;
806 /** Return the currently configured options. */
807 or_options_t *
808 get_options(void)
810 tor_assert(global_options);
811 return global_options;
814 /** Change the current global options to contain <b>new_val</b> instead of
815 * their current value; take action based on the new value; free the old value
816 * as necessary. Returns 0 on success, -1 on failure.
819 set_options(or_options_t *new_val, char **msg)
821 or_options_t *old_options = global_options;
822 global_options = new_val;
823 /* Note that we pass the *old* options below, for comparison. It
824 * pulls the new options directly out of global_options. */
825 if (options_act_reversible(old_options, msg)<0) {
826 tor_assert(*msg);
827 global_options = old_options;
828 return -1;
830 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
831 log_err(LD_BUG,
832 "Acting on config options left us in a broken state. Dying.");
833 exit(1);
836 config_free(&options_format, old_options);
838 return 0;
841 extern const char tor_git_revision[]; /* from tor_main.c */
843 /** The version of this Tor process, as parsed. */
844 static char *_version = NULL;
846 /** Return the current Tor version. */
847 const char *
848 get_version(void)
850 if (_version == NULL) {
851 if (strlen(tor_git_revision)) {
852 size_t len = strlen(VERSION)+strlen(tor_git_revision)+16;
853 _version = tor_malloc(len);
854 tor_snprintf(_version, len, "%s (git-%s)", VERSION, tor_git_revision);
855 } else {
856 _version = tor_strdup(VERSION);
859 return _version;
862 /** Release additional memory allocated in options
864 static void
865 or_options_free(or_options_t *options)
867 if (!options)
868 return;
870 routerset_free(options->_ExcludeExitNodesUnion);
871 config_free(&options_format, options);
874 /** Release all memory and resources held by global configuration structures.
876 void
877 config_free_all(void)
879 or_options_free(global_options);
880 global_options = NULL;
882 config_free(&state_format, global_state);
883 global_state = NULL;
885 config_free_lines(global_cmdline_options);
886 global_cmdline_options = NULL;
888 tor_free(torrc_fname);
889 tor_free(_version);
890 tor_free(global_dirfrontpagecontents);
893 /** If options->SafeLogging is on, return a not very useful string,
894 * else return address.
896 const char *
897 safe_str(const char *address)
899 tor_assert(address);
900 if (get_options()->SafeLogging)
901 return "[scrubbed]";
902 else
903 return address;
906 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
907 * escaped(): don't use this outside the main thread, or twice in the same
908 * log statement. */
909 const char *
910 escaped_safe_str(const char *address)
912 if (get_options()->SafeLogging)
913 return "[scrubbed]";
914 else
915 return escaped(address);
918 /** Add the default directory authorities directly into the trusted dir list,
919 * but only add them insofar as they share bits with <b>type</b>. */
920 static void
921 add_default_trusted_dir_authorities(authority_type_t type)
923 int i;
924 const char *dirservers[] = {
925 "moria1 v1 orport=9001 v3ident=E2A2AF570166665D738736D0DD58169CC61D8A8B "
926 "128.31.0.39:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441",
927 "moria2 v1 orport=9002 128.31.0.34:9032 "
928 "719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF",
929 "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
930 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
931 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
932 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
933 "Tonga orport=443 bridge no-v2 82.94.251.203:80 "
934 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
935 "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
936 "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
937 "gabelmoo orport=443 no-v2 "
938 "v3ident=81349FC1F2DBA2C2C11B45CB9706637D480AB913 "
939 "80.190.246.100:80 6833 3D07 61BC F397 A587 A0C0 B963 E4A9 E99E C4D3",
940 "dannenberg orport=443 no-v2 "
941 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
942 "213.73.91.31:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
943 "urras orport=80 no-v2 v3ident=80550987E1D626E3EBA5E5E75A458DE0626D088C "
944 "208.83.223.34:443 0AD3 FA88 4D18 F89E EA2D 89C0 1937 9E0E 7FD9 4417",
945 NULL
947 for (i=0; dirservers[i]; i++) {
948 if (parse_dir_server_line(dirservers[i], type, 0)<0) {
949 log_err(LD_BUG, "Couldn't parse internal dirserver line %s",
950 dirservers[i]);
955 /** Look at all the config options for using alternate directory
956 * authorities, and make sure none of them are broken. Also, warn the
957 * user if we changed any dangerous ones.
959 static int
960 validate_dir_authorities(or_options_t *options, or_options_t *old_options)
962 config_line_t *cl;
964 if (options->DirServers &&
965 (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
966 options->AlternateHSAuthority)) {
967 log_warn(LD_CONFIG,
968 "You cannot set both DirServers and Alternate*Authority.");
969 return -1;
972 /* do we want to complain to the user about being partitionable? */
973 if ((options->DirServers &&
974 (!old_options ||
975 !config_lines_eq(options->DirServers, old_options->DirServers))) ||
976 (options->AlternateDirAuthority &&
977 (!old_options ||
978 !config_lines_eq(options->AlternateDirAuthority,
979 old_options->AlternateDirAuthority)))) {
980 log_warn(LD_CONFIG,
981 "You have used DirServer or AlternateDirAuthority to "
982 "specify alternate directory authorities in "
983 "your configuration. This is potentially dangerous: it can "
984 "make you look different from all other Tor users, and hurt "
985 "your anonymity. Even if you've specified the same "
986 "authorities as Tor uses by default, the defaults could "
987 "change in the future. Be sure you know what you're doing.");
990 /* Now go through the four ways you can configure an alternate
991 * set of directory authorities, and make sure none are broken. */
992 for (cl = options->DirServers; cl; cl = cl->next)
993 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
994 return -1;
995 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
996 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
997 return -1;
998 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
999 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
1000 return -1;
1001 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
1002 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
1003 return -1;
1004 return 0;
1007 /** Look at all the config options and assign new dir authorities
1008 * as appropriate.
1010 static int
1011 consider_adding_dir_authorities(or_options_t *options,
1012 or_options_t *old_options)
1014 config_line_t *cl;
1015 int need_to_update =
1016 !smartlist_len(router_get_trusted_dir_servers()) || !old_options ||
1017 !config_lines_eq(options->DirServers, old_options->DirServers) ||
1018 !config_lines_eq(options->AlternateBridgeAuthority,
1019 old_options->AlternateBridgeAuthority) ||
1020 !config_lines_eq(options->AlternateDirAuthority,
1021 old_options->AlternateDirAuthority) ||
1022 !config_lines_eq(options->AlternateHSAuthority,
1023 old_options->AlternateHSAuthority);
1025 if (!need_to_update)
1026 return 0; /* all done */
1028 /* Start from a clean slate. */
1029 clear_trusted_dir_servers();
1031 if (!options->DirServers) {
1032 /* then we may want some of the defaults */
1033 authority_type_t type = NO_AUTHORITY;
1034 if (!options->AlternateBridgeAuthority)
1035 type |= BRIDGE_AUTHORITY;
1036 if (!options->AlternateDirAuthority)
1037 type |= V1_AUTHORITY | V2_AUTHORITY | V3_AUTHORITY;
1038 if (!options->AlternateHSAuthority)
1039 type |= HIDSERV_AUTHORITY;
1040 add_default_trusted_dir_authorities(type);
1043 for (cl = options->DirServers; cl; cl = cl->next)
1044 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1045 return -1;
1046 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1047 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1048 return -1;
1049 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1050 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1051 return -1;
1052 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
1053 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1054 return -1;
1055 return 0;
1058 /** Fetch the active option list, and take actions based on it. All of the
1059 * things we do should survive being done repeatedly. If present,
1060 * <b>old_options</b> contains the previous value of the options.
1062 * Return 0 if all goes well, return -1 if things went badly.
1064 static int
1065 options_act_reversible(or_options_t *old_options, char **msg)
1067 smartlist_t *new_listeners = smartlist_create();
1068 smartlist_t *replaced_listeners = smartlist_create();
1069 static int libevent_initialized = 0;
1070 or_options_t *options = get_options();
1071 int running_tor = options->command == CMD_RUN_TOR;
1072 int set_conn_limit = 0;
1073 int r = -1;
1074 int logs_marked = 0;
1076 /* Daemonize _first_, since we only want to open most of this stuff in
1077 * the subprocess. Libevent bases can't be reliably inherited across
1078 * processes. */
1079 if (running_tor && options->RunAsDaemon) {
1080 /* No need to roll back, since you can't change the value. */
1081 start_daemon();
1084 #ifndef HAVE_SYS_UN_H
1085 if (options->ControlSocket) {
1086 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported"
1087 " on this OS/with this build.");
1088 goto rollback;
1090 #endif
1092 if (running_tor) {
1093 /* We need to set the connection limit before we can open the listeners. */
1094 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1095 &options->_ConnLimit) < 0) {
1096 *msg = tor_strdup("Problem with ConnLimit value. See logs for details.");
1097 goto rollback;
1099 set_conn_limit = 1;
1101 /* Set up libevent. (We need to do this before we can register the
1102 * listeners as listeners.) */
1103 if (running_tor && !libevent_initialized) {
1104 init_libevent();
1105 libevent_initialized = 1;
1108 /* Launch the listeners. (We do this before we setuid, so we can bind to
1109 * ports under 1024.) */
1110 if (retry_all_listeners(replaced_listeners, new_listeners) < 0) {
1111 *msg = tor_strdup("Failed to bind one of the listener ports.");
1112 goto rollback;
1116 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1117 /* Open /dev/pf before dropping privileges. */
1118 if (options->TransPort) {
1119 if (get_pf_socket() < 0) {
1120 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1121 goto rollback;
1124 #endif
1126 /* Attempt to lock all current and future memory with mlockall() only once */
1127 if (options->DisableAllSwap) {
1128 if (tor_mlockall() == -1) {
1129 *msg = tor_strdup("DisableAllSwap failure. Do you have proper "
1130 "permissions?");
1131 goto done;
1135 /* Setuid/setgid as appropriate */
1136 if (options->User) {
1137 if (switch_id(options->User) != 0) {
1138 /* No need to roll back, since you can't change the value. */
1139 *msg = tor_strdup("Problem with User value. See logs for details.");
1140 goto done;
1144 /* Ensure data directory is private; create if possible. */
1145 if (check_private_dir(options->DataDirectory,
1146 running_tor ? CPD_CREATE : CPD_CHECK)<0) {
1147 char buf[1024];
1148 int tmp = tor_snprintf(buf, sizeof(buf),
1149 "Couldn't access/create private data directory \"%s\"",
1150 options->DataDirectory);
1151 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1152 goto done;
1153 /* No need to roll back, since you can't change the value. */
1156 if (directory_caches_v2_dir_info(options)) {
1157 size_t len = strlen(options->DataDirectory)+32;
1158 char *fn = tor_malloc(len);
1159 tor_snprintf(fn, len, "%s"PATH_SEPARATOR"cached-status",
1160 options->DataDirectory);
1161 if (check_private_dir(fn, running_tor ? CPD_CREATE : CPD_CHECK) < 0) {
1162 char buf[1024];
1163 int tmp = tor_snprintf(buf, sizeof(buf),
1164 "Couldn't access/create private data directory \"%s\"", fn);
1165 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1166 tor_free(fn);
1167 goto done;
1169 tor_free(fn);
1172 /* Bail out at this point if we're not going to be a client or server:
1173 * we don't run Tor itself. */
1174 if (!running_tor)
1175 goto commit;
1177 mark_logs_temp(); /* Close current logs once new logs are open. */
1178 logs_marked = 1;
1179 if (options_init_logs(options, 0)<0) { /* Configure the log(s) */
1180 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1181 goto rollback;
1184 commit:
1185 r = 0;
1186 if (logs_marked) {
1187 log_severity_list_t *severity =
1188 tor_malloc_zero(sizeof(log_severity_list_t));
1189 close_temp_logs();
1190 add_callback_log(severity, control_event_logmsg);
1191 control_adjust_event_log_severity();
1192 tor_free(severity);
1194 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1196 log_notice(LD_NET, "Closing old %s on %s:%d",
1197 conn_type_to_string(conn->type), conn->address, conn->port);
1198 connection_close_immediate(conn);
1199 connection_mark_for_close(conn);
1201 goto done;
1203 rollback:
1204 r = -1;
1205 tor_assert(*msg);
1207 if (logs_marked) {
1208 rollback_log_changes();
1209 control_adjust_event_log_severity();
1212 if (set_conn_limit && old_options)
1213 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1214 &options->_ConnLimit);
1216 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1218 log_notice(LD_NET, "Closing partially-constructed listener %s on %s:%d",
1219 conn_type_to_string(conn->type), conn->address, conn->port);
1220 connection_close_immediate(conn);
1221 connection_mark_for_close(conn);
1224 done:
1225 smartlist_free(new_listeners);
1226 smartlist_free(replaced_listeners);
1227 return r;
1230 /** If we need to have a GEOIP ip-to-country map to run with our configured
1231 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1233 options_need_geoip_info(or_options_t *options, const char **reason_out)
1235 int bridge_usage =
1236 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1237 int routerset_usage =
1238 routerset_needs_geoip(options->EntryNodes) ||
1239 routerset_needs_geoip(options->ExitNodes) ||
1240 routerset_needs_geoip(options->ExcludeExitNodes) ||
1241 routerset_needs_geoip(options->ExcludeNodes);
1243 if (routerset_usage && reason_out) {
1244 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1245 "countries, and we need GEOIP information to figure out which ones they "
1246 "are.";
1247 } else if (bridge_usage && reason_out) {
1248 *reason_out = "We've been configured to see which countries can access "
1249 "us as a bridge, and we need GEOIP information to tell which countries "
1250 "clients are in.";
1252 return bridge_usage || routerset_usage;
1255 /** Return the bandwidthrate that we are going to report to the authorities
1256 * based on the config options. */
1257 uint32_t
1258 get_effective_bwrate(or_options_t *options)
1260 uint64_t bw = options->BandwidthRate;
1261 if (bw > options->MaxAdvertisedBandwidth)
1262 bw = options->MaxAdvertisedBandwidth;
1263 if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1264 bw = options->RelayBandwidthRate;
1265 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1266 return (uint32_t)bw;
1269 /** Return the bandwidthburst that we are going to report to the authorities
1270 * based on the config options. */
1271 uint32_t
1272 get_effective_bwburst(or_options_t *options)
1274 uint64_t bw = options->BandwidthBurst;
1275 if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1276 bw = options->RelayBandwidthBurst;
1277 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1278 return (uint32_t)bw;
1281 /** Fetch the active option list, and take actions based on it. All of the
1282 * things we do should survive being done repeatedly. If present,
1283 * <b>old_options</b> contains the previous value of the options.
1285 * Return 0 if all goes well, return -1 if it's time to die.
1287 * Note: We haven't moved all the "act on new configuration" logic
1288 * here yet. Some is still in do_hup() and other places.
1290 static int
1291 options_act(or_options_t *old_options)
1293 config_line_t *cl;
1294 or_options_t *options = get_options();
1295 int running_tor = options->command == CMD_RUN_TOR;
1296 char *msg;
1298 if (running_tor && !have_lockfile()) {
1299 if (try_locking(options, 1) < 0)
1300 return -1;
1303 if (consider_adding_dir_authorities(options, old_options) < 0)
1304 return -1;
1306 if (options->Bridges) {
1307 clear_bridge_list();
1308 for (cl = options->Bridges; cl; cl = cl->next) {
1309 if (parse_bridge_line(cl->value, 0)<0) {
1310 log_warn(LD_BUG,
1311 "Previously validated Bridge line could not be added!");
1312 return -1;
1317 if (running_tor && rend_config_services(options, 0)<0) {
1318 log_warn(LD_BUG,
1319 "Previously validated hidden services line could not be added!");
1320 return -1;
1323 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1324 log_warn(LD_BUG, "Previously validated client authorization for "
1325 "hidden services could not be added!");
1326 return -1;
1329 /* Load state */
1330 if (! global_state && running_tor) {
1331 if (or_state_load())
1332 return -1;
1333 rep_hist_load_mtbf_data(time(NULL));
1336 /* Bail out at this point if we're not going to be a client or server:
1337 * we want to not fork, and to log stuff to stderr. */
1338 if (!running_tor)
1339 return 0;
1341 /* Finish backgrounding the process */
1342 if (options->RunAsDaemon) {
1343 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1344 finish_daemon(options->DataDirectory);
1347 /* Write our PID to the PID file. If we do not have write permissions we
1348 * will log a warning */
1349 if (options->PidFile)
1350 write_pidfile(options->PidFile);
1352 /* Register addressmap directives */
1353 config_register_addressmaps(options);
1354 parse_virtual_addr_network(options->VirtualAddrNetwork, 0, &msg);
1356 /* Update address policies. */
1357 if (policies_parse_from_options(options) < 0) {
1358 /* This should be impossible, but let's be sure. */
1359 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1360 return -1;
1363 if (init_cookie_authentication(options->CookieAuthentication) < 0) {
1364 log_warn(LD_CONFIG,"Error creating cookie authentication file.");
1365 return -1;
1368 /* reload keys as needed for rendezvous services. */
1369 if (rend_service_load_keys()<0) {
1370 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1371 return -1;
1374 /* Set up accounting */
1375 if (accounting_parse_options(options, 0)<0) {
1376 log_warn(LD_CONFIG,"Error in accounting options");
1377 return -1;
1379 if (accounting_is_enabled(options))
1380 configure_accounting(time(NULL));
1382 /* Check for transitions that need action. */
1383 if (old_options) {
1384 if (options->UseEntryGuards && !old_options->UseEntryGuards) {
1385 log_info(LD_CIRC,
1386 "Switching to entry guards; abandoning previous circuits");
1387 circuit_mark_all_unused_circs();
1388 circuit_expire_all_dirty_circs();
1391 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
1392 log_info(LD_GENERAL, "Bridge status changed. Forgetting GeoIP stats.");
1393 geoip_remove_old_clients(time(NULL)+(2*60*60));
1396 if (options_transition_affects_workers(old_options, options)) {
1397 log_info(LD_GENERAL,
1398 "Worker-related options changed. Rotating workers.");
1399 if (server_mode(options) && !server_mode(old_options)) {
1400 if (init_keys() < 0) {
1401 log_warn(LD_BUG,"Error initializing keys; exiting");
1402 return -1;
1404 ip_address_changed(0);
1405 if (has_completed_circuit || !any_predicted_circuits(time(NULL)))
1406 inform_testing_reachability();
1408 cpuworkers_rotate();
1409 if (dns_reset())
1410 return -1;
1411 } else {
1412 if (dns_reset())
1413 return -1;
1416 if (options->V3AuthoritativeDir && !old_options->V3AuthoritativeDir)
1417 init_keys();
1420 /* Maybe load geoip file */
1421 if (options->GeoIPFile &&
1422 ((!old_options || !opt_streq(old_options->GeoIPFile, options->GeoIPFile))
1423 || !geoip_is_loaded())) {
1424 /* XXXX Don't use this "<default>" junk; make our filename options
1425 * understand prefixes somehow. -NM */
1426 /* XXXX021 Reload GeoIPFile on SIGHUP. -NM */
1427 char *actual_fname = tor_strdup(options->GeoIPFile);
1428 #ifdef WIN32
1429 if (!strcmp(actual_fname, "<default>")) {
1430 const char *conf_root = get_windows_conf_root();
1431 size_t len = strlen(conf_root)+16;
1432 tor_free(actual_fname);
1433 actual_fname = tor_malloc(len+1);
1434 tor_snprintf(actual_fname, len, "%s\\geoip", conf_root);
1436 #endif
1437 geoip_load_file(actual_fname, options);
1438 tor_free(actual_fname);
1441 if (options->DirReqStatistics && !geoip_is_loaded()) {
1442 /* Check if GeoIP database could be loaded. */
1443 log_warn(LD_CONFIG, "Configured to measure directory request "
1444 "statistics, but no GeoIP database found!");
1445 return -1;
1448 if (options->EntryStatistics) {
1449 if (should_record_bridge_info(options)) {
1450 /* Don't allow measuring statistics on entry guards when configured
1451 * as bridge. */
1452 log_warn(LD_CONFIG, "Bridges cannot be configured to measure "
1453 "additional GeoIP statistics as entry guards.");
1454 return -1;
1455 } else if (!geoip_is_loaded()) {
1456 /* Check if GeoIP database could be loaded. */
1457 log_warn(LD_CONFIG, "Configured to measure entry node statistics, "
1458 "but no GeoIP database found!");
1459 return -1;
1463 /* Check if we need to parse and add the EntryNodes config option. */
1464 if (options->EntryNodes &&
1465 (!old_options ||
1466 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
1467 entry_nodes_should_be_added();
1469 /* Since our options changed, we might need to regenerate and upload our
1470 * server descriptor.
1472 if (!old_options ||
1473 options_transition_affects_descriptor(old_options, options))
1474 mark_my_descriptor_dirty();
1476 /* We may need to reschedule some directory stuff if our status changed. */
1477 if (old_options) {
1478 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1479 dirvote_recalculate_timing(options, time(NULL));
1480 if (!bool_eq(directory_fetches_dir_info_early(options),
1481 directory_fetches_dir_info_early(old_options)) ||
1482 !bool_eq(directory_fetches_dir_info_later(options),
1483 directory_fetches_dir_info_later(old_options))) {
1484 /* Make sure update_router_have_min_dir_info gets called. */
1485 router_dir_info_changed();
1486 /* We might need to download a new consensus status later or sooner than
1487 * we had expected. */
1488 update_consensus_networkstatus_fetch_time(time(NULL));
1492 /* Load the webpage we're going to serve every time someone asks for '/' on
1493 our DirPort. */
1494 tor_free(global_dirfrontpagecontents);
1495 if (options->DirPortFrontPage) {
1496 global_dirfrontpagecontents =
1497 read_file_to_str(options->DirPortFrontPage, 0, NULL);
1498 if (!global_dirfrontpagecontents) {
1499 log_warn(LD_CONFIG,
1500 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1501 options->DirPortFrontPage);
1505 return 0;
1509 * Functions to parse config options
1512 /** If <b>option</b> is an official abbreviation for a longer option,
1513 * return the longer option. Otherwise return <b>option</b>.
1514 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1515 * apply abbreviations that work for the config file and the command line.
1516 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1517 static const char *
1518 expand_abbrev(config_format_t *fmt, const char *option, int command_line,
1519 int warn_obsolete)
1521 int i;
1522 if (! fmt->abbrevs)
1523 return option;
1524 for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
1525 /* Abbreviations are case insensitive. */
1526 if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
1527 (command_line || !fmt->abbrevs[i].commandline_only)) {
1528 if (warn_obsolete && fmt->abbrevs[i].warn) {
1529 log_warn(LD_CONFIG,
1530 "The configuration option '%s' is deprecated; "
1531 "use '%s' instead.",
1532 fmt->abbrevs[i].abbreviated,
1533 fmt->abbrevs[i].full);
1535 /* Keep going through the list in case we want to rewrite it more.
1536 * (We could imagine recursing here, but I don't want to get the
1537 * user into an infinite loop if we craft our list wrong.) */
1538 option = fmt->abbrevs[i].full;
1541 return option;
1544 /** Helper: Read a list of configuration options from the command line.
1545 * If successful, put them in *<b>result</b> and return 0, and return
1546 * -1 and leave *<b>result</b> alone. */
1547 static int
1548 config_get_commandlines(int argc, char **argv, config_line_t **result)
1550 config_line_t *front = NULL;
1551 config_line_t **new = &front;
1552 char *s;
1553 int i = 1;
1555 while (i < argc) {
1556 if (!strcmp(argv[i],"-f") ||
1557 !strcmp(argv[i],"--hash-password")) {
1558 i += 2; /* command-line option with argument. ignore them. */
1559 continue;
1560 } else if (!strcmp(argv[i],"--list-fingerprint") ||
1561 !strcmp(argv[i],"--verify-config") ||
1562 !strcmp(argv[i],"--ignore-missing-torrc") ||
1563 !strcmp(argv[i],"--quiet") ||
1564 !strcmp(argv[i],"--hush")) {
1565 i += 1; /* command-line option. ignore it. */
1566 continue;
1567 } else if (!strcmp(argv[i],"--nt-service") ||
1568 !strcmp(argv[i],"-nt-service")) {
1569 i += 1;
1570 continue;
1573 if (i == argc-1) {
1574 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1575 argv[i]);
1576 config_free_lines(front);
1577 return -1;
1580 *new = tor_malloc_zero(sizeof(config_line_t));
1581 s = argv[i];
1583 /* Each keyword may be prefixed with one or two dashes. */
1584 if (*s == '-')
1585 s++;
1586 if (*s == '-')
1587 s++;
1589 (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1, 1));
1590 (*new)->value = tor_strdup(argv[i+1]);
1591 (*new)->next = NULL;
1592 log(LOG_DEBUG, LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
1593 (*new)->key, (*new)->value);
1595 new = &((*new)->next);
1596 i += 2;
1598 *result = front;
1599 return 0;
1602 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1603 * append it to *<b>lst</b>. */
1604 static void
1605 config_line_append(config_line_t **lst,
1606 const char *key,
1607 const char *val)
1609 config_line_t *newline;
1611 newline = tor_malloc(sizeof(config_line_t));
1612 newline->key = tor_strdup(key);
1613 newline->value = tor_strdup(val);
1614 newline->next = NULL;
1615 while (*lst)
1616 lst = &((*lst)->next);
1618 (*lst) = newline;
1621 /** Helper: parse the config string and strdup into key/value
1622 * strings. Set *result to the list, or NULL if parsing the string
1623 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1624 * misformatted lines. */
1626 config_get_lines(const char *string, config_line_t **result)
1628 config_line_t *list = NULL, **next;
1629 char *k, *v;
1631 next = &list;
1632 do {
1633 k = v = NULL;
1634 string = parse_config_line_from_str(string, &k, &v);
1635 if (!string) {
1636 config_free_lines(list);
1637 tor_free(k);
1638 tor_free(v);
1639 return -1;
1641 if (k && v) {
1642 /* This list can get long, so we keep a pointer to the end of it
1643 * rather than using config_line_append over and over and getting
1644 * n^2 performance. */
1645 *next = tor_malloc(sizeof(config_line_t));
1646 (*next)->key = k;
1647 (*next)->value = v;
1648 (*next)->next = NULL;
1649 next = &((*next)->next);
1650 } else {
1651 tor_free(k);
1652 tor_free(v);
1654 } while (*string);
1656 *result = list;
1657 return 0;
1661 * Free all the configuration lines on the linked list <b>front</b>.
1663 void
1664 config_free_lines(config_line_t *front)
1666 config_line_t *tmp;
1668 while (front) {
1669 tmp = front;
1670 front = tmp->next;
1672 tor_free(tmp->key);
1673 tor_free(tmp->value);
1674 tor_free(tmp);
1678 /** Return the description for a given configuration variable, or NULL if no
1679 * description exists. */
1680 static const char *
1681 config_find_description(config_format_t *fmt, const char *name)
1683 int i;
1684 for (i=0; fmt->descriptions[i].name; ++i) {
1685 if (!strcasecmp(name, fmt->descriptions[i].name))
1686 return fmt->descriptions[i].description;
1688 return NULL;
1691 /** If <b>key</b> is a configuration option, return the corresponding
1692 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1693 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1695 static config_var_t *
1696 config_find_option(config_format_t *fmt, const char *key)
1698 int i;
1699 size_t keylen = strlen(key);
1700 if (!keylen)
1701 return NULL; /* if they say "--" on the command line, it's not an option */
1702 /* First, check for an exact (case-insensitive) match */
1703 for (i=0; fmt->vars[i].name; ++i) {
1704 if (!strcasecmp(key, fmt->vars[i].name)) {
1705 return &fmt->vars[i];
1708 /* If none, check for an abbreviated match */
1709 for (i=0; fmt->vars[i].name; ++i) {
1710 if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
1711 log_warn(LD_CONFIG, "The abbreviation '%s' is deprecated. "
1712 "Please use '%s' instead",
1713 key, fmt->vars[i].name);
1714 return &fmt->vars[i];
1717 /* Okay, unrecognized option */
1718 return NULL;
1722 * Functions to assign config options.
1725 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1726 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1728 * Called from config_assign_line() and option_reset().
1730 static int
1731 config_assign_value(config_format_t *fmt, or_options_t *options,
1732 config_line_t *c, char **msg)
1734 int i, r, ok;
1735 char buf[1024];
1736 config_var_t *var;
1737 void *lvalue;
1739 CHECK(fmt, options);
1741 var = config_find_option(fmt, c->key);
1742 tor_assert(var);
1744 lvalue = STRUCT_VAR_P(options, var->var_offset);
1746 switch (var->type) {
1748 case CONFIG_TYPE_UINT:
1749 i = (int)tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
1750 if (!ok) {
1751 r = tor_snprintf(buf, sizeof(buf),
1752 "Int keyword '%s %s' is malformed or out of bounds.",
1753 c->key, c->value);
1754 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1755 return -1;
1757 *(int *)lvalue = i;
1758 break;
1760 case CONFIG_TYPE_INTERVAL: {
1761 i = config_parse_interval(c->value, &ok);
1762 if (!ok) {
1763 r = tor_snprintf(buf, sizeof(buf),
1764 "Interval '%s %s' is malformed or out of bounds.",
1765 c->key, c->value);
1766 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1767 return -1;
1769 *(int *)lvalue = i;
1770 break;
1773 case CONFIG_TYPE_MEMUNIT: {
1774 uint64_t u64 = config_parse_memunit(c->value, &ok);
1775 if (!ok) {
1776 r = tor_snprintf(buf, sizeof(buf),
1777 "Value '%s %s' is malformed or out of bounds.",
1778 c->key, c->value);
1779 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1780 return -1;
1782 *(uint64_t *)lvalue = u64;
1783 break;
1786 case CONFIG_TYPE_BOOL:
1787 i = (int)tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
1788 if (!ok) {
1789 r = tor_snprintf(buf, sizeof(buf),
1790 "Boolean '%s %s' expects 0 or 1.",
1791 c->key, c->value);
1792 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1793 return -1;
1795 *(int *)lvalue = i;
1796 break;
1798 case CONFIG_TYPE_STRING:
1799 case CONFIG_TYPE_FILENAME:
1800 tor_free(*(char **)lvalue);
1801 *(char **)lvalue = tor_strdup(c->value);
1802 break;
1804 case CONFIG_TYPE_DOUBLE:
1805 *(double *)lvalue = atof(c->value);
1806 break;
1808 case CONFIG_TYPE_ISOTIME:
1809 if (parse_iso_time(c->value, (time_t *)lvalue)) {
1810 r = tor_snprintf(buf, sizeof(buf),
1811 "Invalid time '%s' for keyword '%s'", c->value, c->key);
1812 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1813 return -1;
1815 break;
1817 case CONFIG_TYPE_ROUTERSET:
1818 if (*(routerset_t**)lvalue) {
1819 routerset_free(*(routerset_t**)lvalue);
1821 *(routerset_t**)lvalue = routerset_new();
1822 if (routerset_parse(*(routerset_t**)lvalue, c->value, c->key)<0) {
1823 tor_snprintf(buf, sizeof(buf), "Invalid exit list '%s' for option '%s'",
1824 c->value, c->key);
1825 *msg = tor_strdup(buf);
1826 return -1;
1828 break;
1830 case CONFIG_TYPE_CSV:
1831 if (*(smartlist_t**)lvalue) {
1832 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
1833 smartlist_clear(*(smartlist_t**)lvalue);
1834 } else {
1835 *(smartlist_t**)lvalue = smartlist_create();
1838 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
1839 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1840 break;
1842 case CONFIG_TYPE_LINELIST:
1843 case CONFIG_TYPE_LINELIST_S:
1844 config_line_append((config_line_t**)lvalue, c->key, c->value);
1845 break;
1846 case CONFIG_TYPE_OBSOLETE:
1847 log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
1848 break;
1849 case CONFIG_TYPE_LINELIST_V:
1850 r = tor_snprintf(buf, sizeof(buf),
1851 "You may not provide a value for virtual option '%s'", c->key);
1852 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1853 return -1;
1854 default:
1855 tor_assert(0);
1856 break;
1858 return 0;
1861 /** If <b>c</b> is a syntactically valid configuration line, update
1862 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1863 * key, -2 for bad value.
1865 * If <b>clear_first</b> is set, clear the value first. Then if
1866 * <b>use_defaults</b> is set, set the value to the default.
1868 * Called from config_assign().
1870 static int
1871 config_assign_line(config_format_t *fmt, or_options_t *options,
1872 config_line_t *c, int use_defaults,
1873 int clear_first, char **msg)
1875 config_var_t *var;
1877 CHECK(fmt, options);
1879 var = config_find_option(fmt, c->key);
1880 if (!var) {
1881 if (fmt->extra) {
1882 void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
1883 log_info(LD_CONFIG,
1884 "Found unrecognized option '%s'; saving it.", c->key);
1885 config_line_append((config_line_t**)lvalue, c->key, c->value);
1886 return 0;
1887 } else {
1888 char buf[1024];
1889 int tmp = tor_snprintf(buf, sizeof(buf),
1890 "Unknown option '%s'. Failing.", c->key);
1891 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1892 return -1;
1895 /* Put keyword into canonical case. */
1896 if (strcmp(var->name, c->key)) {
1897 tor_free(c->key);
1898 c->key = tor_strdup(var->name);
1901 if (!strlen(c->value)) {
1902 /* reset or clear it, then return */
1903 if (!clear_first) {
1904 if (var->type == CONFIG_TYPE_LINELIST ||
1905 var->type == CONFIG_TYPE_LINELIST_S) {
1906 /* We got an empty linelist from the torrc or command line.
1907 As a special case, call this an error. Warn and ignore. */
1908 log_warn(LD_CONFIG,
1909 "Linelist option '%s' has no value. Skipping.", c->key);
1910 } else { /* not already cleared */
1911 option_reset(fmt, options, var, use_defaults);
1914 return 0;
1917 if (config_assign_value(fmt, options, c, msg) < 0)
1918 return -2;
1919 return 0;
1922 /** Restore the option named <b>key</b> in options to its default value.
1923 * Called from config_assign(). */
1924 static void
1925 config_reset_line(config_format_t *fmt, or_options_t *options,
1926 const char *key, int use_defaults)
1928 config_var_t *var;
1930 CHECK(fmt, options);
1932 var = config_find_option(fmt, key);
1933 if (!var)
1934 return; /* give error on next pass. */
1936 option_reset(fmt, options, var, use_defaults);
1939 /** Return true iff key is a valid configuration option. */
1941 option_is_recognized(const char *key)
1943 config_var_t *var = config_find_option(&options_format, key);
1944 return (var != NULL);
1947 /** Return the canonical name of a configuration option, or NULL
1948 * if no such option exists. */
1949 const char *
1950 option_get_canonical_name(const char *key)
1952 config_var_t *var = config_find_option(&options_format, key);
1953 return var ? var->name : NULL;
1956 /** Return a canonical list of the options assigned for key.
1958 config_line_t *
1959 option_get_assignment(or_options_t *options, const char *key)
1961 return get_assigned_option(&options_format, options, key, 1);
1964 /** Return true iff value needs to be quoted and escaped to be used in
1965 * a configuration file. */
1966 static int
1967 config_value_needs_escape(const char *value)
1969 if (*value == '\"')
1970 return 1;
1971 while (*value) {
1972 switch (*value)
1974 case '\r':
1975 case '\n':
1976 case '#':
1977 /* Note: quotes and backspaces need special handling when we are using
1978 * quotes, not otherwise, so they don't trigger escaping on their
1979 * own. */
1980 return 1;
1981 default:
1982 if (!TOR_ISPRINT(*value))
1983 return 1;
1985 ++value;
1987 return 0;
1990 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1991 static config_line_t *
1992 config_lines_dup(const config_line_t *inp)
1994 config_line_t *result = NULL;
1995 config_line_t **next_out = &result;
1996 while (inp) {
1997 *next_out = tor_malloc(sizeof(config_line_t));
1998 (*next_out)->key = tor_strdup(inp->key);
1999 (*next_out)->value = tor_strdup(inp->value);
2000 inp = inp->next;
2001 next_out = &((*next_out)->next);
2003 (*next_out) = NULL;
2004 return result;
2007 /** Return newly allocated line or lines corresponding to <b>key</b> in the
2008 * configuration <b>options</b>. If <b>escape_val</b> is true and a
2009 * value needs to be quoted before it's put in a config file, quote and
2010 * escape that value. Return NULL if no such key exists. */
2011 static config_line_t *
2012 get_assigned_option(config_format_t *fmt, void *options,
2013 const char *key, int escape_val)
2015 config_var_t *var;
2016 const void *value;
2017 char buf[32];
2018 config_line_t *result;
2019 tor_assert(options && key);
2021 CHECK(fmt, options);
2023 var = config_find_option(fmt, key);
2024 if (!var) {
2025 log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
2026 return NULL;
2028 value = STRUCT_VAR_P(options, var->var_offset);
2030 result = tor_malloc_zero(sizeof(config_line_t));
2031 result->key = tor_strdup(var->name);
2032 switch (var->type)
2034 case CONFIG_TYPE_STRING:
2035 case CONFIG_TYPE_FILENAME:
2036 if (*(char**)value) {
2037 result->value = tor_strdup(*(char**)value);
2038 } else {
2039 tor_free(result->key);
2040 tor_free(result);
2041 return NULL;
2043 break;
2044 case CONFIG_TYPE_ISOTIME:
2045 if (*(time_t*)value) {
2046 result->value = tor_malloc(ISO_TIME_LEN+1);
2047 format_iso_time(result->value, *(time_t*)value);
2048 } else {
2049 tor_free(result->key);
2050 tor_free(result);
2052 escape_val = 0; /* Can't need escape. */
2053 break;
2054 case CONFIG_TYPE_INTERVAL:
2055 case CONFIG_TYPE_UINT:
2056 /* This means every or_options_t uint or bool element
2057 * needs to be an int. Not, say, a uint16_t or char. */
2058 tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
2059 result->value = tor_strdup(buf);
2060 escape_val = 0; /* Can't need escape. */
2061 break;
2062 case CONFIG_TYPE_MEMUNIT:
2063 tor_snprintf(buf, sizeof(buf), U64_FORMAT,
2064 U64_PRINTF_ARG(*(uint64_t*)value));
2065 result->value = tor_strdup(buf);
2066 escape_val = 0; /* Can't need escape. */
2067 break;
2068 case CONFIG_TYPE_DOUBLE:
2069 tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
2070 result->value = tor_strdup(buf);
2071 escape_val = 0; /* Can't need escape. */
2072 break;
2073 case CONFIG_TYPE_BOOL:
2074 result->value = tor_strdup(*(int*)value ? "1" : "0");
2075 escape_val = 0; /* Can't need escape. */
2076 break;
2077 case CONFIG_TYPE_ROUTERSET:
2078 result->value = routerset_to_string(*(routerset_t**)value);
2079 break;
2080 case CONFIG_TYPE_CSV:
2081 if (*(smartlist_t**)value)
2082 result->value =
2083 smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
2084 else
2085 result->value = tor_strdup("");
2086 break;
2087 case CONFIG_TYPE_OBSOLETE:
2088 log_fn(LOG_PROTOCOL_WARN, LD_CONFIG,
2089 "You asked me for the value of an obsolete config option '%s'.",
2090 key);
2091 tor_free(result->key);
2092 tor_free(result);
2093 return NULL;
2094 case CONFIG_TYPE_LINELIST_S:
2095 log_warn(LD_CONFIG,
2096 "Can't return context-sensitive '%s' on its own", key);
2097 tor_free(result->key);
2098 tor_free(result);
2099 return NULL;
2100 case CONFIG_TYPE_LINELIST:
2101 case CONFIG_TYPE_LINELIST_V:
2102 tor_free(result->key);
2103 tor_free(result);
2104 result = config_lines_dup(*(const config_line_t**)value);
2105 break;
2106 default:
2107 tor_free(result->key);
2108 tor_free(result);
2109 log_warn(LD_BUG,"Unknown type %d for known key '%s'",
2110 var->type, key);
2111 return NULL;
2114 if (escape_val) {
2115 config_line_t *line;
2116 for (line = result; line; line = line->next) {
2117 if (line->value && config_value_needs_escape(line->value)) {
2118 char *newval = esc_for_log(line->value);
2119 tor_free(line->value);
2120 line->value = newval;
2125 return result;
2128 /** Iterate through the linked list of requested options <b>list</b>.
2129 * For each item, convert as appropriate and assign to <b>options</b>.
2130 * If an item is unrecognized, set *msg and return -1 immediately,
2131 * else return 0 for success.
2133 * If <b>clear_first</b>, interpret config options as replacing (not
2134 * extending) their previous values. If <b>clear_first</b> is set,
2135 * then <b>use_defaults</b> to decide if you set to defaults after
2136 * clearing, or make the value 0 or NULL.
2138 * Here are the use cases:
2139 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
2140 * if linelist, replaces current if csv.
2141 * 2. An empty AllowInvalid line in your torrc. Should clear it.
2142 * 3. "RESETCONF AllowInvalid" sets it to default.
2143 * 4. "SETCONF AllowInvalid" makes it NULL.
2144 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
2146 * Use_defaults Clear_first
2147 * 0 0 "append"
2148 * 1 0 undefined, don't use
2149 * 0 1 "set to null first"
2150 * 1 1 "set to defaults first"
2151 * Return 0 on success, -1 on bad key, -2 on bad value.
2153 * As an additional special case, if a LINELIST config option has
2154 * no value and clear_first is 0, then warn and ignore it.
2158 There are three call cases for config_assign() currently.
2160 Case one: Torrc entry
2161 options_init_from_torrc() calls config_assign(0, 0)
2162 calls config_assign_line(0, 0).
2163 if value is empty, calls option_reset(0) and returns.
2164 calls config_assign_value(), appends.
2166 Case two: setconf
2167 options_trial_assign() calls config_assign(0, 1)
2168 calls config_reset_line(0)
2169 calls option_reset(0)
2170 calls option_clear().
2171 calls config_assign_line(0, 1).
2172 if value is empty, returns.
2173 calls config_assign_value(), appends.
2175 Case three: resetconf
2176 options_trial_assign() calls config_assign(1, 1)
2177 calls config_reset_line(1)
2178 calls option_reset(1)
2179 calls option_clear().
2180 calls config_assign_value(default)
2181 calls config_assign_line(1, 1).
2182 returns.
2184 static int
2185 config_assign(config_format_t *fmt, void *options, config_line_t *list,
2186 int use_defaults, int clear_first, char **msg)
2188 config_line_t *p;
2190 CHECK(fmt, options);
2192 /* pass 1: normalize keys */
2193 for (p = list; p; p = p->next) {
2194 const char *full = expand_abbrev(fmt, p->key, 0, 1);
2195 if (strcmp(full,p->key)) {
2196 tor_free(p->key);
2197 p->key = tor_strdup(full);
2201 /* pass 2: if we're reading from a resetting source, clear all
2202 * mentioned config options, and maybe set to their defaults. */
2203 if (clear_first) {
2204 for (p = list; p; p = p->next)
2205 config_reset_line(fmt, options, p->key, use_defaults);
2208 /* pass 3: assign. */
2209 while (list) {
2210 int r;
2211 if ((r=config_assign_line(fmt, options, list, use_defaults,
2212 clear_first, msg)))
2213 return r;
2214 list = list->next;
2216 return 0;
2219 /** Try assigning <b>list</b> to the global options. You do this by duping
2220 * options, assigning list to the new one, then validating it. If it's
2221 * ok, then throw out the old one and stick with the new one. Else,
2222 * revert to old and return failure. Return SETOPT_OK on success, or
2223 * a setopt_err_t on failure.
2225 * If not success, point *<b>msg</b> to a newly allocated string describing
2226 * what went wrong.
2228 setopt_err_t
2229 options_trial_assign(config_line_t *list, int use_defaults,
2230 int clear_first, char **msg)
2232 int r;
2233 or_options_t *trial_options = options_dup(&options_format, get_options());
2235 if ((r=config_assign(&options_format, trial_options,
2236 list, use_defaults, clear_first, msg)) < 0) {
2237 config_free(&options_format, trial_options);
2238 return r;
2241 if (options_validate(get_options(), trial_options, 1, msg) < 0) {
2242 config_free(&options_format, trial_options);
2243 return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2246 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2247 config_free(&options_format, trial_options);
2248 return SETOPT_ERR_TRANSITION;
2251 if (set_options(trial_options, msg)<0) {
2252 config_free(&options_format, trial_options);
2253 return SETOPT_ERR_SETTING;
2256 /* we liked it. put it in place. */
2257 return SETOPT_OK;
2260 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2261 * Called from option_reset() and config_free(). */
2262 static void
2263 option_clear(config_format_t *fmt, or_options_t *options, config_var_t *var)
2265 void *lvalue = STRUCT_VAR_P(options, var->var_offset);
2266 (void)fmt; /* unused */
2267 switch (var->type) {
2268 case CONFIG_TYPE_STRING:
2269 case CONFIG_TYPE_FILENAME:
2270 tor_free(*(char**)lvalue);
2271 break;
2272 case CONFIG_TYPE_DOUBLE:
2273 *(double*)lvalue = 0.0;
2274 break;
2275 case CONFIG_TYPE_ISOTIME:
2276 *(time_t*)lvalue = 0;
2277 break;
2278 case CONFIG_TYPE_INTERVAL:
2279 case CONFIG_TYPE_UINT:
2280 case CONFIG_TYPE_BOOL:
2281 *(int*)lvalue = 0;
2282 break;
2283 case CONFIG_TYPE_MEMUNIT:
2284 *(uint64_t*)lvalue = 0;
2285 break;
2286 case CONFIG_TYPE_ROUTERSET:
2287 if (*(routerset_t**)lvalue) {
2288 routerset_free(*(routerset_t**)lvalue);
2289 *(routerset_t**)lvalue = NULL;
2291 break;
2292 case CONFIG_TYPE_CSV:
2293 if (*(smartlist_t**)lvalue) {
2294 SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
2295 smartlist_free(*(smartlist_t **)lvalue);
2296 *(smartlist_t **)lvalue = NULL;
2298 break;
2299 case CONFIG_TYPE_LINELIST:
2300 case CONFIG_TYPE_LINELIST_S:
2301 config_free_lines(*(config_line_t **)lvalue);
2302 *(config_line_t **)lvalue = NULL;
2303 break;
2304 case CONFIG_TYPE_LINELIST_V:
2305 /* handled by linelist_s. */
2306 break;
2307 case CONFIG_TYPE_OBSOLETE:
2308 break;
2312 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2313 * <b>use_defaults</b>, set it to its default value.
2314 * Called by config_init() and option_reset_line() and option_assign_line(). */
2315 static void
2316 option_reset(config_format_t *fmt, or_options_t *options,
2317 config_var_t *var, int use_defaults)
2319 config_line_t *c;
2320 char *msg = NULL;
2321 CHECK(fmt, options);
2322 option_clear(fmt, options, var); /* clear it first */
2323 if (!use_defaults)
2324 return; /* all done */
2325 if (var->initvalue) {
2326 c = tor_malloc_zero(sizeof(config_line_t));
2327 c->key = tor_strdup(var->name);
2328 c->value = tor_strdup(var->initvalue);
2329 if (config_assign_value(fmt, options, c, &msg) < 0) {
2330 log_warn(LD_BUG, "Failed to assign default: %s", msg);
2331 tor_free(msg); /* if this happens it's a bug */
2333 config_free_lines(c);
2337 /** Print a usage message for tor. */
2338 static void
2339 print_usage(void)
2341 printf(
2342 "Copyright (c) 2001-2004, Roger Dingledine\n"
2343 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2344 "Copyright (c) 2007-2009, The Tor Project, Inc.\n\n"
2345 "tor -f <torrc> [args]\n"
2346 "See man page for options, or https://www.torproject.org/ for "
2347 "documentation.\n");
2350 /** Print all non-obsolete torrc options. */
2351 static void
2352 list_torrc_options(void)
2354 int i;
2355 smartlist_t *lines = smartlist_create();
2356 for (i = 0; _option_vars[i].name; ++i) {
2357 config_var_t *var = &_option_vars[i];
2358 const char *desc;
2359 if (var->type == CONFIG_TYPE_OBSOLETE ||
2360 var->type == CONFIG_TYPE_LINELIST_V)
2361 continue;
2362 desc = config_find_description(&options_format, var->name);
2363 printf("%s\n", var->name);
2364 if (desc) {
2365 wrap_string(lines, desc, 76, " ", " ");
2366 SMARTLIST_FOREACH(lines, char *, cp, {
2367 printf("%s", cp);
2368 tor_free(cp);
2370 smartlist_clear(lines);
2373 smartlist_free(lines);
2376 /** Last value actually set by resolve_my_address. */
2377 static uint32_t last_resolved_addr = 0;
2379 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2380 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2381 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2382 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2383 * public IP address.
2386 resolve_my_address(int warn_severity, or_options_t *options,
2387 uint32_t *addr_out, char **hostname_out)
2389 struct in_addr in;
2390 struct hostent *rent;
2391 char hostname[256];
2392 int explicit_ip=1;
2393 int explicit_hostname=1;
2394 int from_interface=0;
2395 char tmpbuf[INET_NTOA_BUF_LEN];
2396 const char *address = options->Address;
2397 int notice_severity = warn_severity <= LOG_NOTICE ?
2398 LOG_NOTICE : warn_severity;
2400 tor_assert(addr_out);
2402 if (address && *address) {
2403 strlcpy(hostname, address, sizeof(hostname));
2404 } else { /* then we need to guess our address */
2405 explicit_ip = 0; /* it's implicit */
2406 explicit_hostname = 0; /* it's implicit */
2408 if (gethostname(hostname, sizeof(hostname)) < 0) {
2409 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2410 return -1;
2412 log_debug(LD_CONFIG,"Guessed local host name as '%s'",hostname);
2415 /* now we know hostname. resolve it and keep only the IP address */
2417 if (tor_inet_aton(hostname, &in) == 0) {
2418 /* then we have to resolve it */
2419 explicit_ip = 0;
2420 rent = (struct hostent *)gethostbyname(hostname);
2421 if (!rent) {
2422 uint32_t interface_ip;
2424 if (explicit_hostname) {
2425 log_fn(warn_severity, LD_CONFIG,
2426 "Could not resolve local Address '%s'. Failing.", hostname);
2427 return -1;
2429 log_fn(notice_severity, LD_CONFIG,
2430 "Could not resolve guessed local hostname '%s'. "
2431 "Trying something else.", hostname);
2432 if (get_interface_address(warn_severity, &interface_ip)) {
2433 log_fn(warn_severity, LD_CONFIG,
2434 "Could not get local interface IP address. Failing.");
2435 return -1;
2437 from_interface = 1;
2438 in.s_addr = htonl(interface_ip);
2439 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2440 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2441 "local interface. Using that.", tmpbuf);
2442 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2443 } else {
2444 tor_assert(rent->h_length == 4);
2445 memcpy(&in.s_addr, rent->h_addr, rent->h_length);
2447 if (!explicit_hostname &&
2448 is_internal_IP(ntohl(in.s_addr), 0)) {
2449 uint32_t interface_ip;
2451 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2452 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2453 "resolves to a private IP address (%s). Trying something "
2454 "else.", hostname, tmpbuf);
2456 if (get_interface_address(warn_severity, &interface_ip)) {
2457 log_fn(warn_severity, LD_CONFIG,
2458 "Could not get local interface IP address. Too bad.");
2459 } else if (is_internal_IP(interface_ip, 0)) {
2460 struct in_addr in2;
2461 in2.s_addr = htonl(interface_ip);
2462 tor_inet_ntoa(&in2,tmpbuf,sizeof(tmpbuf));
2463 log_fn(notice_severity, LD_CONFIG,
2464 "Interface IP address '%s' is a private address too. "
2465 "Ignoring.", tmpbuf);
2466 } else {
2467 from_interface = 1;
2468 in.s_addr = htonl(interface_ip);
2469 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2470 log_fn(notice_severity, LD_CONFIG,
2471 "Learned IP address '%s' for local interface."
2472 " Using that.", tmpbuf);
2473 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2479 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2480 if (is_internal_IP(ntohl(in.s_addr), 0) &&
2481 options->_PublishServerDescriptor) {
2482 /* make sure we're ok with publishing an internal IP */
2483 if (!options->DirServers && !options->AlternateDirAuthority) {
2484 /* if they are using the default dirservers, disallow internal IPs
2485 * always. */
2486 log_fn(warn_severity, LD_CONFIG,
2487 "Address '%s' resolves to private IP address '%s'. "
2488 "Tor servers that use the default DirServers must have public "
2489 "IP addresses.", hostname, tmpbuf);
2490 return -1;
2492 if (!explicit_ip) {
2493 /* even if they've set their own dirservers, require an explicit IP if
2494 * they're using an internal address. */
2495 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2496 "IP address '%s'. Please set the Address config option to be "
2497 "the IP address you want to use.", hostname, tmpbuf);
2498 return -1;
2502 log_debug(LD_CONFIG, "Resolved Address to '%s'.", tmpbuf);
2503 *addr_out = ntohl(in.s_addr);
2504 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2505 /* Leave this as a notice, regardless of the requested severity,
2506 * at least until dynamic IP address support becomes bulletproof. */
2507 log_notice(LD_NET,
2508 "Your IP address seems to have changed to %s. Updating.",
2509 tmpbuf);
2510 ip_address_changed(0);
2512 if (last_resolved_addr != *addr_out) {
2513 const char *method;
2514 const char *h = hostname;
2515 if (explicit_ip) {
2516 method = "CONFIGURED";
2517 h = NULL;
2518 } else if (explicit_hostname) {
2519 method = "RESOLVED";
2520 } else if (from_interface) {
2521 method = "INTERFACE";
2522 h = NULL;
2523 } else {
2524 method = "GETHOSTNAME";
2526 control_event_server_status(LOG_NOTICE,
2527 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2528 tmpbuf, method, h?"HOSTNAME=":"", h);
2530 last_resolved_addr = *addr_out;
2531 if (hostname_out)
2532 *hostname_out = tor_strdup(hostname);
2533 return 0;
2536 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2537 * on a private network.
2540 is_local_addr(const tor_addr_t *addr)
2542 if (tor_addr_is_internal(addr, 0))
2543 return 1;
2544 /* Check whether ip is on the same /24 as we are. */
2545 if (get_options()->EnforceDistinctSubnets == 0)
2546 return 0;
2547 if (tor_addr_family(addr) == AF_INET) {
2548 /*XXXX022 IP6 what corresponds to an /24? */
2549 uint32_t ip = tor_addr_to_ipv4h(addr);
2551 /* It's possible that this next check will hit before the first time
2552 * resolve_my_address actually succeeds. (For clients, it is likely that
2553 * resolve_my_address will never be called at all). In those cases,
2554 * last_resolved_addr will be 0, and so checking to see whether ip is on
2555 * the same /24 as last_resolved_addr will be the same as checking whether
2556 * it was on net 0, which is already done by is_internal_IP.
2558 if ((last_resolved_addr & (uint32_t)0xffffff00ul)
2559 == (ip & (uint32_t)0xffffff00ul))
2560 return 1;
2562 return 0;
2565 /** Called when we don't have a nickname set. Try to guess a good nickname
2566 * based on the hostname, and return it in a newly allocated string. If we
2567 * can't, return NULL and let the caller warn if it wants to. */
2568 static char *
2569 get_default_nickname(void)
2571 static const char * const bad_default_nicknames[] = {
2572 "localhost",
2573 NULL,
2575 char localhostname[256];
2576 char *cp, *out, *outp;
2577 int i;
2579 if (gethostname(localhostname, sizeof(localhostname)) < 0)
2580 return NULL;
2582 /* Put it in lowercase; stop at the first dot. */
2583 if ((cp = strchr(localhostname, '.')))
2584 *cp = '\0';
2585 tor_strlower(localhostname);
2587 /* Strip invalid characters. */
2588 cp = localhostname;
2589 out = outp = tor_malloc(strlen(localhostname) + 1);
2590 while (*cp) {
2591 if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
2592 *outp++ = *cp++;
2593 else
2594 cp++;
2596 *outp = '\0';
2598 /* Enforce length. */
2599 if (strlen(out) > MAX_NICKNAME_LEN)
2600 out[MAX_NICKNAME_LEN]='\0';
2602 /* Check for dumb names. */
2603 for (i = 0; bad_default_nicknames[i]; ++i) {
2604 if (!strcmp(out, bad_default_nicknames[i])) {
2605 tor_free(out);
2606 return NULL;
2610 return out;
2613 /** Release storage held by <b>options</b>. */
2614 static void
2615 config_free(config_format_t *fmt, void *options)
2617 int i;
2619 if (!options)
2620 return;
2622 tor_assert(fmt);
2624 for (i=0; fmt->vars[i].name; ++i)
2625 option_clear(fmt, options, &(fmt->vars[i]));
2626 if (fmt->extra) {
2627 config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
2628 config_free_lines(*linep);
2629 *linep = NULL;
2631 tor_free(options);
2634 /** Return true iff a and b contain identical keys and values in identical
2635 * order. */
2636 static int
2637 config_lines_eq(config_line_t *a, config_line_t *b)
2639 while (a && b) {
2640 if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
2641 return 0;
2642 a = a->next;
2643 b = b->next;
2645 if (a || b)
2646 return 0;
2647 return 1;
2650 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2651 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2653 static int
2654 option_is_same(config_format_t *fmt,
2655 or_options_t *o1, or_options_t *o2, const char *name)
2657 config_line_t *c1, *c2;
2658 int r = 1;
2659 CHECK(fmt, o1);
2660 CHECK(fmt, o2);
2662 c1 = get_assigned_option(fmt, o1, name, 0);
2663 c2 = get_assigned_option(fmt, o2, name, 0);
2664 r = config_lines_eq(c1, c2);
2665 config_free_lines(c1);
2666 config_free_lines(c2);
2667 return r;
2670 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2671 static or_options_t *
2672 options_dup(config_format_t *fmt, or_options_t *old)
2674 or_options_t *newopts;
2675 int i;
2676 config_line_t *line;
2678 newopts = config_alloc(fmt);
2679 for (i=0; fmt->vars[i].name; ++i) {
2680 if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2681 continue;
2682 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
2683 continue;
2684 line = get_assigned_option(fmt, old, fmt->vars[i].name, 0);
2685 if (line) {
2686 char *msg = NULL;
2687 if (config_assign(fmt, newopts, line, 0, 0, &msg) < 0) {
2688 log_err(LD_BUG, "Config_get_assigned_option() generated "
2689 "something we couldn't config_assign(): %s", msg);
2690 tor_free(msg);
2691 tor_assert(0);
2694 config_free_lines(line);
2696 return newopts;
2699 /** Return a new empty or_options_t. Used for testing. */
2700 or_options_t *
2701 options_new(void)
2703 return config_alloc(&options_format);
2706 /** Set <b>options</b> to hold reasonable defaults for most options.
2707 * Each option defaults to zero. */
2708 void
2709 options_init(or_options_t *options)
2711 config_init(&options_format, options);
2714 /* Check if the port number given in <b>port_option</b> in combination with
2715 * the specified port in <b>listen_options</b> will result in Tor actually
2716 * opening a low port (meaning a port lower than 1024). Return 1 if
2717 * it is, or 0 if it isn't or the concept of a low port isn't applicable for
2718 * the platform we're on. */
2719 static int
2720 is_listening_on_low_port(uint16_t port_option,
2721 const config_line_t *listen_options)
2723 #ifdef MS_WINDOWS
2724 (void) port_option;
2725 (void) listen_options;
2726 return 0; /* No port is too low for windows. */
2727 #else
2728 const config_line_t *l;
2729 uint16_t p;
2730 if (port_option == 0)
2731 return 0; /* We're not listening */
2732 if (listen_options == NULL)
2733 return (port_option < 1024);
2735 for (l = listen_options; l; l = l->next) {
2736 parse_addr_port(LOG_WARN, l->value, NULL, NULL, &p);
2737 if (p<1024) {
2738 return 1;
2741 return 0;
2742 #endif
2745 /** Set all vars in the configuration object <b>options</b> to their default
2746 * values. */
2747 static void
2748 config_init(config_format_t *fmt, void *options)
2750 int i;
2751 config_var_t *var;
2752 CHECK(fmt, options);
2754 for (i=0; fmt->vars[i].name; ++i) {
2755 var = &fmt->vars[i];
2756 if (!var->initvalue)
2757 continue; /* defaults to NULL or 0 */
2758 option_reset(fmt, options, var, 1);
2762 /** Allocate and return a new string holding the written-out values of the vars
2763 * in 'options'. If 'minimal', do not write out any default-valued vars.
2764 * Else, if comment_defaults, write default values as comments.
2766 static char *
2767 config_dump(config_format_t *fmt, void *options, int minimal,
2768 int comment_defaults)
2770 smartlist_t *elements;
2771 or_options_t *defaults;
2772 config_line_t *line, *assigned;
2773 char *result;
2774 int i;
2775 const char *desc;
2776 char *msg = NULL;
2778 defaults = config_alloc(fmt);
2779 config_init(fmt, defaults);
2781 /* XXX use a 1 here so we don't add a new log line while dumping */
2782 if (fmt->validate_fn(NULL,defaults, 1, &msg) < 0) {
2783 log_err(LD_BUG, "Failed to validate default config.");
2784 tor_free(msg);
2785 tor_assert(0);
2788 elements = smartlist_create();
2789 for (i=0; fmt->vars[i].name; ++i) {
2790 int comment_option = 0;
2791 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
2792 fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2793 continue;
2794 /* Don't save 'hidden' control variables. */
2795 if (!strcmpstart(fmt->vars[i].name, "__"))
2796 continue;
2797 if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
2798 continue;
2799 else if (comment_defaults &&
2800 option_is_same(fmt, options, defaults, fmt->vars[i].name))
2801 comment_option = 1;
2803 desc = config_find_description(fmt, fmt->vars[i].name);
2804 line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name, 1);
2806 if (line && desc) {
2807 /* Only dump the description if there's something to describe. */
2808 wrap_string(elements, desc, 78, "# ", "# ");
2811 for (; line; line = line->next) {
2812 size_t len = strlen(line->key) + strlen(line->value) + 5;
2813 char *tmp;
2814 tmp = tor_malloc(len);
2815 if (tor_snprintf(tmp, len, "%s%s %s\n",
2816 comment_option ? "# " : "",
2817 line->key, line->value)<0) {
2818 log_err(LD_BUG,"Internal error writing option value");
2819 tor_assert(0);
2821 smartlist_add(elements, tmp);
2823 config_free_lines(assigned);
2826 if (fmt->extra) {
2827 line = *(config_line_t**)STRUCT_VAR_P(options, fmt->extra->var_offset);
2828 for (; line; line = line->next) {
2829 size_t len = strlen(line->key) + strlen(line->value) + 3;
2830 char *tmp;
2831 tmp = tor_malloc(len);
2832 if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
2833 log_err(LD_BUG,"Internal error writing option value");
2834 tor_assert(0);
2836 smartlist_add(elements, tmp);
2840 result = smartlist_join_strings(elements, "", 0, NULL);
2841 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2842 smartlist_free(elements);
2843 config_free(fmt, defaults);
2844 return result;
2847 /** Return a string containing a possible configuration file that would give
2848 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2849 * include options that are the same as Tor's defaults.
2851 static char *
2852 options_dump(or_options_t *options, int minimal)
2854 return config_dump(&options_format, options, minimal, 0);
2857 /** Return 0 if every element of sl is a string holding a decimal
2858 * representation of a port number, or if sl is NULL.
2859 * Otherwise set *msg and return -1. */
2860 static int
2861 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2863 int i;
2864 char buf[1024];
2865 tor_assert(name);
2867 if (!sl)
2868 return 0;
2870 SMARTLIST_FOREACH(sl, const char *, cp,
2872 i = atoi(cp);
2873 if (i < 1 || i > 65535) {
2874 int r = tor_snprintf(buf, sizeof(buf),
2875 "Port '%s' out of range in %s", cp, name);
2876 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2877 return -1;
2880 return 0;
2883 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2884 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2885 * Else return 0.
2887 static int
2888 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2890 int r;
2891 char buf[1024];
2892 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2893 /* This handles an understandable special case where somebody says "2gb"
2894 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2895 --*value;
2897 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2898 r = tor_snprintf(buf, sizeof(buf), "%s ("U64_FORMAT") must be at most %d",
2899 desc, U64_PRINTF_ARG(*value),
2900 ROUTER_MAX_DECLARED_BANDWIDTH);
2901 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2902 return -1;
2904 return 0;
2907 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2908 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2909 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2910 * Treat "0" as "".
2911 * Return 0 on success or -1 if not a recognized authority type (in which
2912 * case the value of _PublishServerDescriptor is undefined). */
2913 static int
2914 compute_publishserverdescriptor(or_options_t *options)
2916 smartlist_t *list = options->PublishServerDescriptor;
2917 authority_type_t *auth = &options->_PublishServerDescriptor;
2918 *auth = NO_AUTHORITY;
2919 if (!list) /* empty list, answer is none */
2920 return 0;
2921 SMARTLIST_FOREACH(list, const char *, string, {
2922 if (!strcasecmp(string, "v1"))
2923 *auth |= V1_AUTHORITY;
2924 else if (!strcmp(string, "1"))
2925 if (options->BridgeRelay)
2926 *auth |= BRIDGE_AUTHORITY;
2927 else
2928 *auth |= V2_AUTHORITY | V3_AUTHORITY;
2929 else if (!strcasecmp(string, "v2"))
2930 *auth |= V2_AUTHORITY;
2931 else if (!strcasecmp(string, "v3"))
2932 *auth |= V3_AUTHORITY;
2933 else if (!strcasecmp(string, "bridge"))
2934 *auth |= BRIDGE_AUTHORITY;
2935 else if (!strcasecmp(string, "hidserv"))
2936 *auth |= HIDSERV_AUTHORITY;
2937 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2938 /* no authority */;
2939 else
2940 return -1;
2942 return 0;
2945 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2946 * services can overload the directory system. */
2947 #define MIN_REND_POST_PERIOD (10*60)
2949 /** Highest allowable value for RendPostPeriod. */
2950 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2952 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2953 * will generate too many circuits and potentially overload the network. */
2954 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2956 /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
2957 * will generate too many circuits and potentially overload the network. */
2958 #define MIN_CIRCUIT_STREAM_TIMEOUT 10
2960 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2961 * permissible transition from <b>old_options</b>. Else return -1.
2962 * Should have no side effects, except for normalizing the contents of
2963 * <b>options</b>.
2965 * On error, tor_strdup an error explanation into *<b>msg</b>.
2967 * XXX
2968 * If <b>from_setconf</b>, we were called by the controller, and our
2969 * Log line should stay empty. If it's 0, then give us a default log
2970 * if there are no logs defined.
2972 static int
2973 options_validate(or_options_t *old_options, or_options_t *options,
2974 int from_setconf, char **msg)
2976 int i, r;
2977 config_line_t *cl;
2978 const char *uname = get_uname();
2979 char buf[1024];
2980 #define REJECT(arg) \
2981 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2982 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2984 tor_assert(msg);
2985 *msg = NULL;
2987 if (options->ORPort < 0 || options->ORPort > 65535)
2988 REJECT("ORPort option out of bounds.");
2990 if (server_mode(options) &&
2991 (!strcmpstart(uname, "Windows 95") ||
2992 !strcmpstart(uname, "Windows 98") ||
2993 !strcmpstart(uname, "Windows Me"))) {
2994 log(LOG_WARN, LD_CONFIG, "Tor is running as a server, but you are "
2995 "running %s; this probably won't work. See "
2996 "https://wiki.torproject.org/TheOnionRouter/TorFAQ#ServerOS "
2997 "for details.", uname);
3000 if (options->ORPort == 0 && options->ORListenAddress != NULL)
3001 REJECT("ORPort must be defined if ORListenAddress is defined.");
3003 if (options->DirPort == 0 && options->DirListenAddress != NULL)
3004 REJECT("DirPort must be defined if DirListenAddress is defined.");
3006 if (options->DNSPort == 0 && options->DNSListenAddress != NULL)
3007 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
3009 if (options->ControlPort == 0 && options->ControlListenAddress != NULL)
3010 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
3012 if (options->TransPort == 0 && options->TransListenAddress != NULL)
3013 REJECT("TransPort must be defined if TransListenAddress is defined.");
3015 if (options->NatdPort == 0 && options->NatdListenAddress != NULL)
3016 REJECT("NatdPort must be defined if NatdListenAddress is defined.");
3018 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
3019 * configuration does this. */
3021 for (i = 0; i < 3; ++i) {
3022 int is_socks = i==0;
3023 int is_trans = i==1;
3024 config_line_t *line, *opt, *old;
3025 const char *tp;
3026 if (is_socks) {
3027 opt = options->SocksListenAddress;
3028 old = old_options ? old_options->SocksListenAddress : NULL;
3029 tp = "SOCKS proxy";
3030 } else if (is_trans) {
3031 opt = options->TransListenAddress;
3032 old = old_options ? old_options->TransListenAddress : NULL;
3033 tp = "transparent proxy";
3034 } else {
3035 opt = options->NatdListenAddress;
3036 old = old_options ? old_options->NatdListenAddress : NULL;
3037 tp = "natd proxy";
3040 for (line = opt; line; line = line->next) {
3041 char *address = NULL;
3042 uint16_t port;
3043 uint32_t addr;
3044 if (parse_addr_port(LOG_WARN, line->value, &address, &addr, &port)<0)
3045 continue; /* We'll warn about this later. */
3046 if (!is_internal_IP(addr, 1) &&
3047 (!old_options || !config_lines_eq(old, opt))) {
3048 log_warn(LD_CONFIG,
3049 "You specified a public address '%s' for a %s. Other "
3050 "people on the Internet might find your computer and use it as "
3051 "an open %s. Please don't allow this unless you have "
3052 "a good reason.", address, tp, tp);
3054 tor_free(address);
3058 if (validate_data_directory(options)<0)
3059 REJECT("Invalid DataDirectory");
3061 if (options->Nickname == NULL) {
3062 if (server_mode(options)) {
3063 if (!(options->Nickname = get_default_nickname())) {
3064 log_notice(LD_CONFIG, "Couldn't pick a nickname based on "
3065 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME);
3066 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
3067 } else {
3068 log_notice(LD_CONFIG, "Choosing default nickname '%s'",
3069 options->Nickname);
3072 } else {
3073 if (!is_legal_nickname(options->Nickname)) {
3074 r = tor_snprintf(buf, sizeof(buf),
3075 "Nickname '%s' is wrong length or contains illegal characters.",
3076 options->Nickname);
3077 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3078 return -1;
3082 if (server_mode(options) && !options->ContactInfo)
3083 log(LOG_NOTICE, LD_CONFIG, "Your ContactInfo config option is not set. "
3084 "Please consider setting it, so we can contact you if your server is "
3085 "misconfigured or something else goes wrong.");
3087 /* Special case on first boot if no Log options are given. */
3088 if (!options->Logs && !options->RunAsDaemon && !from_setconf)
3089 config_line_append(&options->Logs, "Log", "notice stdout");
3091 if (options_init_logs(options, 1)<0) /* Validate the log(s) */
3092 REJECT("Failed to validate Log options. See logs for details.");
3094 if (options->NoPublish) {
3095 log(LOG_WARN, LD_CONFIG,
3096 "NoPublish is obsolete. Use PublishServerDescriptor instead.");
3097 SMARTLIST_FOREACH(options->PublishServerDescriptor, char *, s,
3098 tor_free(s));
3099 smartlist_clear(options->PublishServerDescriptor);
3102 if (authdir_mode(options)) {
3103 /* confirm that our address isn't broken, so we can complain now */
3104 uint32_t tmp;
3105 if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
3106 REJECT("Failed to resolve/guess local address. See logs for details.");
3109 #ifndef MS_WINDOWS
3110 if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
3111 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
3112 #endif
3114 if (options->SocksPort < 0 || options->SocksPort > 65535)
3115 REJECT("SocksPort option out of bounds.");
3117 if (options->DNSPort < 0 || options->DNSPort > 65535)
3118 REJECT("DNSPort option out of bounds.");
3120 if (options->TransPort < 0 || options->TransPort > 65535)
3121 REJECT("TransPort option out of bounds.");
3123 if (options->NatdPort < 0 || options->NatdPort > 65535)
3124 REJECT("NatdPort option out of bounds.");
3126 if (options->SocksPort == 0 && options->TransPort == 0 &&
3127 options->NatdPort == 0 && options->ORPort == 0 &&
3128 options->DNSPort == 0 && !options->RendConfigLines)
3129 log(LOG_WARN, LD_CONFIG,
3130 "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
3131 "undefined, and there aren't any hidden services configured. "
3132 "Tor will still run, but probably won't do anything.");
3134 if (options->ControlPort < 0 || options->ControlPort > 65535)
3135 REJECT("ControlPort option out of bounds.");
3137 if (options->DirPort < 0 || options->DirPort > 65535)
3138 REJECT("DirPort option out of bounds.");
3140 #ifndef USE_TRANSPARENT
3141 if (options->TransPort || options->TransListenAddress)
3142 REJECT("TransPort and TransListenAddress are disabled in this build.");
3143 #endif
3145 if (options->AccountingMax &&
3146 (is_listening_on_low_port(options->ORPort, options->ORListenAddress) ||
3147 is_listening_on_low_port(options->DirPort, options->DirListenAddress)))
3149 log(LOG_WARN, LD_CONFIG,
3150 "You have set AccountingMax to use hibernation. You have also "
3151 "chosen a low DirPort or OrPort. This combination can make Tor stop "
3152 "working when it tries to re-attach the port after a period of "
3153 "hibernation. Please choose a different port or turn off "
3154 "hibernation unless you know this combination will work on your "
3155 "platform.");
3158 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3159 options->_ExcludeExitNodesUnion = routerset_new();
3160 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeExitNodes);
3161 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeNodes);
3164 if (options->StrictExitNodes &&
3165 (!options->ExitNodes) &&
3166 (!old_options ||
3167 (old_options->StrictExitNodes != options->StrictExitNodes) ||
3168 (!routerset_equal(old_options->ExitNodes,options->ExitNodes))))
3169 COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
3171 if (options->StrictEntryNodes &&
3172 (!options->EntryNodes) &&
3173 (!old_options ||
3174 (old_options->StrictEntryNodes != options->StrictEntryNodes) ||
3175 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
3176 COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
3178 if (options->EntryNodes && !routerset_is_list(options->EntryNodes)) {
3179 /* XXXX fix this; see entry_guards_prepend_from_config(). */
3180 REJECT("IPs or countries are not yet supported in EntryNodes.");
3183 if (options->AuthoritativeDir) {
3184 if (!options->ContactInfo && !options->TestingTorNetwork)
3185 REJECT("Authoritative directory servers must set ContactInfo");
3186 if (options->V1AuthoritativeDir && !options->RecommendedVersions)
3187 REJECT("V1 authoritative dir servers must set RecommendedVersions.");
3188 if (!options->RecommendedClientVersions)
3189 options->RecommendedClientVersions =
3190 config_lines_dup(options->RecommendedVersions);
3191 if (!options->RecommendedServerVersions)
3192 options->RecommendedServerVersions =
3193 config_lines_dup(options->RecommendedVersions);
3194 if (options->VersioningAuthoritativeDir &&
3195 (!options->RecommendedClientVersions ||
3196 !options->RecommendedServerVersions))
3197 REJECT("Versioning authoritative dir servers must set "
3198 "Recommended*Versions.");
3199 if (options->UseEntryGuards) {
3200 log_info(LD_CONFIG, "Authoritative directory servers can't set "
3201 "UseEntryGuards. Disabling.");
3202 options->UseEntryGuards = 0;
3204 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
3205 log_info(LD_CONFIG, "Authoritative directories always try to download "
3206 "extra-info documents. Setting DownloadExtraInfo.");
3207 options->DownloadExtraInfo = 1;
3209 if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
3210 options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
3211 options->V3AuthoritativeDir))
3212 REJECT("AuthoritativeDir is set, but none of "
3213 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
3214 /* If we have a v3bandwidthsfile and it's broken, complain on startup */
3215 if (options->V3BandwidthsFile && !old_options) {
3216 dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
3220 if (options->AuthoritativeDir && !options->DirPort)
3221 REJECT("Running as authoritative directory, but no DirPort set.");
3223 if (options->AuthoritativeDir && !options->ORPort)
3224 REJECT("Running as authoritative directory, but no ORPort set.");
3226 if (options->AuthoritativeDir && options->ClientOnly)
3227 REJECT("Running as authoritative directory, but ClientOnly also set.");
3229 if (options->HSAuthorityRecordStats && !options->HSAuthoritativeDir)
3230 REJECT("HSAuthorityRecordStats is set but we're not running as "
3231 "a hidden service authority.");
3233 if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
3234 REJECT("FetchDirInfoExtraEarly requires that you also set "
3235 "FetchDirInfoEarly");
3237 if (options->ConnLimit <= 0) {
3238 r = tor_snprintf(buf, sizeof(buf),
3239 "ConnLimit must be greater than 0, but was set to %d",
3240 options->ConnLimit);
3241 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3242 return -1;
3245 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3246 return -1;
3248 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3249 return -1;
3251 if (validate_ports_csv(options->RejectPlaintextPorts,
3252 "RejectPlaintextPorts", msg) < 0)
3253 return -1;
3255 if (validate_ports_csv(options->WarnPlaintextPorts,
3256 "WarnPlaintextPorts", msg) < 0)
3257 return -1;
3259 if (options->FascistFirewall && !options->ReachableAddresses) {
3260 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3261 /* We already have firewall ports set, so migrate them to
3262 * ReachableAddresses, which will set ReachableORAddresses and
3263 * ReachableDirAddresses if they aren't set explicitly. */
3264 smartlist_t *instead = smartlist_create();
3265 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3266 new_line->key = tor_strdup("ReachableAddresses");
3267 /* If we're configured with the old format, we need to prepend some
3268 * open ports. */
3269 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3271 int p = atoi(portno);
3272 char *s;
3273 if (p<0) continue;
3274 s = tor_malloc(16);
3275 tor_snprintf(s, 16, "*:%d", p);
3276 smartlist_add(instead, s);
3278 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3279 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3280 log(LOG_NOTICE, LD_CONFIG,
3281 "Converting FascistFirewall and FirewallPorts "
3282 "config options to new format: \"ReachableAddresses %s\"",
3283 new_line->value);
3284 options->ReachableAddresses = new_line;
3285 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3286 smartlist_free(instead);
3287 } else {
3288 /* We do not have FirewallPorts set, so add 80 to
3289 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3290 if (!options->ReachableDirAddresses) {
3291 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3292 new_line->key = tor_strdup("ReachableDirAddresses");
3293 new_line->value = tor_strdup("*:80");
3294 options->ReachableDirAddresses = new_line;
3295 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3296 "to new format: \"ReachableDirAddresses *:80\"");
3298 if (!options->ReachableORAddresses) {
3299 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3300 new_line->key = tor_strdup("ReachableORAddresses");
3301 new_line->value = tor_strdup("*:443");
3302 options->ReachableORAddresses = new_line;
3303 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3304 "to new format: \"ReachableORAddresses *:443\"");
3309 for (i=0; i<3; i++) {
3310 config_line_t **linep =
3311 (i==0) ? &options->ReachableAddresses :
3312 (i==1) ? &options->ReachableORAddresses :
3313 &options->ReachableDirAddresses;
3314 if (!*linep)
3315 continue;
3316 /* We need to end with a reject *:*, not an implicit accept *:* */
3317 for (;;) {
3318 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
3319 break;
3320 linep = &((*linep)->next);
3321 if (!*linep) {
3322 *linep = tor_malloc_zero(sizeof(config_line_t));
3323 (*linep)->key = tor_strdup(
3324 (i==0) ? "ReachableAddresses" :
3325 (i==1) ? "ReachableORAddresses" :
3326 "ReachableDirAddresses");
3327 (*linep)->value = tor_strdup("reject *:*");
3328 break;
3333 if ((options->ReachableAddresses ||
3334 options->ReachableORAddresses ||
3335 options->ReachableDirAddresses) &&
3336 server_mode(options))
3337 REJECT("Servers must be able to freely connect to the rest "
3338 "of the Internet, so they must not set Reachable*Addresses "
3339 "or FascistFirewall.");
3341 if (options->UseBridges &&
3342 server_mode(options))
3343 REJECT("Servers must be able to freely connect to the rest "
3344 "of the Internet, so they must not set UseBridges.");
3346 options->_AllowInvalid = 0;
3347 if (options->AllowInvalidNodes) {
3348 SMARTLIST_FOREACH(options->AllowInvalidNodes, const char *, cp, {
3349 if (!strcasecmp(cp, "entry"))
3350 options->_AllowInvalid |= ALLOW_INVALID_ENTRY;
3351 else if (!strcasecmp(cp, "exit"))
3352 options->_AllowInvalid |= ALLOW_INVALID_EXIT;
3353 else if (!strcasecmp(cp, "middle"))
3354 options->_AllowInvalid |= ALLOW_INVALID_MIDDLE;
3355 else if (!strcasecmp(cp, "introduction"))
3356 options->_AllowInvalid |= ALLOW_INVALID_INTRODUCTION;
3357 else if (!strcasecmp(cp, "rendezvous"))
3358 options->_AllowInvalid |= ALLOW_INVALID_RENDEZVOUS;
3359 else {
3360 r = tor_snprintf(buf, sizeof(buf),
3361 "Unrecognized value '%s' in AllowInvalidNodes", cp);
3362 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3363 return -1;
3368 if (compute_publishserverdescriptor(options) < 0) {
3369 r = tor_snprintf(buf, sizeof(buf),
3370 "Unrecognized value in PublishServerDescriptor");
3371 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3372 return -1;
3375 if ((options->BridgeRelay
3376 || options->_PublishServerDescriptor & BRIDGE_AUTHORITY)
3377 && (options->_PublishServerDescriptor
3378 & (V1_AUTHORITY|V2_AUTHORITY|V3_AUTHORITY))) {
3379 REJECT("Bridges are not supposed to publish router descriptors to the "
3380 "directory authorities. Please correct your "
3381 "PublishServerDescriptor line.");
3384 if (options->MinUptimeHidServDirectoryV2 < 0) {
3385 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3386 "least 0 seconds. Changing to 0.");
3387 options->MinUptimeHidServDirectoryV2 = 0;
3390 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
3391 log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
3392 "raising to %d seconds.", MIN_REND_POST_PERIOD);
3393 options->RendPostPeriod = MIN_REND_POST_PERIOD;
3396 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3397 log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3398 MAX_DIR_PERIOD);
3399 options->RendPostPeriod = MAX_DIR_PERIOD;
3402 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3403 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3404 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3405 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3408 if (options->CircuitStreamTimeout &&
3409 options->CircuitStreamTimeout < MIN_CIRCUIT_STREAM_TIMEOUT) {
3410 log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
3411 "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
3412 options->CircuitStreamTimeout = MIN_CIRCUIT_STREAM_TIMEOUT;
3415 if (options->KeepalivePeriod < 1)
3416 REJECT("KeepalivePeriod option must be positive.");
3418 if (ensure_bandwidth_cap(&options->BandwidthRate,
3419 "BandwidthRate", msg) < 0)
3420 return -1;
3421 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3422 "BandwidthBurst", msg) < 0)
3423 return -1;
3424 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3425 "MaxAdvertisedBandwidth", msg) < 0)
3426 return -1;
3427 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3428 "RelayBandwidthRate", msg) < 0)
3429 return -1;
3430 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3431 "RelayBandwidthBurst", msg) < 0)
3432 return -1;
3434 if (server_mode(options)) {
3435 if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3436 r = tor_snprintf(buf, sizeof(buf),
3437 "BandwidthRate is set to %d bytes/second. "
3438 "For servers, it must be at least %d.",
3439 (int)options->BandwidthRate,
3440 ROUTER_REQUIRED_MIN_BANDWIDTH);
3441 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3442 return -1;
3443 } else if (options->MaxAdvertisedBandwidth <
3444 ROUTER_REQUIRED_MIN_BANDWIDTH/2) {
3445 r = tor_snprintf(buf, sizeof(buf),
3446 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3447 "For servers, it must be at least %d.",
3448 (int)options->MaxAdvertisedBandwidth,
3449 ROUTER_REQUIRED_MIN_BANDWIDTH/2);
3450 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3451 return -1;
3453 if (options->RelayBandwidthRate &&
3454 options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3455 r = tor_snprintf(buf, sizeof(buf),
3456 "RelayBandwidthRate is set to %d bytes/second. "
3457 "For servers, it must be at least %d.",
3458 (int)options->RelayBandwidthRate,
3459 ROUTER_REQUIRED_MIN_BANDWIDTH);
3460 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3461 return -1;
3465 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3466 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3468 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3469 REJECT("RelayBandwidthBurst must be at least equal "
3470 "to RelayBandwidthRate.");
3472 if (options->BandwidthRate > options->BandwidthBurst)
3473 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3475 /* if they set relaybandwidth* really high but left bandwidth*
3476 * at the default, raise the defaults. */
3477 if (options->RelayBandwidthRate > options->BandwidthRate)
3478 options->BandwidthRate = options->RelayBandwidthRate;
3479 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3480 options->BandwidthBurst = options->RelayBandwidthBurst;
3482 if (accounting_parse_options(options, 1)<0)
3483 REJECT("Failed to parse accounting options. See logs for details.");
3485 if (options->HttpProxy) { /* parse it now */
3486 if (tor_addr_port_parse(options->HttpProxy,
3487 &options->HttpProxyAddr, &options->HttpProxyPort) < 0)
3488 REJECT("HttpProxy failed to parse or resolve. Please fix.");
3489 if (options->HttpProxyPort == 0) { /* give it a default */
3490 options->HttpProxyPort = 80;
3494 if (options->HttpProxyAuthenticator) {
3495 if (strlen(options->HttpProxyAuthenticator) >= 48)
3496 REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
3499 if (options->HttpsProxy) { /* parse it now */
3500 if (tor_addr_port_parse(options->HttpsProxy,
3501 &options->HttpsProxyAddr, &options->HttpsProxyPort) <0)
3502 REJECT("HttpsProxy failed to parse or resolve. Please fix.");
3503 if (options->HttpsProxyPort == 0) { /* give it a default */
3504 options->HttpsProxyPort = 443;
3508 if (options->HttpsProxyAuthenticator) {
3509 if (strlen(options->HttpsProxyAuthenticator) >= 48)
3510 REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
3513 if (options->Socks4Proxy) { /* parse it now */
3514 if (tor_addr_port_parse(options->Socks4Proxy,
3515 &options->Socks4ProxyAddr,
3516 &options->Socks4ProxyPort) <0)
3517 REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
3518 if (options->Socks4ProxyPort == 0) { /* give it a default */
3519 options->Socks4ProxyPort = 1080;
3523 if (options->Socks5Proxy) { /* parse it now */
3524 if (tor_addr_port_parse(options->Socks5Proxy,
3525 &options->Socks5ProxyAddr,
3526 &options->Socks5ProxyPort) <0)
3527 REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
3528 if (options->Socks5ProxyPort == 0) { /* give it a default */
3529 options->Socks5ProxyPort = 1080;
3533 if (options->Socks4Proxy && options->Socks5Proxy)
3534 REJECT("You cannot specify both Socks4Proxy and SOCKS5Proxy");
3536 if (options->Socks5ProxyUsername) {
3537 size_t len;
3539 len = strlen(options->Socks5ProxyUsername);
3540 if (len < 1 || len > 255)
3541 REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
3543 if (!options->Socks5ProxyPassword)
3544 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3546 len = strlen(options->Socks5ProxyPassword);
3547 if (len < 1 || len > 255)
3548 REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
3549 } else if (options->Socks5ProxyPassword)
3550 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3552 if (options->HashedControlPassword) {
3553 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3554 if (!sl) {
3555 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3556 } else {
3557 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3558 smartlist_free(sl);
3562 if (options->HashedControlSessionPassword) {
3563 smartlist_t *sl = decode_hashed_passwords(
3564 options->HashedControlSessionPassword);
3565 if (!sl) {
3566 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3567 } else {
3568 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3569 smartlist_free(sl);
3573 if (options->ControlListenAddress) {
3574 int all_are_local = 1;
3575 config_line_t *ln;
3576 for (ln = options->ControlListenAddress; ln; ln = ln->next) {
3577 if (strcmpstart(ln->value, "127."))
3578 all_are_local = 0;
3580 if (!all_are_local) {
3581 if (!options->HashedControlPassword &&
3582 !options->HashedControlSessionPassword &&
3583 !options->CookieAuthentication) {
3584 log_warn(LD_CONFIG,
3585 "You have a ControlListenAddress set to accept "
3586 "unauthenticated connections from a non-local address. "
3587 "This means that programs not running on your computer "
3588 "can reconfigure your Tor, without even having to guess a "
3589 "password. That's so bad that I'm closing your ControlPort "
3590 "for you. If you need to control your Tor remotely, try "
3591 "enabling authentication and using a tool like stunnel or "
3592 "ssh to encrypt remote access.");
3593 options->ControlPort = 0;
3594 } else {
3595 log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
3596 "connections from a non-local address. This means that "
3597 "programs not running on your computer can reconfigure your "
3598 "Tor. That's pretty bad, since the controller "
3599 "protocol isn't encrypted! Maybe you should just listen on "
3600 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
3601 "remote connections to your control port.");
3606 if (options->ControlPort && !options->HashedControlPassword &&
3607 !options->HashedControlSessionPassword &&
3608 !options->CookieAuthentication) {
3609 log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
3610 "has been configured. This means that any program on your "
3611 "computer can reconfigure your Tor. That's bad! You should "
3612 "upgrade your Tor controller as soon as possible.");
3615 if (options->UseEntryGuards && ! options->NumEntryGuards)
3616 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3618 if (check_nickname_list(options->MyFamily, "MyFamily", msg))
3619 return -1;
3620 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3621 if (check_nickname_list(cl->value, "NodeFamily", msg))
3622 return -1;
3625 if (validate_addr_policies(options, msg) < 0)
3626 return -1;
3628 if (validate_dir_authorities(options, old_options) < 0)
3629 REJECT("Directory authority line did not parse. See logs for details.");
3631 if (options->UseBridges && !options->Bridges)
3632 REJECT("If you set UseBridges, you must specify at least one bridge.");
3633 if (options->UseBridges && !options->TunnelDirConns)
3634 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3635 if (options->Bridges) {
3636 for (cl = options->Bridges; cl; cl = cl->next) {
3637 if (parse_bridge_line(cl->value, 1)<0)
3638 REJECT("Bridge line did not parse. See logs for details.");
3642 if (options->ConstrainedSockets) {
3643 /* If the user wants to constrain socket buffer use, make sure the desired
3644 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3645 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3646 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3647 options->ConstrainedSockSize % 1024) {
3648 r = tor_snprintf(buf, sizeof(buf),
3649 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3650 "in 1024 byte increments.",
3651 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3652 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3653 return -1;
3655 if (options->DirPort) {
3656 /* Providing cached directory entries while system TCP buffers are scarce
3657 * will exacerbate the socket errors. Suggest that this be disabled. */
3658 COMPLAIN("You have requested constrained socket buffers while also "
3659 "serving directory entries via DirPort. It is strongly "
3660 "suggested that you disable serving directory requests when "
3661 "system TCP buffer resources are scarce.");
3665 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3666 options->V3AuthVotingInterval/2) {
3667 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3668 "V3AuthVotingInterval");
3670 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
3671 REJECT("V3AuthVoteDelay is way too low.");
3672 if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
3673 REJECT("V3AuthDistDelay is way too low.");
3675 if (options->V3AuthNIntervalsValid < 2)
3676 REJECT("V3AuthNIntervalsValid must be at least 2.");
3678 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3679 REJECT("V3AuthVotingInterval is insanely low.");
3680 } else if (options->V3AuthVotingInterval > 24*60*60) {
3681 REJECT("V3AuthVotingInterval is insanely high.");
3682 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3683 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3686 if (rend_config_services(options, 1) < 0)
3687 REJECT("Failed to configure rendezvous options. See logs for details.");
3689 /* Parse client-side authorization for hidden services. */
3690 if (rend_parse_service_authorization(options, 1) < 0)
3691 REJECT("Failed to configure client authorization for hidden services. "
3692 "See logs for details.");
3694 if (parse_virtual_addr_network(options->VirtualAddrNetwork, 1, NULL)<0)
3695 return -1;
3697 if (options->PreferTunneledDirConns && !options->TunnelDirConns)
3698 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3700 if ((options->Socks4Proxy || options->Socks5Proxy) &&
3701 !options->HttpProxy && !options->PreferTunneledDirConns)
3702 REJECT("When Socks4Proxy or Socks5Proxy is configured, "
3703 "PreferTunneledDirConns and TunnelDirConns must both be "
3704 "set to 1, or HttpProxy must be configured.");
3706 if (options->AutomapHostsSuffixes) {
3707 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
3709 size_t len = strlen(suf);
3710 if (len && suf[len-1] == '.')
3711 suf[len-1] = '\0';
3715 if (options->TestingTorNetwork && !options->DirServers) {
3716 REJECT("TestingTorNetwork may only be configured in combination with "
3717 "a non-default set of DirServers.");
3720 /*XXXX022 checking for defaults manually like this is a bit fragile.*/
3722 /* Keep changes to hard-coded values synchronous to man page and default
3723 * values table. */
3724 if (options->TestingV3AuthInitialVotingInterval != 30*60 &&
3725 !options->TestingTorNetwork) {
3726 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
3727 "Tor networks!");
3728 } else if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
3729 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3730 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
3731 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3732 "30 minutes.");
3735 if (options->TestingV3AuthInitialVoteDelay != 5*60 &&
3736 !options->TestingTorNetwork) {
3737 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
3738 "Tor networks!");
3739 } else if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
3740 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3743 if (options->TestingV3AuthInitialDistDelay != 5*60 &&
3744 !options->TestingTorNetwork) {
3745 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
3746 "Tor networks!");
3747 } else if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
3748 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3751 if (options->TestingV3AuthInitialVoteDelay +
3752 options->TestingV3AuthInitialDistDelay >=
3753 options->TestingV3AuthInitialVotingInterval/2) {
3754 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3755 "must be less than half TestingV3AuthInitialVotingInterval");
3758 if (options->TestingAuthDirTimeToLearnReachability != 30*60 &&
3759 !options->TestingTorNetwork) {
3760 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
3761 "testing Tor networks!");
3762 } else if (options->TestingAuthDirTimeToLearnReachability < 0) {
3763 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3764 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
3765 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3768 if (options->TestingEstimatedDescriptorPropagationTime != 10*60 &&
3769 !options->TestingTorNetwork) {
3770 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
3771 "testing Tor networks!");
3772 } else if (options->TestingEstimatedDescriptorPropagationTime < 0) {
3773 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3774 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
3775 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3778 if (options->TestingTorNetwork) {
3779 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
3780 "almost unusable in the public Tor network, and is "
3781 "therefore only advised if you are building a "
3782 "testing Tor network!");
3785 if (options->AccelName && !options->HardwareAccel)
3786 options->HardwareAccel = 1;
3787 if (options->AccelDir && !options->AccelName)
3788 REJECT("Can't use hardware crypto accelerator dir without engine name.");
3790 return 0;
3791 #undef REJECT
3792 #undef COMPLAIN
3795 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3796 * equal strings. */
3797 static int
3798 opt_streq(const char *s1, const char *s2)
3800 if (!s1 && !s2)
3801 return 1;
3802 else if (s1 && s2 && !strcmp(s1,s2))
3803 return 1;
3804 else
3805 return 0;
3808 /** Check if any of the previous options have changed but aren't allowed to. */
3809 static int
3810 options_transition_allowed(or_options_t *old, or_options_t *new_val,
3811 char **msg)
3813 if (!old)
3814 return 0;
3816 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3817 *msg = tor_strdup("PidFile is not allowed to change.");
3818 return -1;
3821 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3822 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3823 "is not allowed.");
3824 return -1;
3827 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
3828 char buf[1024];
3829 int r = tor_snprintf(buf, sizeof(buf),
3830 "While Tor is running, changing DataDirectory "
3831 "(\"%s\"->\"%s\") is not allowed.",
3832 old->DataDirectory, new_val->DataDirectory);
3833 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3834 return -1;
3837 if (!opt_streq(old->User, new_val->User)) {
3838 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
3839 return -1;
3842 if (!opt_streq(old->Group, new_val->Group)) {
3843 *msg = tor_strdup("While Tor is running, changing Group is not allowed.");
3844 return -1;
3847 if ((old->HardwareAccel != new_val->HardwareAccel)
3848 || !opt_streq(old->AccelName, new_val->AccelName)
3849 || !opt_streq(old->AccelDir, new_val->AccelDir)) {
3850 *msg = tor_strdup("While Tor is running, changing OpenSSL hardware "
3851 "acceleration engine is not allowed.");
3852 return -1;
3855 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
3856 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
3857 "is not allowed.");
3858 return -1;
3861 if (old->CellStatistics != new_val->CellStatistics ||
3862 old->DirReqStatistics != new_val->DirReqStatistics ||
3863 old->EntryStatistics != new_val->EntryStatistics ||
3864 old->ExitPortStatistics != new_val->ExitPortStatistics) {
3865 *msg = tor_strdup("While Tor is running, changing either "
3866 "CellStatistics, DirReqStatistics, EntryStatistics, "
3867 "or ExitPortStatistics is not allowed.");
3868 return -1;
3871 if (old->DisableAllSwap != new_val->DisableAllSwap) {
3872 *msg = tor_strdup("While Tor is running, changing DisableAllSwap "
3873 "is not allowed.");
3874 return -1;
3877 return 0;
3880 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3881 * will require us to rotate the CPU and DNS workers; else return 0. */
3882 static int
3883 options_transition_affects_workers(or_options_t *old_options,
3884 or_options_t *new_options)
3886 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3887 old_options->NumCpus != new_options->NumCpus ||
3888 old_options->ORPort != new_options->ORPort ||
3889 old_options->ServerDNSSearchDomains !=
3890 new_options->ServerDNSSearchDomains ||
3891 old_options->SafeLogging != new_options->SafeLogging ||
3892 old_options->ClientOnly != new_options->ClientOnly ||
3893 !config_lines_eq(old_options->Logs, new_options->Logs))
3894 return 1;
3896 /* Check whether log options match. */
3898 /* Nothing that changed matters. */
3899 return 0;
3902 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3903 * will require us to generate a new descriptor; else return 0. */
3904 static int
3905 options_transition_affects_descriptor(or_options_t *old_options,
3906 or_options_t *new_options)
3908 /* XXX We can be smarter here. If your DirPort isn't being
3909 * published and you just turned it off, no need to republish. Etc. */
3910 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3911 !opt_streq(old_options->Nickname,new_options->Nickname) ||
3912 !opt_streq(old_options->Address,new_options->Address) ||
3913 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
3914 old_options->ExitPolicyRejectPrivate !=
3915 new_options->ExitPolicyRejectPrivate ||
3916 old_options->ORPort != new_options->ORPort ||
3917 old_options->DirPort != new_options->DirPort ||
3918 old_options->ClientOnly != new_options->ClientOnly ||
3919 old_options->NoPublish != new_options->NoPublish ||
3920 old_options->_PublishServerDescriptor !=
3921 new_options->_PublishServerDescriptor ||
3922 get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
3923 get_effective_bwburst(old_options) !=
3924 get_effective_bwburst(new_options) ||
3925 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
3926 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
3927 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
3928 old_options->AccountingMax != new_options->AccountingMax)
3929 return 1;
3931 return 0;
3934 #ifdef MS_WINDOWS
3935 /** Return the directory on windows where we expect to find our application
3936 * data. */
3937 static char *
3938 get_windows_conf_root(void)
3940 static int is_set = 0;
3941 static char path[MAX_PATH+1];
3943 LPITEMIDLIST idl;
3944 IMalloc *m;
3945 HRESULT result;
3947 if (is_set)
3948 return path;
3950 /* Find X:\documents and settings\username\application data\ .
3951 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3953 #ifdef ENABLE_LOCAL_APPDATA
3954 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
3955 #else
3956 #define APPDATA_PATH CSIDL_APPDATA
3957 #endif
3958 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
3959 GetCurrentDirectory(MAX_PATH, path);
3960 is_set = 1;
3961 log_warn(LD_CONFIG,
3962 "I couldn't find your application data folder: are you "
3963 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3964 path);
3965 return path;
3967 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3968 result = SHGetPathFromIDList(idl, path);
3969 /* Now we need to free the */
3970 SHGetMalloc(&m);
3971 if (m) {
3972 m->lpVtbl->Free(m, idl);
3973 m->lpVtbl->Release(m);
3975 if (!SUCCEEDED(result)) {
3976 return NULL;
3978 strlcat(path,"\\tor",MAX_PATH);
3979 is_set = 1;
3980 return path;
3982 #endif
3984 /** Return the default location for our torrc file. */
3985 static const char *
3986 get_default_conf_file(void)
3988 #ifdef MS_WINDOWS
3989 static char path[MAX_PATH+1];
3990 strlcpy(path, get_windows_conf_root(), MAX_PATH);
3991 strlcat(path,"\\torrc",MAX_PATH);
3992 return path;
3993 #else
3994 return (CONFDIR "/torrc");
3995 #endif
3998 /** Verify whether lst is a string containing valid-looking comma-separated
3999 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
4001 static int
4002 check_nickname_list(const char *lst, const char *name, char **msg)
4004 int r = 0;
4005 smartlist_t *sl;
4007 if (!lst)
4008 return 0;
4009 sl = smartlist_create();
4011 smartlist_split_string(sl, lst, ",",
4012 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
4014 SMARTLIST_FOREACH(sl, const char *, s,
4016 if (!is_legal_nickname_or_hexdigest(s)) {
4017 char buf[1024];
4018 int tmp = tor_snprintf(buf, sizeof(buf),
4019 "Invalid nickname '%s' in %s line", s, name);
4020 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
4021 r = -1;
4022 break;
4025 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
4026 smartlist_free(sl);
4027 return r;
4030 /** Learn config file name from command line arguments, or use the default */
4031 static char *
4032 find_torrc_filename(int argc, char **argv,
4033 int *using_default_torrc, int *ignore_missing_torrc)
4035 char *fname=NULL;
4036 int i;
4038 for (i = 1; i < argc; ++i) {
4039 if (i < argc-1 && !strcmp(argv[i],"-f")) {
4040 if (fname) {
4041 log(LOG_WARN, LD_CONFIG, "Duplicate -f options on command line.");
4042 tor_free(fname);
4044 #ifdef MS_WINDOWS
4045 /* XXX one day we might want to extend expand_filename to work
4046 * under Windows as well. */
4047 fname = tor_strdup(argv[i+1]);
4048 #else
4049 fname = expand_filename(argv[i+1]);
4050 #endif
4051 *using_default_torrc = 0;
4052 ++i;
4053 } else if (!strcmp(argv[i],"--ignore-missing-torrc")) {
4054 *ignore_missing_torrc = 1;
4058 if (*using_default_torrc) {
4059 /* didn't find one, try CONFDIR */
4060 const char *dflt = get_default_conf_file();
4061 if (dflt && file_status(dflt) == FN_FILE) {
4062 fname = tor_strdup(dflt);
4063 } else {
4064 #ifndef MS_WINDOWS
4065 char *fn;
4066 fn = expand_filename("~/.torrc");
4067 if (fn && file_status(fn) == FN_FILE) {
4068 fname = fn;
4069 } else {
4070 tor_free(fn);
4071 fname = tor_strdup(dflt);
4073 #else
4074 fname = tor_strdup(dflt);
4075 #endif
4078 return fname;
4081 /** Load torrc from disk, setting torrc_fname if successful */
4082 static char *
4083 load_torrc_from_disk(int argc, char **argv)
4085 char *fname=NULL;
4086 char *cf = NULL;
4087 int using_default_torrc = 1;
4088 int ignore_missing_torrc = 0;
4090 fname = find_torrc_filename(argc, argv,
4091 &using_default_torrc, &ignore_missing_torrc);
4092 tor_assert(fname);
4093 log(LOG_DEBUG, LD_CONFIG, "Opening config file \"%s\"", fname);
4095 tor_free(torrc_fname);
4096 torrc_fname = fname;
4098 /* Open config file */
4099 if (file_status(fname) != FN_FILE ||
4100 !(cf = read_file_to_str(fname,0,NULL))) {
4101 if (using_default_torrc == 1 || ignore_missing_torrc ) {
4102 log(LOG_NOTICE, LD_CONFIG, "Configuration file \"%s\" not present, "
4103 "using reasonable defaults.", fname);
4104 tor_free(fname); /* sets fname to NULL */
4105 torrc_fname = NULL;
4106 cf = tor_strdup("");
4107 } else {
4108 log(LOG_WARN, LD_CONFIG,
4109 "Unable to open configuration file \"%s\".", fname);
4110 goto err;
4114 return cf;
4115 err:
4116 tor_free(fname);
4117 torrc_fname = NULL;
4118 return NULL;
4121 /** Read a configuration file into <b>options</b>, finding the configuration
4122 * file location based on the command line. After loading the file
4123 * call options_init_from_string() to load the config.
4124 * Return 0 if success, -1 if failure. */
4126 options_init_from_torrc(int argc, char **argv)
4128 char *cf=NULL;
4129 int i, retval, command;
4130 static char **backup_argv;
4131 static int backup_argc;
4132 char *command_arg = NULL;
4133 char *errmsg=NULL;
4135 if (argv) { /* first time we're called. save command line args */
4136 backup_argv = argv;
4137 backup_argc = argc;
4138 } else { /* we're reloading. need to clean up old options first. */
4139 argv = backup_argv;
4140 argc = backup_argc;
4142 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
4143 print_usage();
4144 exit(0);
4146 if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
4147 /* For documenting validating whether we've documented everything. */
4148 list_torrc_options();
4149 exit(0);
4152 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
4153 printf("Tor version %s.\n",get_version());
4154 exit(0);
4156 if (argc > 1 && (!strcmp(argv[1],"--digests"))) {
4157 printf("Tor version %s.\n",get_version());
4158 printf("%s", libor_get_digests());
4159 printf("%s", tor_get_digests());
4160 exit(0);
4163 /* Go through command-line variables */
4164 if (!global_cmdline_options) {
4165 /* Or we could redo the list every time we pass this place.
4166 * It does not really matter */
4167 if (config_get_commandlines(argc, argv, &global_cmdline_options) < 0) {
4168 goto err;
4172 command = CMD_RUN_TOR;
4173 for (i = 1; i < argc; ++i) {
4174 if (!strcmp(argv[i],"--list-fingerprint")) {
4175 command = CMD_LIST_FINGERPRINT;
4176 } else if (!strcmp(argv[i],"--hash-password")) {
4177 command = CMD_HASH_PASSWORD;
4178 command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
4179 ++i;
4180 } else if (!strcmp(argv[i],"--verify-config")) {
4181 command = CMD_VERIFY_CONFIG;
4185 if (command == CMD_HASH_PASSWORD) {
4186 cf = tor_strdup("");
4187 } else {
4188 cf = load_torrc_from_disk(argc, argv);
4189 if (!cf)
4190 goto err;
4193 retval = options_init_from_string(cf, command, command_arg, &errmsg);
4194 tor_free(cf);
4195 if (retval < 0)
4196 goto err;
4198 return 0;
4200 err:
4201 if (errmsg) {
4202 log(LOG_WARN,LD_CONFIG,"%s", errmsg);
4203 tor_free(errmsg);
4205 return -1;
4208 /** Load the options from the configuration in <b>cf</b>, validate
4209 * them for consistency and take actions based on them.
4211 * Return 0 if success, negative on error:
4212 * * -1 for general errors.
4213 * * -2 for failure to parse/validate,
4214 * * -3 for transition not allowed
4215 * * -4 for error while setting the new options
4217 setopt_err_t
4218 options_init_from_string(const char *cf,
4219 int command, const char *command_arg,
4220 char **msg)
4222 or_options_t *oldoptions, *newoptions;
4223 config_line_t *cl;
4224 int retval;
4225 setopt_err_t err = SETOPT_ERR_MISC;
4226 tor_assert(msg);
4228 oldoptions = global_options; /* get_options unfortunately asserts if
4229 this is the first time we run*/
4231 newoptions = tor_malloc_zero(sizeof(or_options_t));
4232 newoptions->_magic = OR_OPTIONS_MAGIC;
4233 options_init(newoptions);
4234 newoptions->command = command;
4235 newoptions->command_arg = command_arg;
4237 /* get config lines, assign them */
4238 retval = config_get_lines(cf, &cl);
4239 if (retval < 0) {
4240 err = SETOPT_ERR_PARSE;
4241 goto err;
4243 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4244 config_free_lines(cl);
4245 if (retval < 0) {
4246 err = SETOPT_ERR_PARSE;
4247 goto err;
4250 /* Go through command-line variables too */
4251 retval = config_assign(&options_format, newoptions,
4252 global_cmdline_options, 0, 0, msg);
4253 if (retval < 0) {
4254 err = SETOPT_ERR_PARSE;
4255 goto err;
4258 /* If this is a testing network configuration, change defaults
4259 * for a list of dependent config options, re-initialize newoptions
4260 * with the new defaults, and assign all options to it second time. */
4261 if (newoptions->TestingTorNetwork) {
4262 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4263 * this? We could, for example, make the parsing algorithm do two passes
4264 * over the configuration. If it finds any "suite" options like
4265 * TestingTorNetwork, it could change the defaults before its second pass.
4266 * Not urgent so long as this seems to work, but at any sign of trouble,
4267 * let's clean it up. -NM */
4269 /* Change defaults. */
4270 int i;
4271 for (i = 0; testing_tor_network_defaults[i].name; ++i) {
4272 config_var_t *new_var = &testing_tor_network_defaults[i];
4273 config_var_t *old_var =
4274 config_find_option(&options_format, new_var->name);
4275 tor_assert(new_var);
4276 tor_assert(old_var);
4277 old_var->initvalue = new_var->initvalue;
4280 /* Clear newoptions and re-initialize them with new defaults. */
4281 config_free(&options_format, newoptions);
4282 newoptions = tor_malloc_zero(sizeof(or_options_t));
4283 newoptions->_magic = OR_OPTIONS_MAGIC;
4284 options_init(newoptions);
4285 newoptions->command = command;
4286 newoptions->command_arg = command_arg;
4288 /* Assign all options a second time. */
4289 retval = config_get_lines(cf, &cl);
4290 if (retval < 0) {
4291 err = SETOPT_ERR_PARSE;
4292 goto err;
4294 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4295 config_free_lines(cl);
4296 if (retval < 0) {
4297 err = SETOPT_ERR_PARSE;
4298 goto err;
4300 retval = config_assign(&options_format, newoptions,
4301 global_cmdline_options, 0, 0, msg);
4302 if (retval < 0) {
4303 err = SETOPT_ERR_PARSE;
4304 goto err;
4308 /* Validate newoptions */
4309 if (options_validate(oldoptions, newoptions, 0, msg) < 0) {
4310 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
4311 goto err;
4314 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
4315 err = SETOPT_ERR_TRANSITION;
4316 goto err;
4319 if (set_options(newoptions, msg)) {
4320 err = SETOPT_ERR_SETTING;
4321 goto err; /* frees and replaces old options */
4324 return SETOPT_OK;
4326 err:
4327 config_free(&options_format, newoptions);
4328 if (*msg) {
4329 int len = (int)strlen(*msg)+256;
4330 char *newmsg = tor_malloc(len);
4332 tor_snprintf(newmsg, len, "Failed to parse/validate config: %s", *msg);
4333 tor_free(*msg);
4334 *msg = newmsg;
4336 return err;
4339 /** Return the location for our configuration file.
4341 const char *
4342 get_torrc_fname(void)
4344 if (torrc_fname)
4345 return torrc_fname;
4346 else
4347 return get_default_conf_file();
4350 /** Adjust the address map based on the MapAddress elements in the
4351 * configuration <b>options</b>
4353 static void
4354 config_register_addressmaps(or_options_t *options)
4356 smartlist_t *elts;
4357 config_line_t *opt;
4358 char *from, *to;
4360 addressmap_clear_configured();
4361 elts = smartlist_create();
4362 for (opt = options->AddressMap; opt; opt = opt->next) {
4363 smartlist_split_string(elts, opt->value, NULL,
4364 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4365 if (smartlist_len(elts) >= 2) {
4366 from = smartlist_get(elts,0);
4367 to = smartlist_get(elts,1);
4368 if (address_is_invalid_destination(to, 1)) {
4369 log_warn(LD_CONFIG,
4370 "Skipping invalid argument '%s' to MapAddress", to);
4371 } else {
4372 addressmap_register(from, tor_strdup(to), 0, ADDRMAPSRC_TORRC);
4373 if (smartlist_len(elts)>2) {
4374 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
4377 } else {
4378 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
4379 opt->value);
4381 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4382 smartlist_clear(elts);
4384 smartlist_free(elts);
4388 * Initialize the logs based on the configuration file.
4390 static int
4391 options_init_logs(or_options_t *options, int validate_only)
4393 config_line_t *opt;
4394 int ok;
4395 smartlist_t *elts;
4396 int daemon =
4397 #ifdef MS_WINDOWS
4399 #else
4400 options->RunAsDaemon;
4401 #endif
4403 ok = 1;
4404 elts = smartlist_create();
4406 for (opt = options->Logs; opt; opt = opt->next) {
4407 log_severity_list_t *severity;
4408 const char *cfg = opt->value;
4409 severity = tor_malloc_zero(sizeof(log_severity_list_t));
4410 if (parse_log_severity_config(&cfg, severity) < 0) {
4411 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
4412 opt->value);
4413 ok = 0; goto cleanup;
4416 smartlist_split_string(elts, cfg, NULL,
4417 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4419 if (smartlist_len(elts) == 0)
4420 smartlist_add(elts, tor_strdup("stdout"));
4422 if (smartlist_len(elts) == 1 &&
4423 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
4424 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
4425 int err = smartlist_len(elts) &&
4426 !strcasecmp(smartlist_get(elts,0), "stderr");
4427 if (!validate_only) {
4428 if (daemon) {
4429 log_warn(LD_CONFIG,
4430 "Can't log to %s with RunAsDaemon set; skipping stdout",
4431 err?"stderr":"stdout");
4432 } else {
4433 add_stream_log(severity, err?"<stderr>":"<stdout>",
4434 fileno(err?stderr:stdout));
4437 goto cleanup;
4439 if (smartlist_len(elts) == 1 &&
4440 !strcasecmp(smartlist_get(elts,0), "syslog")) {
4441 #ifdef HAVE_SYSLOG_H
4442 if (!validate_only) {
4443 add_syslog_log(severity);
4445 #else
4446 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
4447 #endif
4448 goto cleanup;
4451 if (smartlist_len(elts) == 2 &&
4452 !strcasecmp(smartlist_get(elts,0), "file")) {
4453 if (!validate_only) {
4454 if (add_file_log(severity, smartlist_get(elts, 1)) < 0) {
4455 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
4456 opt->value, strerror(errno));
4457 ok = 0;
4460 goto cleanup;
4463 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
4464 opt->value);
4465 ok = 0; goto cleanup;
4467 cleanup:
4468 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4469 smartlist_clear(elts);
4470 tor_free(severity);
4472 smartlist_free(elts);
4474 return ok?0:-1;
4477 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4478 * if the line is well-formed, and -1 if it isn't. If
4479 * <b>validate_only</b> is 0, and the line is well-formed, then add
4480 * the bridge described in the line to our internal bridge list. */
4481 static int
4482 parse_bridge_line(const char *line, int validate_only)
4484 smartlist_t *items = NULL;
4485 int r;
4486 char *addrport=NULL, *fingerprint=NULL;
4487 tor_addr_t addr;
4488 uint16_t port = 0;
4489 char digest[DIGEST_LEN];
4491 items = smartlist_create();
4492 smartlist_split_string(items, line, NULL,
4493 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4494 if (smartlist_len(items) < 1) {
4495 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
4496 goto err;
4498 addrport = smartlist_get(items, 0);
4499 smartlist_del_keeporder(items, 0);
4500 if (tor_addr_port_parse(addrport, &addr, &port)<0) {
4501 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
4502 goto err;
4504 if (!port) {
4505 log_info(LD_CONFIG,
4506 "Bridge address '%s' has no port; using default port 443.",
4507 addrport);
4508 port = 443;
4511 if (smartlist_len(items)) {
4512 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4513 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4514 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
4515 goto err;
4517 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4518 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
4519 goto err;
4523 if (!validate_only) {
4524 log_debug(LD_DIR, "Bridge at %s:%d (%s)", fmt_addr(&addr),
4525 (int)port,
4526 fingerprint ? fingerprint : "no key listed");
4527 bridge_add_from_config(&addr, port, fingerprint ? digest : NULL);
4530 r = 0;
4531 goto done;
4533 err:
4534 r = -1;
4536 done:
4537 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4538 smartlist_free(items);
4539 tor_free(addrport);
4540 tor_free(fingerprint);
4541 return r;
4544 /** Read the contents of a DirServer line from <b>line</b>. If
4545 * <b>validate_only</b> is 0, and the line is well-formed, and it
4546 * shares any bits with <b>required_type</b> or <b>required_type</b>
4547 * is 0, then add the dirserver described in the line (minus whatever
4548 * bits it's missing) as a valid authority. Return 0 on success,
4549 * or -1 if the line isn't well-formed or if we can't add it. */
4550 static int
4551 parse_dir_server_line(const char *line, authority_type_t required_type,
4552 int validate_only)
4554 smartlist_t *items = NULL;
4555 int r;
4556 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
4557 uint16_t dir_port = 0, or_port = 0;
4558 char digest[DIGEST_LEN];
4559 char v3_digest[DIGEST_LEN];
4560 authority_type_t type = V2_AUTHORITY;
4561 int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
4563 items = smartlist_create();
4564 smartlist_split_string(items, line, NULL,
4565 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4566 if (smartlist_len(items) < 1) {
4567 log_warn(LD_CONFIG, "No arguments on DirServer line.");
4568 goto err;
4571 if (is_legal_nickname(smartlist_get(items, 0))) {
4572 nickname = smartlist_get(items, 0);
4573 smartlist_del_keeporder(items, 0);
4576 while (smartlist_len(items)) {
4577 char *flag = smartlist_get(items, 0);
4578 if (TOR_ISDIGIT(flag[0]))
4579 break;
4580 if (!strcasecmp(flag, "v1")) {
4581 type |= (V1_AUTHORITY | HIDSERV_AUTHORITY);
4582 } else if (!strcasecmp(flag, "hs")) {
4583 type |= HIDSERV_AUTHORITY;
4584 } else if (!strcasecmp(flag, "no-hs")) {
4585 is_not_hidserv_authority = 1;
4586 } else if (!strcasecmp(flag, "bridge")) {
4587 type |= BRIDGE_AUTHORITY;
4588 } else if (!strcasecmp(flag, "no-v2")) {
4589 is_not_v2_authority = 1;
4590 } else if (!strcasecmpstart(flag, "orport=")) {
4591 int ok;
4592 char *portstring = flag + strlen("orport=");
4593 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
4594 if (!ok)
4595 log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
4596 portstring);
4597 } else if (!strcasecmpstart(flag, "v3ident=")) {
4598 char *idstr = flag + strlen("v3ident=");
4599 if (strlen(idstr) != HEX_DIGEST_LEN ||
4600 base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
4601 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirServer line",
4602 flag);
4603 } else {
4604 type |= V3_AUTHORITY;
4606 } else {
4607 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
4608 flag);
4610 tor_free(flag);
4611 smartlist_del_keeporder(items, 0);
4613 if (is_not_hidserv_authority)
4614 type &= ~HIDSERV_AUTHORITY;
4615 if (is_not_v2_authority)
4616 type &= ~V2_AUTHORITY;
4618 if (smartlist_len(items) < 2) {
4619 log_warn(LD_CONFIG, "Too few arguments to DirServer line.");
4620 goto err;
4622 addrport = smartlist_get(items, 0);
4623 smartlist_del_keeporder(items, 0);
4624 if (parse_addr_port(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
4625 log_warn(LD_CONFIG, "Error parsing DirServer address '%s'", addrport);
4626 goto err;
4628 if (!dir_port) {
4629 log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
4630 goto err;
4633 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4634 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4635 log_warn(LD_CONFIG, "Key digest for DirServer is wrong length %d.",
4636 (int)strlen(fingerprint));
4637 goto err;
4639 if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4640 /* a known bad fingerprint. refuse to use it. We can remove this
4641 * clause once Tor 0.1.2.17 is obsolete. */
4642 log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
4643 "torrc file (%s), or reinstall Tor and use the default torrc.",
4644 get_torrc_fname());
4645 goto err;
4647 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4648 log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
4649 goto err;
4652 if (!validate_only && (!required_type || required_type & type)) {
4653 if (required_type)
4654 type &= required_type; /* pare down what we think of them as an
4655 * authority for. */
4656 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
4657 address, (int)dir_port, (char*)smartlist_get(items,0));
4658 if (!add_trusted_dir_server(nickname, address, dir_port, or_port,
4659 digest, v3_digest, type))
4660 goto err;
4663 r = 0;
4664 goto done;
4666 err:
4667 r = -1;
4669 done:
4670 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4671 smartlist_free(items);
4672 tor_free(addrport);
4673 tor_free(address);
4674 tor_free(nickname);
4675 tor_free(fingerprint);
4676 return r;
4679 /** Adjust the value of options->DataDirectory, or fill it in if it's
4680 * absent. Return 0 on success, -1 on failure. */
4681 static int
4682 normalize_data_directory(or_options_t *options)
4684 #ifdef MS_WINDOWS
4685 char *p;
4686 if (options->DataDirectory)
4687 return 0; /* all set */
4688 p = tor_malloc(MAX_PATH);
4689 strlcpy(p,get_windows_conf_root(),MAX_PATH);
4690 options->DataDirectory = p;
4691 return 0;
4692 #else
4693 const char *d = options->DataDirectory;
4694 if (!d)
4695 d = "~/.tor";
4697 if (strncmp(d,"~/",2) == 0) {
4698 char *fn = expand_filename(d);
4699 if (!fn) {
4700 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
4701 return -1;
4703 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
4704 /* If our homedir is /, we probably don't want to use it. */
4705 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4706 * want. */
4707 log_warn(LD_CONFIG,
4708 "Default DataDirectory is \"~/.tor\". This expands to "
4709 "\"%s\", which is probably not what you want. Using "
4710 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
4711 tor_free(fn);
4712 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
4714 tor_free(options->DataDirectory);
4715 options->DataDirectory = fn;
4717 return 0;
4718 #endif
4721 /** Check and normalize the value of options->DataDirectory; return 0 if it
4722 * sane, -1 otherwise. */
4723 static int
4724 validate_data_directory(or_options_t *options)
4726 if (normalize_data_directory(options) < 0)
4727 return -1;
4728 tor_assert(options->DataDirectory);
4729 if (strlen(options->DataDirectory) > (512-128)) {
4730 log_warn(LD_CONFIG, "DataDirectory is too long.");
4731 return -1;
4733 return 0;
4736 /** This string must remain the same forevermore. It is how we
4737 * recognize that the torrc file doesn't need to be backed up. */
4738 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4739 "if you edit it, comments will not be preserved"
4740 /** This string can change; it tries to give the reader an idea
4741 * that editing this file by hand is not a good plan. */
4742 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4743 "to torrc.orig.1 or similar, and Tor will ignore it"
4745 /** Save a configuration file for the configuration in <b>options</b>
4746 * into the file <b>fname</b>. If the file already exists, and
4747 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4748 * replace it. Return 0 on success, -1 on failure. */
4749 static int
4750 write_configuration_file(const char *fname, or_options_t *options)
4752 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4753 int rename_old = 0, r;
4754 size_t len;
4756 tor_assert(fname);
4758 switch (file_status(fname)) {
4759 case FN_FILE:
4760 old_val = read_file_to_str(fname, 0, NULL);
4761 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4762 rename_old = 1;
4764 tor_free(old_val);
4765 break;
4766 case FN_NOENT:
4767 break;
4768 case FN_ERROR:
4769 case FN_DIR:
4770 default:
4771 log_warn(LD_CONFIG,
4772 "Config file \"%s\" is not a file? Failing.", fname);
4773 return -1;
4776 if (!(new_conf = options_dump(options, 1))) {
4777 log_warn(LD_BUG, "Couldn't get configuration string");
4778 goto err;
4781 len = strlen(new_conf)+256;
4782 new_val = tor_malloc(len);
4783 tor_snprintf(new_val, len, "%s\n%s\n\n%s",
4784 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4786 if (rename_old) {
4787 int i = 1;
4788 size_t fn_tmp_len = strlen(fname)+32;
4789 char *fn_tmp;
4790 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4791 fn_tmp = tor_malloc(fn_tmp_len);
4792 while (1) {
4793 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4794 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4795 tor_free(fn_tmp);
4796 goto err;
4798 if (file_status(fn_tmp) == FN_NOENT)
4799 break;
4800 ++i;
4802 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4803 if (rename(fname, fn_tmp) < 0) {
4804 log_warn(LD_FS,
4805 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4806 fname, fn_tmp, strerror(errno));
4807 tor_free(fn_tmp);
4808 goto err;
4810 tor_free(fn_tmp);
4813 if (write_str_to_file(fname, new_val, 0) < 0)
4814 goto err;
4816 r = 0;
4817 goto done;
4818 err:
4819 r = -1;
4820 done:
4821 tor_free(new_val);
4822 tor_free(new_conf);
4823 return r;
4827 * Save the current configuration file value to disk. Return 0 on
4828 * success, -1 on failure.
4831 options_save_current(void)
4833 if (torrc_fname) {
4834 /* This fails if we can't write to our configuration file.
4836 * If we try falling back to datadirectory or something, we have a better
4837 * chance of saving the configuration, but a better chance of doing
4838 * something the user never expected. Let's just warn instead. */
4839 return write_configuration_file(torrc_fname, get_options());
4841 return write_configuration_file(get_default_conf_file(), get_options());
4844 /** Mapping from a unit name to a multiplier for converting that unit into a
4845 * base unit. */
4846 struct unit_table_t {
4847 const char *unit;
4848 uint64_t multiplier;
4851 /** Table to map the names of memory units to the number of bytes they
4852 * contain. */
4853 static struct unit_table_t memory_units[] = {
4854 { "", 1 },
4855 { "b", 1<< 0 },
4856 { "byte", 1<< 0 },
4857 { "bytes", 1<< 0 },
4858 { "kb", 1<<10 },
4859 { "kbyte", 1<<10 },
4860 { "kbytes", 1<<10 },
4861 { "kilobyte", 1<<10 },
4862 { "kilobytes", 1<<10 },
4863 { "m", 1<<20 },
4864 { "mb", 1<<20 },
4865 { "mbyte", 1<<20 },
4866 { "mbytes", 1<<20 },
4867 { "megabyte", 1<<20 },
4868 { "megabytes", 1<<20 },
4869 { "gb", 1<<30 },
4870 { "gbyte", 1<<30 },
4871 { "gbytes", 1<<30 },
4872 { "gigabyte", 1<<30 },
4873 { "gigabytes", 1<<30 },
4874 { "tb", U64_LITERAL(1)<<40 },
4875 { "terabyte", U64_LITERAL(1)<<40 },
4876 { "terabytes", U64_LITERAL(1)<<40 },
4877 { NULL, 0 },
4880 /** Table to map the names of time units to the number of seconds they
4881 * contain. */
4882 static struct unit_table_t time_units[] = {
4883 { "", 1 },
4884 { "second", 1 },
4885 { "seconds", 1 },
4886 { "minute", 60 },
4887 { "minutes", 60 },
4888 { "hour", 60*60 },
4889 { "hours", 60*60 },
4890 { "day", 24*60*60 },
4891 { "days", 24*60*60 },
4892 { "week", 7*24*60*60 },
4893 { "weeks", 7*24*60*60 },
4894 { NULL, 0 },
4897 /** Parse a string <b>val</b> containing a number, zero or more
4898 * spaces, and an optional unit string. If the unit appears in the
4899 * table <b>u</b>, then multiply the number by the unit multiplier.
4900 * On success, set *<b>ok</b> to 1 and return this product.
4901 * Otherwise, set *<b>ok</b> to 0.
4903 static uint64_t
4904 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4906 uint64_t v = 0;
4907 double d = 0;
4908 int use_float = 0;
4909 char *cp;
4911 tor_assert(ok);
4913 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4914 if (!*ok || (cp && *cp == '.')) {
4915 d = tor_parse_double(val, 0, UINT64_MAX, ok, &cp);
4916 if (!*ok)
4917 goto done;
4918 use_float = 1;
4921 if (!cp) {
4922 *ok = 1;
4923 v = use_float ? DBL_TO_U64(d) : v;
4924 goto done;
4927 cp = (char*) eat_whitespace(cp);
4929 for ( ;u->unit;++u) {
4930 if (!strcasecmp(u->unit, cp)) {
4931 if (use_float)
4932 v = u->multiplier * d;
4933 else
4934 v *= u->multiplier;
4935 *ok = 1;
4936 goto done;
4939 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4940 *ok = 0;
4941 done:
4943 if (*ok)
4944 return v;
4945 else
4946 return 0;
4949 /** Parse a string in the format "number unit", where unit is a unit of
4950 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4951 * and return the number of bytes specified. Otherwise, set
4952 * *<b>ok</b> to false and return 0. */
4953 static uint64_t
4954 config_parse_memunit(const char *s, int *ok)
4956 uint64_t u = config_parse_units(s, memory_units, ok);
4957 return u;
4960 /** Parse a string in the format "number unit", where unit is a unit of time.
4961 * On success, set *<b>ok</b> to true and return the number of seconds in
4962 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4964 static int
4965 config_parse_interval(const char *s, int *ok)
4967 uint64_t r;
4968 r = config_parse_units(s, time_units, ok);
4969 if (!ok)
4970 return -1;
4971 if (r > INT_MAX) {
4972 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4973 *ok = 0;
4974 return -1;
4976 return (int)r;
4980 * Initialize the libevent library.
4982 static void
4983 init_libevent(void)
4985 const char *badness=NULL;
4987 configure_libevent_logging();
4988 /* If the kernel complains that some method (say, epoll) doesn't
4989 * exist, we don't care about it, since libevent will cope.
4991 suppress_libevent_log_msg("Function not implemented");
4993 tor_check_libevent_header_compatibility();
4995 tor_libevent_initialize();
4997 suppress_libevent_log_msg(NULL);
4999 tor_check_libevent_version(tor_libevent_get_method(),
5000 get_options()->ORPort != 0,
5001 &badness);
5002 if (badness) {
5003 const char *v = tor_libevent_get_version_str();
5004 const char *m = tor_libevent_get_method();
5005 control_event_general_status(LOG_WARN,
5006 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
5007 v, m, badness);
5011 /** Return the persistent state struct for this Tor. */
5012 or_state_t *
5013 get_or_state(void)
5015 tor_assert(global_state);
5016 return global_state;
5019 /** Return a newly allocated string holding a filename relative to the data
5020 * directory. If <b>sub1</b> is present, it is the first path component after
5021 * the data directory. If <b>sub2</b> is also present, it is the second path
5022 * component after the data directory. If <b>suffix</b> is present, it
5023 * is appended to the filename.
5025 * Examples:
5026 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
5027 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
5028 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
5029 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
5031 * Note: Consider using the get_datadir_fname* macros in or.h.
5033 char *
5034 options_get_datadir_fname2_suffix(or_options_t *options,
5035 const char *sub1, const char *sub2,
5036 const char *suffix)
5038 char *fname = NULL;
5039 size_t len;
5040 tor_assert(options);
5041 tor_assert(options->DataDirectory);
5042 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
5043 len = strlen(options->DataDirectory);
5044 if (sub1) {
5045 len += strlen(sub1)+1;
5046 if (sub2)
5047 len += strlen(sub2)+1;
5049 if (suffix)
5050 len += strlen(suffix);
5051 len++;
5052 fname = tor_malloc(len);
5053 if (sub1) {
5054 if (sub2) {
5055 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
5056 options->DataDirectory, sub1, sub2);
5057 } else {
5058 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
5059 options->DataDirectory, sub1);
5061 } else {
5062 strlcpy(fname, options->DataDirectory, len);
5064 if (suffix)
5065 strlcat(fname, suffix, len);
5066 return fname;
5069 /** Return 0 if every setting in <b>state</b> is reasonable, and a
5070 * permissible transition from <b>old_state</b>. Else warn and return -1.
5071 * Should have no side effects, except for normalizing the contents of
5072 * <b>state</b>.
5074 /* XXX from_setconf is here because of bug 238 */
5075 static int
5076 or_state_validate(or_state_t *old_state, or_state_t *state,
5077 int from_setconf, char **msg)
5079 /* We don't use these; only options do. Still, we need to match that
5080 * signature. */
5081 (void) from_setconf;
5082 (void) old_state;
5084 if (entry_guards_parse_state(state, 0, msg)<0)
5085 return -1;
5087 return 0;
5090 /** Replace the current persistent state with <b>new_state</b> */
5091 static void
5092 or_state_set(or_state_t *new_state)
5094 char *err = NULL;
5095 tor_assert(new_state);
5096 config_free(&state_format, global_state);
5097 global_state = new_state;
5098 if (entry_guards_parse_state(global_state, 1, &err)<0) {
5099 log_warn(LD_GENERAL,"%s",err);
5100 tor_free(err);
5102 if (rep_hist_load_state(global_state, &err)<0) {
5103 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
5104 tor_free(err);
5106 if (circuit_build_times_parse_state(&circ_times, global_state, &err) < 0) {
5107 log_warn(LD_GENERAL,"%s",err);
5108 tor_free(err);
5112 /** Reload the persistent state from disk, generating a new state as needed.
5113 * Return 0 on success, less than 0 on failure.
5115 static int
5116 or_state_load(void)
5118 or_state_t *new_state = NULL;
5119 char *contents = NULL, *fname;
5120 char *errmsg = NULL;
5121 int r = -1, badstate = 0;
5123 fname = get_datadir_fname("state");
5124 switch (file_status(fname)) {
5125 case FN_FILE:
5126 if (!(contents = read_file_to_str(fname, 0, NULL))) {
5127 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
5128 goto done;
5130 break;
5131 case FN_NOENT:
5132 break;
5133 case FN_ERROR:
5134 case FN_DIR:
5135 default:
5136 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
5137 goto done;
5139 new_state = tor_malloc_zero(sizeof(or_state_t));
5140 new_state->_magic = OR_STATE_MAGIC;
5141 config_init(&state_format, new_state);
5142 if (contents) {
5143 config_line_t *lines=NULL;
5144 int assign_retval;
5145 if (config_get_lines(contents, &lines)<0)
5146 goto done;
5147 assign_retval = config_assign(&state_format, new_state,
5148 lines, 0, 0, &errmsg);
5149 config_free_lines(lines);
5150 if (assign_retval<0)
5151 badstate = 1;
5152 if (errmsg) {
5153 log_warn(LD_GENERAL, "%s", errmsg);
5154 tor_free(errmsg);
5158 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
5159 badstate = 1;
5161 if (errmsg) {
5162 log_warn(LD_GENERAL, "%s", errmsg);
5163 tor_free(errmsg);
5166 if (badstate && !contents) {
5167 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
5168 " This is a bug in Tor.");
5169 goto done;
5170 } else if (badstate && contents) {
5171 int i;
5172 file_status_t status;
5173 size_t len = strlen(fname)+16;
5174 char *fname2 = tor_malloc(len);
5175 for (i = 0; i < 100; ++i) {
5176 tor_snprintf(fname2, len, "%s.%d", fname, i);
5177 status = file_status(fname2);
5178 if (status == FN_NOENT)
5179 break;
5181 if (i == 100) {
5182 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
5183 "state files to move aside. Discarding the old state file.",
5184 fname);
5185 unlink(fname);
5186 } else {
5187 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
5188 "to \"%s\". This could be a bug in Tor; please tell "
5189 "the developers.", fname, fname2);
5190 if (rename(fname, fname2) < 0) {
5191 log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
5192 "OS gave an error of %s", strerror(errno));
5195 tor_free(fname2);
5196 tor_free(contents);
5197 config_free(&state_format, new_state);
5199 new_state = tor_malloc_zero(sizeof(or_state_t));
5200 new_state->_magic = OR_STATE_MAGIC;
5201 config_init(&state_format, new_state);
5202 } else if (contents) {
5203 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
5204 } else {
5205 log_info(LD_GENERAL, "Initialized state");
5207 or_state_set(new_state);
5208 new_state = NULL;
5209 if (!contents) {
5210 global_state->next_write = 0;
5211 or_state_save(time(NULL));
5213 r = 0;
5215 done:
5216 tor_free(fname);
5217 tor_free(contents);
5218 if (new_state)
5219 config_free(&state_format, new_state);
5221 return r;
5224 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
5226 or_state_save(time_t now)
5228 char *state, *contents;
5229 char tbuf[ISO_TIME_LEN+1];
5230 size_t len;
5231 char *fname;
5233 tor_assert(global_state);
5235 if (global_state->next_write > now)
5236 return 0;
5238 /* Call everything else that might dirty the state even more, in order
5239 * to avoid redundant writes. */
5240 entry_guards_update_state(global_state);
5241 rep_hist_update_state(global_state);
5242 circuit_build_times_update_state(&circ_times, global_state);
5243 if (accounting_is_enabled(get_options()))
5244 accounting_run_housekeeping(now);
5246 global_state->LastWritten = time(NULL);
5247 tor_free(global_state->TorVersion);
5248 len = strlen(get_version())+8;
5249 global_state->TorVersion = tor_malloc(len);
5250 tor_snprintf(global_state->TorVersion, len, "Tor %s", get_version());
5252 state = config_dump(&state_format, global_state, 1, 0);
5253 len = strlen(state)+256;
5254 contents = tor_malloc(len);
5255 format_local_iso_time(tbuf, time(NULL));
5256 tor_snprintf(contents, len,
5257 "# Tor state file last generated on %s local time\n"
5258 "# Other times below are in GMT\n"
5259 "# You *do not* need to edit this file.\n\n%s",
5260 tbuf, state);
5261 tor_free(state);
5262 fname = get_datadir_fname("state");
5263 if (write_str_to_file(fname, contents, 0)<0) {
5264 log_warn(LD_FS, "Unable to write state to file \"%s\"", fname);
5265 tor_free(fname);
5266 tor_free(contents);
5267 return -1;
5269 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
5270 tor_free(fname);
5271 tor_free(contents);
5273 global_state->next_write = TIME_MAX;
5274 return 0;
5277 /** Given a file name check to see whether the file exists but has not been
5278 * modified for a very long time. If so, remove it. */
5279 void
5280 remove_file_if_very_old(const char *fname, time_t now)
5282 #define VERY_OLD_FILE_AGE (28*24*60*60)
5283 struct stat st;
5285 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
5286 char buf[ISO_TIME_LEN+1];
5287 format_local_iso_time(buf, st.st_mtime);
5288 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
5289 "Removing it.", fname, buf);
5290 unlink(fname);
5294 /** Helper to implement GETINFO functions about configuration variables (not
5295 * their values). Given a "config/names" question, set *<b>answer</b> to a
5296 * new string describing the supported configuration variables and their
5297 * types. */
5299 getinfo_helper_config(control_connection_t *conn,
5300 const char *question, char **answer)
5302 (void) conn;
5303 if (!strcmp(question, "config/names")) {
5304 smartlist_t *sl = smartlist_create();
5305 int i;
5306 for (i = 0; _option_vars[i].name; ++i) {
5307 config_var_t *var = &_option_vars[i];
5308 const char *type, *desc;
5309 char *line;
5310 size_t len;
5311 desc = config_find_description(&options_format, var->name);
5312 switch (var->type) {
5313 case CONFIG_TYPE_STRING: type = "String"; break;
5314 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
5315 case CONFIG_TYPE_UINT: type = "Integer"; break;
5316 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
5317 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
5318 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
5319 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
5320 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
5321 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
5322 case CONFIG_TYPE_CSV: type = "CommaList"; break;
5323 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
5324 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
5325 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
5326 default:
5327 case CONFIG_TYPE_OBSOLETE:
5328 type = NULL; break;
5330 if (!type)
5331 continue;
5332 len = strlen(var->name)+strlen(type)+16;
5333 if (desc)
5334 len += strlen(desc);
5335 line = tor_malloc(len);
5336 if (desc)
5337 tor_snprintf(line, len, "%s %s %s\n",var->name,type,desc);
5338 else
5339 tor_snprintf(line, len, "%s %s\n",var->name,type);
5340 smartlist_add(sl, line);
5342 *answer = smartlist_join_strings(sl, "", 0, NULL);
5343 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
5344 smartlist_free(sl);
5346 return 0;