Add MainloopStats option.
[tor.git] / src / or / config.c
blob3ae3af55a3492306da99036dc458ff4054b92a55
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-2017, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file config.c
9 * \brief Code to interpret the user's configuration of Tor.
11 * This module handles torrc configuration file, including parsing it,
12 * combining it with torrc.defaults and the command line, allowing
13 * user changes to it (via editing and SIGHUP or via the control port),
14 * writing it back to disk (because of SAVECONF from the control port),
15 * and -- most importantly, acting on it.
17 * The module additionally has some tools for manipulating and
18 * inspecting values that are calculated as a result of the
19 * configured options.
21 * <h3>How to add new options</h3>
23 * To add new items to the torrc, there are a minimum of three places to edit:
24 * <ul>
25 * <li>The or_options_t structure in or.h, where the options are stored.
26 * <li>The option_vars_ array below in this module, which configures
27 * the names of the torrc options, their types, their multiplicities,
28 * and their mappings to fields in or_options_t.
29 * <li>The manual in doc/tor.1.txt, to document what the new option
30 * is, and how it works.
31 * </ul>
33 * Additionally, you might need to edit these places too:
34 * <ul>
35 * <li>options_validate() below, in case you want to reject some possible
36 * values of the new configuration option.
37 * <li>options_transition_allowed() below, in case you need to
38 * forbid some or all changes in the option while Tor is
39 * running.
40 * <li>options_transition_affects_workers(), in case changes in the option
41 * might require Tor to relaunch or reconfigure its worker threads.
42 * <li>options_transition_affects_descriptor(), in case changes in the
43 * option might require a Tor relay to build and publish a new server
44 * descriptor.
45 * <li>options_act() and/or options_act_reversible(), in case there's some
46 * action that needs to be taken immediately based on the option's
47 * value.
48 * </ul>
50 * <h3>Changing the value of an option</h3>
52 * Because of the SAVECONF command from the control port, it's a bad
53 * idea to change the value of any user-configured option in the
54 * or_options_t. If you want to sometimes do this anyway, we recommend
55 * that you create a secondary field in or_options_t; that you have the
56 * user option linked only to the secondary field; that you use the
57 * secondary field to initialize the one that Tor actually looks at; and that
58 * you use the one Tor looks as the one that you modify.
59 **/
61 #define CONFIG_PRIVATE
62 #include "or.h"
63 #include "bridges.h"
64 #include "compat.h"
65 #include "addressmap.h"
66 #include "channel.h"
67 #include "circuitbuild.h"
68 #include "circuitlist.h"
69 #include "circuitmux.h"
70 #include "circuitmux_ewma.h"
71 #include "circuitstats.h"
72 #include "compress.h"
73 #include "config.h"
74 #include "connection.h"
75 #include "connection_edge.h"
76 #include "connection_or.h"
77 #include "consdiffmgr.h"
78 #include "control.h"
79 #include "confparse.h"
80 #include "cpuworker.h"
81 #include "dirserv.h"
82 #include "dirvote.h"
83 #include "dns.h"
84 #include "entrynodes.h"
85 #include "git_revision.h"
86 #include "geoip.h"
87 #include "hibernate.h"
88 #include "main.h"
89 #include "networkstatus.h"
90 #include "nodelist.h"
91 #include "policies.h"
92 #include "relay.h"
93 #include "rendclient.h"
94 #include "rendservice.h"
95 #include "hs_config.h"
96 #include "rephist.h"
97 #include "router.h"
98 #include "sandbox.h"
99 #include "util.h"
100 #include "routerlist.h"
101 #include "routerset.h"
102 #include "scheduler.h"
103 #include "statefile.h"
104 #include "transports.h"
105 #include "ext_orport.h"
106 #ifdef _WIN32
107 #include <shlobj.h>
108 #endif
110 #include "procmon.h"
112 #ifdef HAVE_SYSTEMD
113 # if defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__)
114 /* Systemd's use of gcc's __INCLUDE_LEVEL__ extension macro appears to confuse
115 * Coverity. Here's a kludge to unconfuse it.
117 # define __INCLUDE_LEVEL__ 2
118 #endif /* defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__) */
119 #include <systemd/sd-daemon.h>
120 #endif /* defined(HAVE_SYSTEMD) */
122 /* Prefix used to indicate a Unix socket in a FooPort configuration. */
123 static const char unix_socket_prefix[] = "unix:";
124 /* Prefix used to indicate a Unix socket with spaces in it, in a FooPort
125 * configuration. */
126 static const char unix_q_socket_prefix[] = "unix:\"";
128 /** A list of abbreviations and aliases to map command-line options, obsolete
129 * option names, or alternative option names, to their current values. */
130 static config_abbrev_t option_abbrevs_[] = {
131 PLURAL(AuthDirBadDirCC),
132 PLURAL(AuthDirBadExitCC),
133 PLURAL(AuthDirInvalidCC),
134 PLURAL(AuthDirRejectCC),
135 PLURAL(EntryNode),
136 PLURAL(ExcludeNode),
137 PLURAL(Tor2webRendezvousPoint),
138 PLURAL(FirewallPort),
139 PLURAL(LongLivedPort),
140 PLURAL(HiddenServiceNode),
141 PLURAL(HiddenServiceExcludeNode),
142 PLURAL(NumCPU),
143 PLURAL(RendNode),
144 PLURAL(RecommendedPackage),
145 PLURAL(RendExcludeNode),
146 PLURAL(StrictEntryNode),
147 PLURAL(StrictExitNode),
148 PLURAL(StrictNode),
149 { "l", "Log", 1, 0},
150 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
151 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
152 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
153 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
154 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
155 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
156 { "DirServer", "DirAuthority", 0, 0}, /* XXXX later, make this warn? */
157 { "MaxConn", "ConnLimit", 0, 1},
158 { "MaxMemInCellQueues", "MaxMemInQueues", 0, 0},
159 { "ORBindAddress", "ORListenAddress", 0, 0},
160 { "DirBindAddress", "DirListenAddress", 0, 0},
161 { "SocksBindAddress", "SocksListenAddress", 0, 0},
162 { "UseHelperNodes", "UseEntryGuards", 0, 0},
163 { "NumHelperNodes", "NumEntryGuards", 0, 0},
164 { "UseEntryNodes", "UseEntryGuards", 0, 0},
165 { "NumEntryNodes", "NumEntryGuards", 0, 0},
166 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
167 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
168 { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0},
169 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
170 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
171 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
172 { "VirtualAddrNetwork", "VirtualAddrNetworkIPv4", 0, 0},
173 { NULL, NULL, 0, 0},
176 /** dummy instance of or_options_t, used for type-checking its
177 * members with CONF_CHECK_VAR_TYPE. */
178 DUMMY_TYPECHECK_INSTANCE(or_options_t);
180 /** An entry for config_vars: "The option <b>name</b> has type
181 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
182 * or_options_t.<b>member</b>"
184 #define VAR(name,conftype,member,initvalue) \
185 { name, CONFIG_TYPE_ ## conftype, offsetof(or_options_t, member), \
186 initvalue CONF_TEST_MEMBERS(or_options_t, conftype, member) }
187 /** As VAR, but the option name and member name are the same. */
188 #define V(member,conftype,initvalue) \
189 VAR(#member, conftype, member, initvalue)
190 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
191 #ifdef TOR_UNIT_TESTS
192 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL, {.INT=NULL} }
193 #else
194 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
195 #endif
198 * Macro to declare *Port options. Each one comes in three entries.
199 * For example, most users should use "SocksPort" to configure the
200 * socks port, but TorBrowser wants to use __SocksPort so that it
201 * isn't stored by SAVECONF. The SocksPortLines virtual option is
202 * used to query both options from the controller.
204 #define VPORT(member) \
205 VAR(#member "Lines", LINELIST_V, member ## _lines, NULL), \
206 VAR(#member, LINELIST_S, member ## _lines, NULL), \
207 VAR("__" #member, LINELIST_S, member ## _lines, NULL)
209 /** Array of configuration options. Until we disallow nonstandard
210 * abbreviations, order is significant, since the first matching option will
211 * be chosen first.
213 static config_var_t option_vars_[] = {
214 V(AccountingMax, MEMUNIT, "0 bytes"),
215 VAR("AccountingRule", STRING, AccountingRule_option, "max"),
216 V(AccountingStart, STRING, NULL),
217 V(Address, STRING, NULL),
218 OBSOLETE("AllowDotExit"),
219 OBSOLETE("AllowInvalidNodes"),
220 V(AllowNonRFC953Hostnames, BOOL, "0"),
221 OBSOLETE("AllowSingleHopCircuits"),
222 OBSOLETE("AllowSingleHopExits"),
223 V(AlternateBridgeAuthority, LINELIST, NULL),
224 V(AlternateDirAuthority, LINELIST, NULL),
225 OBSOLETE("AlternateHSAuthority"),
226 V(AssumeReachable, BOOL, "0"),
227 OBSOLETE("AuthDirBadDir"),
228 OBSOLETE("AuthDirBadDirCCs"),
229 V(AuthDirBadExit, LINELIST, NULL),
230 V(AuthDirBadExitCCs, CSV, ""),
231 V(AuthDirInvalid, LINELIST, NULL),
232 V(AuthDirInvalidCCs, CSV, ""),
233 V(AuthDirFastGuarantee, MEMUNIT, "100 KB"),
234 V(AuthDirGuardBWGuarantee, MEMUNIT, "2 MB"),
235 V(AuthDirPinKeys, BOOL, "1"),
236 V(AuthDirReject, LINELIST, NULL),
237 V(AuthDirRejectCCs, CSV, ""),
238 OBSOLETE("AuthDirRejectUnlisted"),
239 OBSOLETE("AuthDirListBadDirs"),
240 V(AuthDirListBadExits, BOOL, "0"),
241 V(AuthDirMaxServersPerAddr, UINT, "2"),
242 OBSOLETE("AuthDirMaxServersPerAuthAddr"),
243 V(AuthDirHasIPv6Connectivity, BOOL, "0"),
244 VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
245 V(AutomapHostsOnResolve, BOOL, "0"),
246 V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
247 V(AvoidDiskWrites, BOOL, "0"),
248 V(BandwidthBurst, MEMUNIT, "1 GB"),
249 V(BandwidthRate, MEMUNIT, "1 GB"),
250 V(BridgeAuthoritativeDir, BOOL, "0"),
251 VAR("Bridge", LINELIST, Bridges, NULL),
252 V(BridgePassword, STRING, NULL),
253 V(BridgeRecordUsageByCountry, BOOL, "1"),
254 V(BridgeRelay, BOOL, "0"),
255 V(BridgeDistribution, STRING, NULL),
256 VAR("CacheDirectory", FILENAME, CacheDirectory_option, NULL),
257 V(CacheDirectoryGroupReadable, BOOL, "0"),
258 V(CellStatistics, BOOL, "0"),
259 V(PaddingStatistics, BOOL, "1"),
260 V(LearnCircuitBuildTimeout, BOOL, "1"),
261 V(CircuitBuildTimeout, INTERVAL, "0"),
262 OBSOLETE("CircuitIdleTimeout"),
263 V(CircuitsAvailableTimeout, INTERVAL, "0"),
264 V(CircuitStreamTimeout, INTERVAL, "0"),
265 V(CircuitPriorityHalflife, DOUBLE, "-100.0"), /*negative:'Use default'*/
266 V(ClientDNSRejectInternalAddresses, BOOL,"1"),
267 V(ClientOnly, BOOL, "0"),
268 V(ClientPreferIPv6ORPort, AUTOBOOL, "auto"),
269 V(ClientPreferIPv6DirPort, AUTOBOOL, "auto"),
270 V(ClientRejectInternalAddresses, BOOL, "1"),
271 V(ClientTransportPlugin, LINELIST, NULL),
272 V(ClientUseIPv6, BOOL, "0"),
273 V(ClientUseIPv4, BOOL, "1"),
274 V(ConsensusParams, STRING, NULL),
275 V(ConnLimit, UINT, "1000"),
276 V(ConnDirectionStatistics, BOOL, "0"),
277 V(ConstrainedSockets, BOOL, "0"),
278 V(ConstrainedSockSize, MEMUNIT, "8192"),
279 V(ContactInfo, STRING, NULL),
280 OBSOLETE("ControlListenAddress"),
281 VPORT(ControlPort),
282 V(ControlPortFileGroupReadable,BOOL, "0"),
283 V(ControlPortWriteToFile, FILENAME, NULL),
284 V(ControlSocket, LINELIST, NULL),
285 V(ControlSocketsGroupWritable, BOOL, "0"),
286 V(SocksSocketsGroupWritable, BOOL, "0"),
287 V(CookieAuthentication, BOOL, "0"),
288 V(CookieAuthFileGroupReadable, BOOL, "0"),
289 V(CookieAuthFile, STRING, NULL),
290 V(CountPrivateBandwidth, BOOL, "0"),
291 VAR("DataDirectory", FILENAME, DataDirectory_option, NULL),
292 V(DataDirectoryGroupReadable, BOOL, "0"),
293 V(DisableOOSCheck, BOOL, "1"),
294 V(DisableNetwork, BOOL, "0"),
295 V(DirAllowPrivateAddresses, BOOL, "0"),
296 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
297 OBSOLETE("DirListenAddress"),
298 V(DirPolicy, LINELIST, NULL),
299 VPORT(DirPort),
300 V(DirPortFrontPage, FILENAME, NULL),
301 VAR("DirReqStatistics", BOOL, DirReqStatistics_option, "1"),
302 VAR("DirAuthority", LINELIST, DirAuthorities, NULL),
303 V(DirCache, BOOL, "1"),
304 V(DirAuthorityFallbackRate, DOUBLE, "1.0"),
305 V(DisableAllSwap, BOOL, "0"),
306 V(DisableDebuggerAttachment, BOOL, "1"),
307 OBSOLETE("DisableIOCP"),
308 OBSOLETE("DisableV2DirectoryInfo_"),
309 OBSOLETE("DynamicDHGroups"),
310 VPORT(DNSPort),
311 OBSOLETE("DNSListenAddress"),
312 V(DownloadExtraInfo, BOOL, "0"),
313 V(TestingEnableConnBwEvent, BOOL, "0"),
314 V(TestingEnableCellStatsEvent, BOOL, "0"),
315 V(TestingEnableTbEmptyEvent, BOOL, "0"),
316 V(EnforceDistinctSubnets, BOOL, "1"),
317 V(EntryNodes, ROUTERSET, NULL),
318 V(EntryStatistics, BOOL, "0"),
319 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
320 V(ExcludeNodes, ROUTERSET, NULL),
321 V(ExcludeExitNodes, ROUTERSET, NULL),
322 OBSOLETE("ExcludeSingleHopRelays"),
323 V(ExitNodes, ROUTERSET, NULL),
324 V(ExitPolicy, LINELIST, NULL),
325 V(ExitPolicyRejectPrivate, BOOL, "1"),
326 V(ExitPolicyRejectLocalInterfaces, BOOL, "0"),
327 V(ExitPortStatistics, BOOL, "0"),
328 V(ExtendAllowPrivateAddresses, BOOL, "0"),
329 V(ExitRelay, AUTOBOOL, "auto"),
330 VPORT(ExtORPort),
331 V(ExtORPortCookieAuthFile, STRING, NULL),
332 V(ExtORPortCookieAuthFileGroupReadable, BOOL, "0"),
333 V(ExtraInfoStatistics, BOOL, "1"),
334 V(ExtendByEd25519ID, AUTOBOOL, "auto"),
335 V(FallbackDir, LINELIST, NULL),
337 V(UseDefaultFallbackDirs, BOOL, "1"),
339 OBSOLETE("FallbackNetworkstatusFile"),
340 V(FascistFirewall, BOOL, "0"),
341 V(FirewallPorts, CSV, ""),
342 OBSOLETE("FastFirstHopPK"),
343 V(FetchDirInfoEarly, BOOL, "0"),
344 V(FetchDirInfoExtraEarly, BOOL, "0"),
345 V(FetchServerDescriptors, BOOL, "1"),
346 V(FetchHidServDescriptors, BOOL, "1"),
347 V(FetchUselessDescriptors, BOOL, "0"),
348 OBSOLETE("FetchV2Networkstatus"),
349 V(GeoIPExcludeUnknown, AUTOBOOL, "auto"),
350 #ifdef _WIN32
351 V(GeoIPFile, FILENAME, "<default>"),
352 V(GeoIPv6File, FILENAME, "<default>"),
353 #else
354 V(GeoIPFile, FILENAME,
355 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
356 V(GeoIPv6File, FILENAME,
357 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip6"),
358 #endif /* defined(_WIN32) */
359 OBSOLETE("Group"),
360 V(GuardLifetime, INTERVAL, "0 minutes"),
361 V(HardwareAccel, BOOL, "0"),
362 V(HeartbeatPeriod, INTERVAL, "6 hours"),
363 V(MainloopStats, BOOL, "0"),
364 V(AccelName, STRING, NULL),
365 V(AccelDir, FILENAME, NULL),
366 V(HashedControlPassword, LINELIST, NULL),
367 OBSOLETE("HidServDirectoryV2"),
368 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
369 VAR("HiddenServiceDirGroupReadable", LINELIST_S, RendConfigLines, NULL),
370 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
371 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
372 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
373 VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
374 VAR("HiddenServiceAllowUnknownPorts",LINELIST_S, RendConfigLines, NULL),
375 VAR("HiddenServiceMaxStreams",LINELIST_S, RendConfigLines, NULL),
376 VAR("HiddenServiceMaxStreamsCloseCircuit",LINELIST_S, RendConfigLines, NULL),
377 VAR("HiddenServiceNumIntroductionPoints", LINELIST_S, RendConfigLines, NULL),
378 VAR("HiddenServiceStatistics", BOOL, HiddenServiceStatistics_option, "1"),
379 V(HidServAuth, LINELIST, NULL),
380 OBSOLETE("CloseHSClientCircuitsImmediatelyOnTimeout"),
381 OBSOLETE("CloseHSServiceRendCircuitsImmediatelyOnTimeout"),
382 V(HiddenServiceSingleHopMode, BOOL, "0"),
383 V(HiddenServiceNonAnonymousMode,BOOL, "0"),
384 V(HTTPProxy, STRING, NULL),
385 V(HTTPProxyAuthenticator, STRING, NULL),
386 V(HTTPSProxy, STRING, NULL),
387 V(HTTPSProxyAuthenticator, STRING, NULL),
388 VPORT(HTTPTunnelPort),
389 V(IPv6Exit, BOOL, "0"),
390 VAR("ServerTransportPlugin", LINELIST, ServerTransportPlugin, NULL),
391 V(ServerTransportListenAddr, LINELIST, NULL),
392 V(ServerTransportOptions, LINELIST, NULL),
393 V(SigningKeyLifetime, INTERVAL, "30 days"),
394 V(Socks4Proxy, STRING, NULL),
395 V(Socks5Proxy, STRING, NULL),
396 V(Socks5ProxyUsername, STRING, NULL),
397 V(Socks5ProxyPassword, STRING, NULL),
398 VAR("KeyDirectory", FILENAME, KeyDirectory_option, NULL),
399 V(KeyDirectoryGroupReadable, BOOL, "0"),
400 V(KeepalivePeriod, INTERVAL, "5 minutes"),
401 V(KeepBindCapabilities, AUTOBOOL, "auto"),
402 VAR("Log", LINELIST, Logs, NULL),
403 V(LogMessageDomains, BOOL, "0"),
404 V(LogTimeGranularity, MSEC_INTERVAL, "1 second"),
405 V(TruncateLogFile, BOOL, "0"),
406 V(SyslogIdentityTag, STRING, NULL),
407 V(AndroidIdentityTag, STRING, NULL),
408 V(LongLivedPorts, CSV,
409 "21,22,706,1863,5050,5190,5222,5223,6523,6667,6697,8300"),
410 VAR("MapAddress", LINELIST, AddressMap, NULL),
411 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
412 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
413 V(MaxClientCircuitsPending, UINT, "32"),
414 V(MaxConsensusAgeForDiffs, INTERVAL, "0 seconds"),
415 VAR("MaxMemInQueues", MEMUNIT, MaxMemInQueues_raw, "0"),
416 OBSOLETE("MaxOnionsPending"),
417 V(MaxOnionQueueDelay, MSEC_INTERVAL, "1750 msec"),
418 V(MaxUnparseableDescSizeToLog, MEMUNIT, "10 MB"),
419 V(MinMeasuredBWsForAuthToIgnoreAdvertised, INT, "500"),
420 VAR("MyFamily", LINELIST, MyFamily_lines, NULL),
421 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
422 OBSOLETE("NamingAuthoritativeDirectory"),
423 OBSOLETE("NATDListenAddress"),
424 VPORT(NATDPort),
425 V(Nickname, STRING, NULL),
426 OBSOLETE("PredictedPortsRelevanceTime"),
427 OBSOLETE("WarnUnsafeSocks"),
428 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
429 V(NoExec, BOOL, "0"),
430 V(NumCPUs, UINT, "0"),
431 V(NumDirectoryGuards, UINT, "0"),
432 V(NumEntryGuards, UINT, "0"),
433 V(OfflineMasterKey, BOOL, "0"),
434 OBSOLETE("ORListenAddress"),
435 VPORT(ORPort),
436 V(OutboundBindAddress, LINELIST, NULL),
437 V(OutboundBindAddressOR, LINELIST, NULL),
438 V(OutboundBindAddressExit, LINELIST, NULL),
440 OBSOLETE("PathBiasDisableRate"),
441 V(PathBiasCircThreshold, INT, "-1"),
442 V(PathBiasNoticeRate, DOUBLE, "-1"),
443 V(PathBiasWarnRate, DOUBLE, "-1"),
444 V(PathBiasExtremeRate, DOUBLE, "-1"),
445 V(PathBiasScaleThreshold, INT, "-1"),
446 OBSOLETE("PathBiasScaleFactor"),
447 OBSOLETE("PathBiasMultFactor"),
448 V(PathBiasDropGuards, AUTOBOOL, "0"),
449 OBSOLETE("PathBiasUseCloseCounts"),
451 V(PathBiasUseThreshold, INT, "-1"),
452 V(PathBiasNoticeUseRate, DOUBLE, "-1"),
453 V(PathBiasExtremeUseRate, DOUBLE, "-1"),
454 V(PathBiasScaleUseThreshold, INT, "-1"),
456 V(PathsNeededToBuildCircuits, DOUBLE, "-1"),
457 V(PerConnBWBurst, MEMUNIT, "0"),
458 V(PerConnBWRate, MEMUNIT, "0"),
459 V(PidFile, STRING, NULL),
460 V(TestingTorNetwork, BOOL, "0"),
461 V(TestingMinExitFlagThreshold, MEMUNIT, "0"),
462 V(TestingMinFastFlagThreshold, MEMUNIT, "0"),
464 V(TestingLinkCertLifetime, INTERVAL, "2 days"),
465 V(TestingAuthKeyLifetime, INTERVAL, "2 days"),
466 V(TestingLinkKeySlop, INTERVAL, "3 hours"),
467 V(TestingAuthKeySlop, INTERVAL, "3 hours"),
468 V(TestingSigningKeySlop, INTERVAL, "1 day"),
470 V(OptimisticData, AUTOBOOL, "auto"),
471 V(PortForwarding, BOOL, "0"),
472 V(PortForwardingHelper, FILENAME, "tor-fw-helper"),
473 OBSOLETE("PreferTunneledDirConns"),
474 V(ProtocolWarnings, BOOL, "0"),
475 V(PublishServerDescriptor, CSV, "1"),
476 V(PublishHidServDescriptors, BOOL, "1"),
477 V(ReachableAddresses, LINELIST, NULL),
478 V(ReachableDirAddresses, LINELIST, NULL),
479 V(ReachableORAddresses, LINELIST, NULL),
480 V(RecommendedVersions, LINELIST, NULL),
481 V(RecommendedClientVersions, LINELIST, NULL),
482 V(RecommendedServerVersions, LINELIST, NULL),
483 V(RecommendedPackages, LINELIST, NULL),
484 V(ReducedConnectionPadding, BOOL, "0"),
485 V(ConnectionPadding, AUTOBOOL, "auto"),
486 V(RefuseUnknownExits, AUTOBOOL, "auto"),
487 V(RejectPlaintextPorts, CSV, ""),
488 V(RelayBandwidthBurst, MEMUNIT, "0"),
489 V(RelayBandwidthRate, MEMUNIT, "0"),
490 V(RendPostPeriod, INTERVAL, "1 hour"),
491 V(RephistTrackTime, INTERVAL, "24 hours"),
492 V(RunAsDaemon, BOOL, "0"),
493 V(ReducedExitPolicy, BOOL, "0"),
494 OBSOLETE("RunTesting"), // currently unused
495 V(Sandbox, BOOL, "0"),
496 V(SafeLogging, STRING, "1"),
497 V(SafeSocks, BOOL, "0"),
498 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
499 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
500 V(ServerDNSDetectHijacking, BOOL, "1"),
501 V(ServerDNSRandomizeCase, BOOL, "1"),
502 V(ServerDNSResolvConfFile, STRING, NULL),
503 V(ServerDNSSearchDomains, BOOL, "0"),
504 V(ServerDNSTestAddresses, CSV,
505 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
506 OBSOLETE("SchedulerLowWaterMark__"),
507 OBSOLETE("SchedulerHighWaterMark__"),
508 OBSOLETE("SchedulerMaxFlushCells__"),
509 V(KISTSchedRunInterval, MSEC_INTERVAL, "0 msec"),
510 V(KISTSockBufSizeFactor, DOUBLE, "1.0"),
511 V(Schedulers, CSV, "KIST,KISTLite,Vanilla"),
512 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
513 OBSOLETE("SocksListenAddress"),
514 V(SocksPolicy, LINELIST, NULL),
515 VPORT(SocksPort),
516 V(SocksTimeout, INTERVAL, "2 minutes"),
517 V(SSLKeyLifetime, INTERVAL, "0"),
518 OBSOLETE("StrictEntryNodes"),
519 OBSOLETE("StrictExitNodes"),
520 V(StrictNodes, BOOL, "0"),
521 OBSOLETE("Support022HiddenServices"),
522 V(TestSocks, BOOL, "0"),
523 V(TokenBucketRefillInterval, MSEC_INTERVAL, "100 msec"),
524 V(Tor2webMode, BOOL, "0"),
525 V(Tor2webRendezvousPoints, ROUTERSET, NULL),
526 OBSOLETE("TLSECGroup"),
527 V(TrackHostExits, CSV, NULL),
528 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
529 OBSOLETE("TransListenAddress"),
530 VPORT(TransPort),
531 V(TransProxyType, STRING, "default"),
532 OBSOLETE("TunnelDirConns"),
533 V(UpdateBridgesFromAuthority, BOOL, "0"),
534 V(UseBridges, BOOL, "0"),
535 VAR("UseEntryGuards", BOOL, UseEntryGuards_option, "1"),
536 OBSOLETE("UseEntryGuardsAsDirGuards"),
537 V(UseGuardFraction, AUTOBOOL, "auto"),
538 V(UseMicrodescriptors, AUTOBOOL, "auto"),
539 OBSOLETE("UseNTorHandshake"),
540 V(User, STRING, NULL),
541 OBSOLETE("UserspaceIOCPBuffers"),
542 V(AuthDirSharedRandomness, BOOL, "1"),
543 V(AuthDirTestEd25519LinkKeys, BOOL, "1"),
544 OBSOLETE("V1AuthoritativeDirectory"),
545 OBSOLETE("V2AuthoritativeDirectory"),
546 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
547 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
548 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
549 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
550 V(TestingV3AuthVotingStartOffset, INTERVAL, "0"),
551 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
552 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
553 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
554 V(V3AuthNIntervalsValid, UINT, "3"),
555 V(V3AuthUseLegacyKey, BOOL, "0"),
556 V(V3BandwidthsFile, FILENAME, NULL),
557 V(GuardfractionFile, FILENAME, NULL),
558 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
559 OBSOLETE("VoteOnHidServDirectoriesV2"),
560 V(VirtualAddrNetworkIPv4, STRING, "127.192.0.0/10"),
561 V(VirtualAddrNetworkIPv6, STRING, "[FE80::]/10"),
562 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
563 OBSOLETE("UseFilteringSSLBufferevents"),
564 OBSOLETE("__UseFilteringSSLBufferevents"),
565 VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
566 VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
567 VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
568 VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
569 VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
570 NULL),
571 VAR("__OwningControllerProcess",STRING,OwningControllerProcess, NULL),
572 VAR("__OwningControllerFD",INT,OwningControllerFD, "-1"),
573 V(MinUptimeHidServDirectoryV2, INTERVAL, "96 hours"),
574 V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 60, 60, 120, "
575 "300, 900, 2147483647"),
576 V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 60, 300, 600, "
577 "2147483647"),
578 V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
579 "300, 600, 1800, 1800, 1800, 1800, "
580 "1800, 3600, 7200"),
581 V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
582 "300, 600, 1800, 3600, 3600, 3600, "
583 "10800, 21600, 43200"),
584 /* With the ClientBootstrapConsensus*Download* below:
585 * Clients with only authorities will try:
586 * - at least 3 authorities over 10 seconds, then exponentially backoff,
587 * with the next attempt 3-21 seconds later,
588 * Clients with authorities and fallbacks will try:
589 * - at least 2 authorities and 4 fallbacks over 21 seconds, then
590 * exponentially backoff, with the next attempts 4-33 seconds later,
591 * Clients will also retry when an application request arrives.
592 * After a number of failed requests, clients retry every 3 days + 1 hour.
594 * Clients used to try 2 authorities over 10 seconds, then wait for
595 * 60 minutes or an application request.
597 * When clients have authorities and fallbacks available, they use these
598 * schedules: (we stagger the times to avoid thundering herds) */
599 V(ClientBootstrapConsensusAuthorityDownloadSchedule, CSV_INTERVAL,
600 "6, 11, 3600, 10800, 25200, 54000, 111600, 262800" /* 3 days + 1 hour */),
601 V(ClientBootstrapConsensusFallbackDownloadSchedule, CSV_INTERVAL,
602 "0, 1, 4, 11, 3600, 10800, 25200, 54000, 111600, 262800"),
603 /* When clients only have authorities available, they use this schedule: */
604 V(ClientBootstrapConsensusAuthorityOnlyDownloadSchedule, CSV_INTERVAL,
605 "0, 3, 7, 3600, 10800, 25200, 54000, 111600, 262800"),
606 /* We don't want to overwhelm slow networks (or mirrors whose replies are
607 * blocked), but we also don't want to fail if only some mirrors are
608 * blackholed. Clients will try 3 directories simultaneously.
609 * (Relays never use simultaneous connections.) */
610 V(ClientBootstrapConsensusMaxInProgressTries, UINT, "3"),
611 /* When a client has any running bridges, check each bridge occasionally,
612 * whether or not that bridge is actually up. */
613 V(TestingBridgeDownloadSchedule, CSV_INTERVAL,
614 "10800, 25200, 54000, 111600, 262800"),
615 /* When a client is just starting, or has no running bridges, check each
616 * bridge a few times quickly, and then try again later. These schedules
617 * are much longer than the other schedules, because we try each and every
618 * configured bridge with this schedule. */
619 V(TestingBridgeBootstrapDownloadSchedule, CSV_INTERVAL,
620 "0, 30, 90, 600, 3600, 10800, 25200, 54000, 111600, 262800"),
621 V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "10 minutes"),
622 V(TestingDirConnectionMaxStall, INTERVAL, "5 minutes"),
623 V(TestingConsensusMaxDownloadTries, UINT, "8"),
624 /* Since we try connections rapidly and simultaneously, we can afford
625 * to give up earlier. (This protects against overloading directories.) */
626 V(ClientBootstrapConsensusMaxDownloadTries, UINT, "7"),
627 /* We want to give up much earlier if we're only using authorities. */
628 V(ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries, UINT, "4"),
629 V(TestingDescriptorMaxDownloadTries, UINT, "8"),
630 V(TestingMicrodescMaxDownloadTries, UINT, "8"),
631 V(TestingCertMaxDownloadTries, UINT, "8"),
632 V(TestingDirAuthVoteExit, ROUTERSET, NULL),
633 V(TestingDirAuthVoteExitIsStrict, BOOL, "0"),
634 V(TestingDirAuthVoteGuard, ROUTERSET, NULL),
635 V(TestingDirAuthVoteGuardIsStrict, BOOL, "0"),
636 V(TestingDirAuthVoteHSDir, ROUTERSET, NULL),
637 V(TestingDirAuthVoteHSDirIsStrict, BOOL, "0"),
638 VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "0"),
640 END_OF_CONFIG_VARS
643 /** Override default values with these if the user sets the TestingTorNetwork
644 * option. */
645 static const config_var_t testing_tor_network_defaults[] = {
646 V(DirAllowPrivateAddresses, BOOL, "1"),
647 V(EnforceDistinctSubnets, BOOL, "0"),
648 V(AssumeReachable, BOOL, "1"),
649 V(AuthDirMaxServersPerAddr, UINT, "0"),
650 V(ClientBootstrapConsensusAuthorityDownloadSchedule, CSV_INTERVAL,
651 "0, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
652 V(ClientBootstrapConsensusFallbackDownloadSchedule, CSV_INTERVAL,
653 "0, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
654 V(ClientBootstrapConsensusAuthorityOnlyDownloadSchedule, CSV_INTERVAL,
655 "0, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
656 V(ClientBootstrapConsensusMaxDownloadTries, UINT, "80"),
657 V(ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries, UINT, "80"),
658 V(ClientDNSRejectInternalAddresses, BOOL,"0"),
659 V(ClientRejectInternalAddresses, BOOL, "0"),
660 V(CountPrivateBandwidth, BOOL, "1"),
661 V(ExitPolicyRejectPrivate, BOOL, "0"),
662 V(ExtendAllowPrivateAddresses, BOOL, "1"),
663 V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
664 V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
665 V(V3AuthDistDelay, INTERVAL, "20 seconds"),
666 V(TestingV3AuthInitialVotingInterval, INTERVAL, "150 seconds"),
667 V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
668 V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
669 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
670 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
671 V(MinUptimeHidServDirectoryV2, INTERVAL, "0 minutes"),
672 V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 5, 10, 15, "
673 "20, 30, 60"),
674 V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, 15, 20, "
675 "30, 60"),
676 V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
677 "15, 20, 30, 60"),
678 V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
679 "15, 20, 30, 60"),
680 V(TestingBridgeDownloadSchedule, CSV_INTERVAL, "10, 30, 60"),
681 V(TestingBridgeBootstrapDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
682 "15, 20, 30, 60"),
683 V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "5 seconds"),
684 V(TestingDirConnectionMaxStall, INTERVAL, "30 seconds"),
685 V(TestingConsensusMaxDownloadTries, UINT, "80"),
686 V(TestingDescriptorMaxDownloadTries, UINT, "80"),
687 V(TestingMicrodescMaxDownloadTries, UINT, "80"),
688 V(TestingCertMaxDownloadTries, UINT, "80"),
689 V(TestingEnableConnBwEvent, BOOL, "1"),
690 V(TestingEnableCellStatsEvent, BOOL, "1"),
691 V(TestingEnableTbEmptyEvent, BOOL, "1"),
692 VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "1"),
693 V(RendPostPeriod, INTERVAL, "2 minutes"),
695 END_OF_CONFIG_VARS
698 #undef VAR
699 #undef V
700 #undef OBSOLETE
702 static const config_deprecation_t option_deprecation_notes_[] = {
703 /* Deprecated since 0.3.2.0-alpha. */
704 { "HTTPProxy", "It only applies to direct unencrypted HTTP connections "
705 "to your directory server, which your Tor probably wasn't using." },
706 { "HTTPProxyAuthenticator", "HTTPProxy is deprecated in favor of HTTPSProxy "
707 "which should be used with HTTPSProxyAuthenticator." },
708 /* End of options deprecated since 0.3.2.1-alpha */
710 /* Options deprecated since 0.3.2.2-alpha */
711 { "ReachableDirAddresses", "It has no effect on relays, and has had no "
712 "effect on clients since 0.2.8." },
713 { "ClientPreferIPv6DirPort", "It has no effect on relays, and has had no "
714 "effect on clients since 0.2.8." },
715 /* End of options deprecated since 0.3.2.2-alpha. */
717 { NULL, NULL }
720 #ifdef _WIN32
721 static char *get_windows_conf_root(void);
722 #endif
723 static int options_act_reversible(const or_options_t *old_options, char **msg);
724 static int options_transition_allowed(const or_options_t *old,
725 const or_options_t *new,
726 char **msg);
727 static int options_transition_affects_workers(
728 const or_options_t *old_options, const or_options_t *new_options);
729 static int options_transition_affects_descriptor(
730 const or_options_t *old_options, const or_options_t *new_options);
731 static int normalize_nickname_list(config_line_t **normalized_out,
732 const config_line_t *lst, const char *name,
733 char **msg);
734 static char *get_bindaddr_from_transport_listen_line(const char *line,
735 const char *transport);
736 static int parse_ports(or_options_t *options, int validate_only,
737 char **msg_out, int *n_ports_out,
738 int *world_writable_control_socket);
739 static int check_server_ports(const smartlist_t *ports,
740 const or_options_t *options,
741 int *num_low_ports_out);
742 static int validate_data_directories(or_options_t *options);
743 static int write_configuration_file(const char *fname,
744 const or_options_t *options);
745 static int options_init_logs(const or_options_t *old_options,
746 or_options_t *options, int validate_only);
748 static void init_libevent(const or_options_t *options);
749 static int opt_streq(const char *s1, const char *s2);
750 static int parse_outbound_addresses(or_options_t *options, int validate_only,
751 char **msg);
752 static void config_maybe_load_geoip_files_(const or_options_t *options,
753 const or_options_t *old_options);
754 static int options_validate_cb(void *old_options, void *options,
755 void *default_options,
756 int from_setconf, char **msg);
757 static uint64_t compute_real_max_mem_in_queues(const uint64_t val,
758 int log_guess);
760 /** Magic value for or_options_t. */
761 #define OR_OPTIONS_MAGIC 9090909
763 /** Configuration format for or_options_t. */
764 STATIC config_format_t options_format = {
765 sizeof(or_options_t),
766 OR_OPTIONS_MAGIC,
767 offsetof(or_options_t, magic_),
768 option_abbrevs_,
769 option_deprecation_notes_,
770 option_vars_,
771 options_validate_cb,
772 NULL
776 * Functions to read and write the global options pointer.
779 /** Command-line and config-file options. */
780 static or_options_t *global_options = NULL;
781 /** The fallback options_t object; this is where we look for options not
782 * in torrc before we fall back to Tor's defaults. */
783 static or_options_t *global_default_options = NULL;
784 /** Name of most recently read torrc file. */
785 static char *torrc_fname = NULL;
786 /** Name of the most recently read torrc-defaults file.*/
787 static char *torrc_defaults_fname = NULL;
788 /** Configuration options set by command line. */
789 static config_line_t *global_cmdline_options = NULL;
790 /** Non-configuration options set by the command line */
791 static config_line_t *global_cmdline_only_options = NULL;
792 /** Boolean: Have we parsed the command line? */
793 static int have_parsed_cmdline = 0;
794 /** Contents of most recently read DirPortFrontPage file. */
795 static char *global_dirfrontpagecontents = NULL;
796 /** List of port_cfg_t for all configured ports. */
797 static smartlist_t *configured_ports = NULL;
798 /** True iff we're currently validating options, and any calls to
799 * get_options() are likely to be bugs. */
800 static int in_option_validation = 0;
802 /** Return the contents of our frontpage string, or NULL if not configured. */
803 MOCK_IMPL(const char*,
804 get_dirportfrontpage, (void))
806 return global_dirfrontpagecontents;
809 /** Returns the currently configured options. */
810 MOCK_IMPL(or_options_t *,
811 get_options_mutable, (void))
813 tor_assert(global_options);
814 tor_assert_nonfatal(! in_option_validation);
815 return global_options;
818 /** Returns the currently configured options */
819 MOCK_IMPL(const or_options_t *,
820 get_options,(void))
822 return get_options_mutable();
825 /** Change the current global options to contain <b>new_val</b> instead of
826 * their current value; take action based on the new value; free the old value
827 * as necessary. Returns 0 on success, -1 on failure.
830 set_options(or_options_t *new_val, char **msg)
832 int i;
833 smartlist_t *elements;
834 config_line_t *line;
835 or_options_t *old_options = global_options;
836 global_options = new_val;
837 /* Note that we pass the *old* options below, for comparison. It
838 * pulls the new options directly out of global_options. */
839 if (options_act_reversible(old_options, msg)<0) {
840 tor_assert(*msg);
841 global_options = old_options;
842 return -1;
844 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
845 if (! tor_event_loop_shutdown_is_pending()) {
846 log_err(LD_BUG,
847 "Acting on config options left us in a broken state. Dying.");
848 tor_shutdown_event_loop_and_exit(1);
850 return -1;
852 /* Issues a CONF_CHANGED event to notify controller of the change. If Tor is
853 * just starting up then the old_options will be undefined. */
854 if (old_options && old_options != global_options) {
855 elements = smartlist_new();
856 for (i=0; options_format.vars[i].name; ++i) {
857 const config_var_t *var = &options_format.vars[i];
858 const char *var_name = var->name;
859 if (var->type == CONFIG_TYPE_LINELIST_S ||
860 var->type == CONFIG_TYPE_OBSOLETE) {
861 continue;
863 if (!config_is_same(&options_format, new_val, old_options, var_name)) {
864 line = config_get_assigned_option(&options_format, new_val,
865 var_name, 1);
867 if (line) {
868 config_line_t *next;
869 for (; line; line = next) {
870 next = line->next;
871 smartlist_add(elements, line->key);
872 smartlist_add(elements, line->value);
873 tor_free(line);
875 } else {
876 smartlist_add_strdup(elements, options_format.vars[i].name);
877 smartlist_add(elements, NULL);
881 control_event_conf_changed(elements);
882 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
883 smartlist_free(elements);
886 if (old_options != global_options)
887 or_options_free(old_options);
889 return 0;
892 /** The version of this Tor process, as parsed. */
893 static char *the_tor_version = NULL;
894 /** A shorter version of this Tor process's version, for export in our router
895 * descriptor. (Does not include the git version, if any.) */
896 static char *the_short_tor_version = NULL;
898 /** Return the current Tor version. */
899 const char *
900 get_version(void)
902 if (the_tor_version == NULL) {
903 if (strlen(tor_git_revision)) {
904 tor_asprintf(&the_tor_version, "%s (git-%s)", get_short_version(),
905 tor_git_revision);
906 } else {
907 the_tor_version = tor_strdup(get_short_version());
910 return the_tor_version;
913 /** Return the current Tor version, without any git tag. */
914 const char *
915 get_short_version(void)
918 if (the_short_tor_version == NULL) {
919 #ifdef TOR_BUILD_TAG
920 tor_asprintf(&the_short_tor_version, "%s (%s)", VERSION, TOR_BUILD_TAG);
921 #else
922 the_short_tor_version = tor_strdup(VERSION);
923 #endif
925 return the_short_tor_version;
928 /** Release additional memory allocated in options
930 STATIC void
931 or_options_free_(or_options_t *options)
933 if (!options)
934 return;
936 routerset_free(options->ExcludeExitNodesUnion_);
937 if (options->NodeFamilySets) {
938 SMARTLIST_FOREACH(options->NodeFamilySets, routerset_t *,
939 rs, routerset_free(rs));
940 smartlist_free(options->NodeFamilySets);
942 if (options->SchedulerTypes_) {
943 SMARTLIST_FOREACH(options->SchedulerTypes_, int *, i, tor_free(i));
944 smartlist_free(options->SchedulerTypes_);
946 if (options->FilesOpenedByIncludes) {
947 SMARTLIST_FOREACH(options->FilesOpenedByIncludes, char *, f, tor_free(f));
948 smartlist_free(options->FilesOpenedByIncludes);
950 tor_free(options->DataDirectory);
951 tor_free(options->CacheDirectory);
952 tor_free(options->KeyDirectory);
953 tor_free(options->BridgePassword_AuthDigest_);
954 tor_free(options->command_arg);
955 tor_free(options->master_key_fname);
956 config_free_lines(options->MyFamily);
957 config_free(&options_format, options);
960 /** Release all memory and resources held by global configuration structures.
962 void
963 config_free_all(void)
965 or_options_free(global_options);
966 global_options = NULL;
967 or_options_free(global_default_options);
968 global_default_options = NULL;
970 config_free_lines(global_cmdline_options);
971 global_cmdline_options = NULL;
973 config_free_lines(global_cmdline_only_options);
974 global_cmdline_only_options = NULL;
976 if (configured_ports) {
977 SMARTLIST_FOREACH(configured_ports,
978 port_cfg_t *, p, port_cfg_free(p));
979 smartlist_free(configured_ports);
980 configured_ports = NULL;
983 tor_free(torrc_fname);
984 tor_free(torrc_defaults_fname);
985 tor_free(global_dirfrontpagecontents);
987 tor_free(the_short_tor_version);
988 tor_free(the_tor_version);
990 have_parsed_cmdline = 0;
993 /** Make <b>address</b> -- a piece of information related to our operation as
994 * a client -- safe to log according to the settings in options->SafeLogging,
995 * and return it.
997 * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
999 const char *
1000 safe_str_client(const char *address)
1002 tor_assert(address);
1003 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
1004 return "[scrubbed]";
1005 else
1006 return address;
1009 /** Make <b>address</b> -- a piece of information of unspecified sensitivity
1010 * -- safe to log according to the settings in options->SafeLogging, and
1011 * return it.
1013 * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
1014 * otherwise.)
1016 const char *
1017 safe_str(const char *address)
1019 tor_assert(address);
1020 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
1021 return "[scrubbed]";
1022 else
1023 return address;
1026 /** Equivalent to escaped(safe_str_client(address)). See reentrancy note on
1027 * escaped(): don't use this outside the main thread, or twice in the same
1028 * log statement. */
1029 const char *
1030 escaped_safe_str_client(const char *address)
1032 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
1033 return "[scrubbed]";
1034 else
1035 return escaped(address);
1038 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
1039 * escaped(): don't use this outside the main thread, or twice in the same
1040 * log statement. */
1041 const char *
1042 escaped_safe_str(const char *address)
1044 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
1045 return "[scrubbed]";
1046 else
1047 return escaped(address);
1051 * The severity level that should be used for warnings of severity
1052 * LOG_PROTOCOL_WARN.
1054 * We keep this outside the options, in case somebody needs to use
1055 * LOG_PROTOCOL_WARN while an option transition is happening.
1057 static int protocol_warning_severity_level = LOG_WARN;
1059 /** Return the severity level that should be used for warnings of severity
1060 * LOG_PROTOCOL_WARN. */
1062 get_protocol_warning_severity_level(void)
1064 return protocol_warning_severity_level;
1067 /** List of default directory authorities */
1069 static const char *default_authorities[] = {
1070 "moria1 orport=9101 "
1071 "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
1072 "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
1073 "tor26 orport=443 "
1074 "v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
1075 "ipv6=[2001:858:2:2:aabb:0:563b:1526]:443 "
1076 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
1077 "dizum orport=443 "
1078 "v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
1079 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
1080 "Bifroest orport=443 bridge "
1081 "37.218.247.217:80 1D8F 3A91 C37C 5D1C 4C19 B1AD 1D0C FBE8 BF72 D8E1",
1082 "gabelmoo orport=443 "
1083 "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
1084 "ipv6=[2001:638:a000:4140::ffff:189]:443 "
1085 "131.188.40.189:80 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
1086 "dannenberg orport=443 "
1087 "v3ident=0232AF901C31A04EE9848595AF9BB7620D4C5B2E "
1088 "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
1089 "maatuska orport=80 "
1090 "v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
1091 "ipv6=[2001:67c:289c::9]:80 "
1092 "171.25.193.9:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
1093 "Faravahar orport=443 "
1094 "v3ident=EFCBE720AB3A82B99F9E953CD5BF50F7EEFC7B97 "
1095 "154.35.175.225:80 CF6D 0AAF B385 BE71 B8E1 11FC 5CFF 4B47 9237 33BC",
1096 "longclaw orport=443 "
1097 "v3ident=23D15D965BC35114467363C165C4F724B64B4F66 "
1098 "199.58.81.140:80 74A9 1064 6BCE EFBC D2E8 74FC 1DC9 9743 0F96 8145",
1099 "bastet orport=443 "
1100 "v3ident=27102BC123E7AF1D4741AE047E160C91ADC76B21 "
1101 "ipv6=[2620:13:4000:6000::1000:118]:443 "
1102 "204.13.164.118:80 24E2 F139 121D 4394 C54B 5BCC 368B 3B41 1857 C413",
1103 NULL
1106 /** List of fallback directory authorities. The list is generated by opt-in of
1107 * relays that meet certain stability criteria.
1109 static const char *default_fallbacks[] = {
1110 #include "fallback_dirs.inc"
1111 NULL
1114 /** Add the default directory authorities directly into the trusted dir list,
1115 * but only add them insofar as they share bits with <b>type</b>.
1116 * Each authority's bits are restricted to the bits shared with <b>type</b>.
1117 * If <b>type</b> is ALL_DIRINFO or NO_DIRINFO (zero), add all authorities. */
1118 STATIC void
1119 add_default_trusted_dir_authorities(dirinfo_type_t type)
1121 int i;
1122 for (i=0; default_authorities[i]; i++) {
1123 if (parse_dir_authority_line(default_authorities[i], type, 0)<0) {
1124 log_err(LD_BUG, "Couldn't parse internal DirAuthority line %s",
1125 default_authorities[i]);
1130 /** Add the default fallback directory servers into the fallback directory
1131 * server list. */
1132 MOCK_IMPL(void,
1133 add_default_fallback_dir_servers,(void))
1135 int i;
1136 for (i=0; default_fallbacks[i]; i++) {
1137 if (parse_dir_fallback_line(default_fallbacks[i], 0)<0) {
1138 log_err(LD_BUG, "Couldn't parse internal FallbackDir line %s",
1139 default_fallbacks[i]);
1144 /** Look at all the config options for using alternate directory
1145 * authorities, and make sure none of them are broken. Also, warn the
1146 * user if we changed any dangerous ones.
1148 static int
1149 validate_dir_servers(or_options_t *options, or_options_t *old_options)
1151 config_line_t *cl;
1153 if (options->DirAuthorities &&
1154 (options->AlternateDirAuthority || options->AlternateBridgeAuthority)) {
1155 log_warn(LD_CONFIG,
1156 "You cannot set both DirAuthority and Alternate*Authority.");
1157 return -1;
1160 /* do we want to complain to the user about being partitionable? */
1161 if ((options->DirAuthorities &&
1162 (!old_options ||
1163 !config_lines_eq(options->DirAuthorities,
1164 old_options->DirAuthorities))) ||
1165 (options->AlternateDirAuthority &&
1166 (!old_options ||
1167 !config_lines_eq(options->AlternateDirAuthority,
1168 old_options->AlternateDirAuthority)))) {
1169 log_warn(LD_CONFIG,
1170 "You have used DirAuthority or AlternateDirAuthority to "
1171 "specify alternate directory authorities in "
1172 "your configuration. This is potentially dangerous: it can "
1173 "make you look different from all other Tor users, and hurt "
1174 "your anonymity. Even if you've specified the same "
1175 "authorities as Tor uses by default, the defaults could "
1176 "change in the future. Be sure you know what you're doing.");
1179 /* Now go through the four ways you can configure an alternate
1180 * set of directory authorities, and make sure none are broken. */
1181 for (cl = options->DirAuthorities; cl; cl = cl->next)
1182 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1183 return -1;
1184 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1185 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1186 return -1;
1187 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1188 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1189 return -1;
1190 for (cl = options->FallbackDir; cl; cl = cl->next)
1191 if (parse_dir_fallback_line(cl->value, 1)<0)
1192 return -1;
1193 return 0;
1196 /** Look at all the config options and assign new dir authorities
1197 * as appropriate.
1200 consider_adding_dir_servers(const or_options_t *options,
1201 const or_options_t *old_options)
1203 config_line_t *cl;
1204 int need_to_update =
1205 !smartlist_len(router_get_trusted_dir_servers()) ||
1206 !smartlist_len(router_get_fallback_dir_servers()) || !old_options ||
1207 !config_lines_eq(options->DirAuthorities, old_options->DirAuthorities) ||
1208 !config_lines_eq(options->FallbackDir, old_options->FallbackDir) ||
1209 (options->UseDefaultFallbackDirs != old_options->UseDefaultFallbackDirs) ||
1210 !config_lines_eq(options->AlternateBridgeAuthority,
1211 old_options->AlternateBridgeAuthority) ||
1212 !config_lines_eq(options->AlternateDirAuthority,
1213 old_options->AlternateDirAuthority);
1215 if (!need_to_update)
1216 return 0; /* all done */
1218 /* "You cannot set both DirAuthority and Alternate*Authority."
1219 * Checking that this restriction holds allows us to simplify
1220 * the unit tests. */
1221 tor_assert(!(options->DirAuthorities &&
1222 (options->AlternateDirAuthority
1223 || options->AlternateBridgeAuthority)));
1225 /* Start from a clean slate. */
1226 clear_dir_servers();
1228 if (!options->DirAuthorities) {
1229 /* then we may want some of the defaults */
1230 dirinfo_type_t type = NO_DIRINFO;
1231 if (!options->AlternateBridgeAuthority) {
1232 type |= BRIDGE_DIRINFO;
1234 if (!options->AlternateDirAuthority) {
1235 type |= V3_DIRINFO | EXTRAINFO_DIRINFO | MICRODESC_DIRINFO;
1236 /* Only add the default fallback directories when the DirAuthorities,
1237 * AlternateDirAuthority, and FallbackDir directory config options
1238 * are set to their defaults, and when UseDefaultFallbackDirs is 1. */
1239 if (!options->FallbackDir && options->UseDefaultFallbackDirs) {
1240 add_default_fallback_dir_servers();
1243 /* if type == NO_DIRINFO, we don't want to add any of the
1244 * default authorities, because we've replaced them all */
1245 if (type != NO_DIRINFO)
1246 add_default_trusted_dir_authorities(type);
1249 for (cl = options->DirAuthorities; cl; cl = cl->next)
1250 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1251 return -1;
1252 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1253 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1254 return -1;
1255 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1256 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1257 return -1;
1258 for (cl = options->FallbackDir; cl; cl = cl->next)
1259 if (parse_dir_fallback_line(cl->value, 0)<0)
1260 return -1;
1261 return 0;
1265 * Make sure that <b>directory</b> exists, with appropriate ownership and
1266 * permissions (as modified by <b>group_readable</b>). If <b>create</b>,
1267 * create the directory if it is missing. Return 0 on success.
1268 * On failure, return -1 and set *<b>msg_out</b>.
1270 static int
1271 check_and_create_data_directory(int create,
1272 const char *directory,
1273 int group_readable,
1274 const char *owner,
1275 char **msg_out)
1277 cpd_check_t cpd_opts = create ? CPD_CREATE : CPD_CHECK;
1278 if (group_readable)
1279 cpd_opts |= CPD_GROUP_READ;
1280 if (check_private_dir(directory,
1281 cpd_opts,
1282 owner) < 0) {
1283 tor_asprintf(msg_out,
1284 "Couldn't %s private data directory \"%s\"",
1285 create ? "create" : "access",
1286 directory);
1287 return -1;
1290 #ifndef _WIN32
1291 if (group_readable) {
1292 /* Only new dirs created get new opts, also enforce group read. */
1293 if (chmod(directory, 0750)) {
1294 log_warn(LD_FS,"Unable to make %s group-readable: %s",
1295 directory, strerror(errno));
1298 #endif /* !defined(_WIN32) */
1300 return 0;
1304 * Ensure that our keys directory exists, with appropriate permissions.
1305 * Return 0 on success, -1 on failure.
1308 create_keys_directory(const or_options_t *options)
1310 /* Make sure DataDirectory exists, and is private. */
1311 cpd_check_t cpd_opts = CPD_CREATE;
1312 if (options->DataDirectoryGroupReadable)
1313 cpd_opts |= CPD_GROUP_READ;
1314 if (check_private_dir(options->DataDirectory, cpd_opts, options->User)) {
1315 log_err(LD_OR, "Can't create/check datadirectory %s",
1316 options->DataDirectory);
1317 return -1;
1320 /* Check the key directory. */
1321 if (check_private_dir(options->KeyDirectory, CPD_CREATE, options->User)) {
1322 return -1;
1324 return 0;
1327 /* Helps determine flags to pass to switch_id. */
1328 static int have_low_ports = -1;
1330 /** Fetch the active option list, and take actions based on it. All of the
1331 * things we do should survive being done repeatedly. If present,
1332 * <b>old_options</b> contains the previous value of the options.
1334 * Return 0 if all goes well, return -1 if things went badly.
1336 static int
1337 options_act_reversible(const or_options_t *old_options, char **msg)
1339 smartlist_t *new_listeners = smartlist_new();
1340 smartlist_t *replaced_listeners = smartlist_new();
1341 static int libevent_initialized = 0;
1342 or_options_t *options = get_options_mutable();
1343 int running_tor = options->command == CMD_RUN_TOR;
1344 int set_conn_limit = 0;
1345 int r = -1;
1346 int logs_marked = 0, logs_initialized = 0;
1347 int old_min_log_level = get_min_log_level();
1349 /* Daemonize _first_, since we only want to open most of this stuff in
1350 * the subprocess. Libevent bases can't be reliably inherited across
1351 * processes. */
1352 if (running_tor && options->RunAsDaemon) {
1353 /* No need to roll back, since you can't change the value. */
1354 start_daemon();
1357 #ifdef HAVE_SYSTEMD
1358 /* Our PID may have changed, inform supervisor */
1359 sd_notifyf(0, "MAINPID=%ld\n", (long int)getpid());
1360 #endif
1362 #ifndef HAVE_SYS_UN_H
1363 if (options->ControlSocket || options->ControlSocketsGroupWritable) {
1364 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported "
1365 "on this OS/with this build.");
1366 goto rollback;
1368 #else /* !(!defined(HAVE_SYS_UN_H)) */
1369 if (options->ControlSocketsGroupWritable && !options->ControlSocket) {
1370 *msg = tor_strdup("Setting ControlSocketGroupWritable without setting"
1371 "a ControlSocket makes no sense.");
1372 goto rollback;
1374 #endif /* !defined(HAVE_SYS_UN_H) */
1376 if (running_tor) {
1377 int n_ports=0;
1378 /* We need to set the connection limit before we can open the listeners. */
1379 if (! sandbox_is_active()) {
1380 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1381 &options->ConnLimit_) < 0) {
1382 *msg = tor_strdup("Problem with ConnLimit value. "
1383 "See logs for details.");
1384 goto rollback;
1386 set_conn_limit = 1;
1387 } else {
1388 tor_assert(old_options);
1389 options->ConnLimit_ = old_options->ConnLimit_;
1392 /* Set up libevent. (We need to do this before we can register the
1393 * listeners as listeners.) */
1394 if (running_tor && !libevent_initialized) {
1395 init_libevent(options);
1396 libevent_initialized = 1;
1398 /* This has to come up after libevent is initialized. */
1399 control_initialize_event_queue();
1402 * Initialize the scheduler - this has to come after
1403 * options_init_from_torrc() sets up libevent - why yes, that seems
1404 * completely sensible to hide the libevent setup in the option parsing
1405 * code! It also needs to happen before init_keys(), so it needs to
1406 * happen here too. How yucky. */
1407 scheduler_init();
1410 /* Adjust the port configuration so we can launch listeners. */
1411 if (parse_ports(options, 0, msg, &n_ports, NULL)) {
1412 if (!*msg)
1413 *msg = tor_strdup("Unexpected problem parsing port config");
1414 goto rollback;
1417 /* Set the hibernation state appropriately.*/
1418 consider_hibernation(time(NULL));
1420 /* Launch the listeners. (We do this before we setuid, so we can bind to
1421 * ports under 1024.) We don't want to rebind if we're hibernating. If
1422 * networking is disabled, this will close all but the control listeners,
1423 * but disable those. */
1424 if (!we_are_hibernating()) {
1425 if (retry_all_listeners(replaced_listeners, new_listeners,
1426 options->DisableNetwork) < 0) {
1427 *msg = tor_strdup("Failed to bind one of the listener ports.");
1428 goto rollback;
1431 if (options->DisableNetwork) {
1432 /* Aggressively close non-controller stuff, NOW */
1433 log_notice(LD_NET, "DisableNetwork is set. Tor will not make or accept "
1434 "non-control network connections. Shutting down all existing "
1435 "connections.");
1436 connection_mark_all_noncontrol_connections();
1437 /* We can't complete circuits until the network is re-enabled. */
1438 note_that_we_maybe_cant_complete_circuits();
1442 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1443 /* Open /dev/pf before dropping privileges. */
1444 if (options->TransPort_set &&
1445 options->TransProxyType_parsed == TPT_DEFAULT) {
1446 if (get_pf_socket() < 0) {
1447 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1448 goto rollback;
1451 #endif /* defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H) */
1453 /* Attempt to lock all current and future memory with mlockall() only once */
1454 if (options->DisableAllSwap) {
1455 if (tor_mlockall() == -1) {
1456 *msg = tor_strdup("DisableAllSwap failure. Do you have proper "
1457 "permissions?");
1458 goto done;
1462 /* Setuid/setgid as appropriate */
1463 if (options->User) {
1464 tor_assert(have_low_ports != -1);
1465 unsigned switch_id_flags = 0;
1466 if (options->KeepBindCapabilities == 1) {
1467 switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
1468 switch_id_flags |= SWITCH_ID_WARN_IF_NO_CAPS;
1470 if (options->KeepBindCapabilities == -1 && have_low_ports) {
1471 switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
1473 if (switch_id(options->User, switch_id_flags) != 0) {
1474 /* No need to roll back, since you can't change the value. */
1475 *msg = tor_strdup("Problem with User value. See logs for details.");
1476 goto done;
1480 /* Ensure data directory is private; create if possible. */
1481 /* It's okay to do this in "options_act_reversible()" even though it isn't
1482 * actually reversible, since you can't change the DataDirectory while
1483 * Tor is running. */
1484 if (check_and_create_data_directory(running_tor /* create */,
1485 options->DataDirectory,
1486 options->DataDirectoryGroupReadable,
1487 options->User,
1488 msg) < 0) {
1489 goto done;
1491 if (check_and_create_data_directory(running_tor /* create */,
1492 options->KeyDirectory,
1493 options->KeyDirectoryGroupReadable,
1494 options->User,
1495 msg) < 0) {
1496 goto done;
1498 if (check_and_create_data_directory(running_tor /* create */,
1499 options->CacheDirectory,
1500 options->CacheDirectoryGroupReadable,
1501 options->User,
1502 msg) < 0) {
1503 goto done;
1506 /* Bail out at this point if we're not going to be a client or server:
1507 * we don't run Tor itself. */
1508 if (!running_tor)
1509 goto commit;
1511 mark_logs_temp(); /* Close current logs once new logs are open. */
1512 logs_marked = 1;
1513 /* Configure the tor_log(s) */
1514 if (options_init_logs(old_options, options, 0)<0) {
1515 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1516 goto rollback;
1518 logs_initialized = 1;
1520 commit:
1521 r = 0;
1522 if (logs_marked) {
1523 log_severity_list_t *severity =
1524 tor_malloc_zero(sizeof(log_severity_list_t));
1525 close_temp_logs();
1526 add_callback_log(severity, control_event_logmsg);
1527 control_adjust_event_log_severity();
1528 tor_free(severity);
1529 tor_log_update_sigsafe_err_fds();
1531 if (logs_initialized) {
1532 flush_log_messages_from_startup();
1536 const char *badness = NULL;
1537 int bad_safelog = 0, bad_severity = 0, new_badness = 0;
1538 if (options->SafeLogging_ != SAFELOG_SCRUB_ALL) {
1539 bad_safelog = 1;
1540 if (!old_options || old_options->SafeLogging_ != options->SafeLogging_)
1541 new_badness = 1;
1543 if (get_min_log_level() >= LOG_INFO) {
1544 bad_severity = 1;
1545 if (get_min_log_level() != old_min_log_level)
1546 new_badness = 1;
1548 if (bad_safelog && bad_severity)
1549 badness = "you disabled SafeLogging, and "
1550 "you're logging more than \"notice\"";
1551 else if (bad_safelog)
1552 badness = "you disabled SafeLogging";
1553 else
1554 badness = "you're logging more than \"notice\"";
1555 if (new_badness)
1556 log_warn(LD_GENERAL, "Your log may contain sensitive information - %s. "
1557 "Don't log unless it serves an important reason. "
1558 "Overwrite the log afterwards.", badness);
1561 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1563 int marked = conn->marked_for_close;
1564 log_notice(LD_NET, "Closing old %s on %s:%d",
1565 conn_type_to_string(conn->type), conn->address, conn->port);
1566 connection_close_immediate(conn);
1567 if (!marked) {
1568 connection_mark_for_close(conn);
1572 if (set_conn_limit) {
1574 * If we adjusted the conn limit, recompute the OOS threshold too
1576 * How many possible sockets to keep in reserve? If we have lots of
1577 * possible sockets, keep this below a limit and set ConnLimit_high_thresh
1578 * very close to ConnLimit_, but if ConnLimit_ is low, shrink it in
1579 * proportion.
1581 * Somewhat arbitrarily, set socks_in_reserve to 5% of ConnLimit_, but
1582 * cap it at 64.
1584 int socks_in_reserve = options->ConnLimit_ / 20;
1585 if (socks_in_reserve > 64) socks_in_reserve = 64;
1587 options->ConnLimit_high_thresh = options->ConnLimit_ - socks_in_reserve;
1588 options->ConnLimit_low_thresh = (options->ConnLimit_ / 4) * 3;
1589 log_info(LD_GENERAL,
1590 "Recomputed OOS thresholds: ConnLimit %d, ConnLimit_ %d, "
1591 "ConnLimit_high_thresh %d, ConnLimit_low_thresh %d",
1592 options->ConnLimit, options->ConnLimit_,
1593 options->ConnLimit_high_thresh,
1594 options->ConnLimit_low_thresh);
1596 /* Give the OOS handler a chance with the new thresholds */
1597 connection_check_oos(get_n_open_sockets(), 0);
1600 goto done;
1602 rollback:
1603 r = -1;
1604 tor_assert(*msg);
1606 if (logs_marked) {
1607 rollback_log_changes();
1608 control_adjust_event_log_severity();
1611 if (set_conn_limit && old_options)
1612 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1613 &options->ConnLimit_);
1615 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1617 log_notice(LD_NET, "Closing partially-constructed %s on %s:%d",
1618 conn_type_to_string(conn->type), conn->address, conn->port);
1619 connection_close_immediate(conn);
1620 connection_mark_for_close(conn);
1623 done:
1624 smartlist_free(new_listeners);
1625 smartlist_free(replaced_listeners);
1626 return r;
1629 /** If we need to have a GEOIP ip-to-country map to run with our configured
1630 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1632 options_need_geoip_info(const or_options_t *options, const char **reason_out)
1634 int bridge_usage =
1635 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1636 int routerset_usage =
1637 routerset_needs_geoip(options->EntryNodes) ||
1638 routerset_needs_geoip(options->ExitNodes) ||
1639 routerset_needs_geoip(options->ExcludeExitNodes) ||
1640 routerset_needs_geoip(options->ExcludeNodes) ||
1641 routerset_needs_geoip(options->Tor2webRendezvousPoints);
1643 if (routerset_usage && reason_out) {
1644 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1645 "countries, and we need GEOIP information to figure out which ones they "
1646 "are.";
1647 } else if (bridge_usage && reason_out) {
1648 *reason_out = "We've been configured to see which countries can access "
1649 "us as a bridge, and we need GEOIP information to tell which countries "
1650 "clients are in.";
1652 return bridge_usage || routerset_usage;
1655 /** Return the bandwidthrate that we are going to report to the authorities
1656 * based on the config options. */
1657 uint32_t
1658 get_effective_bwrate(const or_options_t *options)
1660 uint64_t bw = options->BandwidthRate;
1661 if (bw > options->MaxAdvertisedBandwidth)
1662 bw = options->MaxAdvertisedBandwidth;
1663 if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1664 bw = options->RelayBandwidthRate;
1665 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1666 return (uint32_t)bw;
1669 /** Return the bandwidthburst that we are going to report to the authorities
1670 * based on the config options. */
1671 uint32_t
1672 get_effective_bwburst(const or_options_t *options)
1674 uint64_t bw = options->BandwidthBurst;
1675 if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1676 bw = options->RelayBandwidthBurst;
1677 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1678 return (uint32_t)bw;
1682 * Return true if changing the configuration from <b>old</b> to <b>new</b>
1683 * affects the guard susbsystem.
1685 static int
1686 options_transition_affects_guards(const or_options_t *old,
1687 const or_options_t *new)
1689 /* NOTE: Make sure this function stays in sync with
1690 * node_passes_guard_filter */
1692 tor_assert(old);
1693 tor_assert(new);
1695 return
1696 (old->UseEntryGuards != new->UseEntryGuards ||
1697 old->UseBridges != new->UseBridges ||
1698 old->ClientUseIPv4 != new->ClientUseIPv4 ||
1699 old->ClientUseIPv6 != new->ClientUseIPv6 ||
1700 old->FascistFirewall != new->FascistFirewall ||
1701 !routerset_equal(old->ExcludeNodes, new->ExcludeNodes) ||
1702 !routerset_equal(old->EntryNodes, new->EntryNodes) ||
1703 !smartlist_strings_eq(old->FirewallPorts, new->FirewallPorts) ||
1704 !config_lines_eq(old->Bridges, new->Bridges) ||
1705 !config_lines_eq(old->ReachableORAddresses, new->ReachableORAddresses) ||
1706 !config_lines_eq(old->ReachableDirAddresses, new->ReachableDirAddresses));
1709 /** Fetch the active option list, and take actions based on it. All of the
1710 * things we do should survive being done repeatedly. If present,
1711 * <b>old_options</b> contains the previous value of the options.
1713 * Return 0 if all goes well, return -1 if it's time to die.
1715 * Note: We haven't moved all the "act on new configuration" logic
1716 * here yet. Some is still in do_hup() and other places.
1718 STATIC int
1719 options_act(const or_options_t *old_options)
1721 config_line_t *cl;
1722 or_options_t *options = get_options_mutable();
1723 int running_tor = options->command == CMD_RUN_TOR;
1724 char *msg=NULL;
1725 const int transition_affects_workers =
1726 old_options && options_transition_affects_workers(old_options, options);
1727 int old_ewma_enabled;
1728 const int transition_affects_guards =
1729 old_options && options_transition_affects_guards(old_options, options);
1731 if (options->NoExec || options->Sandbox) {
1732 tor_disable_spawning_background_processes();
1735 /* disable ptrace and later, other basic debugging techniques */
1737 /* Remember if we already disabled debugger attachment */
1738 static int disabled_debugger_attach = 0;
1739 /* Remember if we already warned about being configured not to disable
1740 * debugger attachment */
1741 static int warned_debugger_attach = 0;
1742 /* Don't disable debugger attachment when we're running the unit tests. */
1743 if (options->DisableDebuggerAttachment && !disabled_debugger_attach &&
1744 running_tor) {
1745 int ok = tor_disable_debugger_attach();
1746 /* LCOV_EXCL_START the warned_debugger_attach is 0 can't reach inside. */
1747 if (warned_debugger_attach && ok == 1) {
1748 log_notice(LD_CONFIG, "Disabled attaching debuggers for unprivileged "
1749 "users.");
1751 /* LCOV_EXCL_STOP */
1752 disabled_debugger_attach = (ok == 1);
1753 } else if (!options->DisableDebuggerAttachment &&
1754 !warned_debugger_attach) {
1755 log_notice(LD_CONFIG, "Not disabling debugger attaching for "
1756 "unprivileged users.");
1757 warned_debugger_attach = 1;
1761 /* Write control ports to disk as appropriate */
1762 control_ports_write_to_file();
1764 if (running_tor && !have_lockfile()) {
1765 if (try_locking(options, 1) < 0)
1766 return -1;
1769 if (options->ProtocolWarnings)
1770 protocol_warning_severity_level = LOG_WARN;
1771 else
1772 protocol_warning_severity_level = LOG_INFO;
1774 if (consider_adding_dir_servers(options, old_options) < 0) {
1775 // XXXX This should get validated earlier, and committed here, to
1776 // XXXX lower opportunities for reaching an error case.
1777 return -1;
1780 if (rend_non_anonymous_mode_enabled(options)) {
1781 log_warn(LD_GENERAL, "This copy of Tor was compiled or configured to run "
1782 "in a non-anonymous mode. It will provide NO ANONYMITY.");
1785 #ifdef ENABLE_TOR2WEB_MODE
1786 /* LCOV_EXCL_START */
1787 // XXXX This should move into options_validate()
1788 if (!options->Tor2webMode) {
1789 log_err(LD_CONFIG, "This copy of Tor was compiled to run in "
1790 "'tor2web mode'. It can only be run with the Tor2webMode torrc "
1791 "option enabled.");
1792 return -1;
1794 /* LCOV_EXCL_STOP */
1795 #else /* !(defined(ENABLE_TOR2WEB_MODE)) */
1796 // XXXX This should move into options_validate()
1797 if (options->Tor2webMode) {
1798 log_err(LD_CONFIG, "This copy of Tor was not compiled to run in "
1799 "'tor2web mode'. It cannot be run with the Tor2webMode torrc "
1800 "option enabled. To enable Tor2webMode recompile with the "
1801 "--enable-tor2web-mode option.");
1802 return -1;
1804 #endif /* defined(ENABLE_TOR2WEB_MODE) */
1806 /* If we are a bridge with a pluggable transport proxy but no
1807 Extended ORPort, inform the user that they are missing out. */
1808 if (server_mode(options) && options->ServerTransportPlugin &&
1809 !options->ExtORPort_lines) {
1810 log_notice(LD_CONFIG, "We use pluggable transports but the Extended "
1811 "ORPort is disabled. Tor and your pluggable transports proxy "
1812 "communicate with each other via the Extended ORPort so it "
1813 "is suggested you enable it: it will also allow your Bridge "
1814 "to collect statistics about its clients that use pluggable "
1815 "transports. Please enable it using the ExtORPort torrc option "
1816 "(e.g. set 'ExtORPort auto').");
1819 if (options->Bridges) {
1820 mark_bridge_list();
1821 for (cl = options->Bridges; cl; cl = cl->next) {
1822 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
1823 if (!bridge_line) {
1824 // LCOV_EXCL_START
1825 log_warn(LD_BUG,
1826 "Previously validated Bridge line could not be added!");
1827 return -1;
1828 // LCOV_EXCL_STOP
1830 bridge_add_from_config(bridge_line);
1832 sweep_bridge_list();
1835 if (running_tor && hs_config_service_all(options, 0)<0) {
1836 // LCOV_EXCL_START
1837 log_warn(LD_BUG,
1838 "Previously validated hidden services line could not be added!");
1839 return -1;
1840 // LCOV_EXCL_STOP
1843 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1844 // LCOV_EXCL_START
1845 log_warn(LD_BUG, "Previously validated client authorization for "
1846 "hidden services could not be added!");
1847 return -1;
1848 // LCOV_EXCL_STOP
1851 if (running_tor && !old_options && options->OwningControllerFD != -1) {
1852 #ifdef _WIN32
1853 log_warn(LD_CONFIG, "OwningControllerFD is not supported on Windows. "
1854 "If you need it, tell the Tor developers.");
1855 return -1;
1856 #else
1857 const unsigned ctrl_flags =
1858 CC_LOCAL_FD_IS_OWNER |
1859 CC_LOCAL_FD_IS_AUTHENTICATED;
1860 tor_socket_t ctrl_sock = (tor_socket_t)options->OwningControllerFD;
1861 if (control_connection_add_local_fd(ctrl_sock, ctrl_flags) < 0) {
1862 log_warn(LD_CONFIG, "Could not add local controller connection with "
1863 "given FD.");
1864 return -1;
1866 #endif /* defined(_WIN32) */
1869 /* Load state */
1870 if (! or_state_loaded() && running_tor) {
1871 if (or_state_load())
1872 return -1;
1873 rep_hist_load_mtbf_data(time(NULL));
1876 /* If we have an ExtORPort, initialize its auth cookie. */
1877 if (running_tor &&
1878 init_ext_or_cookie_authentication(!!options->ExtORPort_lines) < 0) {
1879 log_warn(LD_CONFIG,"Error creating Extended ORPort cookie file.");
1880 return -1;
1883 mark_transport_list();
1884 pt_prepare_proxy_list_for_config_read();
1885 if (!options->DisableNetwork) {
1886 if (options->ClientTransportPlugin) {
1887 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
1888 if (parse_transport_line(options, cl->value, 0, 0) < 0) {
1889 // LCOV_EXCL_START
1890 log_warn(LD_BUG,
1891 "Previously validated ClientTransportPlugin line "
1892 "could not be added!");
1893 return -1;
1894 // LCOV_EXCL_STOP
1899 if (options->ServerTransportPlugin && server_mode(options)) {
1900 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
1901 if (parse_transport_line(options, cl->value, 0, 1) < 0) {
1902 // LCOV_EXCL_START
1903 log_warn(LD_BUG,
1904 "Previously validated ServerTransportPlugin line "
1905 "could not be added!");
1906 return -1;
1907 // LCOV_EXCL_STOP
1912 sweep_transport_list();
1913 sweep_proxy_list();
1915 /* Start the PT proxy configuration. By doing this configuration
1916 here, we also figure out which proxies need to be restarted and
1917 which not. */
1918 if (pt_proxies_configuration_pending() && !net_is_disabled())
1919 pt_configure_remaining_proxies();
1921 /* Bail out at this point if we're not going to be a client or server:
1922 * we want to not fork, and to log stuff to stderr. */
1923 if (!running_tor)
1924 return 0;
1926 /* Finish backgrounding the process */
1927 if (options->RunAsDaemon) {
1928 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1929 finish_daemon(options->DataDirectory);
1932 /* We want to reinit keys as needed before we do much of anything else:
1933 keys are important, and other things can depend on them. */
1934 if (transition_affects_workers ||
1935 (options->V3AuthoritativeDir && (!old_options ||
1936 !old_options->V3AuthoritativeDir))) {
1937 if (init_keys() < 0) {
1938 log_warn(LD_BUG,"Error initializing keys; exiting");
1939 return -1;
1943 /* Write our PID to the PID file. If we do not have write permissions we
1944 * will log a warning and exit. */
1945 if (options->PidFile && !sandbox_is_active()) {
1946 if (write_pidfile(options->PidFile) < 0) {
1947 log_err(LD_CONFIG, "Unable to write PIDFile %s",
1948 escaped(options->PidFile));
1949 return -1;
1953 /* Register addressmap directives */
1954 config_register_addressmaps(options);
1955 parse_virtual_addr_network(options->VirtualAddrNetworkIPv4, AF_INET,0,NULL);
1956 parse_virtual_addr_network(options->VirtualAddrNetworkIPv6, AF_INET6,0,NULL);
1958 /* Update address policies. */
1959 if (policies_parse_from_options(options) < 0) {
1960 /* This should be impossible, but let's be sure. */
1961 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1962 return -1;
1965 if (server_mode(options)) {
1966 static int cdm_initialized = 0;
1967 if (cdm_initialized == 0) {
1968 cdm_initialized = 1;
1969 consdiffmgr_configure(NULL);
1970 consdiffmgr_validate();
1974 if (init_control_cookie_authentication(options->CookieAuthentication) < 0) {
1975 log_warn(LD_CONFIG,"Error creating control cookie authentication file.");
1976 return -1;
1979 monitor_owning_controller_process(options->OwningControllerProcess);
1981 /* reload keys as needed for rendezvous services. */
1982 if (hs_service_load_all_keys() < 0) {
1983 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1984 return -1;
1987 /* Inform the scheduler subsystem that a configuration changed happened. It
1988 * might be a change of scheduler or parameter. */
1989 scheduler_conf_changed();
1991 /* Set up accounting */
1992 if (accounting_parse_options(options, 0)<0) {
1993 // LCOV_EXCL_START
1994 log_warn(LD_BUG,"Error in previously validated accounting options");
1995 return -1;
1996 // LCOV_EXCL_STOP
1998 if (accounting_is_enabled(options))
1999 configure_accounting(time(NULL));
2001 old_ewma_enabled = cell_ewma_enabled();
2002 /* Change the cell EWMA settings */
2003 cell_ewma_set_scale_factor(options, networkstatus_get_latest_consensus());
2004 /* If we just enabled ewma, set the cmux policy on all active channels */
2005 if (cell_ewma_enabled() && !old_ewma_enabled) {
2006 channel_set_cmux_policy_everywhere(&ewma_policy);
2007 } else if (!cell_ewma_enabled() && old_ewma_enabled) {
2008 /* Turn it off everywhere */
2009 channel_set_cmux_policy_everywhere(NULL);
2012 /* Update the BridgePassword's hashed version as needed. We store this as a
2013 * digest so that we can do side-channel-proof comparisons on it.
2015 if (options->BridgePassword) {
2016 char *http_authenticator;
2017 http_authenticator = alloc_http_authenticator(options->BridgePassword);
2018 if (!http_authenticator) {
2019 // XXXX This should get validated in options_validate().
2020 log_warn(LD_BUG, "Unable to allocate HTTP authenticator. Not setting "
2021 "BridgePassword.");
2022 return -1;
2024 options->BridgePassword_AuthDigest_ = tor_malloc(DIGEST256_LEN);
2025 crypto_digest256(options->BridgePassword_AuthDigest_,
2026 http_authenticator, strlen(http_authenticator),
2027 DIGEST_SHA256);
2028 tor_free(http_authenticator);
2031 if (parse_outbound_addresses(options, 0, &msg) < 0) {
2032 // LCOV_EXCL_START
2033 log_warn(LD_BUG, "Failed parsing previously validated outbound "
2034 "bind addresses: %s", msg);
2035 tor_free(msg);
2036 return -1;
2037 // LCOV_EXCL_STOP
2040 config_maybe_load_geoip_files_(options, old_options);
2042 if (geoip_is_loaded(AF_INET) && options->GeoIPExcludeUnknown) {
2043 /* ExcludeUnknown is true or "auto" */
2044 const int is_auto = options->GeoIPExcludeUnknown == -1;
2045 int changed;
2047 changed = routerset_add_unknown_ccs(&options->ExcludeNodes, is_auto);
2048 changed += routerset_add_unknown_ccs(&options->ExcludeExitNodes, is_auto);
2050 if (changed)
2051 routerset_add_unknown_ccs(&options->ExcludeExitNodesUnion_, is_auto);
2054 /* Check for transitions that need action. */
2055 if (old_options) {
2056 int revise_trackexithosts = 0;
2057 int revise_automap_entries = 0;
2058 int abandon_circuits = 0;
2059 if ((options->UseEntryGuards && !old_options->UseEntryGuards) ||
2060 options->UseBridges != old_options->UseBridges ||
2061 (options->UseBridges &&
2062 !config_lines_eq(options->Bridges, old_options->Bridges)) ||
2063 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes) ||
2064 !routerset_equal(old_options->ExcludeExitNodes,
2065 options->ExcludeExitNodes) ||
2066 !routerset_equal(old_options->EntryNodes, options->EntryNodes) ||
2067 !routerset_equal(old_options->ExitNodes, options->ExitNodes) ||
2068 !routerset_equal(old_options->Tor2webRendezvousPoints,
2069 options->Tor2webRendezvousPoints) ||
2070 options->StrictNodes != old_options->StrictNodes) {
2071 log_info(LD_CIRC,
2072 "Changed to using entry guards or bridges, or changed "
2073 "preferred or excluded node lists. "
2074 "Abandoning previous circuits.");
2075 abandon_circuits = 1;
2078 if (transition_affects_guards) {
2079 if (guards_update_all()) {
2080 abandon_circuits = 1;
2084 if (abandon_circuits) {
2085 circuit_mark_all_unused_circs();
2086 circuit_mark_all_dirty_circs_as_unusable();
2087 revise_trackexithosts = 1;
2090 if (!smartlist_strings_eq(old_options->TrackHostExits,
2091 options->TrackHostExits))
2092 revise_trackexithosts = 1;
2094 if (revise_trackexithosts)
2095 addressmap_clear_excluded_trackexithosts(options);
2097 if (!options->AutomapHostsOnResolve &&
2098 old_options->AutomapHostsOnResolve) {
2099 revise_automap_entries = 1;
2100 } else {
2101 if (!smartlist_strings_eq(old_options->AutomapHostsSuffixes,
2102 options->AutomapHostsSuffixes))
2103 revise_automap_entries = 1;
2104 else if (!opt_streq(old_options->VirtualAddrNetworkIPv4,
2105 options->VirtualAddrNetworkIPv4) ||
2106 !opt_streq(old_options->VirtualAddrNetworkIPv6,
2107 options->VirtualAddrNetworkIPv6))
2108 revise_automap_entries = 1;
2111 if (revise_automap_entries)
2112 addressmap_clear_invalid_automaps(options);
2114 /* How long should we delay counting bridge stats after becoming a bridge?
2115 * We use this so we don't count clients who used our bridge thinking it is
2116 * a relay. If you change this, don't forget to change the log message
2117 * below. It's 4 hours (the time it takes to stop being used by clients)
2118 * plus some extra time for clock skew. */
2119 #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
2121 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
2122 int was_relay = 0;
2123 if (options->BridgeRelay) {
2124 time_t int_start = time(NULL);
2125 if (config_lines_eq(old_options->ORPort_lines,options->ORPort_lines)) {
2126 int_start += RELAY_BRIDGE_STATS_DELAY;
2127 was_relay = 1;
2129 geoip_bridge_stats_init(int_start);
2130 log_info(LD_CONFIG, "We are acting as a bridge now. Starting new "
2131 "GeoIP stats interval%s.", was_relay ? " in 6 "
2132 "hours from now" : "");
2133 } else {
2134 geoip_bridge_stats_term();
2135 log_info(LD_GENERAL, "We are no longer acting as a bridge. "
2136 "Forgetting GeoIP stats.");
2140 if (transition_affects_workers) {
2141 log_info(LD_GENERAL,
2142 "Worker-related options changed. Rotating workers.");
2144 if (server_mode(options) && !server_mode(old_options)) {
2145 cpu_init();
2146 ip_address_changed(0);
2147 if (have_completed_a_circuit() || !any_predicted_circuits(time(NULL)))
2148 inform_testing_reachability();
2150 cpuworkers_rotate_keyinfo();
2151 if (dns_reset())
2152 return -1;
2153 } else {
2154 if (dns_reset())
2155 return -1;
2158 if (options->PerConnBWRate != old_options->PerConnBWRate ||
2159 options->PerConnBWBurst != old_options->PerConnBWBurst)
2160 connection_or_update_token_buckets(get_connection_array(), options);
2162 if (options->MainloopStats != old_options->MainloopStats) {
2163 reset_main_loop_counters();
2167 /* Only collect directory-request statistics on relays and bridges. */
2168 options->DirReqStatistics = options->DirReqStatistics_option &&
2169 server_mode(options);
2170 options->HiddenServiceStatistics =
2171 options->HiddenServiceStatistics_option && server_mode(options);
2173 if (options->CellStatistics || options->DirReqStatistics ||
2174 options->EntryStatistics || options->ExitPortStatistics ||
2175 options->ConnDirectionStatistics ||
2176 options->HiddenServiceStatistics ||
2177 options->BridgeAuthoritativeDir) {
2178 time_t now = time(NULL);
2179 int print_notice = 0;
2181 /* Only collect other relay-only statistics on relays. */
2182 if (!public_server_mode(options)) {
2183 options->CellStatistics = 0;
2184 options->EntryStatistics = 0;
2185 options->ConnDirectionStatistics = 0;
2186 options->ExitPortStatistics = 0;
2189 if ((!old_options || !old_options->CellStatistics) &&
2190 options->CellStatistics) {
2191 rep_hist_buffer_stats_init(now);
2192 print_notice = 1;
2194 if ((!old_options || !old_options->DirReqStatistics) &&
2195 options->DirReqStatistics) {
2196 if (geoip_is_loaded(AF_INET)) {
2197 geoip_dirreq_stats_init(now);
2198 print_notice = 1;
2199 } else {
2200 /* disable statistics collection since we have no geoip file */
2201 options->DirReqStatistics = 0;
2202 if (options->ORPort_set)
2203 log_notice(LD_CONFIG, "Configured to measure directory request "
2204 "statistics, but no GeoIP database found. "
2205 "Please specify a GeoIP database using the "
2206 "GeoIPFile option.");
2209 if ((!old_options || !old_options->EntryStatistics) &&
2210 options->EntryStatistics && !should_record_bridge_info(options)) {
2211 if (geoip_is_loaded(AF_INET) || geoip_is_loaded(AF_INET6)) {
2212 geoip_entry_stats_init(now);
2213 print_notice = 1;
2214 } else {
2215 options->EntryStatistics = 0;
2216 log_notice(LD_CONFIG, "Configured to measure entry node "
2217 "statistics, but no GeoIP database found. "
2218 "Please specify a GeoIP database using the "
2219 "GeoIPFile option.");
2222 if ((!old_options || !old_options->ExitPortStatistics) &&
2223 options->ExitPortStatistics) {
2224 rep_hist_exit_stats_init(now);
2225 print_notice = 1;
2227 if ((!old_options || !old_options->ConnDirectionStatistics) &&
2228 options->ConnDirectionStatistics) {
2229 rep_hist_conn_stats_init(now);
2231 if ((!old_options || !old_options->HiddenServiceStatistics) &&
2232 options->HiddenServiceStatistics) {
2233 log_info(LD_CONFIG, "Configured to measure hidden service statistics.");
2234 rep_hist_hs_stats_init(now);
2236 if ((!old_options || !old_options->BridgeAuthoritativeDir) &&
2237 options->BridgeAuthoritativeDir) {
2238 rep_hist_desc_stats_init(now);
2239 print_notice = 1;
2241 if (print_notice)
2242 log_notice(LD_CONFIG, "Configured to measure statistics. Look for "
2243 "the *-stats files that will first be written to the "
2244 "data directory in 24 hours from now.");
2247 /* If we used to have statistics enabled but we just disabled them,
2248 stop gathering them. */
2249 if (old_options && old_options->CellStatistics &&
2250 !options->CellStatistics)
2251 rep_hist_buffer_stats_term();
2252 if (old_options && old_options->DirReqStatistics &&
2253 !options->DirReqStatistics)
2254 geoip_dirreq_stats_term();
2255 if (old_options && old_options->EntryStatistics &&
2256 !options->EntryStatistics)
2257 geoip_entry_stats_term();
2258 if (old_options && old_options->HiddenServiceStatistics &&
2259 !options->HiddenServiceStatistics)
2260 rep_hist_hs_stats_term();
2261 if (old_options && old_options->ExitPortStatistics &&
2262 !options->ExitPortStatistics)
2263 rep_hist_exit_stats_term();
2264 if (old_options && old_options->ConnDirectionStatistics &&
2265 !options->ConnDirectionStatistics)
2266 rep_hist_conn_stats_term();
2267 if (old_options && old_options->BridgeAuthoritativeDir &&
2268 !options->BridgeAuthoritativeDir)
2269 rep_hist_desc_stats_term();
2271 /* Since our options changed, we might need to regenerate and upload our
2272 * server descriptor.
2274 if (!old_options ||
2275 options_transition_affects_descriptor(old_options, options))
2276 mark_my_descriptor_dirty("config change");
2278 /* We may need to reschedule some directory stuff if our status changed. */
2279 if (old_options) {
2280 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
2281 dirvote_recalculate_timing(options, time(NULL));
2282 if (!bool_eq(directory_fetches_dir_info_early(options),
2283 directory_fetches_dir_info_early(old_options)) ||
2284 !bool_eq(directory_fetches_dir_info_later(options),
2285 directory_fetches_dir_info_later(old_options))) {
2286 /* Make sure update_router_have_minimum_dir_info() gets called. */
2287 router_dir_info_changed();
2288 /* We might need to download a new consensus status later or sooner than
2289 * we had expected. */
2290 update_consensus_networkstatus_fetch_time(time(NULL));
2294 /* Load the webpage we're going to serve every time someone asks for '/' on
2295 our DirPort. */
2296 tor_free(global_dirfrontpagecontents);
2297 if (options->DirPortFrontPage) {
2298 global_dirfrontpagecontents =
2299 read_file_to_str(options->DirPortFrontPage, 0, NULL);
2300 if (!global_dirfrontpagecontents) {
2301 log_warn(LD_CONFIG,
2302 "DirPortFrontPage file '%s' not found. Continuing anyway.",
2303 options->DirPortFrontPage);
2307 return 0;
2310 typedef enum {
2311 TAKES_NO_ARGUMENT = 0,
2312 ARGUMENT_NECESSARY = 1,
2313 ARGUMENT_OPTIONAL = 2
2314 } takes_argument_t;
2316 static const struct {
2317 const char *name;
2318 takes_argument_t takes_argument;
2319 } CMDLINE_ONLY_OPTIONS[] = {
2320 { "-f", ARGUMENT_NECESSARY },
2321 { "--allow-missing-torrc", TAKES_NO_ARGUMENT },
2322 { "--defaults-torrc", ARGUMENT_NECESSARY },
2323 { "--hash-password", ARGUMENT_NECESSARY },
2324 { "--dump-config", ARGUMENT_OPTIONAL },
2325 { "--list-fingerprint", TAKES_NO_ARGUMENT },
2326 { "--keygen", TAKES_NO_ARGUMENT },
2327 { "--key-expiration", ARGUMENT_OPTIONAL },
2328 { "--newpass", TAKES_NO_ARGUMENT },
2329 { "--no-passphrase", TAKES_NO_ARGUMENT },
2330 { "--passphrase-fd", ARGUMENT_NECESSARY },
2331 { "--verify-config", TAKES_NO_ARGUMENT },
2332 { "--ignore-missing-torrc", TAKES_NO_ARGUMENT },
2333 { "--quiet", TAKES_NO_ARGUMENT },
2334 { "--hush", TAKES_NO_ARGUMENT },
2335 { "--version", TAKES_NO_ARGUMENT },
2336 { "--library-versions", TAKES_NO_ARGUMENT },
2337 { "-h", TAKES_NO_ARGUMENT },
2338 { "--help", TAKES_NO_ARGUMENT },
2339 { "--list-torrc-options", TAKES_NO_ARGUMENT },
2340 { "--list-deprecated-options",TAKES_NO_ARGUMENT },
2341 { "--nt-service", TAKES_NO_ARGUMENT },
2342 { "-nt-service", TAKES_NO_ARGUMENT },
2343 { NULL, 0 },
2346 /** Helper: Read a list of configuration options from the command line. If
2347 * successful, or if ignore_errors is set, put them in *<b>result</b>, put the
2348 * commandline-only options in *<b>cmdline_result</b>, and return 0;
2349 * otherwise, return -1 and leave *<b>result</b> and <b>cmdline_result</b>
2350 * alone. */
2352 config_parse_commandline(int argc, char **argv, int ignore_errors,
2353 config_line_t **result,
2354 config_line_t **cmdline_result)
2356 config_line_t *param = NULL;
2358 config_line_t *front = NULL;
2359 config_line_t **new = &front;
2361 config_line_t *front_cmdline = NULL;
2362 config_line_t **new_cmdline = &front_cmdline;
2364 char *s, *arg;
2365 int i = 1;
2367 while (i < argc) {
2368 unsigned command = CONFIG_LINE_NORMAL;
2369 takes_argument_t want_arg = ARGUMENT_NECESSARY;
2370 int is_cmdline = 0;
2371 int j;
2373 for (j = 0; CMDLINE_ONLY_OPTIONS[j].name != NULL; ++j) {
2374 if (!strcmp(argv[i], CMDLINE_ONLY_OPTIONS[j].name)) {
2375 is_cmdline = 1;
2376 want_arg = CMDLINE_ONLY_OPTIONS[j].takes_argument;
2377 break;
2381 s = argv[i];
2383 /* Each keyword may be prefixed with one or two dashes. */
2384 if (*s == '-')
2385 s++;
2386 if (*s == '-')
2387 s++;
2388 /* Figure out the command, if any. */
2389 if (*s == '+') {
2390 s++;
2391 command = CONFIG_LINE_APPEND;
2392 } else if (*s == '/') {
2393 s++;
2394 command = CONFIG_LINE_CLEAR;
2395 /* A 'clear' command has no argument. */
2396 want_arg = 0;
2399 const int is_last = (i == argc-1);
2401 if (want_arg == ARGUMENT_NECESSARY && is_last) {
2402 if (ignore_errors) {
2403 arg = tor_strdup("");
2404 } else {
2405 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
2406 argv[i]);
2407 config_free_lines(front);
2408 config_free_lines(front_cmdline);
2409 return -1;
2411 } else if (want_arg == ARGUMENT_OPTIONAL && is_last) {
2412 arg = tor_strdup("");
2413 } else {
2414 arg = (want_arg != TAKES_NO_ARGUMENT) ? tor_strdup(argv[i+1]) :
2415 tor_strdup("");
2418 param = tor_malloc_zero(sizeof(config_line_t));
2419 param->key = is_cmdline ? tor_strdup(argv[i]) :
2420 tor_strdup(config_expand_abbrev(&options_format, s, 1, 1));
2421 param->value = arg;
2422 param->command = command;
2423 param->next = NULL;
2424 log_debug(LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
2425 param->key, param->value);
2427 if (is_cmdline) {
2428 *new_cmdline = param;
2429 new_cmdline = &((*new_cmdline)->next);
2430 } else {
2431 *new = param;
2432 new = &((*new)->next);
2435 i += want_arg ? 2 : 1;
2437 *cmdline_result = front_cmdline;
2438 *result = front;
2439 return 0;
2442 /** Return true iff key is a valid configuration option. */
2444 option_is_recognized(const char *key)
2446 const config_var_t *var = config_find_option(&options_format, key);
2447 return (var != NULL);
2450 /** Return the canonical name of a configuration option, or NULL
2451 * if no such option exists. */
2452 const char *
2453 option_get_canonical_name(const char *key)
2455 const config_var_t *var = config_find_option(&options_format, key);
2456 return var ? var->name : NULL;
2459 /** Return a canonical list of the options assigned for key.
2461 config_line_t *
2462 option_get_assignment(const or_options_t *options, const char *key)
2464 return config_get_assigned_option(&options_format, options, key, 1);
2467 /** Try assigning <b>list</b> to the global options. You do this by duping
2468 * options, assigning list to the new one, then validating it. If it's
2469 * ok, then throw out the old one and stick with the new one. Else,
2470 * revert to old and return failure. Return SETOPT_OK on success, or
2471 * a setopt_err_t on failure.
2473 * If not success, point *<b>msg</b> to a newly allocated string describing
2474 * what went wrong.
2476 setopt_err_t
2477 options_trial_assign(config_line_t *list, unsigned flags, char **msg)
2479 int r;
2480 or_options_t *trial_options = config_dup(&options_format, get_options());
2482 if ((r=config_assign(&options_format, trial_options,
2483 list, flags, msg)) < 0) {
2484 or_options_free(trial_options);
2485 return r;
2488 setopt_err_t rv;
2489 or_options_t *cur_options = get_options_mutable();
2491 in_option_validation = 1;
2493 if (options_validate(cur_options, trial_options,
2494 global_default_options, 1, msg) < 0) {
2495 or_options_free(trial_options);
2496 rv = SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2497 goto done;
2500 if (options_transition_allowed(cur_options, trial_options, msg) < 0) {
2501 or_options_free(trial_options);
2502 rv = SETOPT_ERR_TRANSITION;
2503 goto done;
2505 in_option_validation = 0;
2507 if (set_options(trial_options, msg)<0) {
2508 or_options_free(trial_options);
2509 rv = SETOPT_ERR_SETTING;
2510 goto done;
2513 /* we liked it. put it in place. */
2514 rv = SETOPT_OK;
2515 done:
2516 in_option_validation = 0;
2517 return rv;
2520 /** Print a usage message for tor. */
2521 static void
2522 print_usage(void)
2524 printf(
2525 "Copyright (c) 2001-2004, Roger Dingledine\n"
2526 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2527 "Copyright (c) 2007-2017, The Tor Project, Inc.\n\n"
2528 "tor -f <torrc> [args]\n"
2529 "See man page for options, or https://www.torproject.org/ for "
2530 "documentation.\n");
2533 /** Print all non-obsolete torrc options. */
2534 static void
2535 list_torrc_options(void)
2537 int i;
2538 for (i = 0; option_vars_[i].name; ++i) {
2539 const config_var_t *var = &option_vars_[i];
2540 if (var->type == CONFIG_TYPE_OBSOLETE ||
2541 var->type == CONFIG_TYPE_LINELIST_V)
2542 continue;
2543 printf("%s\n", var->name);
2547 /** Print all deprecated but non-obsolete torrc options. */
2548 static void
2549 list_deprecated_options(void)
2551 const config_deprecation_t *d;
2552 for (d = option_deprecation_notes_; d->name; ++d) {
2553 printf("%s\n", d->name);
2557 /** Last value actually set by resolve_my_address. */
2558 static uint32_t last_resolved_addr = 0;
2560 /** Accessor for last_resolved_addr from outside this file. */
2561 uint32_t
2562 get_last_resolved_addr(void)
2564 return last_resolved_addr;
2567 /** Reset last_resolved_addr from outside this file. */
2568 void
2569 reset_last_resolved_addr(void)
2571 last_resolved_addr = 0;
2574 /* Return true if <b>options</b> is using the default authorities, and false
2575 * if any authority-related option has been overridden. */
2577 using_default_dir_authorities(const or_options_t *options)
2579 return (!options->DirAuthorities && !options->AlternateDirAuthority);
2583 * Attempt getting our non-local (as judged by tor_addr_is_internal()
2584 * function) IP address using following techniques, listed in
2585 * order from best (most desirable, try first) to worst (least
2586 * desirable, try if everything else fails).
2588 * First, attempt using <b>options-\>Address</b> to get our
2589 * non-local IP address.
2591 * If <b>options-\>Address</b> represents a non-local IP address,
2592 * consider it ours.
2594 * If <b>options-\>Address</b> is a DNS name that resolves to
2595 * a non-local IP address, consider this IP address ours.
2597 * If <b>options-\>Address</b> is NULL, fall back to getting local
2598 * hostname and using it in above-described ways to try and
2599 * get our IP address.
2601 * In case local hostname cannot be resolved to a non-local IP
2602 * address, try getting an IP address of network interface
2603 * in hopes it will be non-local one.
2605 * Fail if one or more of the following is true:
2606 * - DNS name in <b>options-\>Address</b> cannot be resolved.
2607 * - <b>options-\>Address</b> is a local host address.
2608 * - Attempt at getting local hostname fails.
2609 * - Attempt at getting network interface address fails.
2611 * Return 0 if all is well, or -1 if we can't find a suitable
2612 * public IP address.
2614 * If we are returning 0:
2615 * - Put our public IP address (in host order) into *<b>addr_out</b>.
2616 * - If <b>method_out</b> is non-NULL, set *<b>method_out</b> to a static
2617 * string describing how we arrived at our answer.
2618 * - "CONFIGURED" - parsed from IP address string in
2619 * <b>options-\>Address</b>
2620 * - "RESOLVED" - resolved from DNS name in <b>options-\>Address</b>
2621 * - "GETHOSTNAME" - resolved from a local hostname.
2622 * - "INTERFACE" - retrieved from a network interface.
2623 * - If <b>hostname_out</b> is non-NULL, and we resolved a hostname to
2624 * get our address, set *<b>hostname_out</b> to a newly allocated string
2625 * holding that hostname. (If we didn't get our address by resolving a
2626 * hostname, set *<b>hostname_out</b> to NULL.)
2628 * XXXX ipv6
2631 resolve_my_address(int warn_severity, const or_options_t *options,
2632 uint32_t *addr_out,
2633 const char **method_out, char **hostname_out)
2635 struct in_addr in;
2636 uint32_t addr; /* host order */
2637 char hostname[256];
2638 const char *method_used;
2639 const char *hostname_used;
2640 int explicit_ip=1;
2641 int explicit_hostname=1;
2642 int from_interface=0;
2643 char *addr_string = NULL;
2644 const char *address = options->Address;
2645 int notice_severity = warn_severity <= LOG_NOTICE ?
2646 LOG_NOTICE : warn_severity;
2648 tor_addr_t myaddr;
2649 tor_assert(addr_out);
2652 * Step one: Fill in 'hostname' to be our best guess.
2655 if (address && *address) {
2656 strlcpy(hostname, address, sizeof(hostname));
2657 } else { /* then we need to guess our address */
2658 explicit_ip = 0; /* it's implicit */
2659 explicit_hostname = 0; /* it's implicit */
2661 if (tor_gethostname(hostname, sizeof(hostname)) < 0) {
2662 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2663 return -1;
2665 log_debug(LD_CONFIG, "Guessed local host name as '%s'", hostname);
2669 * Step two: Now that we know 'hostname', parse it or resolve it. If
2670 * it doesn't parse or resolve, look at the interface address. Set 'addr'
2671 * to be our (host-order) 32-bit answer.
2674 if (tor_inet_aton(hostname, &in) == 0) {
2675 /* then we have to resolve it */
2676 explicit_ip = 0;
2677 if (tor_lookup_hostname(hostname, &addr)) { /* failed to resolve */
2678 uint32_t interface_ip; /* host order */
2680 if (explicit_hostname) {
2681 log_fn(warn_severity, LD_CONFIG,
2682 "Could not resolve local Address '%s'. Failing.", hostname);
2683 return -1;
2685 log_fn(notice_severity, LD_CONFIG,
2686 "Could not resolve guessed local hostname '%s'. "
2687 "Trying something else.", hostname);
2688 if (get_interface_address(warn_severity, &interface_ip)) {
2689 log_fn(warn_severity, LD_CONFIG,
2690 "Could not get local interface IP address. Failing.");
2691 return -1;
2693 from_interface = 1;
2694 addr = interface_ip;
2695 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2696 "local interface. Using that.", fmt_addr32(addr));
2697 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2698 } else { /* resolved hostname into addr */
2699 tor_addr_from_ipv4h(&myaddr, addr);
2701 if (!explicit_hostname &&
2702 tor_addr_is_internal(&myaddr, 0)) {
2703 tor_addr_t interface_ip;
2705 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2706 "resolves to a private IP address (%s). Trying something "
2707 "else.", hostname, fmt_addr32(addr));
2709 if (get_interface_address6(warn_severity, AF_INET, &interface_ip)<0) {
2710 log_fn(warn_severity, LD_CONFIG,
2711 "Could not get local interface IP address. Too bad.");
2712 } else if (tor_addr_is_internal(&interface_ip, 0)) {
2713 log_fn(notice_severity, LD_CONFIG,
2714 "Interface IP address '%s' is a private address too. "
2715 "Ignoring.", fmt_addr(&interface_ip));
2716 } else {
2717 from_interface = 1;
2718 addr = tor_addr_to_ipv4h(&interface_ip);
2719 log_fn(notice_severity, LD_CONFIG,
2720 "Learned IP address '%s' for local interface."
2721 " Using that.", fmt_addr32(addr));
2722 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2726 } else {
2727 addr = ntohl(in.s_addr); /* set addr so that addr_string is not
2728 * illformed */
2732 * Step three: Check whether 'addr' is an internal IP address, and error
2733 * out if it is and we don't want that.
2736 tor_addr_from_ipv4h(&myaddr,addr);
2738 addr_string = tor_dup_ip(addr);
2739 if (tor_addr_is_internal(&myaddr, 0)) {
2740 /* make sure we're ok with publishing an internal IP */
2741 if (using_default_dir_authorities(options)) {
2742 /* if they are using the default authorities, disallow internal IPs
2743 * always. */
2744 log_fn(warn_severity, LD_CONFIG,
2745 "Address '%s' resolves to private IP address '%s'. "
2746 "Tor servers that use the default DirAuthorities must have "
2747 "public IP addresses.", hostname, addr_string);
2748 tor_free(addr_string);
2749 return -1;
2751 if (!explicit_ip) {
2752 /* even if they've set their own authorities, require an explicit IP if
2753 * they're using an internal address. */
2754 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2755 "IP address '%s'. Please set the Address config option to be "
2756 "the IP address you want to use.", hostname, addr_string);
2757 tor_free(addr_string);
2758 return -1;
2763 * Step four: We have a winner! 'addr' is our answer for sure, and
2764 * 'addr_string' is its string form. Fill out the various fields to
2765 * say how we decided it.
2768 log_debug(LD_CONFIG, "Resolved Address to '%s'.", addr_string);
2770 if (explicit_ip) {
2771 method_used = "CONFIGURED";
2772 hostname_used = NULL;
2773 } else if (explicit_hostname) {
2774 method_used = "RESOLVED";
2775 hostname_used = hostname;
2776 } else if (from_interface) {
2777 method_used = "INTERFACE";
2778 hostname_used = NULL;
2779 } else {
2780 method_used = "GETHOSTNAME";
2781 hostname_used = hostname;
2784 *addr_out = addr;
2785 if (method_out)
2786 *method_out = method_used;
2787 if (hostname_out)
2788 *hostname_out = hostname_used ? tor_strdup(hostname_used) : NULL;
2791 * Step five: Check if the answer has changed since last time (or if
2792 * there was no last time), and if so call various functions to keep
2793 * us up-to-date.
2796 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2797 /* Leave this as a notice, regardless of the requested severity,
2798 * at least until dynamic IP address support becomes bulletproof. */
2799 log_notice(LD_NET,
2800 "Your IP address seems to have changed to %s "
2801 "(METHOD=%s%s%s). Updating.",
2802 addr_string, method_used,
2803 hostname_used ? " HOSTNAME=" : "",
2804 hostname_used ? hostname_used : "");
2805 ip_address_changed(0);
2808 if (last_resolved_addr != *addr_out) {
2809 control_event_server_status(LOG_NOTICE,
2810 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s%s%s",
2811 addr_string, method_used,
2812 hostname_used ? " HOSTNAME=" : "",
2813 hostname_used ? hostname_used : "");
2815 last_resolved_addr = *addr_out;
2818 * And finally, clean up and return success.
2821 tor_free(addr_string);
2822 return 0;
2825 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2826 * on a private network.
2828 MOCK_IMPL(int,
2829 is_local_addr, (const tor_addr_t *addr))
2831 if (tor_addr_is_internal(addr, 0))
2832 return 1;
2833 /* Check whether ip is on the same /24 as we are. */
2834 if (get_options()->EnforceDistinctSubnets == 0)
2835 return 0;
2836 if (tor_addr_family(addr) == AF_INET) {
2837 uint32_t ip = tor_addr_to_ipv4h(addr);
2839 /* It's possible that this next check will hit before the first time
2840 * resolve_my_address actually succeeds. (For clients, it is likely that
2841 * resolve_my_address will never be called at all). In those cases,
2842 * last_resolved_addr will be 0, and so checking to see whether ip is on
2843 * the same /24 as last_resolved_addr will be the same as checking whether
2844 * it was on net 0, which is already done by tor_addr_is_internal.
2846 if ((last_resolved_addr & (uint32_t)0xffffff00ul)
2847 == (ip & (uint32_t)0xffffff00ul))
2848 return 1;
2850 return 0;
2853 /** Return a new empty or_options_t. Used for testing. */
2854 or_options_t *
2855 options_new(void)
2857 return config_new(&options_format);
2860 /** Set <b>options</b> to hold reasonable defaults for most options.
2861 * Each option defaults to zero. */
2862 void
2863 options_init(or_options_t *options)
2865 config_init(&options_format, options);
2868 /** Return a string containing a possible configuration file that would give
2869 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2870 * include options that are the same as Tor's defaults.
2872 char *
2873 options_dump(const or_options_t *options, int how_to_dump)
2875 const or_options_t *use_defaults;
2876 int minimal;
2877 switch (how_to_dump) {
2878 case OPTIONS_DUMP_MINIMAL:
2879 use_defaults = global_default_options;
2880 minimal = 1;
2881 break;
2882 case OPTIONS_DUMP_DEFAULTS:
2883 use_defaults = NULL;
2884 minimal = 1;
2885 break;
2886 case OPTIONS_DUMP_ALL:
2887 use_defaults = NULL;
2888 minimal = 0;
2889 break;
2890 default:
2891 log_warn(LD_BUG, "Bogus value for how_to_dump==%d", how_to_dump);
2892 return NULL;
2895 return config_dump(&options_format, use_defaults, options, minimal, 0);
2898 /** Return 0 if every element of sl is a string holding a decimal
2899 * representation of a port number, or if sl is NULL.
2900 * Otherwise set *msg and return -1. */
2901 static int
2902 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2904 int i;
2905 tor_assert(name);
2907 if (!sl)
2908 return 0;
2910 SMARTLIST_FOREACH(sl, const char *, cp,
2912 i = atoi(cp);
2913 if (i < 1 || i > 65535) {
2914 tor_asprintf(msg, "Port '%s' out of range in %s", cp, name);
2915 return -1;
2918 return 0;
2921 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2922 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2923 * Else return 0.
2925 static int
2926 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2928 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2929 /* This handles an understandable special case where somebody says "2gb"
2930 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2931 --*value;
2933 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2934 tor_asprintf(msg, "%s ("U64_FORMAT") must be at most %d",
2935 desc, U64_PRINTF_ARG(*value),
2936 ROUTER_MAX_DECLARED_BANDWIDTH);
2937 return -1;
2939 return 0;
2942 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2943 * and write it to <b>options</b>-\>PublishServerDescriptor_. Treat "1"
2944 * as "v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2945 * Treat "0" as "".
2946 * Return 0 on success or -1 if not a recognized authority type (in which
2947 * case the value of PublishServerDescriptor_ is undefined). */
2948 static int
2949 compute_publishserverdescriptor(or_options_t *options)
2951 smartlist_t *list = options->PublishServerDescriptor;
2952 dirinfo_type_t *auth = &options->PublishServerDescriptor_;
2953 *auth = NO_DIRINFO;
2954 if (!list) /* empty list, answer is none */
2955 return 0;
2956 SMARTLIST_FOREACH_BEGIN(list, const char *, string) {
2957 if (!strcasecmp(string, "v1"))
2958 log_warn(LD_CONFIG, "PublishServerDescriptor v1 has no effect, because "
2959 "there are no v1 directory authorities anymore.");
2960 else if (!strcmp(string, "1"))
2961 if (options->BridgeRelay)
2962 *auth |= BRIDGE_DIRINFO;
2963 else
2964 *auth |= V3_DIRINFO;
2965 else if (!strcasecmp(string, "v2"))
2966 log_warn(LD_CONFIG, "PublishServerDescriptor v2 has no effect, because "
2967 "there are no v2 directory authorities anymore.");
2968 else if (!strcasecmp(string, "v3"))
2969 *auth |= V3_DIRINFO;
2970 else if (!strcasecmp(string, "bridge"))
2971 *auth |= BRIDGE_DIRINFO;
2972 else if (!strcasecmp(string, "hidserv"))
2973 log_warn(LD_CONFIG,
2974 "PublishServerDescriptor hidserv is invalid. See "
2975 "PublishHidServDescriptors.");
2976 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2977 /* no authority */;
2978 else
2979 return -1;
2980 } SMARTLIST_FOREACH_END(string);
2981 return 0;
2984 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2985 * services can overload the directory system. */
2986 #define MIN_REND_POST_PERIOD (10*60)
2987 #define MIN_REND_POST_PERIOD_TESTING (5)
2989 /** Highest allowable value for CircuitsAvailableTimeout.
2990 * If this is too large, client connections will stay open for too long,
2991 * incurring extra padding overhead. */
2992 #define MAX_CIRCS_AVAILABLE_TIME (24*60*60)
2994 /** Highest allowable value for RendPostPeriod. */
2995 #define MAX_DIR_PERIOD ((7*24*60*60)/2)
2997 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2998 * will generate too many circuits and potentially overload the network. */
2999 #define MIN_MAX_CIRCUIT_DIRTINESS 10
3001 /** Highest allowable value for MaxCircuitDirtiness: prevents time_t
3002 * overflows. */
3003 #define MAX_MAX_CIRCUIT_DIRTINESS (30*24*60*60)
3005 /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
3006 * will generate too many circuits and potentially overload the network. */
3007 #define MIN_CIRCUIT_STREAM_TIMEOUT 10
3009 /** Lowest recommended value for CircuitBuildTimeout; if it is set too low
3010 * and LearnCircuitBuildTimeout is off, the failure rate for circuit
3011 * construction may be very high. In that case, if it is set below this
3012 * threshold emit a warning.
3013 * */
3014 #define RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT (10)
3016 static int
3017 options_validate_cb(void *old_options, void *options, void *default_options,
3018 int from_setconf, char **msg)
3020 in_option_validation = 1;
3021 int rv = options_validate(old_options, options, default_options,
3022 from_setconf, msg);
3023 in_option_validation = 0;
3024 return rv;
3027 #define REJECT(arg) \
3028 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
3029 #if defined(__GNUC__) && __GNUC__ <= 3
3030 #define COMPLAIN(args...) \
3031 STMT_BEGIN log_warn(LD_CONFIG, args); STMT_END
3032 #else
3033 #define COMPLAIN(args, ...) \
3034 STMT_BEGIN log_warn(LD_CONFIG, args, ##__VA_ARGS__); STMT_END
3035 #endif /* defined(__GNUC__) && __GNUC__ <= 3 */
3037 /** Log a warning message iff <b>filepath</b> is not absolute.
3038 * Warning message must contain option name <b>option</b> and
3039 * an absolute path that <b>filepath</b> will resolve to.
3041 * In case <b>filepath</b> is absolute, do nothing.
3043 * Return 1 if there were relative paths; 0 otherwise.
3045 static int
3046 warn_if_option_path_is_relative(const char *option,
3047 char *filepath)
3049 if (filepath && path_is_relative(filepath)) {
3050 char *abs_path = make_path_absolute(filepath);
3051 COMPLAIN("Path for %s (%s) is relative and will resolve to %s."
3052 " Is this what you wanted?", option, filepath, abs_path);
3053 tor_free(abs_path);
3054 return 1;
3056 return 0;
3059 /** Scan <b>options</b> for occurances of relative file/directory
3060 * path and log a warning whenever it is found.
3062 * Return 1 if there were relative paths; 0 otherwise.
3064 static int
3065 warn_about_relative_paths(or_options_t *options)
3067 tor_assert(options);
3068 int n = 0;
3070 n += warn_if_option_path_is_relative("CookieAuthFile",
3071 options->CookieAuthFile);
3072 n += warn_if_option_path_is_relative("ExtORPortCookieAuthFile",
3073 options->ExtORPortCookieAuthFile);
3074 n += warn_if_option_path_is_relative("DirPortFrontPage",
3075 options->DirPortFrontPage);
3076 n += warn_if_option_path_is_relative("V3BandwidthsFile",
3077 options->V3BandwidthsFile);
3078 n += warn_if_option_path_is_relative("ControlPortWriteToFile",
3079 options->ControlPortWriteToFile);
3080 n += warn_if_option_path_is_relative("GeoIPFile",options->GeoIPFile);
3081 n += warn_if_option_path_is_relative("GeoIPv6File",options->GeoIPv6File);
3082 n += warn_if_option_path_is_relative("Log",options->DebugLogFile);
3083 n += warn_if_option_path_is_relative("AccelDir",options->AccelDir);
3084 n += warn_if_option_path_is_relative("DataDirectory",options->DataDirectory);
3085 n += warn_if_option_path_is_relative("PidFile",options->PidFile);
3087 for (config_line_t *hs_line = options->RendConfigLines; hs_line;
3088 hs_line = hs_line->next) {
3089 if (!strcasecmp(hs_line->key, "HiddenServiceDir"))
3090 n += warn_if_option_path_is_relative("HiddenServiceDir",hs_line->value);
3092 return n != 0;
3095 /* Validate options related to the scheduler. From the Schedulers list, the
3096 * SchedulerTypes_ list is created with int values so once we select the
3097 * scheduler, which can happen anytime at runtime, we don't have to parse
3098 * strings and thus be quick.
3100 * Return 0 on success else -1 and msg is set with an error message. */
3101 static int
3102 options_validate_scheduler(or_options_t *options, char **msg)
3104 tor_assert(options);
3105 tor_assert(msg);
3107 if (!options->Schedulers || smartlist_len(options->Schedulers) == 0) {
3108 REJECT("Empty Schedulers list. Either remove the option so the defaults "
3109 "can be used or set at least one value.");
3111 /* Ok, we do have scheduler types, validate them. */
3112 options->SchedulerTypes_ = smartlist_new();
3113 SMARTLIST_FOREACH_BEGIN(options->Schedulers, const char *, type) {
3114 int *sched_type;
3115 if (!strcasecmp("KISTLite", type)) {
3116 sched_type = tor_malloc_zero(sizeof(int));
3117 *sched_type = SCHEDULER_KIST_LITE;
3118 smartlist_add(options->SchedulerTypes_, sched_type);
3119 } else if (!strcasecmp("KIST", type)) {
3120 sched_type = tor_malloc_zero(sizeof(int));
3121 *sched_type = SCHEDULER_KIST;
3122 smartlist_add(options->SchedulerTypes_, sched_type);
3123 } else if (!strcasecmp("Vanilla", type)) {
3124 sched_type = tor_malloc_zero(sizeof(int));
3125 *sched_type = SCHEDULER_VANILLA;
3126 smartlist_add(options->SchedulerTypes_, sched_type);
3127 } else {
3128 tor_asprintf(msg, "Unknown type %s in option Schedulers. "
3129 "Possible values are KIST, KISTLite and Vanilla.",
3130 escaped(type));
3131 return -1;
3133 } SMARTLIST_FOREACH_END(type);
3135 if (options->KISTSockBufSizeFactor < 0) {
3136 REJECT("KISTSockBufSizeFactor must be at least 0");
3139 /* Don't need to validate that the Interval is less than anything because
3140 * zero is valid and all negative values are valid. */
3141 if (options->KISTSchedRunInterval > KIST_SCHED_RUN_INTERVAL_MAX) {
3142 tor_asprintf(msg, "KISTSchedRunInterval must not be more than %d (ms)",
3143 KIST_SCHED_RUN_INTERVAL_MAX);
3144 return -1;
3147 return 0;
3150 /* Validate options related to single onion services.
3151 * Modifies some options that are incompatible with single onion services.
3152 * On failure returns -1, and sets *msg to an error string.
3153 * Returns 0 on success. */
3154 STATIC int
3155 options_validate_single_onion(or_options_t *options, char **msg)
3157 /* The two single onion service options must have matching values. */
3158 if (options->HiddenServiceSingleHopMode &&
3159 !options->HiddenServiceNonAnonymousMode) {
3160 REJECT("HiddenServiceSingleHopMode does not provide any server anonymity. "
3161 "It must be used with HiddenServiceNonAnonymousMode set to 1.");
3163 if (options->HiddenServiceNonAnonymousMode &&
3164 !options->HiddenServiceSingleHopMode) {
3165 REJECT("HiddenServiceNonAnonymousMode does not provide any server "
3166 "anonymity. It must be used with HiddenServiceSingleHopMode set to "
3167 "1.");
3170 /* Now that we've checked that the two options are consistent, we can safely
3171 * call the rend_service_* functions that abstract these options. */
3173 /* If you run an anonymous client with an active Single Onion service, the
3174 * client loses anonymity. */
3175 const int client_port_set = (options->SocksPort_set ||
3176 options->TransPort_set ||
3177 options->NATDPort_set ||
3178 options->DNSPort_set ||
3179 options->HTTPTunnelPort_set);
3180 if (rend_service_non_anonymous_mode_enabled(options) && client_port_set &&
3181 !options->Tor2webMode) {
3182 REJECT("HiddenServiceNonAnonymousMode is incompatible with using Tor as "
3183 "an anonymous client. Please set Socks/Trans/NATD/DNSPort to 0, or "
3184 "revert HiddenServiceNonAnonymousMode to 0.");
3187 /* If you run a hidden service in non-anonymous mode, the hidden service
3188 * loses anonymity, even if SOCKSPort / Tor2web mode isn't used. */
3189 if (!rend_service_non_anonymous_mode_enabled(options) &&
3190 options->RendConfigLines && options->Tor2webMode) {
3191 REJECT("Non-anonymous (Tor2web) mode is incompatible with using Tor as a "
3192 "hidden service. Please remove all HiddenServiceDir lines, or use "
3193 "a version of tor compiled without --enable-tor2web-mode, or use "
3194 "HiddenServiceNonAnonymousMode.");
3197 if (rend_service_allow_non_anonymous_connection(options)
3198 && options->UseEntryGuards) {
3199 /* Single Onion services only use entry guards when uploading descriptors;
3200 * all other connections are one-hop. Further, Single Onions causes the
3201 * hidden service code to do things which break the path bias
3202 * detector, and it's far easier to turn off entry guards (and
3203 * thus the path bias detector with it) than to figure out how to
3204 * make path bias compatible with single onions.
3206 log_notice(LD_CONFIG,
3207 "HiddenServiceSingleHopMode is enabled; disabling "
3208 "UseEntryGuards.");
3209 options->UseEntryGuards = 0;
3212 return 0;
3215 /** Return 0 if every setting in <b>options</b> is reasonable, is a
3216 * permissible transition from <b>old_options</b>, and none of the
3217 * testing-only settings differ from <b>default_options</b> unless in
3218 * testing mode. Else return -1. Should have no side effects, except for
3219 * normalizing the contents of <b>options</b>.
3221 * On error, tor_strdup an error explanation into *<b>msg</b>.
3223 * XXX
3224 * If <b>from_setconf</b>, we were called by the controller, and our
3225 * Log line should stay empty. If it's 0, then give us a default log
3226 * if there are no logs defined.
3228 STATIC int
3229 options_validate(or_options_t *old_options, or_options_t *options,
3230 or_options_t *default_options, int from_setconf, char **msg)
3232 int i;
3233 config_line_t *cl;
3234 const char *uname = get_uname();
3235 int n_ports=0;
3236 int world_writable_control_socket=0;
3238 tor_assert(msg);
3239 *msg = NULL;
3241 if (parse_ports(options, 1, msg, &n_ports,
3242 &world_writable_control_socket) < 0)
3243 return -1;
3245 /* Set UseEntryGuards from the configured value, before we check it below.
3246 * We change UseEntryGuards when it's incompatible with other options,
3247 * but leave UseEntryGuards_option with the original value.
3248 * Always use the value of UseEntryGuards, not UseEntryGuards_option. */
3249 options->UseEntryGuards = options->UseEntryGuards_option;
3251 if (warn_about_relative_paths(options) && options->RunAsDaemon) {
3252 REJECT("You have specified at least one relative path (see above) "
3253 "with the RunAsDaemon option. RunAsDaemon is not compatible "
3254 "with relative paths.");
3257 if (server_mode(options) &&
3258 (!strcmpstart(uname, "Windows 95") ||
3259 !strcmpstart(uname, "Windows 98") ||
3260 !strcmpstart(uname, "Windows Me"))) {
3261 log_warn(LD_CONFIG, "Tor is running as a server, but you are "
3262 "running %s; this probably won't work. See "
3263 "https://www.torproject.org/docs/faq.html#BestOSForRelay "
3264 "for details.", uname);
3267 if (parse_outbound_addresses(options, 1, msg) < 0)
3268 return -1;
3270 if (validate_data_directories(options)<0)
3271 REJECT("Invalid DataDirectory");
3273 if (options->Nickname == NULL) {
3274 if (server_mode(options)) {
3275 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
3277 } else {
3278 if (!is_legal_nickname(options->Nickname)) {
3279 tor_asprintf(msg,
3280 "Nickname '%s', nicknames must be between 1 and 19 characters "
3281 "inclusive, and must contain only the characters [a-zA-Z0-9].",
3282 options->Nickname);
3283 return -1;
3287 if (server_mode(options) && !options->ContactInfo)
3288 log_notice(LD_CONFIG, "Your ContactInfo config option is not set. "
3289 "Please consider setting it, so we can contact you if your server is "
3290 "misconfigured or something else goes wrong.");
3292 /* Special case on first boot if no Log options are given. */
3293 if (!options->Logs && !options->RunAsDaemon && !from_setconf) {
3294 if (quiet_level == 0)
3295 config_line_append(&options->Logs, "Log", "notice stdout");
3296 else if (quiet_level == 1)
3297 config_line_append(&options->Logs, "Log", "warn stdout");
3300 /* Validate the tor_log(s) */
3301 if (options_init_logs(old_options, options, 1)<0)
3302 REJECT("Failed to validate Log options. See logs for details.");
3304 if (authdir_mode(options)) {
3305 /* confirm that our address isn't broken, so we can complain now */
3306 uint32_t tmp;
3307 if (resolve_my_address(LOG_WARN, options, &tmp, NULL, NULL) < 0)
3308 REJECT("Failed to resolve/guess local address. See logs for details.");
3311 if (server_mode(options) && options->RendConfigLines)
3312 log_warn(LD_CONFIG,
3313 "Tor is currently configured as a relay and a hidden service. "
3314 "That's not very secure: you should probably run your hidden service "
3315 "in a separate Tor process, at least -- see "
3316 "https://trac.torproject.org/8742");
3318 /* XXXX require that the only port not be DirPort? */
3319 /* XXXX require that at least one port be listened-upon. */
3320 if (n_ports == 0 && !options->RendConfigLines)
3321 log_warn(LD_CONFIG,
3322 "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
3323 "undefined, and there aren't any hidden services configured. "
3324 "Tor will still run, but probably won't do anything.");
3326 options->TransProxyType_parsed = TPT_DEFAULT;
3327 #ifdef USE_TRANSPARENT
3328 if (options->TransProxyType) {
3329 if (!strcasecmp(options->TransProxyType, "default")) {
3330 options->TransProxyType_parsed = TPT_DEFAULT;
3331 } else if (!strcasecmp(options->TransProxyType, "pf-divert")) {
3332 #if !defined(OpenBSD) && !defined( DARWIN )
3333 /* Later versions of OS X have pf */
3334 REJECT("pf-divert is a OpenBSD-specific "
3335 "and OS X/Darwin-specific feature.");
3336 #else
3337 options->TransProxyType_parsed = TPT_PF_DIVERT;
3338 #endif /* !defined(OpenBSD) && !defined( DARWIN ) */
3339 } else if (!strcasecmp(options->TransProxyType, "tproxy")) {
3340 #if !defined(__linux__)
3341 REJECT("TPROXY is a Linux-specific feature.");
3342 #else
3343 options->TransProxyType_parsed = TPT_TPROXY;
3344 #endif
3345 } else if (!strcasecmp(options->TransProxyType, "ipfw")) {
3346 #ifndef KERNEL_MAY_SUPPORT_IPFW
3347 /* Earlier versions of OS X have ipfw */
3348 REJECT("ipfw is a FreeBSD-specific "
3349 "and OS X/Darwin-specific feature.");
3350 #else
3351 options->TransProxyType_parsed = TPT_IPFW;
3352 #endif /* !defined(KERNEL_MAY_SUPPORT_IPFW) */
3353 } else {
3354 REJECT("Unrecognized value for TransProxyType");
3357 if (strcasecmp(options->TransProxyType, "default") &&
3358 !options->TransPort_set) {
3359 REJECT("Cannot use TransProxyType without any valid TransPort.");
3362 #else /* !(defined(USE_TRANSPARENT)) */
3363 if (options->TransPort_set)
3364 REJECT("TransPort is disabled in this build.");
3365 #endif /* defined(USE_TRANSPARENT) */
3367 if (options->TokenBucketRefillInterval <= 0
3368 || options->TokenBucketRefillInterval > 1000) {
3369 REJECT("TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
3372 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3373 options->ExcludeExitNodesUnion_ = routerset_new();
3374 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeExitNodes);
3375 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeNodes);
3378 if (options->NodeFamilies) {
3379 options->NodeFamilySets = smartlist_new();
3380 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3381 routerset_t *rs = routerset_new();
3382 if (routerset_parse(rs, cl->value, cl->key) == 0) {
3383 smartlist_add(options->NodeFamilySets, rs);
3384 } else {
3385 routerset_free(rs);
3390 if (options->ExcludeNodes && options->StrictNodes) {
3391 COMPLAIN("You have asked to exclude certain relays from all positions "
3392 "in your circuits. Expect hidden services and other Tor "
3393 "features to be broken in unpredictable ways.");
3396 for (cl = options->RecommendedPackages; cl; cl = cl->next) {
3397 if (! validate_recommended_package_line(cl->value)) {
3398 log_warn(LD_CONFIG, "Invalid RecommendedPackage line %s will be ignored",
3399 escaped(cl->value));
3403 if (options->AuthoritativeDir) {
3404 if (!options->ContactInfo && !options->TestingTorNetwork)
3405 REJECT("Authoritative directory servers must set ContactInfo");
3406 if (!options->RecommendedClientVersions)
3407 options->RecommendedClientVersions =
3408 config_lines_dup(options->RecommendedVersions);
3409 if (!options->RecommendedServerVersions)
3410 options->RecommendedServerVersions =
3411 config_lines_dup(options->RecommendedVersions);
3412 if (options->VersioningAuthoritativeDir &&
3413 (!options->RecommendedClientVersions ||
3414 !options->RecommendedServerVersions))
3415 REJECT("Versioning authoritative dir servers must set "
3416 "Recommended*Versions.");
3417 if (options->UseEntryGuards) {
3418 log_info(LD_CONFIG, "Authoritative directory servers can't set "
3419 "UseEntryGuards. Disabling.");
3420 options->UseEntryGuards = 0;
3422 if (!options->DownloadExtraInfo && authdir_mode_v3(options)) {
3423 log_info(LD_CONFIG, "Authoritative directories always try to download "
3424 "extra-info documents. Setting DownloadExtraInfo.");
3425 options->DownloadExtraInfo = 1;
3427 if (!(options->BridgeAuthoritativeDir ||
3428 options->V3AuthoritativeDir))
3429 REJECT("AuthoritativeDir is set, but none of "
3430 "(Bridge/V3)AuthoritativeDir is set.");
3431 /* If we have a v3bandwidthsfile and it's broken, complain on startup */
3432 if (options->V3BandwidthsFile && !old_options) {
3433 dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
3435 /* same for guardfraction file */
3436 if (options->GuardfractionFile && !old_options) {
3437 dirserv_read_guardfraction_file(options->GuardfractionFile, NULL);
3441 if (options->AuthoritativeDir && !options->DirPort_set)
3442 REJECT("Running as authoritative directory, but no DirPort set.");
3444 if (options->AuthoritativeDir && !options->ORPort_set)
3445 REJECT("Running as authoritative directory, but no ORPort set.");
3447 if (options->AuthoritativeDir && options->ClientOnly)
3448 REJECT("Running as authoritative directory, but ClientOnly also set.");
3450 if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
3451 REJECT("FetchDirInfoExtraEarly requires that you also set "
3452 "FetchDirInfoEarly");
3454 if (options->ConnLimit <= 0) {
3455 tor_asprintf(msg,
3456 "ConnLimit must be greater than 0, but was set to %d",
3457 options->ConnLimit);
3458 return -1;
3461 if (options->PathsNeededToBuildCircuits >= 0.0) {
3462 if (options->PathsNeededToBuildCircuits < 0.25) {
3463 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too low. Increasing "
3464 "to 0.25");
3465 options->PathsNeededToBuildCircuits = 0.25;
3466 } else if (options->PathsNeededToBuildCircuits > 0.95) {
3467 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too high. Decreasing "
3468 "to 0.95");
3469 options->PathsNeededToBuildCircuits = 0.95;
3473 if (options->MaxClientCircuitsPending <= 0 ||
3474 options->MaxClientCircuitsPending > MAX_MAX_CLIENT_CIRCUITS_PENDING) {
3475 tor_asprintf(msg,
3476 "MaxClientCircuitsPending must be between 1 and %d, but "
3477 "was set to %d", MAX_MAX_CLIENT_CIRCUITS_PENDING,
3478 options->MaxClientCircuitsPending);
3479 return -1;
3482 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3483 return -1;
3485 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3486 return -1;
3488 if (validate_ports_csv(options->RejectPlaintextPorts,
3489 "RejectPlaintextPorts", msg) < 0)
3490 return -1;
3492 if (validate_ports_csv(options->WarnPlaintextPorts,
3493 "WarnPlaintextPorts", msg) < 0)
3494 return -1;
3496 if (options->FascistFirewall && !options->ReachableAddresses) {
3497 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3498 /* We already have firewall ports set, so migrate them to
3499 * ReachableAddresses, which will set ReachableORAddresses and
3500 * ReachableDirAddresses if they aren't set explicitly. */
3501 smartlist_t *instead = smartlist_new();
3502 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3503 new_line->key = tor_strdup("ReachableAddresses");
3504 /* If we're configured with the old format, we need to prepend some
3505 * open ports. */
3506 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3508 int p = atoi(portno);
3509 if (p<0) continue;
3510 smartlist_add_asprintf(instead, "*:%d", p);
3512 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3513 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3514 log_notice(LD_CONFIG,
3515 "Converting FascistFirewall and FirewallPorts "
3516 "config options to new format: \"ReachableAddresses %s\"",
3517 new_line->value);
3518 options->ReachableAddresses = new_line;
3519 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3520 smartlist_free(instead);
3521 } else {
3522 /* We do not have FirewallPorts set, so add 80 to
3523 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3524 if (!options->ReachableDirAddresses) {
3525 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3526 new_line->key = tor_strdup("ReachableDirAddresses");
3527 new_line->value = tor_strdup("*:80");
3528 options->ReachableDirAddresses = new_line;
3529 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3530 "to new format: \"ReachableDirAddresses *:80\"");
3532 if (!options->ReachableORAddresses) {
3533 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3534 new_line->key = tor_strdup("ReachableORAddresses");
3535 new_line->value = tor_strdup("*:443");
3536 options->ReachableORAddresses = new_line;
3537 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3538 "to new format: \"ReachableORAddresses *:443\"");
3543 /* Terminate Reachable*Addresses with reject *
3545 for (i=0; i<3; i++) {
3546 config_line_t **linep =
3547 (i==0) ? &options->ReachableAddresses :
3548 (i==1) ? &options->ReachableORAddresses :
3549 &options->ReachableDirAddresses;
3550 if (!*linep)
3551 continue;
3552 /* We need to end with a reject *:*, not an implicit accept *:* */
3553 for (;;) {
3554 linep = &((*linep)->next);
3555 if (!*linep) {
3556 *linep = tor_malloc_zero(sizeof(config_line_t));
3557 (*linep)->key = tor_strdup(
3558 (i==0) ? "ReachableAddresses" :
3559 (i==1) ? "ReachableORAddresses" :
3560 "ReachableDirAddresses");
3561 (*linep)->value = tor_strdup("reject *:*");
3562 break;
3567 if ((options->ReachableAddresses ||
3568 options->ReachableORAddresses ||
3569 options->ReachableDirAddresses ||
3570 options->ClientUseIPv4 == 0) &&
3571 server_mode(options))
3572 REJECT("Servers must be able to freely connect to the rest "
3573 "of the Internet, so they must not set Reachable*Addresses "
3574 "or FascistFirewall or FirewallPorts or ClientUseIPv4 0.");
3576 if (options->UseBridges &&
3577 server_mode(options))
3578 REJECT("Servers must be able to freely connect to the rest "
3579 "of the Internet, so they must not set UseBridges.");
3581 /* If both of these are set, we'll end up with funny behavior where we
3582 * demand enough entrynodes be up and running else we won't build
3583 * circuits, yet we never actually use them. */
3584 if (options->UseBridges && options->EntryNodes)
3585 REJECT("You cannot set both UseBridges and EntryNodes.");
3587 /* If we have UseBridges as 1 and UseEntryGuards as 0, we end up bypassing
3588 * the use of bridges */
3589 if (options->UseBridges && !options->UseEntryGuards)
3590 REJECT("Setting UseBridges requires also setting UseEntryGuards.");
3592 options->MaxMemInQueues =
3593 compute_real_max_mem_in_queues(options->MaxMemInQueues_raw,
3594 server_mode(options));
3595 options->MaxMemInQueues_low_threshold = (options->MaxMemInQueues / 4) * 3;
3597 if (!options->SafeLogging ||
3598 !strcasecmp(options->SafeLogging, "0")) {
3599 options->SafeLogging_ = SAFELOG_SCRUB_NONE;
3600 } else if (!strcasecmp(options->SafeLogging, "relay")) {
3601 options->SafeLogging_ = SAFELOG_SCRUB_RELAY;
3602 } else if (!strcasecmp(options->SafeLogging, "1")) {
3603 options->SafeLogging_ = SAFELOG_SCRUB_ALL;
3604 } else {
3605 tor_asprintf(msg,
3606 "Unrecognized value '%s' in SafeLogging",
3607 escaped(options->SafeLogging));
3608 return -1;
3611 if (compute_publishserverdescriptor(options) < 0) {
3612 tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
3613 return -1;
3616 if ((options->BridgeRelay
3617 || options->PublishServerDescriptor_ & BRIDGE_DIRINFO)
3618 && (options->PublishServerDescriptor_ & V3_DIRINFO)) {
3619 REJECT("Bridges are not supposed to publish router descriptors to the "
3620 "directory authorities. Please correct your "
3621 "PublishServerDescriptor line.");
3624 if (options->BridgeRelay && options->DirPort_set) {
3625 log_warn(LD_CONFIG, "Can't set a DirPort on a bridge relay; disabling "
3626 "DirPort");
3627 config_free_lines(options->DirPort_lines);
3628 options->DirPort_lines = NULL;
3629 options->DirPort_set = 0;
3632 if (server_mode(options) && options->ConnectionPadding != -1) {
3633 REJECT("Relays must use 'auto' for the ConnectionPadding setting.");
3636 if (server_mode(options) && options->ReducedConnectionPadding != 0) {
3637 REJECT("Relays cannot set ReducedConnectionPadding. ");
3640 if (options->BridgeDistribution) {
3641 if (!options->BridgeRelay) {
3642 REJECT("You set BridgeDistribution, but you didn't set BridgeRelay!");
3644 if (check_bridge_distribution_setting(options->BridgeDistribution) < 0) {
3645 REJECT("Invalid BridgeDistribution value.");
3649 if (options->MinUptimeHidServDirectoryV2 < 0) {
3650 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3651 "least 0 seconds. Changing to 0.");
3652 options->MinUptimeHidServDirectoryV2 = 0;
3655 const int min_rendpostperiod =
3656 options->TestingTorNetwork ?
3657 MIN_REND_POST_PERIOD_TESTING : MIN_REND_POST_PERIOD;
3658 if (options->RendPostPeriod < min_rendpostperiod) {
3659 log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
3660 "raising to %d seconds.", min_rendpostperiod);
3661 options->RendPostPeriod = min_rendpostperiod;
3664 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3665 log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3666 MAX_DIR_PERIOD);
3667 options->RendPostPeriod = MAX_DIR_PERIOD;
3670 /* Check the Single Onion Service options */
3671 if (options_validate_single_onion(options, msg) < 0)
3672 return -1;
3674 if (options->CircuitsAvailableTimeout > MAX_CIRCS_AVAILABLE_TIME) {
3675 // options_t is immutable for new code (the above code is older),
3676 // so just make the user fix the value themselves rather than
3677 // silently keep a shadow value lower than what they asked for.
3678 REJECT("CircuitsAvailableTimeout is too large. Max is 24 hours.");
3681 #ifdef ENABLE_TOR2WEB_MODE
3682 if (options->Tor2webMode && options->UseEntryGuards) {
3683 /* tor2web mode clients do not (and should not) use entry guards
3684 * in any meaningful way. Further, tor2web mode causes the hidden
3685 * service client code to do things which break the path bias
3686 * detector, and it's far easier to turn off entry guards (and
3687 * thus the path bias detector with it) than to figure out how to
3688 * make a piece of code which cannot possibly help tor2web mode
3689 * users compatible with tor2web mode.
3691 log_notice(LD_CONFIG,
3692 "Tor2WebMode is enabled; disabling UseEntryGuards.");
3693 options->UseEntryGuards = 0;
3695 #endif /* defined(ENABLE_TOR2WEB_MODE) */
3697 if (options->Tor2webRendezvousPoints && !options->Tor2webMode) {
3698 REJECT("Tor2webRendezvousPoints cannot be set without Tor2webMode.");
3701 if (options->EntryNodes && !options->UseEntryGuards) {
3702 REJECT("If EntryNodes is set, UseEntryGuards must be enabled.");
3705 if (!(options->UseEntryGuards) &&
3706 (options->RendConfigLines != NULL) &&
3707 !rend_service_allow_non_anonymous_connection(options)) {
3708 log_warn(LD_CONFIG,
3709 "UseEntryGuards is disabled, but you have configured one or more "
3710 "hidden services on this Tor instance. Your hidden services "
3711 "will be very easy to locate using a well-known attack -- see "
3712 "http://freehaven.net/anonbib/#hs-attack06 for details.");
3715 if (options->EntryNodes &&
3716 routerset_is_list(options->EntryNodes) &&
3717 (routerset_len(options->EntryNodes) == 1) &&
3718 (options->RendConfigLines != NULL)) {
3719 tor_asprintf(msg,
3720 "You have one single EntryNodes and at least one hidden service "
3721 "configured. This is bad because it's very easy to locate your "
3722 "entry guard which can then lead to the deanonymization of your "
3723 "hidden service -- for more details, see "
3724 "https://trac.torproject.org/projects/tor/ticket/14917. "
3725 "For this reason, the use of one EntryNodes with an hidden "
3726 "service is prohibited until a better solution is found.");
3727 return -1;
3730 /* Inform the hidden service operator that pinning EntryNodes can possibly
3731 * be harmful for the service anonymity. */
3732 if (options->EntryNodes &&
3733 routerset_is_list(options->EntryNodes) &&
3734 (options->RendConfigLines != NULL)) {
3735 log_warn(LD_CONFIG,
3736 "EntryNodes is set with multiple entries and at least one "
3737 "hidden service is configured. Pinning entry nodes can possibly "
3738 "be harmful to the service anonymity. Because of this, we "
3739 "recommend you either don't do that or make sure you know what "
3740 "you are doing. For more details, please look at "
3741 "https://trac.torproject.org/projects/tor/ticket/21155.");
3744 /* Single Onion Services: non-anonymous hidden services */
3745 if (rend_service_non_anonymous_mode_enabled(options)) {
3746 log_warn(LD_CONFIG,
3747 "HiddenServiceNonAnonymousMode is set. Every hidden service on "
3748 "this tor instance is NON-ANONYMOUS. If "
3749 "the HiddenServiceNonAnonymousMode option is changed, Tor will "
3750 "refuse to launch hidden services from the same directories, to "
3751 "protect your anonymity against config errors. This setting is "
3752 "for experimental use only.");
3755 if (!options->LearnCircuitBuildTimeout && options->CircuitBuildTimeout &&
3756 options->CircuitBuildTimeout < RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT) {
3757 log_warn(LD_CONFIG,
3758 "CircuitBuildTimeout is shorter (%d seconds) than the recommended "
3759 "minimum (%d seconds), and LearnCircuitBuildTimeout is disabled. "
3760 "If tor isn't working, raise this value or enable "
3761 "LearnCircuitBuildTimeout.",
3762 options->CircuitBuildTimeout,
3763 RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT );
3764 } else if (!options->LearnCircuitBuildTimeout &&
3765 !options->CircuitBuildTimeout) {
3766 int severity = LOG_NOTICE;
3767 /* Be a little quieter if we've deliberately disabled
3768 * LearnCircuitBuildTimeout. */
3769 if (circuit_build_times_disabled_(options, 1)) {
3770 severity = LOG_INFO;
3772 log_fn(severity, LD_CONFIG, "You disabled LearnCircuitBuildTimeout, but "
3773 "didn't specify a CircuitBuildTimeout. I'll pick a plausible "
3774 "default.");
3777 if (options->PathBiasNoticeRate > 1.0) {
3778 tor_asprintf(msg,
3779 "PathBiasNoticeRate is too high. "
3780 "It must be between 0 and 1.0");
3781 return -1;
3783 if (options->PathBiasWarnRate > 1.0) {
3784 tor_asprintf(msg,
3785 "PathBiasWarnRate is too high. "
3786 "It must be between 0 and 1.0");
3787 return -1;
3789 if (options->PathBiasExtremeRate > 1.0) {
3790 tor_asprintf(msg,
3791 "PathBiasExtremeRate is too high. "
3792 "It must be between 0 and 1.0");
3793 return -1;
3795 if (options->PathBiasNoticeUseRate > 1.0) {
3796 tor_asprintf(msg,
3797 "PathBiasNoticeUseRate is too high. "
3798 "It must be between 0 and 1.0");
3799 return -1;
3801 if (options->PathBiasExtremeUseRate > 1.0) {
3802 tor_asprintf(msg,
3803 "PathBiasExtremeUseRate is too high. "
3804 "It must be between 0 and 1.0");
3805 return -1;
3808 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3809 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3810 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3811 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3814 if (options->MaxCircuitDirtiness > MAX_MAX_CIRCUIT_DIRTINESS) {
3815 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too high; "
3816 "setting to %d days.", MAX_MAX_CIRCUIT_DIRTINESS/86400);
3817 options->MaxCircuitDirtiness = MAX_MAX_CIRCUIT_DIRTINESS;
3820 if (options->CircuitStreamTimeout &&
3821 options->CircuitStreamTimeout < MIN_CIRCUIT_STREAM_TIMEOUT) {
3822 log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
3823 "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
3824 options->CircuitStreamTimeout = MIN_CIRCUIT_STREAM_TIMEOUT;
3827 if (options->HeartbeatPeriod &&
3828 options->HeartbeatPeriod < MIN_HEARTBEAT_PERIOD) {
3829 log_warn(LD_CONFIG, "HeartbeatPeriod option is too short; "
3830 "raising to %d seconds.", MIN_HEARTBEAT_PERIOD);
3831 options->HeartbeatPeriod = MIN_HEARTBEAT_PERIOD;
3834 if (options->KeepalivePeriod < 1)
3835 REJECT("KeepalivePeriod option must be positive.");
3837 if (options->PortForwarding && options->Sandbox) {
3838 REJECT("PortForwarding is not compatible with Sandbox; at most one can "
3839 "be set");
3841 if (options->PortForwarding && options->NoExec) {
3842 COMPLAIN("Both PortForwarding and NoExec are set; PortForwarding will "
3843 "be ignored.");
3846 if (ensure_bandwidth_cap(&options->BandwidthRate,
3847 "BandwidthRate", msg) < 0)
3848 return -1;
3849 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3850 "BandwidthBurst", msg) < 0)
3851 return -1;
3852 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3853 "MaxAdvertisedBandwidth", msg) < 0)
3854 return -1;
3855 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3856 "RelayBandwidthRate", msg) < 0)
3857 return -1;
3858 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3859 "RelayBandwidthBurst", msg) < 0)
3860 return -1;
3861 if (ensure_bandwidth_cap(&options->PerConnBWRate,
3862 "PerConnBWRate", msg) < 0)
3863 return -1;
3864 if (ensure_bandwidth_cap(&options->PerConnBWBurst,
3865 "PerConnBWBurst", msg) < 0)
3866 return -1;
3867 if (ensure_bandwidth_cap(&options->AuthDirFastGuarantee,
3868 "AuthDirFastGuarantee", msg) < 0)
3869 return -1;
3870 if (ensure_bandwidth_cap(&options->AuthDirGuardBWGuarantee,
3871 "AuthDirGuardBWGuarantee", msg) < 0)
3872 return -1;
3874 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3875 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3876 if (options->RelayBandwidthBurst && !options->RelayBandwidthRate)
3877 options->RelayBandwidthRate = options->RelayBandwidthBurst;
3879 if (server_mode(options)) {
3880 const unsigned required_min_bw =
3881 public_server_mode(options) ?
3882 RELAY_REQUIRED_MIN_BANDWIDTH : BRIDGE_REQUIRED_MIN_BANDWIDTH;
3883 const char * const optbridge =
3884 public_server_mode(options) ? "" : "bridge ";
3885 if (options->BandwidthRate < required_min_bw) {
3886 tor_asprintf(msg,
3887 "BandwidthRate is set to %d bytes/second. "
3888 "For %sservers, it must be at least %u.",
3889 (int)options->BandwidthRate, optbridge,
3890 required_min_bw);
3891 return -1;
3892 } else if (options->MaxAdvertisedBandwidth <
3893 required_min_bw/2) {
3894 tor_asprintf(msg,
3895 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3896 "For %sservers, it must be at least %u.",
3897 (int)options->MaxAdvertisedBandwidth, optbridge,
3898 required_min_bw/2);
3899 return -1;
3901 if (options->RelayBandwidthRate &&
3902 options->RelayBandwidthRate < required_min_bw) {
3903 tor_asprintf(msg,
3904 "RelayBandwidthRate is set to %d bytes/second. "
3905 "For %sservers, it must be at least %u.",
3906 (int)options->RelayBandwidthRate, optbridge,
3907 required_min_bw);
3908 return -1;
3912 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3913 REJECT("RelayBandwidthBurst must be at least equal "
3914 "to RelayBandwidthRate.");
3916 if (options->BandwidthRate > options->BandwidthBurst)
3917 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3919 /* if they set relaybandwidth* really high but left bandwidth*
3920 * at the default, raise the defaults. */
3921 if (options->RelayBandwidthRate > options->BandwidthRate)
3922 options->BandwidthRate = options->RelayBandwidthRate;
3923 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3924 options->BandwidthBurst = options->RelayBandwidthBurst;
3926 if (accounting_parse_options(options, 1)<0)
3927 REJECT("Failed to parse accounting options. See logs for details.");
3929 if (options->AccountingMax) {
3930 if (options->RendConfigLines && server_mode(options)) {
3931 log_warn(LD_CONFIG, "Using accounting with a hidden service and an "
3932 "ORPort is risky: your hidden service(s) and your public "
3933 "address will all turn off at the same time, which may alert "
3934 "observers that they are being run by the same party.");
3935 } else if (config_count_key(options->RendConfigLines,
3936 "HiddenServiceDir") > 1) {
3937 log_warn(LD_CONFIG, "Using accounting with multiple hidden services is "
3938 "risky: they will all turn off at the same time, which may "
3939 "alert observers that they are being run by the same party.");
3943 options->AccountingRule = ACCT_MAX;
3944 if (options->AccountingRule_option) {
3945 if (!strcmp(options->AccountingRule_option, "sum"))
3946 options->AccountingRule = ACCT_SUM;
3947 else if (!strcmp(options->AccountingRule_option, "max"))
3948 options->AccountingRule = ACCT_MAX;
3949 else if (!strcmp(options->AccountingRule_option, "in"))
3950 options->AccountingRule = ACCT_IN;
3951 else if (!strcmp(options->AccountingRule_option, "out"))
3952 options->AccountingRule = ACCT_OUT;
3953 else
3954 REJECT("AccountingRule must be 'sum', 'max', 'in', or 'out'");
3957 if (options->DirPort_set && !options->DirCache) {
3958 REJECT("DirPort configured but DirCache disabled. DirPort requires "
3959 "DirCache.");
3962 if (options->BridgeRelay && !options->DirCache) {
3963 REJECT("We're a bridge but DirCache is disabled. BridgeRelay requires "
3964 "DirCache.");
3967 if (server_mode(options)) {
3968 char *dircache_msg = NULL;
3969 if (have_enough_mem_for_dircache(options, 0, &dircache_msg)) {
3970 log_warn(LD_CONFIG, "%s", dircache_msg);
3971 tor_free(dircache_msg);
3975 if (options->HTTPProxy) { /* parse it now */
3976 if (tor_addr_port_lookup(options->HTTPProxy,
3977 &options->HTTPProxyAddr, &options->HTTPProxyPort) < 0)
3978 REJECT("HTTPProxy failed to parse or resolve. Please fix.");
3979 if (options->HTTPProxyPort == 0) { /* give it a default */
3980 options->HTTPProxyPort = 80;
3984 if (options->HTTPProxyAuthenticator) {
3985 if (strlen(options->HTTPProxyAuthenticator) >= 512)
3986 REJECT("HTTPProxyAuthenticator is too long (>= 512 chars).");
3989 if (options->HTTPSProxy) { /* parse it now */
3990 if (tor_addr_port_lookup(options->HTTPSProxy,
3991 &options->HTTPSProxyAddr, &options->HTTPSProxyPort) <0)
3992 REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
3993 if (options->HTTPSProxyPort == 0) { /* give it a default */
3994 options->HTTPSProxyPort = 443;
3998 if (options->HTTPSProxyAuthenticator) {
3999 if (strlen(options->HTTPSProxyAuthenticator) >= 512)
4000 REJECT("HTTPSProxyAuthenticator is too long (>= 512 chars).");
4003 if (options->Socks4Proxy) { /* parse it now */
4004 if (tor_addr_port_lookup(options->Socks4Proxy,
4005 &options->Socks4ProxyAddr,
4006 &options->Socks4ProxyPort) <0)
4007 REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
4008 if (options->Socks4ProxyPort == 0) { /* give it a default */
4009 options->Socks4ProxyPort = 1080;
4013 if (options->Socks5Proxy) { /* parse it now */
4014 if (tor_addr_port_lookup(options->Socks5Proxy,
4015 &options->Socks5ProxyAddr,
4016 &options->Socks5ProxyPort) <0)
4017 REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
4018 if (options->Socks5ProxyPort == 0) { /* give it a default */
4019 options->Socks5ProxyPort = 1080;
4023 /* Check if more than one exclusive proxy type has been enabled. */
4024 if (!!options->Socks4Proxy + !!options->Socks5Proxy +
4025 !!options->HTTPSProxy > 1)
4026 REJECT("You have configured more than one proxy type. "
4027 "(Socks4Proxy|Socks5Proxy|HTTPSProxy)");
4029 /* Check if the proxies will give surprising behavior. */
4030 if (options->HTTPProxy && !(options->Socks4Proxy ||
4031 options->Socks5Proxy ||
4032 options->HTTPSProxy)) {
4033 log_warn(LD_CONFIG, "HTTPProxy configured, but no SOCKS proxy or "
4034 "HTTPS proxy configured. Watch out: this configuration will "
4035 "proxy unencrypted directory connections only.");
4038 if (options->Socks5ProxyUsername) {
4039 size_t len;
4041 len = strlen(options->Socks5ProxyUsername);
4042 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
4043 REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
4045 if (!options->Socks5ProxyPassword)
4046 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
4048 len = strlen(options->Socks5ProxyPassword);
4049 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
4050 REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
4051 } else if (options->Socks5ProxyPassword)
4052 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
4054 if (options->HashedControlPassword) {
4055 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
4056 if (!sl) {
4057 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
4058 } else {
4059 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
4060 smartlist_free(sl);
4064 if (options->HashedControlSessionPassword) {
4065 smartlist_t *sl = decode_hashed_passwords(
4066 options->HashedControlSessionPassword);
4067 if (!sl) {
4068 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
4069 } else {
4070 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
4071 smartlist_free(sl);
4075 if (options->OwningControllerProcess) {
4076 const char *validate_pspec_msg = NULL;
4077 if (tor_validate_process_specifier(options->OwningControllerProcess,
4078 &validate_pspec_msg)) {
4079 tor_asprintf(msg, "Bad OwningControllerProcess: %s",
4080 validate_pspec_msg);
4081 return -1;
4085 if ((options->ControlPort_set || world_writable_control_socket) &&
4086 !options->HashedControlPassword &&
4087 !options->HashedControlSessionPassword &&
4088 !options->CookieAuthentication) {
4089 log_warn(LD_CONFIG, "Control%s is %s, but no authentication method "
4090 "has been configured. This means that any program on your "
4091 "computer can reconfigure your Tor. That's bad! You should "
4092 "upgrade your Tor controller as soon as possible.",
4093 options->ControlPort_set ? "Port" : "Socket",
4094 options->ControlPort_set ? "open" : "world writable");
4097 if (options->CookieAuthFileGroupReadable && !options->CookieAuthFile) {
4098 log_warn(LD_CONFIG, "CookieAuthFileGroupReadable is set, but will have "
4099 "no effect: you must specify an explicit CookieAuthFile to "
4100 "have it group-readable.");
4103 if (options->MyFamily_lines && options->BridgeRelay) {
4104 log_warn(LD_CONFIG, "Listing a family for a bridge relay is not "
4105 "supported: it can reveal bridge fingerprints to censors. "
4106 "You should also make sure you aren't listing this bridge's "
4107 "fingerprint in any other MyFamily.");
4109 if (normalize_nickname_list(&options->MyFamily,
4110 options->MyFamily_lines, "MyFamily", msg))
4111 return -1;
4112 for (cl = options->NodeFamilies; cl; cl = cl->next) {
4113 routerset_t *rs = routerset_new();
4114 if (routerset_parse(rs, cl->value, cl->key)) {
4115 routerset_free(rs);
4116 return -1;
4118 routerset_free(rs);
4121 if (validate_addr_policies(options, msg) < 0)
4122 return -1;
4124 /* If FallbackDir is set, we don't UseDefaultFallbackDirs */
4125 if (options->UseDefaultFallbackDirs && options->FallbackDir) {
4126 log_info(LD_CONFIG, "You have set UseDefaultFallbackDirs 1 and "
4127 "FallbackDir(s). Ignoring UseDefaultFallbackDirs, and "
4128 "using the FallbackDir(s) you have set.");
4131 if (validate_dir_servers(options, old_options) < 0)
4132 REJECT("Directory authority/fallback line did not parse. See logs "
4133 "for details.");
4135 if (options->UseBridges && !options->Bridges)
4136 REJECT("If you set UseBridges, you must specify at least one bridge.");
4138 for (cl = options->Bridges; cl; cl = cl->next) {
4139 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
4140 if (!bridge_line)
4141 REJECT("Bridge line did not parse. See logs for details.");
4142 bridge_line_free(bridge_line);
4145 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
4146 if (parse_transport_line(options, cl->value, 1, 0) < 0)
4147 REJECT("Invalid client transport line. See logs for details.");
4150 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
4151 if (parse_transport_line(options, cl->value, 1, 1) < 0)
4152 REJECT("Invalid server transport line. See logs for details.");
4155 if (options->ServerTransportPlugin && !server_mode(options)) {
4156 log_notice(LD_GENERAL, "Tor is not configured as a relay but you specified"
4157 " a ServerTransportPlugin line (%s). The ServerTransportPlugin "
4158 "line will be ignored.",
4159 escaped(options->ServerTransportPlugin->value));
4162 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
4163 /** If get_bindaddr_from_transport_listen_line() fails with
4164 'transport' being NULL, it means that something went wrong
4165 while parsing the ServerTransportListenAddr line. */
4166 char *bindaddr = get_bindaddr_from_transport_listen_line(cl->value, NULL);
4167 if (!bindaddr)
4168 REJECT("ServerTransportListenAddr did not parse. See logs for details.");
4169 tor_free(bindaddr);
4172 if (options->ServerTransportListenAddr && !options->ServerTransportPlugin) {
4173 log_notice(LD_GENERAL, "You need at least a single managed-proxy to "
4174 "specify a transport listen address. The "
4175 "ServerTransportListenAddr line will be ignored.");
4178 for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
4179 /** If get_options_from_transport_options_line() fails with
4180 'transport' being NULL, it means that something went wrong
4181 while parsing the ServerTransportOptions line. */
4182 smartlist_t *options_sl =
4183 get_options_from_transport_options_line(cl->value, NULL);
4184 if (!options_sl)
4185 REJECT("ServerTransportOptions did not parse. See logs for details.");
4187 SMARTLIST_FOREACH(options_sl, char *, cp, tor_free(cp));
4188 smartlist_free(options_sl);
4191 if (options->ConstrainedSockets) {
4192 /* If the user wants to constrain socket buffer use, make sure the desired
4193 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
4194 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
4195 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
4196 options->ConstrainedSockSize % 1024) {
4197 tor_asprintf(msg,
4198 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
4199 "in 1024 byte increments.",
4200 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
4201 return -1;
4203 if (options->DirPort_set) {
4204 /* Providing cached directory entries while system TCP buffers are scarce
4205 * will exacerbate the socket errors. Suggest that this be disabled. */
4206 COMPLAIN("You have requested constrained socket buffers while also "
4207 "serving directory entries via DirPort. It is strongly "
4208 "suggested that you disable serving directory requests when "
4209 "system TCP buffer resources are scarce.");
4213 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
4214 options->V3AuthVotingInterval/2) {
4216 This doesn't work, but it seems like it should:
4217 what code is preventing the interval being less than twice the lead-up?
4218 if (options->TestingTorNetwork) {
4219 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
4220 options->V3AuthVotingInterval) {
4221 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than "
4222 "V3AuthVotingInterval");
4223 } else {
4224 COMPLAIN("V3AuthVoteDelay plus V3AuthDistDelay is more than half "
4225 "V3AuthVotingInterval. This may lead to "
4226 "consensus instability, particularly if clocks drift.");
4228 } else {
4230 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
4231 "V3AuthVotingInterval");
4237 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS) {
4238 if (options->TestingTorNetwork) {
4239 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS_TESTING) {
4240 REJECT("V3AuthVoteDelay is way too low.");
4241 } else {
4242 COMPLAIN("V3AuthVoteDelay is very low. "
4243 "This may lead to failure to vote for a consensus.");
4245 } else {
4246 REJECT("V3AuthVoteDelay is way too low.");
4250 if (options->V3AuthDistDelay < MIN_DIST_SECONDS) {
4251 if (options->TestingTorNetwork) {
4252 if (options->V3AuthDistDelay < MIN_DIST_SECONDS_TESTING) {
4253 REJECT("V3AuthDistDelay is way too low.");
4254 } else {
4255 COMPLAIN("V3AuthDistDelay is very low. "
4256 "This may lead to missing votes in a consensus.");
4258 } else {
4259 REJECT("V3AuthDistDelay is way too low.");
4263 if (options->V3AuthNIntervalsValid < 2)
4264 REJECT("V3AuthNIntervalsValid must be at least 2.");
4266 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
4267 if (options->TestingTorNetwork) {
4268 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL_TESTING) {
4269 REJECT("V3AuthVotingInterval is insanely low.");
4270 } else {
4271 COMPLAIN("V3AuthVotingInterval is very low. "
4272 "This may lead to failure to synchronise for a consensus.");
4274 } else {
4275 REJECT("V3AuthVotingInterval is insanely low.");
4277 } else if (options->V3AuthVotingInterval > 24*60*60) {
4278 REJECT("V3AuthVotingInterval is insanely high.");
4279 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
4280 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
4283 if (hs_config_service_all(options, 1) < 0)
4284 REJECT("Failed to configure rendezvous options. See logs for details.");
4286 /* Parse client-side authorization for hidden services. */
4287 if (rend_parse_service_authorization(options, 1) < 0)
4288 REJECT("Failed to configure client authorization for hidden services. "
4289 "See logs for details.");
4291 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv4,
4292 AF_INET, 1, msg)<0)
4293 return -1;
4294 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv6,
4295 AF_INET6, 1, msg)<0)
4296 return -1;
4298 if (options->TestingTorNetwork &&
4299 !(options->DirAuthorities ||
4300 (options->AlternateDirAuthority &&
4301 options->AlternateBridgeAuthority))) {
4302 REJECT("TestingTorNetwork may only be configured in combination with "
4303 "a non-default set of DirAuthority or both of "
4304 "AlternateDirAuthority and AlternateBridgeAuthority configured.");
4307 #define CHECK_DEFAULT(arg) \
4308 STMT_BEGIN \
4309 if (!options->TestingTorNetwork && \
4310 !options->UsingTestNetworkDefaults_ && \
4311 !config_is_same(&options_format,options, \
4312 default_options,#arg)) { \
4313 REJECT(#arg " may only be changed in testing Tor " \
4314 "networks!"); \
4315 } STMT_END
4316 CHECK_DEFAULT(TestingV3AuthInitialVotingInterval);
4317 CHECK_DEFAULT(TestingV3AuthInitialVoteDelay);
4318 CHECK_DEFAULT(TestingV3AuthInitialDistDelay);
4319 CHECK_DEFAULT(TestingV3AuthVotingStartOffset);
4320 CHECK_DEFAULT(TestingAuthDirTimeToLearnReachability);
4321 CHECK_DEFAULT(TestingEstimatedDescriptorPropagationTime);
4322 CHECK_DEFAULT(TestingServerDownloadSchedule);
4323 CHECK_DEFAULT(TestingClientDownloadSchedule);
4324 CHECK_DEFAULT(TestingServerConsensusDownloadSchedule);
4325 CHECK_DEFAULT(TestingClientConsensusDownloadSchedule);
4326 CHECK_DEFAULT(TestingBridgeDownloadSchedule);
4327 CHECK_DEFAULT(TestingBridgeBootstrapDownloadSchedule);
4328 CHECK_DEFAULT(TestingClientMaxIntervalWithoutRequest);
4329 CHECK_DEFAULT(TestingDirConnectionMaxStall);
4330 CHECK_DEFAULT(TestingConsensusMaxDownloadTries);
4331 CHECK_DEFAULT(TestingDescriptorMaxDownloadTries);
4332 CHECK_DEFAULT(TestingMicrodescMaxDownloadTries);
4333 CHECK_DEFAULT(TestingCertMaxDownloadTries);
4334 CHECK_DEFAULT(TestingAuthKeyLifetime);
4335 CHECK_DEFAULT(TestingLinkCertLifetime);
4336 CHECK_DEFAULT(TestingSigningKeySlop);
4337 CHECK_DEFAULT(TestingAuthKeySlop);
4338 CHECK_DEFAULT(TestingLinkKeySlop);
4339 #undef CHECK_DEFAULT
4341 if (!options->ClientDNSRejectInternalAddresses &&
4342 !(options->DirAuthorities ||
4343 (options->AlternateDirAuthority && options->AlternateBridgeAuthority)))
4344 REJECT("ClientDNSRejectInternalAddresses used for default network.");
4345 if (options->SigningKeyLifetime < options->TestingSigningKeySlop*2)
4346 REJECT("SigningKeyLifetime is too short.");
4347 if (options->TestingLinkCertLifetime < options->TestingAuthKeySlop*2)
4348 REJECT("LinkCertLifetime is too short.");
4349 if (options->TestingAuthKeyLifetime < options->TestingLinkKeySlop*2)
4350 REJECT("TestingAuthKeyLifetime is too short.");
4352 if (options->TestingV3AuthInitialVotingInterval
4353 < MIN_VOTE_INTERVAL_TESTING_INITIAL) {
4354 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
4355 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
4356 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
4357 "30 minutes.");
4360 if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS_TESTING) {
4361 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
4364 if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS_TESTING) {
4365 REJECT("TestingV3AuthInitialDistDelay is way too low.");
4368 if (options->TestingV3AuthInitialVoteDelay +
4369 options->TestingV3AuthInitialDistDelay >=
4370 options->TestingV3AuthInitialVotingInterval) {
4371 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
4372 "must be less than TestingV3AuthInitialVotingInterval");
4375 if (options->TestingV3AuthVotingStartOffset >
4376 MIN(options->TestingV3AuthInitialVotingInterval,
4377 options->V3AuthVotingInterval)) {
4378 REJECT("TestingV3AuthVotingStartOffset is higher than the voting "
4379 "interval.");
4380 } else if (options->TestingV3AuthVotingStartOffset < 0) {
4381 REJECT("TestingV3AuthVotingStartOffset must be non-negative.");
4384 if (options->TestingAuthDirTimeToLearnReachability < 0) {
4385 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
4386 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
4387 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
4390 if (options->TestingEstimatedDescriptorPropagationTime < 0) {
4391 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
4392 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
4393 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
4396 if (options->TestingClientMaxIntervalWithoutRequest < 1) {
4397 REJECT("TestingClientMaxIntervalWithoutRequest is way too low.");
4398 } else if (options->TestingClientMaxIntervalWithoutRequest > 3600) {
4399 COMPLAIN("TestingClientMaxIntervalWithoutRequest is insanely high.");
4402 if (options->TestingDirConnectionMaxStall < 5) {
4403 REJECT("TestingDirConnectionMaxStall is way too low.");
4404 } else if (options->TestingDirConnectionMaxStall > 3600) {
4405 COMPLAIN("TestingDirConnectionMaxStall is insanely high.");
4408 if (options->TestingConsensusMaxDownloadTries < 2) {
4409 REJECT("TestingConsensusMaxDownloadTries must be greater than 2.");
4410 } else if (options->TestingConsensusMaxDownloadTries > 800) {
4411 COMPLAIN("TestingConsensusMaxDownloadTries is insanely high.");
4414 if (options->ClientBootstrapConsensusMaxDownloadTries < 2) {
4415 REJECT("ClientBootstrapConsensusMaxDownloadTries must be greater "
4416 "than 2."
4418 } else if (options->ClientBootstrapConsensusMaxDownloadTries > 800) {
4419 COMPLAIN("ClientBootstrapConsensusMaxDownloadTries is insanely "
4420 "high.");
4423 if (options->ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries
4424 < 2) {
4425 REJECT("ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries must "
4426 "be greater than 2."
4428 } else if (
4429 options->ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries
4430 > 800) {
4431 COMPLAIN("ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries is "
4432 "insanely high.");
4435 if (options->ClientBootstrapConsensusMaxInProgressTries < 1) {
4436 REJECT("ClientBootstrapConsensusMaxInProgressTries must be greater "
4437 "than 0.");
4438 } else if (options->ClientBootstrapConsensusMaxInProgressTries
4439 > 100) {
4440 COMPLAIN("ClientBootstrapConsensusMaxInProgressTries is insanely "
4441 "high.");
4444 if (options->TestingDescriptorMaxDownloadTries < 2) {
4445 REJECT("TestingDescriptorMaxDownloadTries must be greater than 1.");
4446 } else if (options->TestingDescriptorMaxDownloadTries > 800) {
4447 COMPLAIN("TestingDescriptorMaxDownloadTries is insanely high.");
4450 if (options->TestingMicrodescMaxDownloadTries < 2) {
4451 REJECT("TestingMicrodescMaxDownloadTries must be greater than 1.");
4452 } else if (options->TestingMicrodescMaxDownloadTries > 800) {
4453 COMPLAIN("TestingMicrodescMaxDownloadTries is insanely high.");
4456 if (options->TestingCertMaxDownloadTries < 2) {
4457 REJECT("TestingCertMaxDownloadTries must be greater than 1.");
4458 } else if (options->TestingCertMaxDownloadTries > 800) {
4459 COMPLAIN("TestingCertMaxDownloadTries is insanely high.");
4462 if (options->TestingEnableConnBwEvent &&
4463 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4464 REJECT("TestingEnableConnBwEvent may only be changed in testing "
4465 "Tor networks!");
4468 if (options->TestingEnableCellStatsEvent &&
4469 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4470 REJECT("TestingEnableCellStatsEvent may only be changed in testing "
4471 "Tor networks!");
4474 if (options->TestingEnableTbEmptyEvent &&
4475 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4476 REJECT("TestingEnableTbEmptyEvent may only be changed in testing "
4477 "Tor networks!");
4480 if (options->TestingTorNetwork) {
4481 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
4482 "almost unusable in the public Tor network, and is "
4483 "therefore only advised if you are building a "
4484 "testing Tor network!");
4487 if (options->AccelName && !options->HardwareAccel)
4488 options->HardwareAccel = 1;
4489 if (options->AccelDir && !options->AccelName)
4490 REJECT("Can't use hardware crypto accelerator dir without engine name.");
4492 if (options->PublishServerDescriptor)
4493 SMARTLIST_FOREACH(options->PublishServerDescriptor, const char *, pubdes, {
4494 if (!strcmp(pubdes, "1") || !strcmp(pubdes, "0"))
4495 if (smartlist_len(options->PublishServerDescriptor) > 1) {
4496 COMPLAIN("You have passed a list of multiple arguments to the "
4497 "PublishServerDescriptor option that includes 0 or 1. "
4498 "0 or 1 should only be used as the sole argument. "
4499 "This configuration will be rejected in a future release.");
4500 break;
4504 if (options->BridgeRelay == 1 && ! options->ORPort_set)
4505 REJECT("BridgeRelay is 1, ORPort is not set. This is an invalid "
4506 "combination.");
4508 if (options_validate_scheduler(options, msg) < 0) {
4509 return -1;
4512 return 0;
4515 #undef REJECT
4516 #undef COMPLAIN
4518 /* Given the value that the user has set for MaxMemInQueues, compute the
4519 * actual maximum value. We clip this value if it's too low, and autodetect
4520 * it if it's set to 0. */
4521 static uint64_t
4522 compute_real_max_mem_in_queues(const uint64_t val, int log_guess)
4524 uint64_t result;
4526 if (val == 0) {
4527 #define ONE_GIGABYTE (U64_LITERAL(1) << 30)
4528 #define ONE_MEGABYTE (U64_LITERAL(1) << 20)
4529 #if SIZEOF_VOID_P >= 8
4530 #define MAX_DEFAULT_MAXMEM (8*ONE_GIGABYTE)
4531 #else
4532 #define MAX_DEFAULT_MAXMEM (2*ONE_GIGABYTE)
4533 #endif
4534 /* The user didn't pick a memory limit. Choose a very large one
4535 * that is still smaller than the system memory */
4536 static int notice_sent = 0;
4537 size_t ram = 0;
4538 if (get_total_system_memory(&ram) < 0) {
4539 /* We couldn't determine our total system memory! */
4540 #if SIZEOF_VOID_P >= 8
4541 /* 64-bit system. Let's hope for 8 GB. */
4542 result = 8 * ONE_GIGABYTE;
4543 #else
4544 /* (presumably) 32-bit system. Let's hope for 1 GB. */
4545 result = ONE_GIGABYTE;
4546 #endif /* SIZEOF_VOID_P >= 8 */
4547 } else {
4548 /* We detected it, so let's pick 3/4 of the total RAM as our limit. */
4549 const uint64_t avail = (ram / 4) * 3;
4551 /* Make sure it's in range from 0.25 GB to 8 GB. */
4552 if (avail > MAX_DEFAULT_MAXMEM) {
4553 /* If you want to use more than this much RAM, you need to configure
4554 it yourself */
4555 result = MAX_DEFAULT_MAXMEM;
4556 } else if (avail < ONE_GIGABYTE / 4) {
4557 result = ONE_GIGABYTE / 4;
4558 } else {
4559 result = avail;
4562 if (log_guess && ! notice_sent) {
4563 log_notice(LD_CONFIG, "%sMaxMemInQueues is set to "U64_FORMAT" MB. "
4564 "You can override this by setting MaxMemInQueues by hand.",
4565 ram ? "Based on detected system memory, " : "",
4566 U64_PRINTF_ARG(result / ONE_MEGABYTE));
4567 notice_sent = 1;
4569 return result;
4570 } else if (val < ONE_GIGABYTE / 4) {
4571 log_warn(LD_CONFIG, "MaxMemInQueues must be at least 256 MB for now. "
4572 "Ideally, have it as large as you can afford.");
4573 return ONE_GIGABYTE / 4;
4574 } else {
4575 /* The value was fine all along */
4576 return val;
4580 /* If we have less than 300 MB suggest disabling dircache */
4581 #define DIRCACHE_MIN_MEM_MB 300
4582 #define DIRCACHE_MIN_MEM_BYTES (DIRCACHE_MIN_MEM_MB*ONE_MEGABYTE)
4583 #define STRINGIFY(val) #val
4585 /** Create a warning message for emitting if we are a dircache but may not have
4586 * enough system memory, or if we are not a dircache but probably should be.
4587 * Return -1 when a message is returned in *msg*, else return 0. */
4588 STATIC int
4589 have_enough_mem_for_dircache(const or_options_t *options, size_t total_mem,
4590 char **msg)
4592 *msg = NULL;
4593 /* XXX We should possibly be looking at MaxMemInQueues here
4594 * unconditionally. Or we should believe total_mem unconditionally. */
4595 if (total_mem == 0) {
4596 if (get_total_system_memory(&total_mem) < 0) {
4597 total_mem = options->MaxMemInQueues >= SIZE_MAX ?
4598 SIZE_MAX : (size_t)options->MaxMemInQueues;
4601 if (options->DirCache) {
4602 if (total_mem < DIRCACHE_MIN_MEM_BYTES) {
4603 if (options->BridgeRelay) {
4604 *msg = tor_strdup("Running a Bridge with less than "
4605 STRINGIFY(DIRCACHE_MIN_MEM_MB) " MB of memory is not "
4606 "recommended.");
4607 } else {
4608 *msg = tor_strdup("Being a directory cache (default) with less than "
4609 STRINGIFY(DIRCACHE_MIN_MEM_MB) " MB of memory is not "
4610 "recommended and may consume most of the available "
4611 "resources, consider disabling this functionality by "
4612 "setting the DirCache option to 0.");
4615 } else {
4616 if (total_mem >= DIRCACHE_MIN_MEM_BYTES) {
4617 *msg = tor_strdup("DirCache is disabled and we are configured as a "
4618 "relay. This may disqualify us from becoming a guard in the "
4619 "future.");
4622 return *msg == NULL ? 0 : -1;
4624 #undef STRINGIFY
4626 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
4627 * equal strings. */
4628 static int
4629 opt_streq(const char *s1, const char *s2)
4631 return 0 == strcmp_opt(s1, s2);
4634 /** Check if any of the previous options have changed but aren't allowed to. */
4635 static int
4636 options_transition_allowed(const or_options_t *old,
4637 const or_options_t *new_val,
4638 char **msg)
4640 if (!old)
4641 return 0;
4643 if (!opt_streq(old->PidFile, new_val->PidFile)) {
4644 *msg = tor_strdup("PidFile is not allowed to change.");
4645 return -1;
4648 if (old->RunAsDaemon != new_val->RunAsDaemon) {
4649 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
4650 "is not allowed.");
4651 return -1;
4654 if (old->Sandbox != new_val->Sandbox) {
4655 *msg = tor_strdup("While Tor is running, changing Sandbox "
4656 "is not allowed.");
4657 return -1;
4660 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
4661 tor_asprintf(msg,
4662 "While Tor is running, changing DataDirectory "
4663 "(\"%s\"->\"%s\") is not allowed.",
4664 old->DataDirectory, new_val->DataDirectory);
4665 return -1;
4668 if (!opt_streq(old->KeyDirectory, new_val->KeyDirectory)) {
4669 tor_asprintf(msg,
4670 "While Tor is running, changing KeyDirectory "
4671 "(\"%s\"->\"%s\") is not allowed.",
4672 old->KeyDirectory, new_val->KeyDirectory);
4673 return -1;
4676 if (!opt_streq(old->CacheDirectory, new_val->CacheDirectory)) {
4677 tor_asprintf(msg,
4678 "While Tor is running, changing CacheDirectory "
4679 "(\"%s\"->\"%s\") is not allowed.",
4680 old->CacheDirectory, new_val->CacheDirectory);
4681 return -1;
4684 if (!opt_streq(old->User, new_val->User)) {
4685 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
4686 return -1;
4689 if (old->KeepBindCapabilities != new_val->KeepBindCapabilities) {
4690 *msg = tor_strdup("While Tor is running, changing KeepBindCapabilities is "
4691 "not allowed.");
4692 return -1;
4695 if (!opt_streq(old->SyslogIdentityTag, new_val->SyslogIdentityTag)) {
4696 *msg = tor_strdup("While Tor is running, changing "
4697 "SyslogIdentityTag is not allowed.");
4698 return -1;
4701 if (!opt_streq(old->AndroidIdentityTag, new_val->AndroidIdentityTag)) {
4702 *msg = tor_strdup("While Tor is running, changing "
4703 "AndroidIdentityTag is not allowed.");
4704 return -1;
4707 if ((old->HardwareAccel != new_val->HardwareAccel)
4708 || !opt_streq(old->AccelName, new_val->AccelName)
4709 || !opt_streq(old->AccelDir, new_val->AccelDir)) {
4710 *msg = tor_strdup("While Tor is running, changing OpenSSL hardware "
4711 "acceleration engine is not allowed.");
4712 return -1;
4715 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
4716 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
4717 "is not allowed.");
4718 return -1;
4721 if (old->DisableAllSwap != new_val->DisableAllSwap) {
4722 *msg = tor_strdup("While Tor is running, changing DisableAllSwap "
4723 "is not allowed.");
4724 return -1;
4727 if (old->TokenBucketRefillInterval != new_val->TokenBucketRefillInterval) {
4728 *msg = tor_strdup("While Tor is running, changing TokenBucketRefill"
4729 "Interval is not allowed");
4730 return -1;
4733 if (old->HiddenServiceSingleHopMode != new_val->HiddenServiceSingleHopMode) {
4734 *msg = tor_strdup("While Tor is running, changing "
4735 "HiddenServiceSingleHopMode is not allowed.");
4736 return -1;
4739 if (old->HiddenServiceNonAnonymousMode !=
4740 new_val->HiddenServiceNonAnonymousMode) {
4741 *msg = tor_strdup("While Tor is running, changing "
4742 "HiddenServiceNonAnonymousMode is not allowed.");
4743 return -1;
4746 if (old->DisableDebuggerAttachment &&
4747 !new_val->DisableDebuggerAttachment) {
4748 *msg = tor_strdup("While Tor is running, disabling "
4749 "DisableDebuggerAttachment is not allowed.");
4750 return -1;
4753 if (old->NoExec && !new_val->NoExec) {
4754 *msg = tor_strdup("While Tor is running, disabling "
4755 "NoExec is not allowed.");
4756 return -1;
4759 if (old->OwningControllerFD != new_val->OwningControllerFD) {
4760 *msg = tor_strdup("While Tor is running, changing OwningControllerFD "
4761 "is not allowed.");
4762 return -1;
4765 if (sandbox_is_active()) {
4766 #define SB_NOCHANGE_STR(opt) \
4767 do { \
4768 if (! opt_streq(old->opt, new_val->opt)) { \
4769 *msg = tor_strdup("Can't change " #opt " while Sandbox is active"); \
4770 return -1; \
4772 } while (0)
4774 SB_NOCHANGE_STR(Address);
4775 SB_NOCHANGE_STR(ServerDNSResolvConfFile);
4776 SB_NOCHANGE_STR(DirPortFrontPage);
4777 SB_NOCHANGE_STR(CookieAuthFile);
4778 SB_NOCHANGE_STR(ExtORPortCookieAuthFile);
4780 #undef SB_NOCHANGE_STR
4782 if (! config_lines_eq(old->Logs, new_val->Logs)) {
4783 *msg = tor_strdup("Can't change Logs while Sandbox is active");
4784 return -1;
4786 if (old->ConnLimit != new_val->ConnLimit) {
4787 *msg = tor_strdup("Can't change ConnLimit while Sandbox is active");
4788 return -1;
4790 if (server_mode(old) != server_mode(new_val)) {
4791 *msg = tor_strdup("Can't start/stop being a server while "
4792 "Sandbox is active");
4793 return -1;
4797 return 0;
4800 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
4801 * will require us to rotate the CPU and DNS workers; else return 0. */
4802 static int
4803 options_transition_affects_workers(const or_options_t *old_options,
4804 const or_options_t *new_options)
4806 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
4807 old_options->NumCPUs != new_options->NumCPUs ||
4808 !config_lines_eq(old_options->ORPort_lines, new_options->ORPort_lines) ||
4809 old_options->ServerDNSSearchDomains !=
4810 new_options->ServerDNSSearchDomains ||
4811 old_options->SafeLogging_ != new_options->SafeLogging_ ||
4812 old_options->ClientOnly != new_options->ClientOnly ||
4813 server_mode(old_options) != server_mode(new_options) ||
4814 public_server_mode(old_options) != public_server_mode(new_options) ||
4815 !config_lines_eq(old_options->Logs, new_options->Logs) ||
4816 old_options->LogMessageDomains != new_options->LogMessageDomains)
4817 return 1;
4819 /* Check whether log options match. */
4821 /* Nothing that changed matters. */
4822 return 0;
4825 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
4826 * will require us to generate a new descriptor; else return 0. */
4827 static int
4828 options_transition_affects_descriptor(const or_options_t *old_options,
4829 const or_options_t *new_options)
4831 /* XXX We can be smarter here. If your DirPort isn't being
4832 * published and you just turned it off, no need to republish. Etc. */
4833 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
4834 !opt_streq(old_options->Nickname,new_options->Nickname) ||
4835 !opt_streq(old_options->Address,new_options->Address) ||
4836 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
4837 old_options->ExitRelay != new_options->ExitRelay ||
4838 old_options->ExitPolicyRejectPrivate !=
4839 new_options->ExitPolicyRejectPrivate ||
4840 old_options->ExitPolicyRejectLocalInterfaces !=
4841 new_options->ExitPolicyRejectLocalInterfaces ||
4842 old_options->IPv6Exit != new_options->IPv6Exit ||
4843 !config_lines_eq(old_options->ORPort_lines,
4844 new_options->ORPort_lines) ||
4845 !config_lines_eq(old_options->DirPort_lines,
4846 new_options->DirPort_lines) ||
4847 old_options->ClientOnly != new_options->ClientOnly ||
4848 old_options->DisableNetwork != new_options->DisableNetwork ||
4849 old_options->PublishServerDescriptor_ !=
4850 new_options->PublishServerDescriptor_ ||
4851 get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
4852 get_effective_bwburst(old_options) !=
4853 get_effective_bwburst(new_options) ||
4854 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
4855 !opt_streq(old_options->BridgeDistribution,
4856 new_options->BridgeDistribution) ||
4857 !config_lines_eq(old_options->MyFamily, new_options->MyFamily) ||
4858 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
4859 old_options->AccountingMax != new_options->AccountingMax ||
4860 old_options->AccountingRule != new_options->AccountingRule ||
4861 public_server_mode(old_options) != public_server_mode(new_options) ||
4862 old_options->DirCache != new_options->DirCache ||
4863 old_options->AssumeReachable != new_options->AssumeReachable)
4864 return 1;
4866 return 0;
4869 #ifdef _WIN32
4870 /** Return the directory on windows where we expect to find our application
4871 * data. */
4872 static char *
4873 get_windows_conf_root(void)
4875 static int is_set = 0;
4876 static char path[MAX_PATH*2+1];
4877 TCHAR tpath[MAX_PATH] = {0};
4879 LPITEMIDLIST idl;
4880 IMalloc *m;
4881 HRESULT result;
4883 if (is_set)
4884 return path;
4886 /* Find X:\documents and settings\username\application data\ .
4887 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
4889 #ifdef ENABLE_LOCAL_APPDATA
4890 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
4891 #else
4892 #define APPDATA_PATH CSIDL_APPDATA
4893 #endif
4894 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
4895 getcwd(path,MAX_PATH);
4896 is_set = 1;
4897 log_warn(LD_CONFIG,
4898 "I couldn't find your application data folder: are you "
4899 "running an ancient version of Windows 95? Defaulting to \"%s\"",
4900 path);
4901 return path;
4903 /* Convert the path from an "ID List" (whatever that is!) to a path. */
4904 result = SHGetPathFromIDList(idl, tpath);
4905 #ifdef UNICODE
4906 wcstombs(path,tpath,sizeof(path));
4907 path[sizeof(path)-1] = '\0';
4908 #else
4909 strlcpy(path,tpath,sizeof(path));
4910 #endif /* defined(UNICODE) */
4912 /* Now we need to free the memory that the path-idl was stored in. In
4913 * typical Windows fashion, we can't just call 'free()' on it. */
4914 SHGetMalloc(&m);
4915 if (m) {
4916 m->lpVtbl->Free(m, idl);
4917 m->lpVtbl->Release(m);
4919 if (!SUCCEEDED(result)) {
4920 return NULL;
4922 strlcat(path,"\\tor",MAX_PATH);
4923 is_set = 1;
4924 return path;
4926 #endif /* defined(_WIN32) */
4928 /** Return the default location for our torrc file (if <b>defaults_file</b> is
4929 * false), or for the torrc-defaults file (if <b>defaults_file</b> is true). */
4930 static const char *
4931 get_default_conf_file(int defaults_file)
4933 #ifdef DISABLE_SYSTEM_TORRC
4934 (void) defaults_file;
4935 return NULL;
4936 #elif defined(_WIN32)
4937 if (defaults_file) {
4938 static char defaults_path[MAX_PATH+1];
4939 tor_snprintf(defaults_path, MAX_PATH, "%s\\torrc-defaults",
4940 get_windows_conf_root());
4941 return defaults_path;
4942 } else {
4943 static char path[MAX_PATH+1];
4944 tor_snprintf(path, MAX_PATH, "%s\\torrc",
4945 get_windows_conf_root());
4946 return path;
4948 #else
4949 return defaults_file ? CONFDIR "/torrc-defaults" : CONFDIR "/torrc";
4950 #endif /* defined(DISABLE_SYSTEM_TORRC) || ... */
4953 /** Verify whether lst is a list of strings containing valid-looking
4954 * comma-separated nicknames, or NULL. Will normalise <b>lst</b> to prefix '$'
4955 * to any nickname or fingerprint that needs it. Also splits comma-separated
4956 * list elements into multiple elements. Return 0 on success.
4957 * Warn and return -1 on failure.
4959 static int
4960 normalize_nickname_list(config_line_t **normalized_out,
4961 const config_line_t *lst, const char *name,
4962 char **msg)
4964 if (!lst)
4965 return 0;
4967 config_line_t *new_nicknames = NULL;
4968 config_line_t **new_nicknames_next = &new_nicknames;
4970 const config_line_t *cl;
4971 for (cl = lst; cl; cl = cl->next) {
4972 const char *line = cl->value;
4973 if (!line)
4974 continue;
4976 int valid_line = 1;
4977 smartlist_t *sl = smartlist_new();
4978 smartlist_split_string(sl, line, ",",
4979 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
4980 SMARTLIST_FOREACH_BEGIN(sl, char *, s)
4982 char *normalized = NULL;
4983 if (!is_legal_nickname_or_hexdigest(s)) {
4984 // check if first char is dollar
4985 if (s[0] != '$') {
4986 // Try again but with a dollar symbol prepended
4987 char *prepended;
4988 tor_asprintf(&prepended, "$%s", s);
4990 if (is_legal_nickname_or_hexdigest(prepended)) {
4991 // The nickname is valid when it's prepended, set it as the
4992 // normalized version
4993 normalized = prepended;
4994 } else {
4995 // Still not valid, free and fallback to error message
4996 tor_free(prepended);
5000 if (!normalized) {
5001 tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
5002 valid_line = 0;
5003 break;
5005 } else {
5006 normalized = tor_strdup(s);
5009 config_line_t *next = tor_malloc_zero(sizeof(*next));
5010 next->key = tor_strdup(cl->key);
5011 next->value = normalized;
5012 next->next = NULL;
5014 *new_nicknames_next = next;
5015 new_nicknames_next = &next->next;
5016 } SMARTLIST_FOREACH_END(s);
5018 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
5019 smartlist_free(sl);
5021 if (!valid_line) {
5022 config_free_lines(new_nicknames);
5023 return -1;
5027 *normalized_out = new_nicknames;
5029 return 0;
5032 /** Learn config file name from command line arguments, or use the default.
5034 * If <b>defaults_file</b> is true, we're looking for torrc-defaults;
5035 * otherwise, we're looking for the regular torrc_file.
5037 * Set *<b>using_default_fname</b> to true if we're using the default
5038 * configuration file name; or false if we've set it from the command line.
5040 * Set *<b>ignore_missing_torrc</b> to true if we should ignore the resulting
5041 * filename if it doesn't exist.
5043 static char *
5044 find_torrc_filename(config_line_t *cmd_arg,
5045 int defaults_file,
5046 int *using_default_fname, int *ignore_missing_torrc)
5048 char *fname=NULL;
5049 config_line_t *p_index;
5050 const char *fname_opt = defaults_file ? "--defaults-torrc" : "-f";
5051 const char *ignore_opt = defaults_file ? NULL : "--ignore-missing-torrc";
5053 if (defaults_file)
5054 *ignore_missing_torrc = 1;
5056 for (p_index = cmd_arg; p_index; p_index = p_index->next) {
5057 if (!strcmp(p_index->key, fname_opt)) {
5058 if (fname) {
5059 log_warn(LD_CONFIG, "Duplicate %s options on command line.",
5060 fname_opt);
5061 tor_free(fname);
5063 fname = expand_filename(p_index->value);
5066 char *absfname;
5067 absfname = make_path_absolute(fname);
5068 tor_free(fname);
5069 fname = absfname;
5072 *using_default_fname = 0;
5073 } else if (ignore_opt && !strcmp(p_index->key,ignore_opt)) {
5074 *ignore_missing_torrc = 1;
5078 if (*using_default_fname) {
5079 /* didn't find one, try CONFDIR */
5080 const char *dflt = get_default_conf_file(defaults_file);
5081 file_status_t st = file_status(dflt);
5082 if (dflt && (st == FN_FILE || st == FN_EMPTY)) {
5083 fname = tor_strdup(dflt);
5084 } else {
5085 #ifndef _WIN32
5086 char *fn = NULL;
5087 if (!defaults_file) {
5088 fn = expand_filename("~/.torrc");
5090 if (fn) {
5091 file_status_t hmst = file_status(fn);
5092 if (hmst == FN_FILE || hmst == FN_EMPTY || dflt == NULL) {
5093 fname = fn;
5094 } else {
5095 tor_free(fn);
5096 fname = tor_strdup(dflt);
5098 } else {
5099 fname = dflt ? tor_strdup(dflt) : NULL;
5101 #else /* !(!defined(_WIN32)) */
5102 fname = dflt ? tor_strdup(dflt) : NULL;
5103 #endif /* !defined(_WIN32) */
5106 return fname;
5109 /** Read the torrc from standard input and return it as a string.
5110 * Upon failure, return NULL.
5112 static char *
5113 load_torrc_from_stdin(void)
5115 size_t sz_out;
5117 return read_file_to_str_until_eof(STDIN_FILENO,SIZE_MAX,&sz_out);
5120 /** Load a configuration file from disk, setting torrc_fname or
5121 * torrc_defaults_fname if successful.
5123 * If <b>defaults_file</b> is true, load torrc-defaults; otherwise load torrc.
5125 * Return the contents of the file on success, and NULL on failure.
5127 static char *
5128 load_torrc_from_disk(config_line_t *cmd_arg, int defaults_file)
5130 char *fname=NULL;
5131 char *cf = NULL;
5132 int using_default_torrc = 1;
5133 int ignore_missing_torrc = 0;
5134 char **fname_var = defaults_file ? &torrc_defaults_fname : &torrc_fname;
5136 if (*fname_var == NULL) {
5137 fname = find_torrc_filename(cmd_arg, defaults_file,
5138 &using_default_torrc, &ignore_missing_torrc);
5139 tor_free(*fname_var);
5140 *fname_var = fname;
5141 } else {
5142 fname = *fname_var;
5144 log_debug(LD_CONFIG, "Opening config file \"%s\"", fname?fname:"<NULL>");
5146 /* Open config file */
5147 file_status_t st = fname ? file_status(fname) : FN_EMPTY;
5148 if (fname == NULL ||
5149 !(st == FN_FILE || st == FN_EMPTY) ||
5150 !(cf = read_file_to_str(fname,0,NULL))) {
5151 if (using_default_torrc == 1 || ignore_missing_torrc) {
5152 if (!defaults_file)
5153 log_notice(LD_CONFIG, "Configuration file \"%s\" not present, "
5154 "using reasonable defaults.", fname);
5155 tor_free(fname); /* sets fname to NULL */
5156 *fname_var = NULL;
5157 cf = tor_strdup("");
5158 } else {
5159 log_warn(LD_CONFIG,
5160 "Unable to open configuration file \"%s\".", fname);
5161 goto err;
5163 } else {
5164 log_notice(LD_CONFIG, "Read configuration file \"%s\".", fname);
5167 return cf;
5168 err:
5169 tor_free(fname);
5170 *fname_var = NULL;
5171 return NULL;
5174 /** Read a configuration file into <b>options</b>, finding the configuration
5175 * file location based on the command line. After loading the file
5176 * call options_init_from_string() to load the config.
5177 * Return 0 if success, -1 if failure, and 1 if we succeeded but should exit
5178 * anyway. */
5180 options_init_from_torrc(int argc, char **argv)
5182 char *cf=NULL, *cf_defaults=NULL;
5183 int command;
5184 int retval = -1;
5185 char *command_arg = NULL;
5186 char *errmsg=NULL;
5187 config_line_t *p_index = NULL;
5188 config_line_t *cmdline_only_options = NULL;
5190 /* Go through command-line variables */
5191 if (! have_parsed_cmdline) {
5192 /* Or we could redo the list every time we pass this place.
5193 * It does not really matter */
5194 if (config_parse_commandline(argc, argv, 0, &global_cmdline_options,
5195 &global_cmdline_only_options) < 0) {
5196 goto err;
5198 have_parsed_cmdline = 1;
5200 cmdline_only_options = global_cmdline_only_options;
5202 if (config_line_find(cmdline_only_options, "-h") ||
5203 config_line_find(cmdline_only_options, "--help")) {
5204 print_usage();
5205 return 1;
5207 if (config_line_find(cmdline_only_options, "--list-torrc-options")) {
5208 /* For validating whether we've documented everything. */
5209 list_torrc_options();
5210 return 1;
5212 if (config_line_find(cmdline_only_options, "--list-deprecated-options")) {
5213 /* For validating whether what we have deprecated really exists. */
5214 list_deprecated_options();
5215 return 1;
5218 if (config_line_find(cmdline_only_options, "--version")) {
5219 printf("Tor version %s.\n",get_version());
5220 return 1;
5223 if (config_line_find(cmdline_only_options, "--library-versions")) {
5224 printf("Tor version %s. \n", get_version());
5225 printf("Library versions\tCompiled\t\tRuntime\n");
5226 printf("Libevent\t\t%-15s\t\t%s\n",
5227 tor_libevent_get_header_version_str(),
5228 tor_libevent_get_version_str());
5229 printf("OpenSSL \t\t%-15s\t\t%s\n",
5230 crypto_openssl_get_header_version_str(),
5231 crypto_openssl_get_version_str());
5232 if (tor_compress_supports_method(ZLIB_METHOD)) {
5233 printf("Zlib \t\t%-15s\t\t%s\n",
5234 tor_compress_version_str(ZLIB_METHOD),
5235 tor_compress_header_version_str(ZLIB_METHOD));
5237 if (tor_compress_supports_method(LZMA_METHOD)) {
5238 printf("Liblzma \t\t%-15s\t\t%s\n",
5239 tor_compress_version_str(LZMA_METHOD),
5240 tor_compress_header_version_str(LZMA_METHOD));
5242 if (tor_compress_supports_method(ZSTD_METHOD)) {
5243 printf("Libzstd \t\t%-15s\t\t%s\n",
5244 tor_compress_version_str(ZSTD_METHOD),
5245 tor_compress_header_version_str(ZSTD_METHOD));
5247 //TODO: Hex versions?
5248 return 1;
5251 command = CMD_RUN_TOR;
5252 for (p_index = cmdline_only_options; p_index; p_index = p_index->next) {
5253 if (!strcmp(p_index->key,"--keygen")) {
5254 command = CMD_KEYGEN;
5255 } else if (!strcmp(p_index->key, "--key-expiration")) {
5256 command = CMD_KEY_EXPIRATION;
5257 command_arg = p_index->value;
5258 } else if (!strcmp(p_index->key,"--list-fingerprint")) {
5259 command = CMD_LIST_FINGERPRINT;
5260 } else if (!strcmp(p_index->key, "--hash-password")) {
5261 command = CMD_HASH_PASSWORD;
5262 command_arg = p_index->value;
5263 } else if (!strcmp(p_index->key, "--dump-config")) {
5264 command = CMD_DUMP_CONFIG;
5265 command_arg = p_index->value;
5266 } else if (!strcmp(p_index->key, "--verify-config")) {
5267 command = CMD_VERIFY_CONFIG;
5271 if (command == CMD_HASH_PASSWORD) {
5272 cf_defaults = tor_strdup("");
5273 cf = tor_strdup("");
5274 } else {
5275 cf_defaults = load_torrc_from_disk(cmdline_only_options, 1);
5277 const config_line_t *f_line = config_line_find(cmdline_only_options,
5278 "-f");
5280 const int read_torrc_from_stdin =
5281 (f_line != NULL && strcmp(f_line->value, "-") == 0);
5283 if (read_torrc_from_stdin) {
5284 cf = load_torrc_from_stdin();
5285 } else {
5286 cf = load_torrc_from_disk(cmdline_only_options, 0);
5289 if (!cf) {
5290 if (config_line_find(cmdline_only_options, "--allow-missing-torrc")) {
5291 cf = tor_strdup("");
5292 } else {
5293 goto err;
5298 retval = options_init_from_string(cf_defaults, cf, command, command_arg,
5299 &errmsg);
5301 if (retval < 0)
5302 goto err;
5304 if (config_line_find(cmdline_only_options, "--no-passphrase")) {
5305 if (command == CMD_KEYGEN) {
5306 get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_OFF;
5307 } else {
5308 log_err(LD_CONFIG, "--no-passphrase specified without --keygen!");
5309 retval = -1;
5310 goto err;
5314 if (config_line_find(cmdline_only_options, "--newpass")) {
5315 if (command == CMD_KEYGEN) {
5316 get_options_mutable()->change_key_passphrase = 1;
5317 } else {
5318 log_err(LD_CONFIG, "--newpass specified without --keygen!");
5319 retval = -1;
5320 goto err;
5325 const config_line_t *fd_line = config_line_find(cmdline_only_options,
5326 "--passphrase-fd");
5327 if (fd_line) {
5328 if (get_options()->keygen_force_passphrase == FORCE_PASSPHRASE_OFF) {
5329 log_err(LD_CONFIG, "--no-passphrase specified with --passphrase-fd!");
5330 retval = -1;
5331 goto err;
5332 } else if (command != CMD_KEYGEN) {
5333 log_err(LD_CONFIG, "--passphrase-fd specified without --keygen!");
5334 retval = -1;
5335 goto err;
5336 } else {
5337 const char *v = fd_line->value;
5338 int ok = 1;
5339 long fd = tor_parse_long(v, 10, 0, INT_MAX, &ok, NULL);
5340 if (fd < 0 || ok == 0) {
5341 log_err(LD_CONFIG, "Invalid --passphrase-fd value %s", escaped(v));
5342 retval = -1;
5343 goto err;
5345 get_options_mutable()->keygen_passphrase_fd = (int)fd;
5346 get_options_mutable()->use_keygen_passphrase_fd = 1;
5347 get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_ON;
5353 const config_line_t *key_line = config_line_find(cmdline_only_options,
5354 "--master-key");
5355 if (key_line) {
5356 if (command != CMD_KEYGEN) {
5357 log_err(LD_CONFIG, "--master-key without --keygen!");
5358 retval = -1;
5359 goto err;
5360 } else {
5361 get_options_mutable()->master_key_fname = tor_strdup(key_line->value);
5366 err:
5368 tor_free(cf);
5369 tor_free(cf_defaults);
5370 if (errmsg) {
5371 log_warn(LD_CONFIG,"%s", errmsg);
5372 tor_free(errmsg);
5374 return retval < 0 ? -1 : 0;
5377 /** Load the options from the configuration in <b>cf</b>, validate
5378 * them for consistency and take actions based on them.
5380 * Return 0 if success, negative on error:
5381 * * -1 for general errors.
5382 * * -2 for failure to parse/validate,
5383 * * -3 for transition not allowed
5384 * * -4 for error while setting the new options
5386 setopt_err_t
5387 options_init_from_string(const char *cf_defaults, const char *cf,
5388 int command, const char *command_arg,
5389 char **msg)
5391 or_options_t *oldoptions, *newoptions, *newdefaultoptions=NULL;
5392 config_line_t *cl;
5393 int retval;
5394 setopt_err_t err = SETOPT_ERR_MISC;
5395 int cf_has_include = 0;
5396 tor_assert(msg);
5398 oldoptions = global_options; /* get_options unfortunately asserts if
5399 this is the first time we run*/
5401 newoptions = tor_malloc_zero(sizeof(or_options_t));
5402 newoptions->magic_ = OR_OPTIONS_MAGIC;
5403 options_init(newoptions);
5404 newoptions->command = command;
5405 newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
5407 smartlist_t *opened_files = smartlist_new();
5408 for (int i = 0; i < 2; ++i) {
5409 const char *body = i==0 ? cf_defaults : cf;
5410 if (!body)
5411 continue;
5413 /* get config lines, assign them */
5414 retval = config_get_lines_include(body, &cl, 1,
5415 body == cf ? &cf_has_include : NULL,
5416 opened_files);
5417 if (retval < 0) {
5418 err = SETOPT_ERR_PARSE;
5419 goto err;
5421 retval = config_assign(&options_format, newoptions, cl,
5422 CAL_WARN_DEPRECATIONS, msg);
5423 config_free_lines(cl);
5424 if (retval < 0) {
5425 err = SETOPT_ERR_PARSE;
5426 goto err;
5428 if (i==0)
5429 newdefaultoptions = config_dup(&options_format, newoptions);
5432 if (newdefaultoptions == NULL) {
5433 newdefaultoptions = config_dup(&options_format, global_default_options);
5436 /* Go through command-line variables too */
5437 retval = config_assign(&options_format, newoptions,
5438 global_cmdline_options, CAL_WARN_DEPRECATIONS, msg);
5439 if (retval < 0) {
5440 err = SETOPT_ERR_PARSE;
5441 goto err;
5444 newoptions->IncludeUsed = cf_has_include;
5445 newoptions->FilesOpenedByIncludes = opened_files;
5447 /* If this is a testing network configuration, change defaults
5448 * for a list of dependent config options, re-initialize newoptions
5449 * with the new defaults, and assign all options to it second time. */
5450 if (newoptions->TestingTorNetwork) {
5451 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
5452 * this? We could, for example, make the parsing algorithm do two passes
5453 * over the configuration. If it finds any "suite" options like
5454 * TestingTorNetwork, it could change the defaults before its second pass.
5455 * Not urgent so long as this seems to work, but at any sign of trouble,
5456 * let's clean it up. -NM */
5458 /* Change defaults. */
5459 for (int i = 0; testing_tor_network_defaults[i].name; ++i) {
5460 const config_var_t *new_var = &testing_tor_network_defaults[i];
5461 config_var_t *old_var =
5462 config_find_option_mutable(&options_format, new_var->name);
5463 tor_assert(new_var);
5464 tor_assert(old_var);
5465 old_var->initvalue = new_var->initvalue;
5467 if ((config_find_deprecation(&options_format, new_var->name))) {
5468 log_warn(LD_GENERAL, "Testing options override the deprecated "
5469 "option %s. Is that intentional?",
5470 new_var->name);
5474 /* Clear newoptions and re-initialize them with new defaults. */
5475 or_options_free(newoptions);
5476 or_options_free(newdefaultoptions);
5477 newdefaultoptions = NULL;
5478 newoptions = tor_malloc_zero(sizeof(or_options_t));
5479 newoptions->magic_ = OR_OPTIONS_MAGIC;
5480 options_init(newoptions);
5481 newoptions->command = command;
5482 newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
5484 /* Assign all options a second time. */
5485 opened_files = smartlist_new();
5486 for (int i = 0; i < 2; ++i) {
5487 const char *body = i==0 ? cf_defaults : cf;
5488 if (!body)
5489 continue;
5491 /* get config lines, assign them */
5492 retval = config_get_lines_include(body, &cl, 1,
5493 body == cf ? &cf_has_include : NULL,
5494 opened_files);
5495 if (retval < 0) {
5496 err = SETOPT_ERR_PARSE;
5497 goto err;
5499 retval = config_assign(&options_format, newoptions, cl, 0, msg);
5500 config_free_lines(cl);
5501 if (retval < 0) {
5502 err = SETOPT_ERR_PARSE;
5503 goto err;
5505 if (i==0)
5506 newdefaultoptions = config_dup(&options_format, newoptions);
5508 /* Assign command-line variables a second time too */
5509 retval = config_assign(&options_format, newoptions,
5510 global_cmdline_options, 0, msg);
5511 if (retval < 0) {
5512 err = SETOPT_ERR_PARSE;
5513 goto err;
5517 newoptions->IncludeUsed = cf_has_include;
5518 in_option_validation = 1;
5519 newoptions->FilesOpenedByIncludes = opened_files;
5521 /* Validate newoptions */
5522 if (options_validate(oldoptions, newoptions, newdefaultoptions,
5523 0, msg) < 0) {
5524 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
5525 goto err;
5528 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
5529 err = SETOPT_ERR_TRANSITION;
5530 goto err;
5532 in_option_validation = 0;
5534 if (set_options(newoptions, msg)) {
5535 err = SETOPT_ERR_SETTING;
5536 goto err; /* frees and replaces old options */
5539 or_options_free(global_default_options);
5540 global_default_options = newdefaultoptions;
5542 return SETOPT_OK;
5544 err:
5545 in_option_validation = 0;
5546 if (opened_files) {
5547 SMARTLIST_FOREACH(opened_files, char *, f, tor_free(f));
5548 smartlist_free(opened_files);
5550 // may have been set to opened_files, avoid double free
5551 newoptions->FilesOpenedByIncludes = NULL;
5552 or_options_free(newoptions);
5553 or_options_free(newdefaultoptions);
5554 if (*msg) {
5555 char *old_msg = *msg;
5556 tor_asprintf(msg, "Failed to parse/validate config: %s", old_msg);
5557 tor_free(old_msg);
5559 return err;
5562 /** Return the location for our configuration file. May return NULL.
5564 const char *
5565 get_torrc_fname(int defaults_fname)
5567 const char *fname = defaults_fname ? torrc_defaults_fname : torrc_fname;
5569 if (fname)
5570 return fname;
5571 else
5572 return get_default_conf_file(defaults_fname);
5575 /** Adjust the address map based on the MapAddress elements in the
5576 * configuration <b>options</b>
5578 void
5579 config_register_addressmaps(const or_options_t *options)
5581 smartlist_t *elts;
5582 config_line_t *opt;
5583 const char *from, *to, *msg;
5585 addressmap_clear_configured();
5586 elts = smartlist_new();
5587 for (opt = options->AddressMap; opt; opt = opt->next) {
5588 smartlist_split_string(elts, opt->value, NULL,
5589 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
5590 if (smartlist_len(elts) < 2) {
5591 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
5592 opt->value);
5593 goto cleanup;
5596 from = smartlist_get(elts,0);
5597 to = smartlist_get(elts,1);
5599 if (to[0] == '.' || from[0] == '.') {
5600 log_warn(LD_CONFIG,"MapAddress '%s' is ambiguous - address starts with a"
5601 "'.'. Ignoring.",opt->value);
5602 goto cleanup;
5605 if (addressmap_register_auto(from, to, 0, ADDRMAPSRC_TORRC, &msg) < 0) {
5606 log_warn(LD_CONFIG,"MapAddress '%s' failed: %s. Ignoring.", opt->value,
5607 msg);
5608 goto cleanup;
5611 if (smartlist_len(elts) > 2)
5612 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
5614 cleanup:
5615 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
5616 smartlist_clear(elts);
5618 smartlist_free(elts);
5621 /** As addressmap_register(), but detect the wildcarded status of "from" and
5622 * "to", and do not steal a reference to <b>to</b>. */
5623 /* XXXX move to connection_edge.c */
5625 addressmap_register_auto(const char *from, const char *to,
5626 time_t expires,
5627 addressmap_entry_source_t addrmap_source,
5628 const char **msg)
5630 int from_wildcard = 0, to_wildcard = 0;
5632 *msg = "whoops, forgot the error message";
5634 if (!strcmp(to, "*") || !strcmp(from, "*")) {
5635 *msg = "can't remap from or to *";
5636 return -1;
5638 /* Detect asterisks in expressions of type: '*.example.com' */
5639 if (!strncmp(from,"*.",2)) {
5640 from += 2;
5641 from_wildcard = 1;
5643 if (!strncmp(to,"*.",2)) {
5644 to += 2;
5645 to_wildcard = 1;
5648 if (to_wildcard && !from_wildcard) {
5649 *msg = "can only use wildcard (i.e. '*.') if 'from' address "
5650 "uses wildcard also";
5651 return -1;
5654 if (address_is_invalid_destination(to, 1)) {
5655 *msg = "destination is invalid";
5656 return -1;
5659 addressmap_register(from, tor_strdup(to), expires, addrmap_source,
5660 from_wildcard, to_wildcard);
5662 return 0;
5666 * Initialize the logs based on the configuration file.
5668 static int
5669 options_init_logs(const or_options_t *old_options, or_options_t *options,
5670 int validate_only)
5672 config_line_t *opt;
5673 int ok;
5674 smartlist_t *elts;
5675 int run_as_daemon =
5676 #ifdef _WIN32
5678 #else
5679 options->RunAsDaemon;
5680 #endif
5682 if (options->LogTimeGranularity <= 0) {
5683 log_warn(LD_CONFIG, "Log time granularity '%d' has to be positive.",
5684 options->LogTimeGranularity);
5685 return -1;
5686 } else if (1000 % options->LogTimeGranularity != 0 &&
5687 options->LogTimeGranularity % 1000 != 0) {
5688 int granularity = options->LogTimeGranularity;
5689 if (granularity < 40) {
5690 do granularity++;
5691 while (1000 % granularity != 0);
5692 } else if (granularity < 1000) {
5693 granularity = 1000 / granularity;
5694 while (1000 % granularity != 0)
5695 granularity--;
5696 granularity = 1000 / granularity;
5697 } else {
5698 granularity = 1000 * ((granularity / 1000) + 1);
5700 log_warn(LD_CONFIG, "Log time granularity '%d' has to be either a "
5701 "divisor or a multiple of 1 second. Changing to "
5702 "'%d'.",
5703 options->LogTimeGranularity, granularity);
5704 if (!validate_only)
5705 set_log_time_granularity(granularity);
5706 } else {
5707 if (!validate_only)
5708 set_log_time_granularity(options->LogTimeGranularity);
5711 ok = 1;
5712 elts = smartlist_new();
5714 for (opt = options->Logs; opt; opt = opt->next) {
5715 log_severity_list_t *severity;
5716 const char *cfg = opt->value;
5717 severity = tor_malloc_zero(sizeof(log_severity_list_t));
5718 if (parse_log_severity_config(&cfg, severity) < 0) {
5719 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
5720 opt->value);
5721 ok = 0; goto cleanup;
5724 smartlist_split_string(elts, cfg, NULL,
5725 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
5727 if (smartlist_len(elts) == 0)
5728 smartlist_add_strdup(elts, "stdout");
5730 if (smartlist_len(elts) == 1 &&
5731 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
5732 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
5733 int err = smartlist_len(elts) &&
5734 !strcasecmp(smartlist_get(elts,0), "stderr");
5735 if (!validate_only) {
5736 if (run_as_daemon) {
5737 log_warn(LD_CONFIG,
5738 "Can't log to %s with RunAsDaemon set; skipping stdout",
5739 err?"stderr":"stdout");
5740 } else {
5741 add_stream_log(severity, err?"<stderr>":"<stdout>",
5742 fileno(err?stderr:stdout));
5745 goto cleanup;
5747 if (smartlist_len(elts) == 1) {
5748 if (!strcasecmp(smartlist_get(elts,0), "syslog")) {
5749 #ifdef HAVE_SYSLOG_H
5750 if (!validate_only) {
5751 add_syslog_log(severity, options->SyslogIdentityTag);
5753 #else
5754 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
5755 #endif /* defined(HAVE_SYSLOG_H) */
5756 goto cleanup;
5759 if (!strcasecmp(smartlist_get(elts, 0), "android")) {
5760 #ifdef HAVE_ANDROID_LOG_H
5761 if (!validate_only) {
5762 add_android_log(severity, options->AndroidIdentityTag);
5764 #else
5765 log_warn(LD_CONFIG, "Android logging is not supported"
5766 " on this system. Sorry.");
5767 #endif // HAVE_ANDROID_LOG_H.
5768 goto cleanup;
5772 if (smartlist_len(elts) == 2 &&
5773 !strcasecmp(smartlist_get(elts,0), "file")) {
5774 if (!validate_only) {
5775 char *fname = expand_filename(smartlist_get(elts, 1));
5776 /* Truncate if TruncateLogFile is set and we haven't seen this option
5777 line before. */
5778 int truncate_log = 0;
5779 if (options->TruncateLogFile) {
5780 truncate_log = 1;
5781 if (old_options) {
5782 config_line_t *opt2;
5783 for (opt2 = old_options->Logs; opt2; opt2 = opt2->next)
5784 if (!strcmp(opt->value, opt2->value)) {
5785 truncate_log = 0;
5786 break;
5790 if (add_file_log(severity, fname, truncate_log) < 0) {
5791 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
5792 opt->value, strerror(errno));
5793 ok = 0;
5795 tor_free(fname);
5797 goto cleanup;
5800 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
5801 opt->value);
5802 ok = 0; goto cleanup;
5804 cleanup:
5805 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
5806 smartlist_clear(elts);
5807 tor_free(severity);
5809 smartlist_free(elts);
5811 if (ok && !validate_only)
5812 logs_set_domain_logging(options->LogMessageDomains);
5814 return ok?0:-1;
5817 /** Given a smartlist of SOCKS arguments to be passed to a transport
5818 * proxy in <b>args</b>, validate them and return -1 if they are
5819 * corrupted. Return 0 if they seem OK. */
5820 static int
5821 validate_transport_socks_arguments(const smartlist_t *args)
5823 char *socks_string = NULL;
5824 size_t socks_string_len;
5826 tor_assert(args);
5827 tor_assert(smartlist_len(args) > 0);
5829 SMARTLIST_FOREACH_BEGIN(args, const char *, s) {
5830 if (!string_is_key_value(LOG_WARN, s)) { /* items should be k=v items */
5831 log_warn(LD_CONFIG, "'%s' is not a k=v item.", s);
5832 return -1;
5834 } SMARTLIST_FOREACH_END(s);
5836 socks_string = pt_stringify_socks_args(args);
5837 if (!socks_string)
5838 return -1;
5840 socks_string_len = strlen(socks_string);
5841 tor_free(socks_string);
5843 if (socks_string_len > MAX_SOCKS5_AUTH_SIZE_TOTAL) {
5844 log_warn(LD_CONFIG, "SOCKS arguments can't be more than %u bytes (%lu).",
5845 MAX_SOCKS5_AUTH_SIZE_TOTAL,
5846 (unsigned long) socks_string_len);
5847 return -1;
5850 return 0;
5853 /** Deallocate a bridge_line_t structure. */
5854 /* private */ void
5855 bridge_line_free_(bridge_line_t *bridge_line)
5857 if (!bridge_line)
5858 return;
5860 if (bridge_line->socks_args) {
5861 SMARTLIST_FOREACH(bridge_line->socks_args, char*, s, tor_free(s));
5862 smartlist_free(bridge_line->socks_args);
5864 tor_free(bridge_line->transport_name);
5865 tor_free(bridge_line);
5868 /** Parse the contents of a string, <b>line</b>, containing a Bridge line,
5869 * into a bridge_line_t.
5871 * Validates that the IP:PORT, fingerprint, and SOCKS arguments (given to the
5872 * Pluggable Transport, if a one was specified) are well-formed.
5874 * Returns NULL If the Bridge line could not be validated, and returns a
5875 * bridge_line_t containing the parsed information otherwise.
5877 * Bridge line format:
5878 * Bridge [transport] IP:PORT [id-fingerprint] [k=v] [k=v] ...
5880 /* private */ bridge_line_t *
5881 parse_bridge_line(const char *line)
5883 smartlist_t *items = NULL;
5884 char *addrport=NULL, *fingerprint=NULL;
5885 char *field=NULL;
5886 bridge_line_t *bridge_line = tor_malloc_zero(sizeof(bridge_line_t));
5888 items = smartlist_new();
5889 smartlist_split_string(items, line, NULL,
5890 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5891 if (smartlist_len(items) < 1) {
5892 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
5893 goto err;
5896 /* first field is either a transport name or addrport */
5897 field = smartlist_get(items, 0);
5898 smartlist_del_keeporder(items, 0);
5900 if (string_is_C_identifier(field)) {
5901 /* It's a transport name. */
5902 bridge_line->transport_name = field;
5903 if (smartlist_len(items) < 1) {
5904 log_warn(LD_CONFIG, "Too few items to Bridge line.");
5905 goto err;
5907 addrport = smartlist_get(items, 0); /* Next field is addrport then. */
5908 smartlist_del_keeporder(items, 0);
5909 } else {
5910 addrport = field;
5913 if (tor_addr_port_parse(LOG_INFO, addrport,
5914 &bridge_line->addr, &bridge_line->port, 443)<0) {
5915 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
5916 goto err;
5919 /* If transports are enabled, next field could be a fingerprint or a
5920 socks argument. If transports are disabled, next field must be
5921 a fingerprint. */
5922 if (smartlist_len(items)) {
5923 if (bridge_line->transport_name) { /* transports enabled: */
5924 field = smartlist_get(items, 0);
5925 smartlist_del_keeporder(items, 0);
5927 /* If it's a key=value pair, then it's a SOCKS argument for the
5928 transport proxy... */
5929 if (string_is_key_value(LOG_DEBUG, field)) {
5930 bridge_line->socks_args = smartlist_new();
5931 smartlist_add(bridge_line->socks_args, field);
5932 } else { /* ...otherwise, it's the bridge fingerprint. */
5933 fingerprint = field;
5936 } else { /* transports disabled: */
5937 fingerprint = smartlist_join_strings(items, "", 0, NULL);
5941 /* Handle fingerprint, if it was provided. */
5942 if (fingerprint) {
5943 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
5944 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
5945 goto err;
5947 if (base16_decode(bridge_line->digest, DIGEST_LEN,
5948 fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
5949 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
5950 goto err;
5954 /* If we are using transports, any remaining items in the smartlist
5955 should be k=v values. */
5956 if (bridge_line->transport_name && smartlist_len(items)) {
5957 if (!bridge_line->socks_args)
5958 bridge_line->socks_args = smartlist_new();
5960 /* append remaining items of 'items' to 'socks_args' */
5961 smartlist_add_all(bridge_line->socks_args, items);
5962 smartlist_clear(items);
5964 tor_assert(smartlist_len(bridge_line->socks_args) > 0);
5967 if (bridge_line->socks_args) {
5968 if (validate_transport_socks_arguments(bridge_line->socks_args) < 0)
5969 goto err;
5972 goto done;
5974 err:
5975 bridge_line_free(bridge_line);
5976 bridge_line = NULL;
5978 done:
5979 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5980 smartlist_free(items);
5981 tor_free(addrport);
5982 tor_free(fingerprint);
5984 return bridge_line;
5987 /** Read the contents of a ClientTransportPlugin or ServerTransportPlugin
5988 * line from <b>line</b>, depending on the value of <b>server</b>. Return 0
5989 * if the line is well-formed, and -1 if it isn't.
5991 * If <b>validate_only</b> is 0, the line is well-formed, and the transport is
5992 * needed by some bridge:
5993 * - If it's an external proxy line, add the transport described in the line to
5994 * our internal transport list.
5995 * - If it's a managed proxy line, launch the managed proxy.
5998 STATIC int
5999 parse_transport_line(const or_options_t *options,
6000 const char *line, int validate_only,
6001 int server)
6004 smartlist_t *items = NULL;
6005 int r;
6006 const char *transports = NULL;
6007 smartlist_t *transport_list = NULL;
6008 char *type = NULL;
6009 char *addrport = NULL;
6010 tor_addr_t addr;
6011 uint16_t port = 0;
6012 int socks_ver = PROXY_NONE;
6014 /* managed proxy options */
6015 int is_managed = 0;
6016 char **proxy_argv = NULL;
6017 char **tmp = NULL;
6018 int proxy_argc, i;
6019 int is_useless_proxy = 1;
6021 int line_length;
6023 /* Split the line into space-separated tokens */
6024 items = smartlist_new();
6025 smartlist_split_string(items, line, NULL,
6026 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6027 line_length = smartlist_len(items);
6029 if (line_length < 3) {
6030 log_warn(LD_CONFIG,
6031 "Too few arguments on %sTransportPlugin line.",
6032 server ? "Server" : "Client");
6033 goto err;
6036 /* Get the first line element, split it to commas into
6037 transport_list (in case it's multiple transports) and validate
6038 the transport names. */
6039 transports = smartlist_get(items, 0);
6040 transport_list = smartlist_new();
6041 smartlist_split_string(transport_list, transports, ",",
6042 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
6043 SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
6044 /* validate transport names */
6045 if (!string_is_C_identifier(transport_name)) {
6046 log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
6047 transport_name);
6048 goto err;
6051 /* see if we actually need the transports provided by this proxy */
6052 if (!validate_only && transport_is_needed(transport_name))
6053 is_useless_proxy = 0;
6054 } SMARTLIST_FOREACH_END(transport_name);
6056 type = smartlist_get(items, 1);
6057 if (!strcmp(type, "exec")) {
6058 is_managed = 1;
6059 } else if (server && !strcmp(type, "proxy")) {
6060 /* 'proxy' syntax only with ServerTransportPlugin */
6061 is_managed = 0;
6062 } else if (!server && !strcmp(type, "socks4")) {
6063 /* 'socks4' syntax only with ClientTransportPlugin */
6064 is_managed = 0;
6065 socks_ver = PROXY_SOCKS4;
6066 } else if (!server && !strcmp(type, "socks5")) {
6067 /* 'socks5' syntax only with ClientTransportPlugin */
6068 is_managed = 0;
6069 socks_ver = PROXY_SOCKS5;
6070 } else {
6071 log_warn(LD_CONFIG,
6072 "Strange %sTransportPlugin type '%s'",
6073 server ? "Server" : "Client", type);
6074 goto err;
6077 if (is_managed && options->Sandbox) {
6078 log_warn(LD_CONFIG,
6079 "Managed proxies are not compatible with Sandbox mode."
6080 "(%sTransportPlugin line was %s)",
6081 server ? "Server" : "Client", escaped(line));
6082 goto err;
6085 if (is_managed && options->NoExec) {
6086 log_warn(LD_CONFIG,
6087 "Managed proxies are not compatible with NoExec mode; ignoring."
6088 "(%sTransportPlugin line was %s)",
6089 server ? "Server" : "Client", escaped(line));
6090 r = 0;
6091 goto done;
6094 if (is_managed) {
6095 /* managed */
6097 if (!server && !validate_only && is_useless_proxy) {
6098 log_info(LD_GENERAL,
6099 "Pluggable transport proxy (%s) does not provide "
6100 "any needed transports and will not be launched.",
6101 line);
6105 * If we are not just validating, use the rest of the line as the
6106 * argv of the proxy to be launched. Also, make sure that we are
6107 * only launching proxies that contribute useful transports.
6110 if (!validate_only && (server || !is_useless_proxy)) {
6111 proxy_argc = line_length - 2;
6112 tor_assert(proxy_argc > 0);
6113 proxy_argv = tor_calloc((proxy_argc + 1), sizeof(char *));
6114 tmp = proxy_argv;
6116 for (i = 0; i < proxy_argc; i++) {
6117 /* store arguments */
6118 *tmp++ = smartlist_get(items, 2);
6119 smartlist_del_keeporder(items, 2);
6121 *tmp = NULL; /* terminated with NULL, just like execve() likes it */
6123 /* kickstart the thing */
6124 if (server) {
6125 pt_kickstart_server_proxy(transport_list, proxy_argv);
6126 } else {
6127 pt_kickstart_client_proxy(transport_list, proxy_argv);
6130 } else {
6131 /* external */
6133 /* ClientTransportPlugins connecting through a proxy is managed only. */
6134 if (!server && (options->Socks4Proxy || options->Socks5Proxy ||
6135 options->HTTPSProxy)) {
6136 log_warn(LD_CONFIG, "You have configured an external proxy with another "
6137 "proxy type. (Socks4Proxy|Socks5Proxy|HTTPSProxy)");
6138 goto err;
6141 if (smartlist_len(transport_list) != 1) {
6142 log_warn(LD_CONFIG,
6143 "You can't have an external proxy with more than "
6144 "one transport.");
6145 goto err;
6148 addrport = smartlist_get(items, 2);
6150 if (tor_addr_port_lookup(addrport, &addr, &port) < 0) {
6151 log_warn(LD_CONFIG,
6152 "Error parsing transport address '%s'", addrport);
6153 goto err;
6156 if (!port) {
6157 log_warn(LD_CONFIG,
6158 "Transport address '%s' has no port.", addrport);
6159 goto err;
6162 if (!validate_only) {
6163 log_info(LD_DIR, "%s '%s' at %s.",
6164 server ? "Server transport" : "Transport",
6165 transports, fmt_addrport(&addr, port));
6167 if (!server) {
6168 transport_add_from_config(&addr, port,
6169 smartlist_get(transport_list, 0),
6170 socks_ver);
6175 r = 0;
6176 goto done;
6178 err:
6179 r = -1;
6181 done:
6182 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
6183 smartlist_free(items);
6184 if (transport_list) {
6185 SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
6186 smartlist_free(transport_list);
6189 return r;
6192 /** Given a ServerTransportListenAddr <b>line</b>, return its
6193 * <address:port> string. Return NULL if the line was not
6194 * well-formed.
6196 * If <b>transport</b> is set, return NULL if the line is not
6197 * referring to <b>transport</b>.
6199 * The returned string is allocated on the heap and it's the
6200 * responsibility of the caller to free it. */
6201 static char *
6202 get_bindaddr_from_transport_listen_line(const char *line,const char *transport)
6204 smartlist_t *items = NULL;
6205 const char *parsed_transport = NULL;
6206 char *addrport = NULL;
6207 tor_addr_t addr;
6208 uint16_t port = 0;
6210 items = smartlist_new();
6211 smartlist_split_string(items, line, NULL,
6212 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6214 if (smartlist_len(items) < 2) {
6215 log_warn(LD_CONFIG,"Too few arguments on ServerTransportListenAddr line.");
6216 goto err;
6219 parsed_transport = smartlist_get(items, 0);
6220 addrport = tor_strdup(smartlist_get(items, 1));
6222 /* If 'transport' is given, check if it matches the one on the line */
6223 if (transport && strcmp(transport, parsed_transport))
6224 goto err;
6226 /* Validate addrport */
6227 if (tor_addr_port_parse(LOG_WARN, addrport, &addr, &port, -1)<0) {
6228 log_warn(LD_CONFIG, "Error parsing ServerTransportListenAddr "
6229 "address '%s'", addrport);
6230 goto err;
6233 goto done;
6235 err:
6236 tor_free(addrport);
6237 addrport = NULL;
6239 done:
6240 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
6241 smartlist_free(items);
6243 return addrport;
6246 /** Given a ServerTransportOptions <b>line</b>, return a smartlist
6247 * with the options. Return NULL if the line was not well-formed.
6249 * If <b>transport</b> is set, return NULL if the line is not
6250 * referring to <b>transport</b>.
6252 * The returned smartlist and its strings are allocated on the heap
6253 * and it's the responsibility of the caller to free it. */
6254 smartlist_t *
6255 get_options_from_transport_options_line(const char *line,const char *transport)
6257 smartlist_t *items = smartlist_new();
6258 smartlist_t *options = smartlist_new();
6259 const char *parsed_transport = NULL;
6261 smartlist_split_string(items, line, NULL,
6262 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6264 if (smartlist_len(items) < 2) {
6265 log_warn(LD_CONFIG,"Too few arguments on ServerTransportOptions line.");
6266 goto err;
6269 parsed_transport = smartlist_get(items, 0);
6270 /* If 'transport' is given, check if it matches the one on the line */
6271 if (transport && strcmp(transport, parsed_transport))
6272 goto err;
6274 SMARTLIST_FOREACH_BEGIN(items, const char *, option) {
6275 if (option_sl_idx == 0) /* skip the transport field (first field)*/
6276 continue;
6278 /* validate that it's a k=v value */
6279 if (!string_is_key_value(LOG_WARN, option)) {
6280 log_warn(LD_CONFIG, "%s is not a k=v value.", escaped(option));
6281 goto err;
6284 /* add it to the options smartlist */
6285 smartlist_add_strdup(options, option);
6286 log_debug(LD_CONFIG, "Added %s to the list of options", escaped(option));
6287 } SMARTLIST_FOREACH_END(option);
6289 goto done;
6291 err:
6292 SMARTLIST_FOREACH(options, char*, s, tor_free(s));
6293 smartlist_free(options);
6294 options = NULL;
6296 done:
6297 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
6298 smartlist_free(items);
6300 return options;
6303 /** Given the name of a pluggable transport in <b>transport</b>, check
6304 * the configuration file to see if the user has explicitly asked for
6305 * it to listen on a specific port. Return a <address:port> string if
6306 * so, otherwise NULL. */
6307 char *
6308 get_transport_bindaddr_from_config(const char *transport)
6310 config_line_t *cl;
6311 const or_options_t *options = get_options();
6313 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
6314 char *bindaddr =
6315 get_bindaddr_from_transport_listen_line(cl->value, transport);
6316 if (bindaddr)
6317 return bindaddr;
6320 return NULL;
6323 /** Given the name of a pluggable transport in <b>transport</b>, check
6324 * the configuration file to see if the user has asked us to pass any
6325 * parameters to the pluggable transport. Return a smartlist
6326 * containing the parameters, otherwise NULL. */
6327 smartlist_t *
6328 get_options_for_server_transport(const char *transport)
6330 config_line_t *cl;
6331 const or_options_t *options = get_options();
6333 for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
6334 smartlist_t *options_sl =
6335 get_options_from_transport_options_line(cl->value, transport);
6336 if (options_sl)
6337 return options_sl;
6340 return NULL;
6343 /** Read the contents of a DirAuthority line from <b>line</b>. If
6344 * <b>validate_only</b> is 0, and the line is well-formed, and it
6345 * shares any bits with <b>required_type</b> or <b>required_type</b>
6346 * is NO_DIRINFO (zero), then add the dirserver described in the line
6347 * (minus whatever bits it's missing) as a valid authority.
6348 * Return 0 on success or filtering out by type,
6349 * or -1 if the line isn't well-formed or if we can't add it. */
6350 STATIC int
6351 parse_dir_authority_line(const char *line, dirinfo_type_t required_type,
6352 int validate_only)
6354 smartlist_t *items = NULL;
6355 int r;
6356 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
6357 tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
6358 uint16_t dir_port = 0, or_port = 0;
6359 char digest[DIGEST_LEN];
6360 char v3_digest[DIGEST_LEN];
6361 dirinfo_type_t type = 0;
6362 double weight = 1.0;
6364 memset(v3_digest, 0, sizeof(v3_digest));
6366 items = smartlist_new();
6367 smartlist_split_string(items, line, NULL,
6368 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6369 if (smartlist_len(items) < 1) {
6370 log_warn(LD_CONFIG, "No arguments on DirAuthority line.");
6371 goto err;
6374 if (is_legal_nickname(smartlist_get(items, 0))) {
6375 nickname = smartlist_get(items, 0);
6376 smartlist_del_keeporder(items, 0);
6379 while (smartlist_len(items)) {
6380 char *flag = smartlist_get(items, 0);
6381 if (TOR_ISDIGIT(flag[0]))
6382 break;
6383 if (!strcasecmp(flag, "hs") ||
6384 !strcasecmp(flag, "no-hs")) {
6385 log_warn(LD_CONFIG, "The DirAuthority options 'hs' and 'no-hs' are "
6386 "obsolete; you don't need them any more.");
6387 } else if (!strcasecmp(flag, "bridge")) {
6388 type |= BRIDGE_DIRINFO;
6389 } else if (!strcasecmp(flag, "no-v2")) {
6390 /* obsolete, but may still be contained in DirAuthority lines generated
6391 by various tools */;
6392 } else if (!strcasecmpstart(flag, "orport=")) {
6393 int ok;
6394 char *portstring = flag + strlen("orport=");
6395 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
6396 if (!ok)
6397 log_warn(LD_CONFIG, "Invalid orport '%s' on DirAuthority line.",
6398 portstring);
6399 } else if (!strcmpstart(flag, "weight=")) {
6400 int ok;
6401 const char *wstring = flag + strlen("weight=");
6402 weight = tor_parse_double(wstring, 0, (double)UINT64_MAX, &ok, NULL);
6403 if (!ok) {
6404 log_warn(LD_CONFIG, "Invalid weight '%s' on DirAuthority line.",flag);
6405 weight=1.0;
6407 } else if (!strcasecmpstart(flag, "v3ident=")) {
6408 char *idstr = flag + strlen("v3ident=");
6409 if (strlen(idstr) != HEX_DIGEST_LEN ||
6410 base16_decode(v3_digest, DIGEST_LEN,
6411 idstr, HEX_DIGEST_LEN) != DIGEST_LEN) {
6412 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirAuthority line",
6413 flag);
6414 } else {
6415 type |= V3_DIRINFO|EXTRAINFO_DIRINFO|MICRODESC_DIRINFO;
6417 } else if (!strcasecmpstart(flag, "ipv6=")) {
6418 if (ipv6_addrport_ptr) {
6419 log_warn(LD_CONFIG, "Redundant ipv6 addr/port on DirAuthority line");
6420 } else {
6421 if (tor_addr_port_parse(LOG_WARN, flag+strlen("ipv6="),
6422 &ipv6_addrport.addr, &ipv6_addrport.port,
6423 -1) < 0
6424 || tor_addr_family(&ipv6_addrport.addr) != AF_INET6) {
6425 log_warn(LD_CONFIG, "Bad ipv6 addr/port %s on DirAuthority line",
6426 escaped(flag));
6427 goto err;
6429 ipv6_addrport_ptr = &ipv6_addrport;
6431 } else {
6432 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirAuthority line",
6433 flag);
6435 tor_free(flag);
6436 smartlist_del_keeporder(items, 0);
6439 if (smartlist_len(items) < 2) {
6440 log_warn(LD_CONFIG, "Too few arguments to DirAuthority line.");
6441 goto err;
6443 addrport = smartlist_get(items, 0);
6444 smartlist_del_keeporder(items, 0);
6445 if (addr_port_lookup(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
6446 log_warn(LD_CONFIG, "Error parsing DirAuthority address '%s'", addrport);
6447 goto err;
6449 if (!dir_port) {
6450 log_warn(LD_CONFIG, "Missing port in DirAuthority address '%s'",addrport);
6451 goto err;
6454 fingerprint = smartlist_join_strings(items, "", 0, NULL);
6455 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
6456 log_warn(LD_CONFIG, "Key digest '%s' for DirAuthority is wrong length %d.",
6457 fingerprint, (int)strlen(fingerprint));
6458 goto err;
6460 if (base16_decode(digest, DIGEST_LEN,
6461 fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
6462 log_warn(LD_CONFIG, "Unable to decode DirAuthority key digest.");
6463 goto err;
6466 if (!validate_only && (!required_type || required_type & type)) {
6467 dir_server_t *ds;
6468 if (required_type)
6469 type &= required_type; /* pare down what we think of them as an
6470 * authority for. */
6471 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
6472 address, (int)dir_port, (char*)smartlist_get(items,0));
6473 if (!(ds = trusted_dir_server_new(nickname, address, dir_port, or_port,
6474 ipv6_addrport_ptr,
6475 digest, v3_digest, type, weight)))
6476 goto err;
6477 dir_server_add(ds);
6480 r = 0;
6481 goto done;
6483 err:
6484 r = -1;
6486 done:
6487 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
6488 smartlist_free(items);
6489 tor_free(addrport);
6490 tor_free(address);
6491 tor_free(nickname);
6492 tor_free(fingerprint);
6493 return r;
6496 /** Read the contents of a FallbackDir line from <b>line</b>. If
6497 * <b>validate_only</b> is 0, and the line is well-formed, then add the
6498 * dirserver described in the line as a fallback directory. Return 0 on
6499 * success, or -1 if the line isn't well-formed or if we can't add it. */
6501 parse_dir_fallback_line(const char *line,
6502 int validate_only)
6504 int r = -1;
6505 smartlist_t *items = smartlist_new(), *positional = smartlist_new();
6506 int orport = -1;
6507 uint16_t dirport;
6508 tor_addr_t addr;
6509 int ok;
6510 char id[DIGEST_LEN];
6511 char *address=NULL;
6512 tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
6513 double weight=1.0;
6515 memset(id, 0, sizeof(id));
6516 smartlist_split_string(items, line, NULL,
6517 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6518 SMARTLIST_FOREACH_BEGIN(items, const char *, cp) {
6519 const char *eq = strchr(cp, '=');
6520 ok = 1;
6521 if (! eq) {
6522 smartlist_add(positional, (char*)cp);
6523 continue;
6525 if (!strcmpstart(cp, "orport=")) {
6526 orport = (int)tor_parse_long(cp+strlen("orport="), 10,
6527 1, 65535, &ok, NULL);
6528 } else if (!strcmpstart(cp, "id=")) {
6529 ok = base16_decode(id, DIGEST_LEN, cp+strlen("id="),
6530 strlen(cp)-strlen("id=")) == DIGEST_LEN;
6531 } else if (!strcasecmpstart(cp, "ipv6=")) {
6532 if (ipv6_addrport_ptr) {
6533 log_warn(LD_CONFIG, "Redundant ipv6 addr/port on FallbackDir line");
6534 } else {
6535 if (tor_addr_port_parse(LOG_WARN, cp+strlen("ipv6="),
6536 &ipv6_addrport.addr, &ipv6_addrport.port,
6537 -1) < 0
6538 || tor_addr_family(&ipv6_addrport.addr) != AF_INET6) {
6539 log_warn(LD_CONFIG, "Bad ipv6 addr/port %s on FallbackDir line",
6540 escaped(cp));
6541 goto end;
6543 ipv6_addrport_ptr = &ipv6_addrport;
6545 } else if (!strcmpstart(cp, "weight=")) {
6546 int num_ok;
6547 const char *wstring = cp + strlen("weight=");
6548 weight = tor_parse_double(wstring, 0, (double)UINT64_MAX, &num_ok, NULL);
6549 if (!num_ok) {
6550 log_warn(LD_CONFIG, "Invalid weight '%s' on FallbackDir line.", cp);
6551 weight=1.0;
6555 if (!ok) {
6556 log_warn(LD_CONFIG, "Bad FallbackDir option %s", escaped(cp));
6557 goto end;
6559 } SMARTLIST_FOREACH_END(cp);
6561 if (smartlist_len(positional) != 1) {
6562 log_warn(LD_CONFIG, "Couldn't parse FallbackDir line %s", escaped(line));
6563 goto end;
6566 if (tor_digest_is_zero(id)) {
6567 log_warn(LD_CONFIG, "Missing identity on FallbackDir line");
6568 goto end;
6571 if (orport <= 0) {
6572 log_warn(LD_CONFIG, "Missing orport on FallbackDir line");
6573 goto end;
6576 if (tor_addr_port_split(LOG_INFO, smartlist_get(positional, 0),
6577 &address, &dirport) < 0 ||
6578 tor_addr_parse(&addr, address)<0) {
6579 log_warn(LD_CONFIG, "Couldn't parse address:port %s on FallbackDir line",
6580 (const char*)smartlist_get(positional, 0));
6581 goto end;
6584 if (!validate_only) {
6585 dir_server_t *ds;
6586 ds = fallback_dir_server_new(&addr, dirport, orport, ipv6_addrport_ptr,
6587 id, weight);
6588 if (!ds) {
6589 log_warn(LD_CONFIG, "Couldn't create FallbackDir %s", escaped(line));
6590 goto end;
6592 dir_server_add(ds);
6595 r = 0;
6597 end:
6598 SMARTLIST_FOREACH(items, char *, cp, tor_free(cp));
6599 smartlist_free(items);
6600 smartlist_free(positional);
6601 tor_free(address);
6602 return r;
6605 /** Allocate and return a new port_cfg_t with reasonable defaults. */
6606 STATIC port_cfg_t *
6607 port_cfg_new(size_t namelen)
6609 tor_assert(namelen <= SIZE_T_CEILING - sizeof(port_cfg_t) - 1);
6610 port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t) + namelen + 1);
6611 cfg->entry_cfg.ipv4_traffic = 1;
6612 cfg->entry_cfg.ipv6_traffic = 1;
6613 cfg->entry_cfg.dns_request = 1;
6614 cfg->entry_cfg.onion_traffic = 1;
6615 cfg->entry_cfg.prefer_ipv6_virtaddr = 1;
6616 return cfg;
6619 /** Free all storage held in <b>port</b> */
6620 STATIC void
6621 port_cfg_free_(port_cfg_t *port)
6623 tor_free(port);
6626 /** Warn for every port in <b>ports</b> of type <b>listener_type</b> that is
6627 * on a publicly routable address. */
6628 static void
6629 warn_nonlocal_client_ports(const smartlist_t *ports,
6630 const char *portname,
6631 const int listener_type)
6633 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
6634 if (port->type != listener_type)
6635 continue;
6636 if (port->is_unix_addr) {
6637 /* Unix sockets aren't accessible over a network. */
6638 } else if (!tor_addr_is_internal(&port->addr, 1)) {
6639 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
6640 "Other people on the Internet might find your computer and "
6641 "use it as an open proxy. Please don't allow this unless you "
6642 "have a good reason.",
6643 fmt_addrport(&port->addr, port->port), portname);
6644 } else if (!tor_addr_is_loopback(&port->addr)) {
6645 log_notice(LD_CONFIG, "You configured a non-loopback address '%s' "
6646 "for %sPort. This allows everybody on your local network to "
6647 "use your machine as a proxy. Make sure this is what you "
6648 "wanted.",
6649 fmt_addrport(&port->addr, port->port), portname);
6651 } SMARTLIST_FOREACH_END(port);
6654 /** Warn for every Extended ORPort port in <b>ports</b> that is on a
6655 * publicly routable address. */
6656 static void
6657 warn_nonlocal_ext_orports(const smartlist_t *ports, const char *portname)
6659 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
6660 if (port->type != CONN_TYPE_EXT_OR_LISTENER)
6661 continue;
6662 if (port->is_unix_addr)
6663 continue;
6664 /* XXX maybe warn even if address is RFC1918? */
6665 if (!tor_addr_is_internal(&port->addr, 1)) {
6666 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
6667 "This is not advised; this address is supposed to only be "
6668 "exposed on localhost so that your pluggable transport "
6669 "proxies can connect to it.",
6670 fmt_addrport(&port->addr, port->port), portname);
6672 } SMARTLIST_FOREACH_END(port);
6675 /** Given a list of port_cfg_t in <b>ports</b>, warn if any controller port
6676 * there is listening on any non-loopback address. If <b>forbid_nonlocal</b>
6677 * is true, then emit a stronger warning and remove the port from the list.
6679 static void
6680 warn_nonlocal_controller_ports(smartlist_t *ports, unsigned forbid_nonlocal)
6682 int warned = 0;
6683 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
6684 if (port->type != CONN_TYPE_CONTROL_LISTENER)
6685 continue;
6686 if (port->is_unix_addr)
6687 continue;
6688 if (!tor_addr_is_loopback(&port->addr)) {
6689 if (forbid_nonlocal) {
6690 if (!warned)
6691 log_warn(LD_CONFIG,
6692 "You have a ControlPort set to accept "
6693 "unauthenticated connections from a non-local address. "
6694 "This means that programs not running on your computer "
6695 "can reconfigure your Tor, without even having to guess a "
6696 "password. That's so bad that I'm closing your ControlPort "
6697 "for you. If you need to control your Tor remotely, try "
6698 "enabling authentication and using a tool like stunnel or "
6699 "ssh to encrypt remote access.");
6700 warned = 1;
6701 port_cfg_free(port);
6702 SMARTLIST_DEL_CURRENT(ports, port);
6703 } else {
6704 log_warn(LD_CONFIG, "You have a ControlPort set to accept "
6705 "connections from a non-local address. This means that "
6706 "programs not running on your computer can reconfigure your "
6707 "Tor. That's pretty bad, since the controller "
6708 "protocol isn't encrypted! Maybe you should just listen on "
6709 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
6710 "remote connections to your control port.");
6711 return; /* No point in checking the rest */
6714 } SMARTLIST_FOREACH_END(port);
6718 * Take a string (<b>line</b>) that begins with either an address:port, a
6719 * port, or an AF_UNIX address, optionally quoted, prefixed with
6720 * "unix:". Parse that line, and on success, set <b>addrport_out</b> to a new
6721 * string containing the beginning portion (without prefix). Iff there was a
6722 * unix: prefix, set <b>is_unix_out</b> to true. On success, also set
6723 * <b>rest_out</b> to point to the part of the line after the address portion.
6725 * Return 0 on success, -1 on failure.
6728 port_cfg_line_extract_addrport(const char *line,
6729 char **addrport_out,
6730 int *is_unix_out,
6731 const char **rest_out)
6733 tor_assert(line);
6734 tor_assert(addrport_out);
6735 tor_assert(is_unix_out);
6736 tor_assert(rest_out);
6738 line = eat_whitespace(line);
6740 if (!strcmpstart(line, unix_q_socket_prefix)) {
6741 // It starts with unix:"
6742 size_t sz;
6743 *is_unix_out = 1;
6744 *addrport_out = NULL;
6745 line += strlen(unix_socket_prefix); /*No q: Keep the quote */
6746 *rest_out = unescape_string(line, addrport_out, &sz);
6747 if (!*rest_out || (*addrport_out && sz != strlen(*addrport_out))) {
6748 tor_free(*addrport_out);
6749 return -1;
6751 *rest_out = eat_whitespace(*rest_out);
6752 return 0;
6753 } else {
6754 // Is there a unix: prefix?
6755 if (!strcmpstart(line, unix_socket_prefix)) {
6756 line += strlen(unix_socket_prefix);
6757 *is_unix_out = 1;
6758 } else {
6759 *is_unix_out = 0;
6762 const char *end = find_whitespace(line);
6763 if (BUG(!end)) {
6764 end = strchr(line, '\0'); // LCOV_EXCL_LINE -- this can't be NULL
6766 tor_assert(end && end >= line);
6767 *addrport_out = tor_strndup(line, end - line);
6768 *rest_out = eat_whitespace(end);
6769 return 0;
6773 static void
6774 warn_client_dns_cache(const char *option, int disabling)
6776 if (disabling)
6777 return;
6779 warn_deprecated_option(option,
6780 "Client-side DNS cacheing enables a wide variety of route-"
6781 "capture attacks. If a single bad exit node lies to you about "
6782 "an IP address, cacheing that address would make you visit "
6783 "an address of the attacker's choice every time you connected "
6784 "to your destination.");
6788 * Validate the configured bridge distribution method from a BridgeDistribution
6789 * config line.
6791 * The input <b>bd</b>, is a string taken from the BridgeDistribution config
6792 * line (if present). If the option wasn't set, return 0 immediately. The
6793 * BridgeDistribution option is then validated. Currently valid, recognised
6794 * options are:
6796 * - "none"
6797 * - "any"
6798 * - "https"
6799 * - "email"
6800 * - "moat"
6801 * - "hyphae"
6803 * If the option string is unrecognised, a warning will be logged and 0 is
6804 * returned. If the option string contains an invalid character, -1 is
6805 * returned.
6807 STATIC int
6808 check_bridge_distribution_setting(const char *bd)
6810 if (bd == NULL)
6811 return 0;
6813 const char *RECOGNIZED[] = {
6814 "none", "any", "https", "email", "moat", "hyphae"
6816 unsigned i;
6817 for (i = 0; i < ARRAY_LENGTH(RECOGNIZED); ++i) {
6818 if (!strcmp(bd, RECOGNIZED[i]))
6819 return 0;
6822 const char *cp = bd;
6823 // Method = (KeywordChar | "_") +
6824 while (TOR_ISALNUM(*cp) || *cp == '-' || *cp == '_')
6825 ++cp;
6827 if (*cp == 0) {
6828 log_warn(LD_CONFIG, "Unrecognized BridgeDistribution value %s. I'll "
6829 "assume you know what you are doing...", escaped(bd));
6830 return 0; // we reached the end of the string; all is well
6831 } else {
6832 return -1; // we found a bad character in the string.
6837 * Parse port configuration for a single port type.
6839 * Read entries of the "FooPort" type from the list <b>ports</b>. Syntax is
6840 * that FooPort can have any number of entries of the format
6841 * "[Address:][Port] IsolationOptions".
6843 * In log messages, describe the port type as <b>portname</b>.
6845 * If no address is specified, default to <b>defaultaddr</b>. If no
6846 * FooPort is given, default to defaultport (if 0, there is no default).
6848 * If CL_PORT_NO_STREAM_OPTIONS is set in <b>flags</b>, do not allow stream
6849 * isolation options in the FooPort entries.
6851 * If CL_PORT_WARN_NONLOCAL is set in <b>flags</b>, warn if any of the
6852 * ports are not on a local address. If CL_PORT_FORBID_NONLOCAL is set,
6853 * this is a control port with no password set: don't even allow it.
6855 * If CL_PORT_SERVER_OPTIONS is set in <b>flags</b>, do not allow stream
6856 * isolation options in the FooPort entries; instead allow the
6857 * server-port option set.
6859 * If CL_PORT_TAKES_HOSTNAMES is set in <b>flags</b>, allow the options
6860 * {No,}IPv{4,6}Traffic.
6862 * On success, if <b>out</b> is given, add a new port_cfg_t entry to
6863 * <b>out</b> for every port that the client should listen on. Return 0
6864 * on success, -1 on failure.
6866 STATIC int
6867 parse_port_config(smartlist_t *out,
6868 const config_line_t *ports,
6869 const char *portname,
6870 int listener_type,
6871 const char *defaultaddr,
6872 int defaultport,
6873 const unsigned flags)
6875 smartlist_t *elts;
6876 int retval = -1;
6877 const unsigned is_control = (listener_type == CONN_TYPE_CONTROL_LISTENER);
6878 const unsigned is_ext_orport = (listener_type == CONN_TYPE_EXT_OR_LISTENER);
6879 const unsigned allow_no_stream_options = flags & CL_PORT_NO_STREAM_OPTIONS;
6880 const unsigned use_server_options = flags & CL_PORT_SERVER_OPTIONS;
6881 const unsigned warn_nonlocal = flags & CL_PORT_WARN_NONLOCAL;
6882 const unsigned forbid_nonlocal = flags & CL_PORT_FORBID_NONLOCAL;
6883 const unsigned default_to_group_writable =
6884 flags & CL_PORT_DFLT_GROUP_WRITABLE;
6885 const unsigned takes_hostnames = flags & CL_PORT_TAKES_HOSTNAMES;
6886 const unsigned is_unix_socket = flags & CL_PORT_IS_UNIXSOCKET;
6887 int got_zero_port=0, got_nonzero_port=0;
6888 char *unix_socket_path = NULL;
6890 /* If there's no FooPort, then maybe make a default one. */
6891 if (! ports) {
6892 if (defaultport && defaultaddr && out) {
6893 port_cfg_t *cfg = port_cfg_new(is_unix_socket ? strlen(defaultaddr) : 0);
6894 cfg->type = listener_type;
6895 if (is_unix_socket) {
6896 tor_addr_make_unspec(&cfg->addr);
6897 memcpy(cfg->unix_addr, defaultaddr, strlen(defaultaddr) + 1);
6898 cfg->is_unix_addr = 1;
6899 } else {
6900 cfg->port = defaultport;
6901 tor_addr_parse(&cfg->addr, defaultaddr);
6903 cfg->entry_cfg.session_group = SESSION_GROUP_UNSET;
6904 cfg->entry_cfg.isolation_flags = ISO_DEFAULT;
6905 smartlist_add(out, cfg);
6907 return 0;
6910 /* At last we can actually parse the FooPort lines. The syntax is:
6911 * [Addr:](Port|auto) [Options].*/
6912 elts = smartlist_new();
6913 char *addrport = NULL;
6915 for (; ports; ports = ports->next) {
6916 tor_addr_t addr;
6917 int port;
6918 int sessiongroup = SESSION_GROUP_UNSET;
6919 unsigned isolation = ISO_DEFAULT;
6920 int prefer_no_auth = 0;
6921 int socks_iso_keep_alive = 0;
6923 uint16_t ptmp=0;
6924 int ok;
6925 /* This must be kept in sync with port_cfg_new's defaults */
6926 int no_listen = 0, no_advertise = 0, all_addrs = 0,
6927 bind_ipv4_only = 0, bind_ipv6_only = 0,
6928 ipv4_traffic = 1, ipv6_traffic = 1, prefer_ipv6 = 0, dns_request = 1,
6929 onion_traffic = 1,
6930 cache_ipv4 = 0, use_cached_ipv4 = 0,
6931 cache_ipv6 = 0, use_cached_ipv6 = 0,
6932 prefer_ipv6_automap = 1, world_writable = 0, group_writable = 0,
6933 relax_dirmode_check = 0,
6934 has_used_unix_socket_only_option = 0;
6936 int is_unix_tagged_addr = 0;
6937 const char *rest_of_line = NULL;
6938 if (port_cfg_line_extract_addrport(ports->value,
6939 &addrport, &is_unix_tagged_addr, &rest_of_line)<0) {
6940 log_warn(LD_CONFIG, "Invalid %sPort line with unparsable address",
6941 portname);
6942 goto err;
6944 if (strlen(addrport) == 0) {
6945 log_warn(LD_CONFIG, "Invalid %sPort line with no address", portname);
6946 goto err;
6949 /* Split the remainder... */
6950 smartlist_split_string(elts, rest_of_line, NULL,
6951 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
6953 /* Let's start to check if it's a Unix socket path. */
6954 if (is_unix_tagged_addr) {
6955 #ifndef HAVE_SYS_UN_H
6956 log_warn(LD_CONFIG, "Unix sockets not supported on this system.");
6957 goto err;
6958 #endif
6959 unix_socket_path = addrport;
6960 addrport = NULL;
6963 if (unix_socket_path &&
6964 ! conn_listener_type_supports_af_unix(listener_type)) {
6965 log_warn(LD_CONFIG, "%sPort does not support unix sockets", portname);
6966 goto err;
6969 if (unix_socket_path) {
6970 port = 1;
6971 } else if (is_unix_socket) {
6972 if (BUG(!addrport))
6973 goto err; // LCOV_EXCL_LINE unreachable, but coverity can't tell that
6974 unix_socket_path = tor_strdup(addrport);
6975 if (!strcmp(addrport, "0"))
6976 port = 0;
6977 else
6978 port = 1;
6979 } else if (!strcmp(addrport, "auto")) {
6980 port = CFG_AUTO_PORT;
6981 int af = tor_addr_parse(&addr, defaultaddr);
6982 tor_assert(af >= 0);
6983 } else if (!strcasecmpend(addrport, ":auto")) {
6984 char *addrtmp = tor_strndup(addrport, strlen(addrport)-5);
6985 port = CFG_AUTO_PORT;
6986 if (tor_addr_port_lookup(addrtmp, &addr, &ptmp)<0 || ptmp) {
6987 log_warn(LD_CONFIG, "Invalid address '%s' for %sPort",
6988 escaped(addrport), portname);
6989 tor_free(addrtmp);
6990 goto err;
6992 tor_free(addrtmp);
6993 } else {
6994 /* Try parsing integer port before address, because, who knows?
6995 "9050" might be a valid address. */
6996 port = (int) tor_parse_long(addrport, 10, 0, 65535, &ok, NULL);
6997 if (ok) {
6998 int af = tor_addr_parse(&addr, defaultaddr);
6999 tor_assert(af >= 0);
7000 } else if (tor_addr_port_lookup(addrport, &addr, &ptmp) == 0) {
7001 if (ptmp == 0) {
7002 log_warn(LD_CONFIG, "%sPort line has address but no port", portname);
7003 goto err;
7005 port = ptmp;
7006 } else {
7007 log_warn(LD_CONFIG, "Couldn't parse address %s for %sPort",
7008 escaped(addrport), portname);
7009 goto err;
7013 if (unix_socket_path && default_to_group_writable)
7014 group_writable = 1;
7016 /* Now parse the rest of the options, if any. */
7017 if (use_server_options) {
7018 /* This is a server port; parse advertising options */
7019 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
7020 if (!strcasecmp(elt, "NoAdvertise")) {
7021 no_advertise = 1;
7022 } else if (!strcasecmp(elt, "NoListen")) {
7023 no_listen = 1;
7024 #if 0
7025 /* not implemented yet. */
7026 } else if (!strcasecmp(elt, "AllAddrs")) {
7028 all_addrs = 1;
7029 #endif /* 0 */
7030 } else if (!strcasecmp(elt, "IPv4Only")) {
7031 bind_ipv4_only = 1;
7032 } else if (!strcasecmp(elt, "IPv6Only")) {
7033 bind_ipv6_only = 1;
7034 } else {
7035 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
7036 portname, escaped(elt));
7038 } SMARTLIST_FOREACH_END(elt);
7040 if (no_advertise && no_listen) {
7041 log_warn(LD_CONFIG, "Tried to set both NoListen and NoAdvertise "
7042 "on %sPort line '%s'",
7043 portname, escaped(ports->value));
7044 goto err;
7046 if (bind_ipv4_only && bind_ipv6_only) {
7047 log_warn(LD_CONFIG, "Tried to set both IPv4Only and IPv6Only "
7048 "on %sPort line '%s'",
7049 portname, escaped(ports->value));
7050 goto err;
7052 if (bind_ipv4_only && tor_addr_family(&addr) == AF_INET6) {
7053 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv6",
7054 portname);
7055 goto err;
7057 if (bind_ipv6_only && tor_addr_family(&addr) == AF_INET) {
7058 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv4",
7059 portname);
7060 goto err;
7062 } else {
7063 /* This is a client port; parse isolation options */
7064 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
7065 int no = 0, isoflag = 0;
7066 const char *elt_orig = elt;
7068 if (!strcasecmpstart(elt, "SessionGroup=")) {
7069 int group = (int)tor_parse_long(elt+strlen("SessionGroup="),
7070 10, 0, INT_MAX, &ok, NULL);
7071 if (!ok || !allow_no_stream_options) {
7072 log_warn(LD_CONFIG, "Invalid %sPort option '%s'",
7073 portname, escaped(elt));
7074 goto err;
7076 if (sessiongroup >= 0) {
7077 log_warn(LD_CONFIG, "Multiple SessionGroup options on %sPort",
7078 portname);
7079 goto err;
7081 sessiongroup = group;
7082 continue;
7085 if (!strcasecmpstart(elt, "No")) {
7086 no = 1;
7087 elt += 2;
7090 if (!strcasecmp(elt, "GroupWritable")) {
7091 group_writable = !no;
7092 has_used_unix_socket_only_option = 1;
7093 continue;
7094 } else if (!strcasecmp(elt, "WorldWritable")) {
7095 world_writable = !no;
7096 has_used_unix_socket_only_option = 1;
7097 continue;
7098 } else if (!strcasecmp(elt, "RelaxDirModeCheck")) {
7099 relax_dirmode_check = !no;
7100 has_used_unix_socket_only_option = 1;
7101 continue;
7104 if (allow_no_stream_options) {
7105 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
7106 portname, escaped(elt));
7107 continue;
7110 if (takes_hostnames) {
7111 if (!strcasecmp(elt, "IPv4Traffic")) {
7112 ipv4_traffic = ! no;
7113 continue;
7114 } else if (!strcasecmp(elt, "IPv6Traffic")) {
7115 ipv6_traffic = ! no;
7116 continue;
7117 } else if (!strcasecmp(elt, "PreferIPv6")) {
7118 prefer_ipv6 = ! no;
7119 continue;
7120 } else if (!strcasecmp(elt, "DNSRequest")) {
7121 dns_request = ! no;
7122 continue;
7123 } else if (!strcasecmp(elt, "OnionTraffic")) {
7124 onion_traffic = ! no;
7125 continue;
7126 } else if (!strcasecmp(elt, "OnionTrafficOnly")) {
7127 /* Only connect to .onion addresses. Equivalent to
7128 * NoDNSRequest, NoIPv4Traffic, NoIPv6Traffic. The option
7129 * NoOnionTrafficOnly is not supported, it's too confusing. */
7130 if (no) {
7131 log_warn(LD_CONFIG, "Unsupported %sPort option 'No%s'. Use "
7132 "DNSRequest, IPv4Traffic, and/or IPv6Traffic instead.",
7133 portname, escaped(elt));
7134 } else {
7135 ipv4_traffic = ipv6_traffic = dns_request = 0;
7137 continue;
7140 if (!strcasecmp(elt, "CacheIPv4DNS")) {
7141 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
7142 cache_ipv4 = ! no;
7143 continue;
7144 } else if (!strcasecmp(elt, "CacheIPv6DNS")) {
7145 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
7146 cache_ipv6 = ! no;
7147 continue;
7148 } else if (!strcasecmp(elt, "CacheDNS")) {
7149 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
7150 cache_ipv4 = cache_ipv6 = ! no;
7151 continue;
7152 } else if (!strcasecmp(elt, "UseIPv4Cache")) {
7153 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
7154 use_cached_ipv4 = ! no;
7155 continue;
7156 } else if (!strcasecmp(elt, "UseIPv6Cache")) {
7157 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
7158 use_cached_ipv6 = ! no;
7159 continue;
7160 } else if (!strcasecmp(elt, "UseDNSCache")) {
7161 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
7162 use_cached_ipv4 = use_cached_ipv6 = ! no;
7163 continue;
7164 } else if (!strcasecmp(elt, "PreferIPv6Automap")) {
7165 prefer_ipv6_automap = ! no;
7166 continue;
7167 } else if (!strcasecmp(elt, "PreferSOCKSNoAuth")) {
7168 prefer_no_auth = ! no;
7169 continue;
7170 } else if (!strcasecmp(elt, "KeepAliveIsolateSOCKSAuth")) {
7171 socks_iso_keep_alive = ! no;
7172 continue;
7175 if (!strcasecmpend(elt, "s"))
7176 elt[strlen(elt)-1] = '\0'; /* kill plurals. */
7178 if (!strcasecmp(elt, "IsolateDestPort")) {
7179 isoflag = ISO_DESTPORT;
7180 } else if (!strcasecmp(elt, "IsolateDestAddr")) {
7181 isoflag = ISO_DESTADDR;
7182 } else if (!strcasecmp(elt, "IsolateSOCKSAuth")) {
7183 isoflag = ISO_SOCKSAUTH;
7184 } else if (!strcasecmp(elt, "IsolateClientProtocol")) {
7185 isoflag = ISO_CLIENTPROTO;
7186 } else if (!strcasecmp(elt, "IsolateClientAddr")) {
7187 isoflag = ISO_CLIENTADDR;
7188 } else {
7189 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
7190 portname, escaped(elt_orig));
7193 if (no) {
7194 isolation &= ~isoflag;
7195 } else {
7196 isolation |= isoflag;
7198 } SMARTLIST_FOREACH_END(elt);
7201 if (port)
7202 got_nonzero_port = 1;
7203 else
7204 got_zero_port = 1;
7206 if (dns_request == 0 && listener_type == CONN_TYPE_AP_DNS_LISTENER) {
7207 log_warn(LD_CONFIG, "You have a %sPort entry with DNS disabled; that "
7208 "won't work.", portname);
7209 goto err;
7212 if (ipv4_traffic == 0 && ipv6_traffic == 0 && onion_traffic == 0
7213 && listener_type != CONN_TYPE_AP_DNS_LISTENER) {
7214 log_warn(LD_CONFIG, "You have a %sPort entry with all of IPv4 and "
7215 "IPv6 and .onion disabled; that won't work.", portname);
7216 goto err;
7219 if (dns_request == 1 && ipv4_traffic == 0 && ipv6_traffic == 0
7220 && listener_type != CONN_TYPE_AP_DNS_LISTENER) {
7221 log_warn(LD_CONFIG, "You have a %sPort entry with DNSRequest enabled, "
7222 "but IPv4 and IPv6 disabled; DNS-based sites won't work.",
7223 portname);
7224 goto err;
7227 if ( has_used_unix_socket_only_option && ! unix_socket_path) {
7228 log_warn(LD_CONFIG, "You have a %sPort entry with GroupWritable, "
7229 "WorldWritable, or RelaxDirModeCheck, but it is not a "
7230 "unix socket.", portname);
7231 goto err;
7234 if (!(isolation & ISO_SOCKSAUTH) && socks_iso_keep_alive) {
7235 log_warn(LD_CONFIG, "You have a %sPort entry with both "
7236 "NoIsolateSOCKSAuth and KeepAliveIsolateSOCKSAuth set.",
7237 portname);
7238 goto err;
7241 if (unix_socket_path && (isolation & ISO_CLIENTADDR)) {
7242 /* `IsolateClientAddr` is nonsensical in the context of AF_LOCAL.
7243 * just silently remove the isolation flag.
7245 isolation &= ~ISO_CLIENTADDR;
7248 if (out && port) {
7249 size_t namelen = unix_socket_path ? strlen(unix_socket_path) : 0;
7250 port_cfg_t *cfg = port_cfg_new(namelen);
7251 if (unix_socket_path) {
7252 tor_addr_make_unspec(&cfg->addr);
7253 memcpy(cfg->unix_addr, unix_socket_path, namelen + 1);
7254 cfg->is_unix_addr = 1;
7255 tor_free(unix_socket_path);
7256 } else {
7257 tor_addr_copy(&cfg->addr, &addr);
7258 cfg->port = port;
7260 cfg->type = listener_type;
7261 cfg->is_world_writable = world_writable;
7262 cfg->is_group_writable = group_writable;
7263 cfg->relax_dirmode_check = relax_dirmode_check;
7264 cfg->entry_cfg.isolation_flags = isolation;
7265 cfg->entry_cfg.session_group = sessiongroup;
7266 cfg->server_cfg.no_advertise = no_advertise;
7267 cfg->server_cfg.no_listen = no_listen;
7268 cfg->server_cfg.all_addrs = all_addrs;
7269 cfg->server_cfg.bind_ipv4_only = bind_ipv4_only;
7270 cfg->server_cfg.bind_ipv6_only = bind_ipv6_only;
7271 cfg->entry_cfg.ipv4_traffic = ipv4_traffic;
7272 cfg->entry_cfg.ipv6_traffic = ipv6_traffic;
7273 cfg->entry_cfg.prefer_ipv6 = prefer_ipv6;
7274 cfg->entry_cfg.dns_request = dns_request;
7275 cfg->entry_cfg.onion_traffic = onion_traffic;
7276 cfg->entry_cfg.cache_ipv4_answers = cache_ipv4;
7277 cfg->entry_cfg.cache_ipv6_answers = cache_ipv6;
7278 cfg->entry_cfg.use_cached_ipv4_answers = use_cached_ipv4;
7279 cfg->entry_cfg.use_cached_ipv6_answers = use_cached_ipv6;
7280 cfg->entry_cfg.prefer_ipv6_virtaddr = prefer_ipv6_automap;
7281 cfg->entry_cfg.socks_prefer_no_auth = prefer_no_auth;
7282 if (! (isolation & ISO_SOCKSAUTH))
7283 cfg->entry_cfg.socks_prefer_no_auth = 1;
7284 cfg->entry_cfg.socks_iso_keep_alive = socks_iso_keep_alive;
7286 smartlist_add(out, cfg);
7288 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
7289 smartlist_clear(elts);
7290 tor_free(addrport);
7291 tor_free(unix_socket_path);
7294 if (warn_nonlocal && out) {
7295 if (is_control)
7296 warn_nonlocal_controller_ports(out, forbid_nonlocal);
7297 else if (is_ext_orport)
7298 warn_nonlocal_ext_orports(out, portname);
7299 else
7300 warn_nonlocal_client_ports(out, portname, listener_type);
7303 if (got_zero_port && got_nonzero_port) {
7304 log_warn(LD_CONFIG, "You specified a nonzero %sPort along with '%sPort 0' "
7305 "in the same configuration. Did you mean to disable %sPort or "
7306 "not?", portname, portname, portname);
7307 goto err;
7310 retval = 0;
7311 err:
7312 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
7313 smartlist_free(elts);
7314 tor_free(unix_socket_path);
7315 tor_free(addrport);
7316 return retval;
7319 /** Return the number of ports which are actually going to listen with type
7320 * <b>listenertype</b>. Do not count no_listen ports. Only count unix
7321 * sockets if count_sockets is true. */
7322 static int
7323 count_real_listeners(const smartlist_t *ports, int listenertype,
7324 int count_sockets)
7326 int n = 0;
7327 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
7328 if (port->server_cfg.no_listen)
7329 continue;
7330 if (!count_sockets && port->is_unix_addr)
7331 continue;
7332 if (port->type != listenertype)
7333 continue;
7334 ++n;
7335 } SMARTLIST_FOREACH_END(port);
7336 return n;
7339 /** Parse all ports from <b>options</b>. On success, set *<b>n_ports_out</b>
7340 * to the number of ports that are listed, update the *Port_set values in
7341 * <b>options</b>, and return 0. On failure, set *<b>msg</b> to a
7342 * description of the problem and return -1.
7344 * If <b>validate_only</b> is false, set configured_client_ports to the
7345 * new list of ports parsed from <b>options</b>.
7347 static int
7348 parse_ports(or_options_t *options, int validate_only,
7349 char **msg, int *n_ports_out,
7350 int *world_writable_control_socket)
7352 smartlist_t *ports;
7353 int retval = -1;
7355 ports = smartlist_new();
7357 *n_ports_out = 0;
7359 const unsigned gw_flag = options->SocksSocketsGroupWritable ?
7360 CL_PORT_DFLT_GROUP_WRITABLE : 0;
7361 if (parse_port_config(ports,
7362 options->SocksPort_lines,
7363 "Socks", CONN_TYPE_AP_LISTENER,
7364 "127.0.0.1", 9050,
7365 ((validate_only ? 0 : CL_PORT_WARN_NONLOCAL)
7366 | CL_PORT_TAKES_HOSTNAMES | gw_flag)) < 0) {
7367 *msg = tor_strdup("Invalid SocksPort configuration");
7368 goto err;
7370 if (parse_port_config(ports,
7371 options->DNSPort_lines,
7372 "DNS", CONN_TYPE_AP_DNS_LISTENER,
7373 "127.0.0.1", 0,
7374 CL_PORT_WARN_NONLOCAL|CL_PORT_TAKES_HOSTNAMES) < 0) {
7375 *msg = tor_strdup("Invalid DNSPort configuration");
7376 goto err;
7378 if (parse_port_config(ports,
7379 options->TransPort_lines,
7380 "Trans", CONN_TYPE_AP_TRANS_LISTENER,
7381 "127.0.0.1", 0,
7382 CL_PORT_WARN_NONLOCAL) < 0) {
7383 *msg = tor_strdup("Invalid TransPort configuration");
7384 goto err;
7386 if (parse_port_config(ports,
7387 options->NATDPort_lines,
7388 "NATD", CONN_TYPE_AP_NATD_LISTENER,
7389 "127.0.0.1", 0,
7390 CL_PORT_WARN_NONLOCAL) < 0) {
7391 *msg = tor_strdup("Invalid NatdPort configuration");
7392 goto err;
7394 if (parse_port_config(ports,
7395 options->HTTPTunnelPort_lines,
7396 "HTTP Tunnel", CONN_TYPE_AP_HTTP_CONNECT_LISTENER,
7397 "127.0.0.1", 0,
7398 ((validate_only ? 0 : CL_PORT_WARN_NONLOCAL)
7399 | CL_PORT_TAKES_HOSTNAMES | gw_flag)) < 0) {
7400 *msg = tor_strdup("Invalid HTTPTunnelPort configuration");
7401 goto err;
7404 unsigned control_port_flags = CL_PORT_NO_STREAM_OPTIONS |
7405 CL_PORT_WARN_NONLOCAL;
7406 const int any_passwords = (options->HashedControlPassword ||
7407 options->HashedControlSessionPassword ||
7408 options->CookieAuthentication);
7409 if (! any_passwords)
7410 control_port_flags |= CL_PORT_FORBID_NONLOCAL;
7411 if (options->ControlSocketsGroupWritable)
7412 control_port_flags |= CL_PORT_DFLT_GROUP_WRITABLE;
7414 if (parse_port_config(ports,
7415 options->ControlPort_lines,
7416 "Control", CONN_TYPE_CONTROL_LISTENER,
7417 "127.0.0.1", 0,
7418 control_port_flags) < 0) {
7419 *msg = tor_strdup("Invalid ControlPort configuration");
7420 goto err;
7423 if (parse_port_config(ports, options->ControlSocket,
7424 "ControlSocket",
7425 CONN_TYPE_CONTROL_LISTENER, NULL, 0,
7426 control_port_flags | CL_PORT_IS_UNIXSOCKET) < 0) {
7427 *msg = tor_strdup("Invalid ControlSocket configuration");
7428 goto err;
7431 if (! options->ClientOnly) {
7432 if (parse_port_config(ports,
7433 options->ORPort_lines,
7434 "OR", CONN_TYPE_OR_LISTENER,
7435 "0.0.0.0", 0,
7436 CL_PORT_SERVER_OPTIONS) < 0) {
7437 *msg = tor_strdup("Invalid ORPort configuration");
7438 goto err;
7440 if (parse_port_config(ports,
7441 options->ExtORPort_lines,
7442 "ExtOR", CONN_TYPE_EXT_OR_LISTENER,
7443 "127.0.0.1", 0,
7444 CL_PORT_SERVER_OPTIONS|CL_PORT_WARN_NONLOCAL) < 0) {
7445 *msg = tor_strdup("Invalid ExtORPort configuration");
7446 goto err;
7448 if (parse_port_config(ports,
7449 options->DirPort_lines,
7450 "Dir", CONN_TYPE_DIR_LISTENER,
7451 "0.0.0.0", 0,
7452 CL_PORT_SERVER_OPTIONS) < 0) {
7453 *msg = tor_strdup("Invalid DirPort configuration");
7454 goto err;
7458 int n_low_ports = 0;
7459 if (check_server_ports(ports, options, &n_low_ports) < 0) {
7460 *msg = tor_strdup("Misconfigured server ports");
7461 goto err;
7463 if (have_low_ports < 0)
7464 have_low_ports = (n_low_ports > 0);
7466 *n_ports_out = smartlist_len(ports);
7468 retval = 0;
7470 /* Update the *Port_set options. The !! here is to force a boolean out of
7471 an integer. */
7472 options->ORPort_set =
7473 !! count_real_listeners(ports, CONN_TYPE_OR_LISTENER, 0);
7474 options->SocksPort_set =
7475 !! count_real_listeners(ports, CONN_TYPE_AP_LISTENER, 1);
7476 options->TransPort_set =
7477 !! count_real_listeners(ports, CONN_TYPE_AP_TRANS_LISTENER, 1);
7478 options->NATDPort_set =
7479 !! count_real_listeners(ports, CONN_TYPE_AP_NATD_LISTENER, 1);
7480 options->HTTPTunnelPort_set =
7481 !! count_real_listeners(ports, CONN_TYPE_AP_HTTP_CONNECT_LISTENER, 1);
7482 /* Use options->ControlSocket to test if a control socket is set */
7483 options->ControlPort_set =
7484 !! count_real_listeners(ports, CONN_TYPE_CONTROL_LISTENER, 0);
7485 options->DirPort_set =
7486 !! count_real_listeners(ports, CONN_TYPE_DIR_LISTENER, 0);
7487 options->DNSPort_set =
7488 !! count_real_listeners(ports, CONN_TYPE_AP_DNS_LISTENER, 1);
7489 options->ExtORPort_set =
7490 !! count_real_listeners(ports, CONN_TYPE_EXT_OR_LISTENER, 0);
7492 if (world_writable_control_socket) {
7493 SMARTLIST_FOREACH(ports, port_cfg_t *, p,
7494 if (p->type == CONN_TYPE_CONTROL_LISTENER &&
7495 p->is_unix_addr &&
7496 p->is_world_writable) {
7497 *world_writable_control_socket = 1;
7498 break;
7502 if (!validate_only) {
7503 if (configured_ports) {
7504 SMARTLIST_FOREACH(configured_ports,
7505 port_cfg_t *, p, port_cfg_free(p));
7506 smartlist_free(configured_ports);
7508 configured_ports = ports;
7509 ports = NULL; /* prevent free below. */
7512 err:
7513 if (ports) {
7514 SMARTLIST_FOREACH(ports, port_cfg_t *, p, port_cfg_free(p));
7515 smartlist_free(ports);
7517 return retval;
7520 /* Does port bind to IPv4? */
7521 static int
7522 port_binds_ipv4(const port_cfg_t *port)
7524 return tor_addr_family(&port->addr) == AF_INET ||
7525 (tor_addr_family(&port->addr) == AF_UNSPEC
7526 && !port->server_cfg.bind_ipv6_only);
7529 /* Does port bind to IPv6? */
7530 static int
7531 port_binds_ipv6(const port_cfg_t *port)
7533 return tor_addr_family(&port->addr) == AF_INET6 ||
7534 (tor_addr_family(&port->addr) == AF_UNSPEC
7535 && !port->server_cfg.bind_ipv4_only);
7538 /** Given a list of <b>port_cfg_t</b> in <b>ports</b>, check them for internal
7539 * consistency and warn as appropriate. Set *<b>n_low_ports_out</b> to the
7540 * number of sub-1024 ports we will be binding. */
7541 static int
7542 check_server_ports(const smartlist_t *ports,
7543 const or_options_t *options,
7544 int *n_low_ports_out)
7546 int n_orport_advertised = 0;
7547 int n_orport_advertised_ipv4 = 0;
7548 int n_orport_listeners = 0;
7549 int n_dirport_advertised = 0;
7550 int n_dirport_listeners = 0;
7551 int n_low_port = 0;
7552 int r = 0;
7554 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
7555 if (port->type == CONN_TYPE_DIR_LISTENER) {
7556 if (! port->server_cfg.no_advertise)
7557 ++n_dirport_advertised;
7558 if (! port->server_cfg.no_listen)
7559 ++n_dirport_listeners;
7560 } else if (port->type == CONN_TYPE_OR_LISTENER) {
7561 if (! port->server_cfg.no_advertise) {
7562 ++n_orport_advertised;
7563 if (port_binds_ipv4(port))
7564 ++n_orport_advertised_ipv4;
7566 if (! port->server_cfg.no_listen)
7567 ++n_orport_listeners;
7568 } else {
7569 continue;
7571 #ifndef _WIN32
7572 if (!port->server_cfg.no_listen && port->port < 1024)
7573 ++n_low_port;
7574 #endif
7575 } SMARTLIST_FOREACH_END(port);
7577 if (n_orport_advertised && !n_orport_listeners) {
7578 log_warn(LD_CONFIG, "We are advertising an ORPort, but not actually "
7579 "listening on one.");
7580 r = -1;
7582 if (n_orport_listeners && !n_orport_advertised) {
7583 log_warn(LD_CONFIG, "We are listening on an ORPort, but not advertising "
7584 "any ORPorts. This will keep us from building a %s "
7585 "descriptor, and make us impossible to use.",
7586 options->BridgeRelay ? "bridge" : "router");
7587 r = -1;
7589 if (n_dirport_advertised && !n_dirport_listeners) {
7590 log_warn(LD_CONFIG, "We are advertising a DirPort, but not actually "
7591 "listening on one.");
7592 r = -1;
7594 if (n_dirport_advertised > 1) {
7595 log_warn(LD_CONFIG, "Can't advertise more than one DirPort.");
7596 r = -1;
7598 if (n_orport_advertised && !n_orport_advertised_ipv4 &&
7599 !options->BridgeRelay) {
7600 log_warn(LD_CONFIG, "Configured non-bridge only to listen on an IPv6 "
7601 "address.");
7602 r = -1;
7605 if (n_low_port && options->AccountingMax &&
7606 (!have_capability_support() || options->KeepBindCapabilities == 0)) {
7607 const char *extra = "";
7608 if (options->KeepBindCapabilities == 0 && have_capability_support())
7609 extra = ", and you have disabled KeepBindCapabilities.";
7610 log_warn(LD_CONFIG,
7611 "You have set AccountingMax to use hibernation. You have also "
7612 "chosen a low DirPort or OrPort%s."
7613 "This combination can make Tor stop "
7614 "working when it tries to re-attach the port after a period of "
7615 "hibernation. Please choose a different port or turn off "
7616 "hibernation unless you know this combination will work on your "
7617 "platform.", extra);
7620 if (n_low_ports_out)
7621 *n_low_ports_out = n_low_port;
7623 return r;
7626 /** Return a list of port_cfg_t for client ports parsed from the
7627 * options. */
7628 MOCK_IMPL(const smartlist_t *,
7629 get_configured_ports,(void))
7631 if (!configured_ports)
7632 configured_ports = smartlist_new();
7633 return configured_ports;
7636 /** Return an address:port string representation of the address
7637 * where the first <b>listener_type</b> listener waits for
7638 * connections. Return NULL if we couldn't find a listener. The
7639 * string is allocated on the heap and it's the responsibility of the
7640 * caller to free it after use.
7642 * This function is meant to be used by the pluggable transport proxy
7643 * spawning code, please make sure that it fits your purposes before
7644 * using it. */
7645 char *
7646 get_first_listener_addrport_string(int listener_type)
7648 static const char *ipv4_localhost = "127.0.0.1";
7649 static const char *ipv6_localhost = "[::1]";
7650 const char *address;
7651 uint16_t port;
7652 char *string = NULL;
7654 if (!configured_ports)
7655 return NULL;
7657 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
7658 if (cfg->server_cfg.no_listen)
7659 continue;
7661 if (cfg->type == listener_type &&
7662 tor_addr_family(&cfg->addr) != AF_UNSPEC) {
7664 /* We found the first listener of the type we are interested in! */
7666 /* If a listener is listening on INADDR_ANY, assume that it's
7667 also listening on 127.0.0.1, and point the transport proxy
7668 there: */
7669 if (tor_addr_is_null(&cfg->addr))
7670 address = tor_addr_is_v4(&cfg->addr) ? ipv4_localhost : ipv6_localhost;
7671 else
7672 address = fmt_and_decorate_addr(&cfg->addr);
7674 /* If a listener is configured with port 'auto', we are forced
7675 to iterate all listener connections and find out in which
7676 port it ended up listening: */
7677 if (cfg->port == CFG_AUTO_PORT) {
7678 port = router_get_active_listener_port_by_type_af(listener_type,
7679 tor_addr_family(&cfg->addr));
7680 if (!port)
7681 return NULL;
7682 } else {
7683 port = cfg->port;
7686 tor_asprintf(&string, "%s:%u", address, port);
7688 return string;
7691 } SMARTLIST_FOREACH_END(cfg);
7693 return NULL;
7696 /** Return the first advertised port of type <b>listener_type</b> in
7697 * <b>address_family</b>. Returns 0 when no port is found, and when passed
7698 * AF_UNSPEC. */
7700 get_first_advertised_port_by_type_af(int listener_type, int address_family)
7702 if (address_family == AF_UNSPEC)
7703 return 0;
7705 const smartlist_t *conf_ports = get_configured_ports();
7706 SMARTLIST_FOREACH_BEGIN(conf_ports, const port_cfg_t *, cfg) {
7707 if (cfg->type == listener_type &&
7708 !cfg->server_cfg.no_advertise) {
7709 if ((address_family == AF_INET && port_binds_ipv4(cfg)) ||
7710 (address_family == AF_INET6 && port_binds_ipv6(cfg))) {
7711 return cfg->port;
7714 } SMARTLIST_FOREACH_END(cfg);
7715 return 0;
7718 /** Return the first advertised address of type <b>listener_type</b> in
7719 * <b>address_family</b>. Returns NULL if there is no advertised address,
7720 * and when passed AF_UNSPEC. */
7721 const tor_addr_t *
7722 get_first_advertised_addr_by_type_af(int listener_type, int address_family)
7724 if (address_family == AF_UNSPEC)
7725 return NULL;
7726 if (!configured_ports)
7727 return NULL;
7728 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
7729 if (cfg->type == listener_type &&
7730 !cfg->server_cfg.no_advertise) {
7731 if ((address_family == AF_INET && port_binds_ipv4(cfg)) ||
7732 (address_family == AF_INET6 && port_binds_ipv6(cfg))) {
7733 return &cfg->addr;
7736 } SMARTLIST_FOREACH_END(cfg);
7737 return NULL;
7740 /** Return 1 if a port exists of type <b>listener_type</b> on <b>addr</b> and
7741 * <b>port</b>. If <b>check_wildcard</b> is true, INADDR[6]_ANY and AF_UNSPEC
7742 * addresses match any address of the appropriate family; and port -1 matches
7743 * any port.
7744 * To match auto ports, pass CFG_PORT_AUTO. (Does not match on the actual
7745 * automatically chosen listener ports.) */
7747 port_exists_by_type_addr_port(int listener_type, const tor_addr_t *addr,
7748 int port, int check_wildcard)
7750 if (!configured_ports || !addr)
7751 return 0;
7752 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
7753 if (cfg->type == listener_type) {
7754 if (cfg->port == port || (check_wildcard && port == -1)) {
7755 /* Exact match */
7756 if (tor_addr_eq(&cfg->addr, addr)) {
7757 return 1;
7759 /* Skip wildcard matches if we're not doing them */
7760 if (!check_wildcard) {
7761 continue;
7763 /* Wildcard matches IPv4 */
7764 const int cfg_v4 = port_binds_ipv4(cfg);
7765 const int cfg_any_v4 = tor_addr_is_null(&cfg->addr) && cfg_v4;
7766 const int addr_v4 = tor_addr_family(addr) == AF_INET ||
7767 tor_addr_family(addr) == AF_UNSPEC;
7768 const int addr_any_v4 = tor_addr_is_null(&cfg->addr) && addr_v4;
7769 if ((cfg_any_v4 && addr_v4) || (cfg_v4 && addr_any_v4)) {
7770 return 1;
7772 /* Wildcard matches IPv6 */
7773 const int cfg_v6 = port_binds_ipv6(cfg);
7774 const int cfg_any_v6 = tor_addr_is_null(&cfg->addr) && cfg_v6;
7775 const int addr_v6 = tor_addr_family(addr) == AF_INET6 ||
7776 tor_addr_family(addr) == AF_UNSPEC;
7777 const int addr_any_v6 = tor_addr_is_null(&cfg->addr) && addr_v6;
7778 if ((cfg_any_v6 && addr_v6) || (cfg_v6 && addr_any_v6)) {
7779 return 1;
7783 } SMARTLIST_FOREACH_END(cfg);
7784 return 0;
7787 /* Like port_exists_by_type_addr_port, but accepts a host-order IPv4 address
7788 * instead. */
7790 port_exists_by_type_addr32h_port(int listener_type, uint32_t addr_ipv4h,
7791 int port, int check_wildcard)
7793 tor_addr_t ipv4;
7794 tor_addr_from_ipv4h(&ipv4, addr_ipv4h);
7795 return port_exists_by_type_addr_port(listener_type, &ipv4, port,
7796 check_wildcard);
7799 /** Allocate and return a good value for the DataDirectory based on
7800 * <b>val</b>, which may be NULL. Return NULL on failure. */
7801 static char *
7802 get_data_directory(const char *val)
7804 #ifdef _WIN32
7805 if (val) {
7806 return tor_strdup(val);
7807 } else {
7808 return tor_strdup(get_windows_conf_root());
7810 #else /* !(defined(_WIN32)) */
7811 const char *d = val;
7812 if (!d)
7813 d = "~/.tor";
7815 if (!strcmpstart(d, "~/")) {
7816 char *fn = expand_filename(d);
7817 if (!fn) {
7818 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
7819 return NULL;
7821 if (!val && !strcmp(fn,"/.tor")) {
7822 /* If our homedir is /, we probably don't want to use it. */
7823 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
7824 * want. */
7825 log_warn(LD_CONFIG,
7826 "Default DataDirectory is \"~/.tor\". This expands to "
7827 "\"%s\", which is probably not what you want. Using "
7828 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
7829 tor_free(fn);
7830 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
7832 return fn;
7834 return tor_strdup(d);
7835 #endif /* defined(_WIN32) */
7838 /** Check and normalize the values of options->{Key,Data,Cache}Directory;
7839 * return 0 if it is sane, -1 otherwise. */
7840 static int
7841 validate_data_directories(or_options_t *options)
7843 tor_free(options->DataDirectory);
7844 options->DataDirectory = get_data_directory(options->DataDirectory_option);
7845 if (!options->DataDirectory)
7846 return -1;
7847 if (strlen(options->DataDirectory) > (512-128)) {
7848 log_warn(LD_CONFIG, "DataDirectory is too long.");
7849 return -1;
7852 tor_free(options->KeyDirectory);
7853 if (options->KeyDirectory_option) {
7854 options->KeyDirectory = get_data_directory(options->KeyDirectory_option);
7855 if (!options->KeyDirectory)
7856 return -1;
7857 } else {
7858 /* Default to the data directory's keys subdir */
7859 tor_asprintf(&options->KeyDirectory, "%s"PATH_SEPARATOR"keys",
7860 options->DataDirectory);
7863 tor_free(options->CacheDirectory);
7864 if (options->CacheDirectory_option) {
7865 options->CacheDirectory = get_data_directory(
7866 options->CacheDirectory_option);
7867 if (!options->CacheDirectory)
7868 return -1;
7869 } else {
7870 /* Default to the data directory. */
7871 options->CacheDirectory = tor_strdup(options->DataDirectory);
7874 return 0;
7877 /** This string must remain the same forevermore. It is how we
7878 * recognize that the torrc file doesn't need to be backed up. */
7879 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
7880 "if you edit it, comments will not be preserved"
7881 /** This string can change; it tries to give the reader an idea
7882 * that editing this file by hand is not a good plan. */
7883 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
7884 "to torrc.orig.1 or similar, and Tor will ignore it"
7886 /** Save a configuration file for the configuration in <b>options</b>
7887 * into the file <b>fname</b>. If the file already exists, and
7888 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
7889 * replace it. Return 0 on success, -1 on failure. */
7890 static int
7891 write_configuration_file(const char *fname, const or_options_t *options)
7893 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
7894 int rename_old = 0, r;
7896 if (!fname)
7897 return -1;
7899 switch (file_status(fname)) {
7900 /* create backups of old config files, even if they're empty */
7901 case FN_FILE:
7902 case FN_EMPTY:
7903 old_val = read_file_to_str(fname, 0, NULL);
7904 if (!old_val || strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
7905 rename_old = 1;
7907 tor_free(old_val);
7908 break;
7909 case FN_NOENT:
7910 break;
7911 case FN_ERROR:
7912 case FN_DIR:
7913 default:
7914 log_warn(LD_CONFIG,
7915 "Config file \"%s\" is not a file? Failing.", fname);
7916 return -1;
7919 if (!(new_conf = options_dump(options, OPTIONS_DUMP_MINIMAL))) {
7920 log_warn(LD_BUG, "Couldn't get configuration string");
7921 goto err;
7924 tor_asprintf(&new_val, "%s\n%s\n\n%s",
7925 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
7927 if (rename_old) {
7928 int i = 1;
7929 char *fn_tmp = NULL;
7930 while (1) {
7931 tor_asprintf(&fn_tmp, "%s.orig.%d", fname, i);
7932 if (file_status(fn_tmp) == FN_NOENT)
7933 break;
7934 tor_free(fn_tmp);
7935 ++i;
7937 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
7938 if (tor_rename(fname, fn_tmp) < 0) {//XXXX sandbox doesn't allow
7939 log_warn(LD_FS,
7940 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
7941 fname, fn_tmp, strerror(errno));
7942 tor_free(fn_tmp);
7943 goto err;
7945 tor_free(fn_tmp);
7948 if (write_str_to_file(fname, new_val, 0) < 0)
7949 goto err;
7951 r = 0;
7952 goto done;
7953 err:
7954 r = -1;
7955 done:
7956 tor_free(new_val);
7957 tor_free(new_conf);
7958 return r;
7962 * Save the current configuration file value to disk. Return 0 on
7963 * success, -1 on failure.
7966 options_save_current(void)
7968 /* This fails if we can't write to our configuration file.
7970 * If we try falling back to datadirectory or something, we have a better
7971 * chance of saving the configuration, but a better chance of doing
7972 * something the user never expected. */
7973 return write_configuration_file(get_torrc_fname(0), get_options());
7976 /** Return the number of cpus configured in <b>options</b>. If we are
7977 * told to auto-detect the number of cpus, return the auto-detected number. */
7979 get_num_cpus(const or_options_t *options)
7981 if (options->NumCPUs == 0) {
7982 int n = compute_num_cpus();
7983 return (n >= 1) ? n : 1;
7984 } else {
7985 return options->NumCPUs;
7990 * Initialize the libevent library.
7992 static void
7993 init_libevent(const or_options_t *options)
7995 tor_libevent_cfg cfg;
7997 tor_assert(options);
7999 configure_libevent_logging();
8000 /* If the kernel complains that some method (say, epoll) doesn't
8001 * exist, we don't care about it, since libevent will cope.
8003 suppress_libevent_log_msg("Function not implemented");
8005 memset(&cfg, 0, sizeof(cfg));
8006 cfg.num_cpus = get_num_cpus(options);
8007 cfg.msec_per_tick = options->TokenBucketRefillInterval;
8009 tor_libevent_initialize(&cfg);
8011 suppress_libevent_log_msg(NULL);
8014 /** Return a newly allocated string holding a filename relative to the
8015 * directory in <b>options</b> specified by <b>roottype</b>.
8016 * If <b>sub1</b> is present, it is the first path component after
8017 * the data directory. If <b>sub2</b> is also present, it is the second path
8018 * component after the data directory. If <b>suffix</b> is present, it
8019 * is appended to the filename.
8021 * Note: Consider using macros in config.h that wrap this function;
8022 * you should probably never need to call it as-is.
8024 MOCK_IMPL(char *,
8025 options_get_dir_fname2_suffix,(const or_options_t *options,
8026 directory_root_t roottype,
8027 const char *sub1, const char *sub2,
8028 const char *suffix))
8030 tor_assert(options);
8032 const char *rootdir = NULL;
8033 switch (roottype) {
8034 case DIRROOT_DATADIR:
8035 rootdir = options->DataDirectory;
8036 break;
8037 case DIRROOT_CACHEDIR:
8038 rootdir = options->CacheDirectory;
8039 break;
8040 case DIRROOT_KEYDIR:
8041 rootdir = options->KeyDirectory;
8042 break;
8043 default:
8044 tor_assert_unreached();
8045 break;
8047 tor_assert(rootdir);
8049 if (!suffix)
8050 suffix = "";
8052 char *fname = NULL;
8054 if (sub1 == NULL) {
8055 tor_asprintf(&fname, "%s%s", rootdir, suffix);
8056 tor_assert(!sub2); /* If sub2 is present, sub1 must be present. */
8057 } else if (sub2 == NULL) {
8058 tor_asprintf(&fname, "%s"PATH_SEPARATOR"%s%s", rootdir, sub1, suffix);
8059 } else {
8060 tor_asprintf(&fname, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s%s",
8061 rootdir, sub1, sub2, suffix);
8064 return fname;
8067 /** Check wether the data directory has a private subdirectory
8068 * <b>subdir</b>. If not, try to create it. Return 0 on success,
8069 * -1 otherwise. */
8071 check_or_create_data_subdir(const char *subdir)
8073 char *statsdir = get_datadir_fname(subdir);
8074 int return_val = 0;
8076 if (check_private_dir(statsdir, CPD_CREATE, get_options()->User) < 0) {
8077 log_warn(LD_HIST, "Unable to create %s/ directory!", subdir);
8078 return_val = -1;
8080 tor_free(statsdir);
8081 return return_val;
8084 /** Create a file named <b>fname</b> with contents <b>str</b> in the
8085 * subdirectory <b>subdir</b> of the data directory. <b>descr</b>
8086 * should be a short description of the file's content and will be
8087 * used for the warning message, if it's present and the write process
8088 * fails. Return 0 on success, -1 otherwise.*/
8090 write_to_data_subdir(const char* subdir, const char* fname,
8091 const char* str, const char* descr)
8093 char *filename = get_datadir_fname2(subdir, fname);
8094 int return_val = 0;
8096 if (write_str_to_file(filename, str, 0) < 0) {
8097 log_warn(LD_HIST, "Unable to write %s to disk!", descr ? descr : fname);
8098 return_val = -1;
8100 tor_free(filename);
8101 return return_val;
8104 /** Return a smartlist of ports that must be forwarded by
8105 * tor-fw-helper. The smartlist contains the ports in a string format
8106 * that is understandable by tor-fw-helper. */
8107 smartlist_t *
8108 get_list_of_ports_to_forward(void)
8110 smartlist_t *ports_to_forward = smartlist_new();
8111 int port = 0;
8113 /** XXX TODO tor-fw-helper does not support forwarding ports to
8114 other hosts than the local one. If the user is binding to a
8115 different IP address, tor-fw-helper won't work. */
8116 port = router_get_advertised_or_port(get_options()); /* Get ORPort */
8117 if (port)
8118 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
8120 port = router_get_advertised_dir_port(get_options(), 0); /* Get DirPort */
8121 if (port)
8122 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
8124 /* Get ports of transport proxies */
8126 smartlist_t *transport_ports = get_transport_proxy_ports();
8127 if (transport_ports) {
8128 smartlist_add_all(ports_to_forward, transport_ports);
8129 smartlist_free(transport_ports);
8133 if (!smartlist_len(ports_to_forward)) {
8134 smartlist_free(ports_to_forward);
8135 ports_to_forward = NULL;
8138 return ports_to_forward;
8141 /** Helper to implement GETINFO functions about configuration variables (not
8142 * their values). Given a "config/names" question, set *<b>answer</b> to a
8143 * new string describing the supported configuration variables and their
8144 * types. */
8146 getinfo_helper_config(control_connection_t *conn,
8147 const char *question, char **answer,
8148 const char **errmsg)
8150 (void) conn;
8151 (void) errmsg;
8152 if (!strcmp(question, "config/names")) {
8153 smartlist_t *sl = smartlist_new();
8154 int i;
8155 for (i = 0; option_vars_[i].name; ++i) {
8156 const config_var_t *var = &option_vars_[i];
8157 const char *type;
8158 /* don't tell controller about triple-underscore options */
8159 if (!strncmp(option_vars_[i].name, "___", 3))
8160 continue;
8161 switch (var->type) {
8162 case CONFIG_TYPE_STRING: type = "String"; break;
8163 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
8164 case CONFIG_TYPE_UINT: type = "Integer"; break;
8165 case CONFIG_TYPE_INT: type = "SignedInteger"; break;
8166 case CONFIG_TYPE_PORT: type = "Port"; break;
8167 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
8168 case CONFIG_TYPE_MSEC_INTERVAL: type = "TimeMsecInterval"; break;
8169 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
8170 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
8171 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
8172 case CONFIG_TYPE_AUTOBOOL: type = "Boolean+Auto"; break;
8173 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
8174 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
8175 case CONFIG_TYPE_CSV: type = "CommaList"; break;
8176 case CONFIG_TYPE_CSV_INTERVAL: type = "TimeIntervalCommaList"; break;
8177 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
8178 case CONFIG_TYPE_LINELIST_S: type = "Dependent"; break;
8179 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
8180 default:
8181 case CONFIG_TYPE_OBSOLETE:
8182 type = NULL; break;
8184 if (!type)
8185 continue;
8186 smartlist_add_asprintf(sl, "%s %s\n",var->name,type);
8188 *answer = smartlist_join_strings(sl, "", 0, NULL);
8189 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
8190 smartlist_free(sl);
8191 } else if (!strcmp(question, "config/defaults")) {
8192 smartlist_t *sl = smartlist_new();
8193 int dirauth_lines_seen = 0, fallback_lines_seen = 0;
8194 for (int i = 0; option_vars_[i].name; ++i) {
8195 const config_var_t *var = &option_vars_[i];
8196 if (var->initvalue != NULL) {
8197 if (strcmp(option_vars_[i].name, "DirAuthority") == 0) {
8199 * Count dirauth lines we have a default for; we'll use the
8200 * count later to decide whether to add the defaults manually
8202 ++dirauth_lines_seen;
8204 if (strcmp(option_vars_[i].name, "FallbackDir") == 0) {
8206 * Similarly count fallback lines, so that we can decided later
8207 * to add the defaults manually.
8209 ++fallback_lines_seen;
8211 char *val = esc_for_log(var->initvalue);
8212 smartlist_add_asprintf(sl, "%s %s\n",var->name,val);
8213 tor_free(val);
8217 if (dirauth_lines_seen == 0) {
8219 * We didn't see any directory authorities with default values,
8220 * so add the list of default authorities manually.
8224 * default_authorities is defined earlier in this file and
8225 * is a const char ** NULL-terminated array of dirauth config
8226 * lines.
8228 for (const char **i = default_authorities; *i != NULL; ++i) {
8229 char *val = esc_for_log(*i);
8230 smartlist_add_asprintf(sl, "DirAuthority %s\n", val);
8231 tor_free(val);
8235 if (fallback_lines_seen == 0 &&
8236 get_options()->UseDefaultFallbackDirs == 1) {
8238 * We didn't see any explicitly configured fallback mirrors,
8239 * so add the defaults to the list manually.
8241 * default_fallbacks is included earlier in this file and
8242 * is a const char ** NULL-terminated array of fallback config lines.
8244 const char **i;
8246 for (i = default_fallbacks; *i != NULL; ++i) {
8247 char *val = esc_for_log(*i);
8248 smartlist_add_asprintf(sl, "FallbackDir %s\n", val);
8249 tor_free(val);
8253 *answer = smartlist_join_strings(sl, "", 0, NULL);
8254 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
8255 smartlist_free(sl);
8257 return 0;
8260 /* Check whether an address has already been set against the options
8261 * depending on address family and destination type. Any exsting
8262 * value will lead to a fail, even if it is the same value. If not
8263 * set and not only validating, copy it into this location too.
8264 * Returns 0 on success or -1 if this address is already set.
8266 static int
8267 verify_and_store_outbound_address(sa_family_t family, tor_addr_t *addr,
8268 outbound_addr_t type, or_options_t *options, int validate_only)
8270 if (type>=OUTBOUND_ADDR_MAX || (family!=AF_INET && family!=AF_INET6)) {
8271 return -1;
8273 int fam_index=0;
8274 if (family==AF_INET6) {
8275 fam_index=1;
8277 tor_addr_t *dest=&options->OutboundBindAddresses[type][fam_index];
8278 if (!tor_addr_is_null(dest)) {
8279 return -1;
8281 if (!validate_only) {
8282 tor_addr_copy(dest, addr);
8284 return 0;
8287 /* Parse a list of address lines for a specific destination type.
8288 * Will store them into the options if not validate_only. If a
8289 * problem occurs, a suitable error message is store in msg.
8290 * Returns 0 on success or -1 if any address is already set.
8292 static int
8293 parse_outbound_address_lines(const config_line_t *lines, outbound_addr_t type,
8294 or_options_t *options, int validate_only, char **msg)
8296 tor_addr_t addr;
8297 sa_family_t family;
8298 while (lines) {
8299 family = tor_addr_parse(&addr, lines->value);
8300 if (verify_and_store_outbound_address(family, &addr, type,
8301 options, validate_only)) {
8302 if (msg)
8303 tor_asprintf(msg, "Multiple%s%s outbound bind addresses "
8304 "configured: %s",
8305 family==AF_INET?" IPv4":(family==AF_INET6?" IPv6":""),
8306 type==OUTBOUND_ADDR_OR?" OR":
8307 (type==OUTBOUND_ADDR_EXIT?" exit":""), lines->value);
8308 return -1;
8310 lines = lines->next;
8312 return 0;
8315 /** Parse outbound bind address option lines. If <b>validate_only</b>
8316 * is not 0 update OutboundBindAddresses in <b>options</b>.
8317 * Only one address can be set for any of these values.
8318 * On failure, set <b>msg</b> (if provided) to a newly allocated string
8319 * containing a description of the problem and return -1.
8321 static int
8322 parse_outbound_addresses(or_options_t *options, int validate_only, char **msg)
8324 if (!validate_only) {
8325 memset(&options->OutboundBindAddresses, 0,
8326 sizeof(options->OutboundBindAddresses));
8329 if (parse_outbound_address_lines(options->OutboundBindAddress,
8330 OUTBOUND_ADDR_EXIT_AND_OR, options,
8331 validate_only, msg) < 0) {
8332 goto err;
8335 if (parse_outbound_address_lines(options->OutboundBindAddressOR,
8336 OUTBOUND_ADDR_OR, options, validate_only,
8337 msg) < 0) {
8338 goto err;
8341 if (parse_outbound_address_lines(options->OutboundBindAddressExit,
8342 OUTBOUND_ADDR_EXIT, options, validate_only,
8343 msg) < 0) {
8344 goto err;
8347 return 0;
8348 err:
8349 return -1;
8352 /** Load one of the geoip files, <a>family</a> determining which
8353 * one. <a>default_fname</a> is used if on Windows and
8354 * <a>fname</a> equals "<default>". */
8355 static void
8356 config_load_geoip_file_(sa_family_t family,
8357 const char *fname,
8358 const char *default_fname)
8360 #ifdef _WIN32
8361 char *free_fname = NULL; /* Used to hold any temporary-allocated value */
8362 /* XXXX Don't use this "<default>" junk; make our filename options
8363 * understand prefixes somehow. -NM */
8364 if (!strcmp(fname, "<default>")) {
8365 const char *conf_root = get_windows_conf_root();
8366 tor_asprintf(&free_fname, "%s\\%s", conf_root, default_fname);
8367 fname = free_fname;
8369 geoip_load_file(family, fname);
8370 tor_free(free_fname);
8371 #else /* !(defined(_WIN32)) */
8372 (void)default_fname;
8373 geoip_load_file(family, fname);
8374 #endif /* defined(_WIN32) */
8377 /** Load geoip files for IPv4 and IPv6 if <a>options</a> and
8378 * <a>old_options</a> indicate we should. */
8379 static void
8380 config_maybe_load_geoip_files_(const or_options_t *options,
8381 const or_options_t *old_options)
8383 /* XXXX Reload GeoIPFile on SIGHUP. -NM */
8385 if (options->GeoIPFile &&
8386 ((!old_options || !opt_streq(old_options->GeoIPFile,
8387 options->GeoIPFile))
8388 || !geoip_is_loaded(AF_INET)))
8389 config_load_geoip_file_(AF_INET, options->GeoIPFile, "geoip");
8390 if (options->GeoIPv6File &&
8391 ((!old_options || !opt_streq(old_options->GeoIPv6File,
8392 options->GeoIPv6File))
8393 || !geoip_is_loaded(AF_INET6)))
8394 config_load_geoip_file_(AF_INET6, options->GeoIPv6File, "geoip6");
8397 /** Initialize cookie authentication (used so far by the ControlPort
8398 * and Extended ORPort).
8400 * Allocate memory and create a cookie (of length <b>cookie_len</b>)
8401 * in <b>cookie_out</b>.
8402 * Then write it down to <b>fname</b> and prepend it with <b>header</b>.
8404 * If <b>group_readable</b> is set, set <b>fname</b> to be readable
8405 * by the default GID.
8407 * If the whole procedure was successful, set
8408 * <b>cookie_is_set_out</b> to True. */
8410 init_cookie_authentication(const char *fname, const char *header,
8411 int cookie_len, int group_readable,
8412 uint8_t **cookie_out, int *cookie_is_set_out)
8414 char cookie_file_str_len = strlen(header) + cookie_len;
8415 char *cookie_file_str = tor_malloc(cookie_file_str_len);
8416 int retval = -1;
8418 /* We don't want to generate a new cookie every time we call
8419 * options_act(). One should be enough. */
8420 if (*cookie_is_set_out) {
8421 retval = 0; /* we are all set */
8422 goto done;
8425 /* If we've already set the cookie, free it before re-setting
8426 it. This can happen if we previously generated a cookie, but
8427 couldn't write it to a disk. */
8428 if (*cookie_out)
8429 tor_free(*cookie_out);
8431 /* Generate the cookie */
8432 *cookie_out = tor_malloc(cookie_len);
8433 crypto_rand((char *)*cookie_out, cookie_len);
8435 /* Create the string that should be written on the file. */
8436 memcpy(cookie_file_str, header, strlen(header));
8437 memcpy(cookie_file_str+strlen(header), *cookie_out, cookie_len);
8438 if (write_bytes_to_file(fname, cookie_file_str, cookie_file_str_len, 1)) {
8439 log_warn(LD_FS,"Error writing auth cookie to %s.", escaped(fname));
8440 goto done;
8443 #ifndef _WIN32
8444 if (group_readable) {
8445 if (chmod(fname, 0640)) {
8446 log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
8449 #else /* !(!defined(_WIN32)) */
8450 (void) group_readable;
8451 #endif /* !defined(_WIN32) */
8453 /* Success! */
8454 log_info(LD_GENERAL, "Generated auth cookie file in '%s'.", escaped(fname));
8455 *cookie_is_set_out = 1;
8456 retval = 0;
8458 done:
8459 memwipe(cookie_file_str, 0, cookie_file_str_len);
8460 tor_free(cookie_file_str);
8461 return retval;