whitespace and typo fixes
[tor.git] / src / or / config.c
blob796c15d9f7afd661c5687f311dbfd9cfb6175bef
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 /* A DirAuthorityFallbackRate of 0.1 means that 0.5% of clients try an
305 * authority when all fallbacks are up, and 2% try an authority when 25% of
306 * fallbacks are down. (We rebuild the list when 25% of fallbacks are down).
308 * We want to reduce load on authorities, but keep these two figures within
309 * an order of magnitude, so there isn't too much load shifting to
310 * authorities when fallbacks go down. */
311 V(DirAuthorityFallbackRate, DOUBLE, "0.1"),
312 V(DisableAllSwap, BOOL, "0"),
313 V(DisableDebuggerAttachment, BOOL, "1"),
314 OBSOLETE("DisableIOCP"),
315 OBSOLETE("DisableV2DirectoryInfo_"),
316 OBSOLETE("DynamicDHGroups"),
317 VPORT(DNSPort),
318 OBSOLETE("DNSListenAddress"),
319 V(DownloadExtraInfo, BOOL, "0"),
320 V(TestingEnableConnBwEvent, BOOL, "0"),
321 V(TestingEnableCellStatsEvent, BOOL, "0"),
322 V(TestingEnableTbEmptyEvent, BOOL, "0"),
323 V(EnforceDistinctSubnets, BOOL, "1"),
324 V(EntryNodes, ROUTERSET, NULL),
325 V(EntryStatistics, BOOL, "0"),
326 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
327 V(ExcludeNodes, ROUTERSET, NULL),
328 V(ExcludeExitNodes, ROUTERSET, NULL),
329 OBSOLETE("ExcludeSingleHopRelays"),
330 V(ExitNodes, ROUTERSET, NULL),
331 V(ExitPolicy, LINELIST, NULL),
332 V(ExitPolicyRejectPrivate, BOOL, "1"),
333 V(ExitPolicyRejectLocalInterfaces, BOOL, "0"),
334 V(ExitPortStatistics, BOOL, "0"),
335 V(ExtendAllowPrivateAddresses, BOOL, "0"),
336 V(ExitRelay, AUTOBOOL, "auto"),
337 VPORT(ExtORPort),
338 V(ExtORPortCookieAuthFile, STRING, NULL),
339 V(ExtORPortCookieAuthFileGroupReadable, BOOL, "0"),
340 V(ExtraInfoStatistics, BOOL, "1"),
341 V(ExtendByEd25519ID, AUTOBOOL, "auto"),
342 V(FallbackDir, LINELIST, NULL),
344 V(UseDefaultFallbackDirs, BOOL, "1"),
346 OBSOLETE("FallbackNetworkstatusFile"),
347 V(FascistFirewall, BOOL, "0"),
348 V(FirewallPorts, CSV, ""),
349 OBSOLETE("FastFirstHopPK"),
350 V(FetchDirInfoEarly, BOOL, "0"),
351 V(FetchDirInfoExtraEarly, BOOL, "0"),
352 V(FetchServerDescriptors, BOOL, "1"),
353 V(FetchHidServDescriptors, BOOL, "1"),
354 V(FetchUselessDescriptors, BOOL, "0"),
355 OBSOLETE("FetchV2Networkstatus"),
356 V(GeoIPExcludeUnknown, AUTOBOOL, "auto"),
357 #ifdef _WIN32
358 V(GeoIPFile, FILENAME, "<default>"),
359 V(GeoIPv6File, FILENAME, "<default>"),
360 #else
361 V(GeoIPFile, FILENAME,
362 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
363 V(GeoIPv6File, FILENAME,
364 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip6"),
365 #endif /* defined(_WIN32) */
366 OBSOLETE("Group"),
367 V(GuardLifetime, INTERVAL, "0 minutes"),
368 V(HardwareAccel, BOOL, "0"),
369 V(HeartbeatPeriod, INTERVAL, "6 hours"),
370 V(MainloopStats, BOOL, "0"),
371 V(AccelName, STRING, NULL),
372 V(AccelDir, FILENAME, NULL),
373 V(HashedControlPassword, LINELIST, NULL),
374 OBSOLETE("HidServDirectoryV2"),
375 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
376 VAR("HiddenServiceDirGroupReadable", LINELIST_S, RendConfigLines, NULL),
377 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
378 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
379 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
380 VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
381 VAR("HiddenServiceAllowUnknownPorts",LINELIST_S, RendConfigLines, NULL),
382 VAR("HiddenServiceMaxStreams",LINELIST_S, RendConfigLines, NULL),
383 VAR("HiddenServiceMaxStreamsCloseCircuit",LINELIST_S, RendConfigLines, NULL),
384 VAR("HiddenServiceNumIntroductionPoints", LINELIST_S, RendConfigLines, NULL),
385 VAR("HiddenServiceStatistics", BOOL, HiddenServiceStatistics_option, "1"),
386 V(HidServAuth, LINELIST, NULL),
387 OBSOLETE("CloseHSClientCircuitsImmediatelyOnTimeout"),
388 OBSOLETE("CloseHSServiceRendCircuitsImmediatelyOnTimeout"),
389 V(HiddenServiceSingleHopMode, BOOL, "0"),
390 V(HiddenServiceNonAnonymousMode,BOOL, "0"),
391 V(HTTPProxy, STRING, NULL),
392 V(HTTPProxyAuthenticator, STRING, NULL),
393 V(HTTPSProxy, STRING, NULL),
394 V(HTTPSProxyAuthenticator, STRING, NULL),
395 VPORT(HTTPTunnelPort),
396 V(IPv6Exit, BOOL, "0"),
397 VAR("ServerTransportPlugin", LINELIST, ServerTransportPlugin, NULL),
398 V(ServerTransportListenAddr, LINELIST, NULL),
399 V(ServerTransportOptions, LINELIST, NULL),
400 V(SigningKeyLifetime, INTERVAL, "30 days"),
401 V(Socks4Proxy, STRING, NULL),
402 V(Socks5Proxy, STRING, NULL),
403 V(Socks5ProxyUsername, STRING, NULL),
404 V(Socks5ProxyPassword, STRING, NULL),
405 VAR("KeyDirectory", FILENAME, KeyDirectory_option, NULL),
406 V(KeyDirectoryGroupReadable, BOOL, "0"),
407 V(KeepalivePeriod, INTERVAL, "5 minutes"),
408 V(KeepBindCapabilities, AUTOBOOL, "auto"),
409 VAR("Log", LINELIST, Logs, NULL),
410 V(LogMessageDomains, BOOL, "0"),
411 V(LogTimeGranularity, MSEC_INTERVAL, "1 second"),
412 V(TruncateLogFile, BOOL, "0"),
413 V(SyslogIdentityTag, STRING, NULL),
414 V(AndroidIdentityTag, STRING, NULL),
415 V(LongLivedPorts, CSV,
416 "21,22,706,1863,5050,5190,5222,5223,6523,6667,6697,8300"),
417 VAR("MapAddress", LINELIST, AddressMap, NULL),
418 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
419 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
420 V(MaxClientCircuitsPending, UINT, "32"),
421 V(MaxConsensusAgeForDiffs, INTERVAL, "0 seconds"),
422 VAR("MaxMemInQueues", MEMUNIT, MaxMemInQueues_raw, "0"),
423 OBSOLETE("MaxOnionsPending"),
424 V(MaxOnionQueueDelay, MSEC_INTERVAL, "1750 msec"),
425 V(MaxUnparseableDescSizeToLog, MEMUNIT, "10 MB"),
426 V(MinMeasuredBWsForAuthToIgnoreAdvertised, INT, "500"),
427 VAR("MyFamily", LINELIST, MyFamily_lines, NULL),
428 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
429 OBSOLETE("NamingAuthoritativeDirectory"),
430 OBSOLETE("NATDListenAddress"),
431 VPORT(NATDPort),
432 V(Nickname, STRING, NULL),
433 OBSOLETE("PredictedPortsRelevanceTime"),
434 OBSOLETE("WarnUnsafeSocks"),
435 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
436 V(NoExec, BOOL, "0"),
437 V(NumCPUs, UINT, "0"),
438 V(NumDirectoryGuards, UINT, "0"),
439 V(NumEntryGuards, UINT, "0"),
440 V(OfflineMasterKey, BOOL, "0"),
441 OBSOLETE("ORListenAddress"),
442 VPORT(ORPort),
443 V(OutboundBindAddress, LINELIST, NULL),
444 V(OutboundBindAddressOR, LINELIST, NULL),
445 V(OutboundBindAddressExit, LINELIST, NULL),
447 OBSOLETE("PathBiasDisableRate"),
448 V(PathBiasCircThreshold, INT, "-1"),
449 V(PathBiasNoticeRate, DOUBLE, "-1"),
450 V(PathBiasWarnRate, DOUBLE, "-1"),
451 V(PathBiasExtremeRate, DOUBLE, "-1"),
452 V(PathBiasScaleThreshold, INT, "-1"),
453 OBSOLETE("PathBiasScaleFactor"),
454 OBSOLETE("PathBiasMultFactor"),
455 V(PathBiasDropGuards, AUTOBOOL, "0"),
456 OBSOLETE("PathBiasUseCloseCounts"),
458 V(PathBiasUseThreshold, INT, "-1"),
459 V(PathBiasNoticeUseRate, DOUBLE, "-1"),
460 V(PathBiasExtremeUseRate, DOUBLE, "-1"),
461 V(PathBiasScaleUseThreshold, INT, "-1"),
463 V(PathsNeededToBuildCircuits, DOUBLE, "-1"),
464 V(PerConnBWBurst, MEMUNIT, "0"),
465 V(PerConnBWRate, MEMUNIT, "0"),
466 V(PidFile, STRING, NULL),
467 V(TestingTorNetwork, BOOL, "0"),
468 V(TestingMinExitFlagThreshold, MEMUNIT, "0"),
469 V(TestingMinFastFlagThreshold, MEMUNIT, "0"),
471 V(TestingLinkCertLifetime, INTERVAL, "2 days"),
472 V(TestingAuthKeyLifetime, INTERVAL, "2 days"),
473 V(TestingLinkKeySlop, INTERVAL, "3 hours"),
474 V(TestingAuthKeySlop, INTERVAL, "3 hours"),
475 V(TestingSigningKeySlop, INTERVAL, "1 day"),
477 V(OptimisticData, AUTOBOOL, "auto"),
478 V(PortForwarding, BOOL, "0"),
479 V(PortForwardingHelper, FILENAME, "tor-fw-helper"),
480 OBSOLETE("PreferTunneledDirConns"),
481 V(ProtocolWarnings, BOOL, "0"),
482 V(PublishServerDescriptor, CSV, "1"),
483 V(PublishHidServDescriptors, BOOL, "1"),
484 V(ReachableAddresses, LINELIST, NULL),
485 V(ReachableDirAddresses, LINELIST, NULL),
486 V(ReachableORAddresses, LINELIST, NULL),
487 V(RecommendedVersions, LINELIST, NULL),
488 V(RecommendedClientVersions, LINELIST, NULL),
489 V(RecommendedServerVersions, LINELIST, NULL),
490 V(RecommendedPackages, LINELIST, NULL),
491 V(ReducedConnectionPadding, BOOL, "0"),
492 V(ConnectionPadding, AUTOBOOL, "auto"),
493 V(RefuseUnknownExits, AUTOBOOL, "auto"),
494 V(RejectPlaintextPorts, CSV, ""),
495 V(RelayBandwidthBurst, MEMUNIT, "0"),
496 V(RelayBandwidthRate, MEMUNIT, "0"),
497 V(RendPostPeriod, INTERVAL, "1 hour"),
498 V(RephistTrackTime, INTERVAL, "24 hours"),
499 V(RunAsDaemon, BOOL, "0"),
500 V(ReducedExitPolicy, BOOL, "0"),
501 OBSOLETE("RunTesting"), // currently unused
502 V(Sandbox, BOOL, "0"),
503 V(SafeLogging, STRING, "1"),
504 V(SafeSocks, BOOL, "0"),
505 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
506 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
507 V(ServerDNSDetectHijacking, BOOL, "1"),
508 V(ServerDNSRandomizeCase, BOOL, "1"),
509 V(ServerDNSResolvConfFile, STRING, NULL),
510 V(ServerDNSSearchDomains, BOOL, "0"),
511 V(ServerDNSTestAddresses, CSV,
512 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
513 OBSOLETE("SchedulerLowWaterMark__"),
514 OBSOLETE("SchedulerHighWaterMark__"),
515 OBSOLETE("SchedulerMaxFlushCells__"),
516 V(KISTSchedRunInterval, MSEC_INTERVAL, "0 msec"),
517 V(KISTSockBufSizeFactor, DOUBLE, "1.0"),
518 V(Schedulers, CSV, "KIST,KISTLite,Vanilla"),
519 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
520 OBSOLETE("SocksListenAddress"),
521 V(SocksPolicy, LINELIST, NULL),
522 VPORT(SocksPort),
523 V(SocksTimeout, INTERVAL, "2 minutes"),
524 V(SSLKeyLifetime, INTERVAL, "0"),
525 OBSOLETE("StrictEntryNodes"),
526 OBSOLETE("StrictExitNodes"),
527 V(StrictNodes, BOOL, "0"),
528 OBSOLETE("Support022HiddenServices"),
529 V(TestSocks, BOOL, "0"),
530 V(TokenBucketRefillInterval, MSEC_INTERVAL, "100 msec"),
531 V(Tor2webMode, BOOL, "0"),
532 V(Tor2webRendezvousPoints, ROUTERSET, NULL),
533 OBSOLETE("TLSECGroup"),
534 V(TrackHostExits, CSV, NULL),
535 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
536 OBSOLETE("TransListenAddress"),
537 VPORT(TransPort),
538 V(TransProxyType, STRING, "default"),
539 OBSOLETE("TunnelDirConns"),
540 V(UpdateBridgesFromAuthority, BOOL, "0"),
541 V(UseBridges, BOOL, "0"),
542 VAR("UseEntryGuards", BOOL, UseEntryGuards_option, "1"),
543 OBSOLETE("UseEntryGuardsAsDirGuards"),
544 V(UseGuardFraction, AUTOBOOL, "auto"),
545 V(UseMicrodescriptors, AUTOBOOL, "auto"),
546 OBSOLETE("UseNTorHandshake"),
547 V(User, STRING, NULL),
548 OBSOLETE("UserspaceIOCPBuffers"),
549 V(AuthDirSharedRandomness, BOOL, "1"),
550 V(AuthDirTestEd25519LinkKeys, BOOL, "1"),
551 OBSOLETE("V1AuthoritativeDirectory"),
552 OBSOLETE("V2AuthoritativeDirectory"),
553 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
554 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
555 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
556 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
557 V(TestingV3AuthVotingStartOffset, INTERVAL, "0"),
558 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
559 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
560 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
561 V(V3AuthNIntervalsValid, UINT, "3"),
562 V(V3AuthUseLegacyKey, BOOL, "0"),
563 V(V3BandwidthsFile, FILENAME, NULL),
564 V(GuardfractionFile, FILENAME, NULL),
565 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
566 OBSOLETE("VoteOnHidServDirectoriesV2"),
567 V(VirtualAddrNetworkIPv4, STRING, "127.192.0.0/10"),
568 V(VirtualAddrNetworkIPv6, STRING, "[FE80::]/10"),
569 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
570 OBSOLETE("UseFilteringSSLBufferevents"),
571 OBSOLETE("__UseFilteringSSLBufferevents"),
572 VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
573 VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
574 VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
575 VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
576 VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
577 NULL),
578 VAR("__OwningControllerProcess",STRING,OwningControllerProcess, NULL),
579 VAR("__OwningControllerFD",INT,OwningControllerFD, "-1"),
580 V(MinUptimeHidServDirectoryV2, INTERVAL, "96 hours"),
581 V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 60, 60, 120, "
582 "300, 900, 2147483647"),
583 V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 60, 300, 600, "
584 "2147483647"),
585 V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
586 "300, 600, 1800, 1800, 1800, 1800, "
587 "1800, 3600, 7200"),
588 V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
589 "300, 600, 1800, 3600, 3600, 3600, "
590 "10800, 21600, 43200"),
591 /* With the ClientBootstrapConsensus*Download* below:
592 * Clients with only authorities will try:
593 * - at least 3 authorities over 10 seconds, then exponentially backoff,
594 * with the next attempt 3-21 seconds later,
595 * Clients with authorities and fallbacks will try:
596 * - at least 2 authorities and 4 fallbacks over 21 seconds, then
597 * exponentially backoff, with the next attempts 4-33 seconds later,
598 * Clients will also retry when an application request arrives.
599 * After a number of failed requests, clients retry every 3 days + 1 hour.
601 * Clients used to try 2 authorities over 10 seconds, then wait for
602 * 60 minutes or an application request.
604 * When clients have authorities and fallbacks available, they use these
605 * schedules: (we stagger the times to avoid thundering herds) */
606 V(ClientBootstrapConsensusAuthorityDownloadSchedule, CSV_INTERVAL,
607 "6, 11, 3600, 10800, 25200, 54000, 111600, 262800" /* 3 days + 1 hour */),
608 V(ClientBootstrapConsensusFallbackDownloadSchedule, CSV_INTERVAL,
609 "0, 1, 4, 11, 3600, 10800, 25200, 54000, 111600, 262800"),
610 /* When clients only have authorities available, they use this schedule: */
611 V(ClientBootstrapConsensusAuthorityOnlyDownloadSchedule, CSV_INTERVAL,
612 "0, 3, 7, 3600, 10800, 25200, 54000, 111600, 262800"),
613 /* We don't want to overwhelm slow networks (or mirrors whose replies are
614 * blocked), but we also don't want to fail if only some mirrors are
615 * blackholed. Clients will try 3 directories simultaneously.
616 * (Relays never use simultaneous connections.) */
617 V(ClientBootstrapConsensusMaxInProgressTries, UINT, "3"),
618 /* When a client has any running bridges, check each bridge occasionally,
619 * whether or not that bridge is actually up. */
620 V(TestingBridgeDownloadSchedule, CSV_INTERVAL,
621 "10800, 25200, 54000, 111600, 262800"),
622 /* When a client is just starting, or has no running bridges, check each
623 * bridge a few times quickly, and then try again later. These schedules
624 * are much longer than the other schedules, because we try each and every
625 * configured bridge with this schedule. */
626 V(TestingBridgeBootstrapDownloadSchedule, CSV_INTERVAL,
627 "0, 30, 90, 600, 3600, 10800, 25200, 54000, 111600, 262800"),
628 V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "10 minutes"),
629 V(TestingDirConnectionMaxStall, INTERVAL, "5 minutes"),
630 V(TestingConsensusMaxDownloadTries, UINT, "8"),
631 /* Since we try connections rapidly and simultaneously, we can afford
632 * to give up earlier. (This protects against overloading directories.) */
633 V(ClientBootstrapConsensusMaxDownloadTries, UINT, "7"),
634 /* We want to give up much earlier if we're only using authorities. */
635 V(ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries, UINT, "4"),
636 V(TestingDescriptorMaxDownloadTries, UINT, "8"),
637 V(TestingMicrodescMaxDownloadTries, UINT, "8"),
638 V(TestingCertMaxDownloadTries, UINT, "8"),
639 V(TestingDirAuthVoteExit, ROUTERSET, NULL),
640 V(TestingDirAuthVoteExitIsStrict, BOOL, "0"),
641 V(TestingDirAuthVoteGuard, ROUTERSET, NULL),
642 V(TestingDirAuthVoteGuardIsStrict, BOOL, "0"),
643 V(TestingDirAuthVoteHSDir, ROUTERSET, NULL),
644 V(TestingDirAuthVoteHSDirIsStrict, BOOL, "0"),
645 VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "0"),
647 END_OF_CONFIG_VARS
650 /** Override default values with these if the user sets the TestingTorNetwork
651 * option. */
652 static const config_var_t testing_tor_network_defaults[] = {
653 V(DirAllowPrivateAddresses, BOOL, "1"),
654 V(EnforceDistinctSubnets, BOOL, "0"),
655 V(AssumeReachable, BOOL, "1"),
656 V(AuthDirMaxServersPerAddr, UINT, "0"),
657 V(ClientBootstrapConsensusAuthorityDownloadSchedule, CSV_INTERVAL,
658 "0, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
659 V(ClientBootstrapConsensusFallbackDownloadSchedule, CSV_INTERVAL,
660 "0, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
661 V(ClientBootstrapConsensusAuthorityOnlyDownloadSchedule, CSV_INTERVAL,
662 "0, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
663 V(ClientBootstrapConsensusMaxDownloadTries, UINT, "80"),
664 V(ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries, UINT, "80"),
665 V(ClientDNSRejectInternalAddresses, BOOL,"0"),
666 V(ClientRejectInternalAddresses, BOOL, "0"),
667 V(CountPrivateBandwidth, BOOL, "1"),
668 V(ExitPolicyRejectPrivate, BOOL, "0"),
669 V(ExtendAllowPrivateAddresses, BOOL, "1"),
670 V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
671 V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
672 V(V3AuthDistDelay, INTERVAL, "20 seconds"),
673 V(TestingV3AuthInitialVotingInterval, INTERVAL, "150 seconds"),
674 V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
675 V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
676 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
677 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
678 V(MinUptimeHidServDirectoryV2, INTERVAL, "0 minutes"),
679 V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 5, 10, 15, "
680 "20, 30, 60"),
681 V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, 15, 20, "
682 "30, 60"),
683 V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
684 "15, 20, 30, 60"),
685 V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
686 "15, 20, 30, 60"),
687 V(TestingBridgeDownloadSchedule, CSV_INTERVAL, "10, 30, 60"),
688 V(TestingBridgeBootstrapDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
689 "15, 20, 30, 60"),
690 V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "5 seconds"),
691 V(TestingDirConnectionMaxStall, INTERVAL, "30 seconds"),
692 V(TestingConsensusMaxDownloadTries, UINT, "80"),
693 V(TestingDescriptorMaxDownloadTries, UINT, "80"),
694 V(TestingMicrodescMaxDownloadTries, UINT, "80"),
695 V(TestingCertMaxDownloadTries, UINT, "80"),
696 V(TestingEnableConnBwEvent, BOOL, "1"),
697 V(TestingEnableCellStatsEvent, BOOL, "1"),
698 V(TestingEnableTbEmptyEvent, BOOL, "1"),
699 VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "1"),
700 V(RendPostPeriod, INTERVAL, "2 minutes"),
702 END_OF_CONFIG_VARS
705 #undef VAR
706 #undef V
707 #undef OBSOLETE
709 static const config_deprecation_t option_deprecation_notes_[] = {
710 /* Deprecated since 0.3.2.0-alpha. */
711 { "HTTPProxy", "It only applies to direct unencrypted HTTP connections "
712 "to your directory server, which your Tor probably wasn't using." },
713 { "HTTPProxyAuthenticator", "HTTPProxy is deprecated in favor of HTTPSProxy "
714 "which should be used with HTTPSProxyAuthenticator." },
715 /* End of options deprecated since 0.3.2.1-alpha */
717 /* Options deprecated since 0.3.2.2-alpha */
718 { "ReachableDirAddresses", "It has no effect on relays, and has had no "
719 "effect on clients since 0.2.8." },
720 { "ClientPreferIPv6DirPort", "It has no effect on relays, and has had no "
721 "effect on clients since 0.2.8." },
722 /* End of options deprecated since 0.3.2.2-alpha. */
724 { NULL, NULL }
727 #ifdef _WIN32
728 static char *get_windows_conf_root(void);
729 #endif
730 static int options_act_reversible(const or_options_t *old_options, char **msg);
731 static int options_transition_allowed(const or_options_t *old,
732 const or_options_t *new,
733 char **msg);
734 static int options_transition_affects_workers(
735 const or_options_t *old_options, const or_options_t *new_options);
736 static int options_transition_affects_descriptor(
737 const or_options_t *old_options, const or_options_t *new_options);
738 static int normalize_nickname_list(config_line_t **normalized_out,
739 const config_line_t *lst, const char *name,
740 char **msg);
741 static char *get_bindaddr_from_transport_listen_line(const char *line,
742 const char *transport);
743 static int parse_ports(or_options_t *options, int validate_only,
744 char **msg_out, int *n_ports_out,
745 int *world_writable_control_socket);
746 static int check_server_ports(const smartlist_t *ports,
747 const or_options_t *options,
748 int *num_low_ports_out);
749 static int validate_data_directories(or_options_t *options);
750 static int write_configuration_file(const char *fname,
751 const or_options_t *options);
752 static int options_init_logs(const or_options_t *old_options,
753 or_options_t *options, int validate_only);
755 static void init_libevent(const or_options_t *options);
756 static int opt_streq(const char *s1, const char *s2);
757 static int parse_outbound_addresses(or_options_t *options, int validate_only,
758 char **msg);
759 static void config_maybe_load_geoip_files_(const or_options_t *options,
760 const or_options_t *old_options);
761 static int options_validate_cb(void *old_options, void *options,
762 void *default_options,
763 int from_setconf, char **msg);
764 static uint64_t compute_real_max_mem_in_queues(const uint64_t val,
765 int log_guess);
767 /** Magic value for or_options_t. */
768 #define OR_OPTIONS_MAGIC 9090909
770 /** Configuration format for or_options_t. */
771 STATIC config_format_t options_format = {
772 sizeof(or_options_t),
773 OR_OPTIONS_MAGIC,
774 offsetof(or_options_t, magic_),
775 option_abbrevs_,
776 option_deprecation_notes_,
777 option_vars_,
778 options_validate_cb,
779 NULL
783 * Functions to read and write the global options pointer.
786 /** Command-line and config-file options. */
787 static or_options_t *global_options = NULL;
788 /** The fallback options_t object; this is where we look for options not
789 * in torrc before we fall back to Tor's defaults. */
790 static or_options_t *global_default_options = NULL;
791 /** Name of most recently read torrc file. */
792 static char *torrc_fname = NULL;
793 /** Name of the most recently read torrc-defaults file.*/
794 static char *torrc_defaults_fname = NULL;
795 /** Configuration options set by command line. */
796 static config_line_t *global_cmdline_options = NULL;
797 /** Non-configuration options set by the command line */
798 static config_line_t *global_cmdline_only_options = NULL;
799 /** Boolean: Have we parsed the command line? */
800 static int have_parsed_cmdline = 0;
801 /** Contents of most recently read DirPortFrontPage file. */
802 static char *global_dirfrontpagecontents = NULL;
803 /** List of port_cfg_t for all configured ports. */
804 static smartlist_t *configured_ports = NULL;
805 /** True iff we're currently validating options, and any calls to
806 * get_options() are likely to be bugs. */
807 static int in_option_validation = 0;
809 /** Return the contents of our frontpage string, or NULL if not configured. */
810 MOCK_IMPL(const char*,
811 get_dirportfrontpage, (void))
813 return global_dirfrontpagecontents;
816 /** Returns the currently configured options. */
817 MOCK_IMPL(or_options_t *,
818 get_options_mutable, (void))
820 tor_assert(global_options);
821 tor_assert_nonfatal(! in_option_validation);
822 return global_options;
825 /** Returns the currently configured options */
826 MOCK_IMPL(const or_options_t *,
827 get_options,(void))
829 return get_options_mutable();
832 /** Change the current global options to contain <b>new_val</b> instead of
833 * their current value; take action based on the new value; free the old value
834 * as necessary. Returns 0 on success, -1 on failure.
837 set_options(or_options_t *new_val, char **msg)
839 int i;
840 smartlist_t *elements;
841 config_line_t *line;
842 or_options_t *old_options = global_options;
843 global_options = new_val;
844 /* Note that we pass the *old* options below, for comparison. It
845 * pulls the new options directly out of global_options. */
846 if (options_act_reversible(old_options, msg)<0) {
847 tor_assert(*msg);
848 global_options = old_options;
849 return -1;
851 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
852 if (! tor_event_loop_shutdown_is_pending()) {
853 log_err(LD_BUG,
854 "Acting on config options left us in a broken state. Dying.");
855 tor_shutdown_event_loop_and_exit(1);
857 return -1;
859 /* Issues a CONF_CHANGED event to notify controller of the change. If Tor is
860 * just starting up then the old_options will be undefined. */
861 if (old_options && old_options != global_options) {
862 elements = smartlist_new();
863 for (i=0; options_format.vars[i].name; ++i) {
864 const config_var_t *var = &options_format.vars[i];
865 const char *var_name = var->name;
866 if (var->type == CONFIG_TYPE_LINELIST_S ||
867 var->type == CONFIG_TYPE_OBSOLETE) {
868 continue;
870 if (!config_is_same(&options_format, new_val, old_options, var_name)) {
871 line = config_get_assigned_option(&options_format, new_val,
872 var_name, 1);
874 if (line) {
875 config_line_t *next;
876 for (; line; line = next) {
877 next = line->next;
878 smartlist_add(elements, line->key);
879 smartlist_add(elements, line->value);
880 tor_free(line);
882 } else {
883 smartlist_add_strdup(elements, options_format.vars[i].name);
884 smartlist_add(elements, NULL);
888 control_event_conf_changed(elements);
889 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
890 smartlist_free(elements);
893 if (old_options != global_options)
894 or_options_free(old_options);
896 return 0;
899 /** The version of this Tor process, as parsed. */
900 static char *the_tor_version = NULL;
901 /** A shorter version of this Tor process's version, for export in our router
902 * descriptor. (Does not include the git version, if any.) */
903 static char *the_short_tor_version = NULL;
905 /** Return the current Tor version. */
906 const char *
907 get_version(void)
909 if (the_tor_version == NULL) {
910 if (strlen(tor_git_revision)) {
911 tor_asprintf(&the_tor_version, "%s (git-%s)", get_short_version(),
912 tor_git_revision);
913 } else {
914 the_tor_version = tor_strdup(get_short_version());
917 return the_tor_version;
920 /** Return the current Tor version, without any git tag. */
921 const char *
922 get_short_version(void)
925 if (the_short_tor_version == NULL) {
926 #ifdef TOR_BUILD_TAG
927 tor_asprintf(&the_short_tor_version, "%s (%s)", VERSION, TOR_BUILD_TAG);
928 #else
929 the_short_tor_version = tor_strdup(VERSION);
930 #endif
932 return the_short_tor_version;
935 /** Release additional memory allocated in options
937 STATIC void
938 or_options_free_(or_options_t *options)
940 if (!options)
941 return;
943 routerset_free(options->ExcludeExitNodesUnion_);
944 if (options->NodeFamilySets) {
945 SMARTLIST_FOREACH(options->NodeFamilySets, routerset_t *,
946 rs, routerset_free(rs));
947 smartlist_free(options->NodeFamilySets);
949 if (options->SchedulerTypes_) {
950 SMARTLIST_FOREACH(options->SchedulerTypes_, int *, i, tor_free(i));
951 smartlist_free(options->SchedulerTypes_);
953 if (options->FilesOpenedByIncludes) {
954 SMARTLIST_FOREACH(options->FilesOpenedByIncludes, char *, f, tor_free(f));
955 smartlist_free(options->FilesOpenedByIncludes);
957 tor_free(options->DataDirectory);
958 tor_free(options->CacheDirectory);
959 tor_free(options->KeyDirectory);
960 tor_free(options->BridgePassword_AuthDigest_);
961 tor_free(options->command_arg);
962 tor_free(options->master_key_fname);
963 config_free_lines(options->MyFamily);
964 config_free(&options_format, options);
967 /** Release all memory and resources held by global configuration structures.
969 void
970 config_free_all(void)
972 or_options_free(global_options);
973 global_options = NULL;
974 or_options_free(global_default_options);
975 global_default_options = NULL;
977 config_free_lines(global_cmdline_options);
978 global_cmdline_options = NULL;
980 config_free_lines(global_cmdline_only_options);
981 global_cmdline_only_options = NULL;
983 if (configured_ports) {
984 SMARTLIST_FOREACH(configured_ports,
985 port_cfg_t *, p, port_cfg_free(p));
986 smartlist_free(configured_ports);
987 configured_ports = NULL;
990 tor_free(torrc_fname);
991 tor_free(torrc_defaults_fname);
992 tor_free(global_dirfrontpagecontents);
994 tor_free(the_short_tor_version);
995 tor_free(the_tor_version);
997 have_parsed_cmdline = 0;
1000 /** Make <b>address</b> -- a piece of information related to our operation as
1001 * a client -- safe to log according to the settings in options->SafeLogging,
1002 * and return it.
1004 * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
1006 const char *
1007 safe_str_client(const char *address)
1009 tor_assert(address);
1010 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
1011 return "[scrubbed]";
1012 else
1013 return address;
1016 /** Make <b>address</b> -- a piece of information of unspecified sensitivity
1017 * -- safe to log according to the settings in options->SafeLogging, and
1018 * return it.
1020 * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
1021 * otherwise.)
1023 const char *
1024 safe_str(const char *address)
1026 tor_assert(address);
1027 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
1028 return "[scrubbed]";
1029 else
1030 return address;
1033 /** Equivalent to escaped(safe_str_client(address)). See reentrancy note on
1034 * escaped(): don't use this outside the main thread, or twice in the same
1035 * log statement. */
1036 const char *
1037 escaped_safe_str_client(const char *address)
1039 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
1040 return "[scrubbed]";
1041 else
1042 return escaped(address);
1045 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
1046 * escaped(): don't use this outside the main thread, or twice in the same
1047 * log statement. */
1048 const char *
1049 escaped_safe_str(const char *address)
1051 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
1052 return "[scrubbed]";
1053 else
1054 return escaped(address);
1058 * The severity level that should be used for warnings of severity
1059 * LOG_PROTOCOL_WARN.
1061 * We keep this outside the options, in case somebody needs to use
1062 * LOG_PROTOCOL_WARN while an option transition is happening.
1064 static int protocol_warning_severity_level = LOG_WARN;
1066 /** Return the severity level that should be used for warnings of severity
1067 * LOG_PROTOCOL_WARN. */
1069 get_protocol_warning_severity_level(void)
1071 return protocol_warning_severity_level;
1074 /** List of default directory authorities */
1076 static const char *default_authorities[] = {
1077 "moria1 orport=9101 "
1078 "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
1079 "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
1080 "tor26 orport=443 "
1081 "v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
1082 "ipv6=[2001:858:2:2:aabb:0:563b:1526]:443 "
1083 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
1084 "dizum orport=443 "
1085 "v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
1086 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
1087 "Bifroest orport=443 bridge "
1088 "37.218.247.217:80 1D8F 3A91 C37C 5D1C 4C19 B1AD 1D0C FBE8 BF72 D8E1",
1089 "gabelmoo orport=443 "
1090 "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
1091 "ipv6=[2001:638:a000:4140::ffff:189]:443 "
1092 "131.188.40.189:80 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
1093 "dannenberg orport=443 "
1094 "v3ident=0232AF901C31A04EE9848595AF9BB7620D4C5B2E "
1095 "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
1096 "maatuska orport=80 "
1097 "v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
1098 "ipv6=[2001:67c:289c::9]:80 "
1099 "171.25.193.9:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
1100 "Faravahar orport=443 "
1101 "v3ident=EFCBE720AB3A82B99F9E953CD5BF50F7EEFC7B97 "
1102 "154.35.175.225:80 CF6D 0AAF B385 BE71 B8E1 11FC 5CFF 4B47 9237 33BC",
1103 "longclaw orport=443 "
1104 "v3ident=23D15D965BC35114467363C165C4F724B64B4F66 "
1105 "199.58.81.140:80 74A9 1064 6BCE EFBC D2E8 74FC 1DC9 9743 0F96 8145",
1106 "bastet orport=443 "
1107 "v3ident=27102BC123E7AF1D4741AE047E160C91ADC76B21 "
1108 "ipv6=[2620:13:4000:6000::1000:118]:443 "
1109 "204.13.164.118:80 24E2 F139 121D 4394 C54B 5BCC 368B 3B41 1857 C413",
1110 NULL
1113 /** List of fallback directory authorities. The list is generated by opt-in of
1114 * relays that meet certain stability criteria.
1116 static const char *default_fallbacks[] = {
1117 #include "fallback_dirs.inc"
1118 NULL
1121 /** Add the default directory authorities directly into the trusted dir list,
1122 * but only add them insofar as they share bits with <b>type</b>.
1123 * Each authority's bits are restricted to the bits shared with <b>type</b>.
1124 * If <b>type</b> is ALL_DIRINFO or NO_DIRINFO (zero), add all authorities. */
1125 STATIC void
1126 add_default_trusted_dir_authorities(dirinfo_type_t type)
1128 int i;
1129 for (i=0; default_authorities[i]; i++) {
1130 if (parse_dir_authority_line(default_authorities[i], type, 0)<0) {
1131 log_err(LD_BUG, "Couldn't parse internal DirAuthority line %s",
1132 default_authorities[i]);
1137 /** Add the default fallback directory servers into the fallback directory
1138 * server list. */
1139 MOCK_IMPL(void,
1140 add_default_fallback_dir_servers,(void))
1142 int i;
1143 for (i=0; default_fallbacks[i]; i++) {
1144 if (parse_dir_fallback_line(default_fallbacks[i], 0)<0) {
1145 log_err(LD_BUG, "Couldn't parse internal FallbackDir line %s",
1146 default_fallbacks[i]);
1151 /** Look at all the config options for using alternate directory
1152 * authorities, and make sure none of them are broken. Also, warn the
1153 * user if we changed any dangerous ones.
1155 static int
1156 validate_dir_servers(or_options_t *options, or_options_t *old_options)
1158 config_line_t *cl;
1160 if (options->DirAuthorities &&
1161 (options->AlternateDirAuthority || options->AlternateBridgeAuthority)) {
1162 log_warn(LD_CONFIG,
1163 "You cannot set both DirAuthority and Alternate*Authority.");
1164 return -1;
1167 /* do we want to complain to the user about being partitionable? */
1168 if ((options->DirAuthorities &&
1169 (!old_options ||
1170 !config_lines_eq(options->DirAuthorities,
1171 old_options->DirAuthorities))) ||
1172 (options->AlternateDirAuthority &&
1173 (!old_options ||
1174 !config_lines_eq(options->AlternateDirAuthority,
1175 old_options->AlternateDirAuthority)))) {
1176 log_warn(LD_CONFIG,
1177 "You have used DirAuthority or AlternateDirAuthority to "
1178 "specify alternate directory authorities in "
1179 "your configuration. This is potentially dangerous: it can "
1180 "make you look different from all other Tor users, and hurt "
1181 "your anonymity. Even if you've specified the same "
1182 "authorities as Tor uses by default, the defaults could "
1183 "change in the future. Be sure you know what you're doing.");
1186 /* Now go through the four ways you can configure an alternate
1187 * set of directory authorities, and make sure none are broken. */
1188 for (cl = options->DirAuthorities; cl; cl = cl->next)
1189 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1190 return -1;
1191 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1192 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1193 return -1;
1194 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1195 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1196 return -1;
1197 for (cl = options->FallbackDir; cl; cl = cl->next)
1198 if (parse_dir_fallback_line(cl->value, 1)<0)
1199 return -1;
1200 return 0;
1203 /** Look at all the config options and assign new dir authorities
1204 * as appropriate.
1207 consider_adding_dir_servers(const or_options_t *options,
1208 const or_options_t *old_options)
1210 config_line_t *cl;
1211 int need_to_update =
1212 !smartlist_len(router_get_trusted_dir_servers()) ||
1213 !smartlist_len(router_get_fallback_dir_servers()) || !old_options ||
1214 !config_lines_eq(options->DirAuthorities, old_options->DirAuthorities) ||
1215 !config_lines_eq(options->FallbackDir, old_options->FallbackDir) ||
1216 (options->UseDefaultFallbackDirs != old_options->UseDefaultFallbackDirs) ||
1217 !config_lines_eq(options->AlternateBridgeAuthority,
1218 old_options->AlternateBridgeAuthority) ||
1219 !config_lines_eq(options->AlternateDirAuthority,
1220 old_options->AlternateDirAuthority);
1222 if (!need_to_update)
1223 return 0; /* all done */
1225 /* "You cannot set both DirAuthority and Alternate*Authority."
1226 * Checking that this restriction holds allows us to simplify
1227 * the unit tests. */
1228 tor_assert(!(options->DirAuthorities &&
1229 (options->AlternateDirAuthority
1230 || options->AlternateBridgeAuthority)));
1232 /* Start from a clean slate. */
1233 clear_dir_servers();
1235 if (!options->DirAuthorities) {
1236 /* then we may want some of the defaults */
1237 dirinfo_type_t type = NO_DIRINFO;
1238 if (!options->AlternateBridgeAuthority) {
1239 type |= BRIDGE_DIRINFO;
1241 if (!options->AlternateDirAuthority) {
1242 type |= V3_DIRINFO | EXTRAINFO_DIRINFO | MICRODESC_DIRINFO;
1243 /* Only add the default fallback directories when the DirAuthorities,
1244 * AlternateDirAuthority, and FallbackDir directory config options
1245 * are set to their defaults, and when UseDefaultFallbackDirs is 1. */
1246 if (!options->FallbackDir && options->UseDefaultFallbackDirs) {
1247 add_default_fallback_dir_servers();
1250 /* if type == NO_DIRINFO, we don't want to add any of the
1251 * default authorities, because we've replaced them all */
1252 if (type != NO_DIRINFO)
1253 add_default_trusted_dir_authorities(type);
1256 for (cl = options->DirAuthorities; cl; cl = cl->next)
1257 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1258 return -1;
1259 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1260 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1261 return -1;
1262 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1263 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1264 return -1;
1265 for (cl = options->FallbackDir; cl; cl = cl->next)
1266 if (parse_dir_fallback_line(cl->value, 0)<0)
1267 return -1;
1268 return 0;
1272 * Make sure that <b>directory</b> exists, with appropriate ownership and
1273 * permissions (as modified by <b>group_readable</b>). If <b>create</b>,
1274 * create the directory if it is missing. Return 0 on success.
1275 * On failure, return -1 and set *<b>msg_out</b>.
1277 static int
1278 check_and_create_data_directory(int create,
1279 const char *directory,
1280 int group_readable,
1281 const char *owner,
1282 char **msg_out)
1284 cpd_check_t cpd_opts = create ? CPD_CREATE : CPD_CHECK;
1285 if (group_readable)
1286 cpd_opts |= CPD_GROUP_READ;
1287 if (check_private_dir(directory,
1288 cpd_opts,
1289 owner) < 0) {
1290 tor_asprintf(msg_out,
1291 "Couldn't %s private data directory \"%s\"",
1292 create ? "create" : "access",
1293 directory);
1294 return -1;
1297 #ifndef _WIN32
1298 if (group_readable) {
1299 /* Only new dirs created get new opts, also enforce group read. */
1300 if (chmod(directory, 0750)) {
1301 log_warn(LD_FS,"Unable to make %s group-readable: %s",
1302 directory, strerror(errno));
1305 #endif /* !defined(_WIN32) */
1307 return 0;
1311 * Ensure that our keys directory exists, with appropriate permissions.
1312 * Return 0 on success, -1 on failure.
1315 create_keys_directory(const or_options_t *options)
1317 /* Make sure DataDirectory exists, and is private. */
1318 cpd_check_t cpd_opts = CPD_CREATE;
1319 if (options->DataDirectoryGroupReadable)
1320 cpd_opts |= CPD_GROUP_READ;
1321 if (check_private_dir(options->DataDirectory, cpd_opts, options->User)) {
1322 log_err(LD_OR, "Can't create/check datadirectory %s",
1323 options->DataDirectory);
1324 return -1;
1327 /* Check the key directory. */
1328 if (check_private_dir(options->KeyDirectory, CPD_CREATE, options->User)) {
1329 return -1;
1331 return 0;
1334 /* Helps determine flags to pass to switch_id. */
1335 static int have_low_ports = -1;
1337 /** Fetch the active option list, and take actions based on it. All of the
1338 * things we do should survive being done repeatedly. If present,
1339 * <b>old_options</b> contains the previous value of the options.
1341 * Return 0 if all goes well, return -1 if things went badly.
1343 static int
1344 options_act_reversible(const or_options_t *old_options, char **msg)
1346 smartlist_t *new_listeners = smartlist_new();
1347 smartlist_t *replaced_listeners = smartlist_new();
1348 static int libevent_initialized = 0;
1349 or_options_t *options = get_options_mutable();
1350 int running_tor = options->command == CMD_RUN_TOR;
1351 int set_conn_limit = 0;
1352 int r = -1;
1353 int logs_marked = 0, logs_initialized = 0;
1354 int old_min_log_level = get_min_log_level();
1356 /* Daemonize _first_, since we only want to open most of this stuff in
1357 * the subprocess. Libevent bases can't be reliably inherited across
1358 * processes. */
1359 if (running_tor && options->RunAsDaemon) {
1360 /* No need to roll back, since you can't change the value. */
1361 start_daemon();
1364 #ifdef HAVE_SYSTEMD
1365 /* Our PID may have changed, inform supervisor */
1366 sd_notifyf(0, "MAINPID=%ld\n", (long int)getpid());
1367 #endif
1369 #ifndef HAVE_SYS_UN_H
1370 if (options->ControlSocket || options->ControlSocketsGroupWritable) {
1371 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported "
1372 "on this OS/with this build.");
1373 goto rollback;
1375 #else /* !(!defined(HAVE_SYS_UN_H)) */
1376 if (options->ControlSocketsGroupWritable && !options->ControlSocket) {
1377 *msg = tor_strdup("Setting ControlSocketGroupWritable without setting"
1378 "a ControlSocket makes no sense.");
1379 goto rollback;
1381 #endif /* !defined(HAVE_SYS_UN_H) */
1383 if (running_tor) {
1384 int n_ports=0;
1385 /* We need to set the connection limit before we can open the listeners. */
1386 if (! sandbox_is_active()) {
1387 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1388 &options->ConnLimit_) < 0) {
1389 *msg = tor_strdup("Problem with ConnLimit value. "
1390 "See logs for details.");
1391 goto rollback;
1393 set_conn_limit = 1;
1394 } else {
1395 tor_assert(old_options);
1396 options->ConnLimit_ = old_options->ConnLimit_;
1399 /* Set up libevent. (We need to do this before we can register the
1400 * listeners as listeners.) */
1401 if (running_tor && !libevent_initialized) {
1402 init_libevent(options);
1403 libevent_initialized = 1;
1405 /* This has to come up after libevent is initialized. */
1406 control_initialize_event_queue();
1409 * Initialize the scheduler - this has to come after
1410 * options_init_from_torrc() sets up libevent - why yes, that seems
1411 * completely sensible to hide the libevent setup in the option parsing
1412 * code! It also needs to happen before init_keys(), so it needs to
1413 * happen here too. How yucky. */
1414 scheduler_init();
1417 /* Adjust the port configuration so we can launch listeners. */
1418 if (parse_ports(options, 0, msg, &n_ports, NULL)) {
1419 if (!*msg)
1420 *msg = tor_strdup("Unexpected problem parsing port config");
1421 goto rollback;
1424 /* Set the hibernation state appropriately.*/
1425 consider_hibernation(time(NULL));
1427 /* Launch the listeners. (We do this before we setuid, so we can bind to
1428 * ports under 1024.) We don't want to rebind if we're hibernating. If
1429 * networking is disabled, this will close all but the control listeners,
1430 * but disable those. */
1431 if (!we_are_hibernating()) {
1432 if (retry_all_listeners(replaced_listeners, new_listeners,
1433 options->DisableNetwork) < 0) {
1434 *msg = tor_strdup("Failed to bind one of the listener ports.");
1435 goto rollback;
1438 if (options->DisableNetwork) {
1439 /* Aggressively close non-controller stuff, NOW */
1440 log_notice(LD_NET, "DisableNetwork is set. Tor will not make or accept "
1441 "non-control network connections. Shutting down all existing "
1442 "connections.");
1443 connection_mark_all_noncontrol_connections();
1444 /* We can't complete circuits until the network is re-enabled. */
1445 note_that_we_maybe_cant_complete_circuits();
1449 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1450 /* Open /dev/pf before dropping privileges. */
1451 if (options->TransPort_set &&
1452 options->TransProxyType_parsed == TPT_DEFAULT) {
1453 if (get_pf_socket() < 0) {
1454 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1455 goto rollback;
1458 #endif /* defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H) */
1460 /* Attempt to lock all current and future memory with mlockall() only once */
1461 if (options->DisableAllSwap) {
1462 if (tor_mlockall() == -1) {
1463 *msg = tor_strdup("DisableAllSwap failure. Do you have proper "
1464 "permissions?");
1465 goto done;
1469 /* Setuid/setgid as appropriate */
1470 if (options->User) {
1471 tor_assert(have_low_ports != -1);
1472 unsigned switch_id_flags = 0;
1473 if (options->KeepBindCapabilities == 1) {
1474 switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
1475 switch_id_flags |= SWITCH_ID_WARN_IF_NO_CAPS;
1477 if (options->KeepBindCapabilities == -1 && have_low_ports) {
1478 switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
1480 if (switch_id(options->User, switch_id_flags) != 0) {
1481 /* No need to roll back, since you can't change the value. */
1482 *msg = tor_strdup("Problem with User value. See logs for details.");
1483 goto done;
1487 /* Ensure data directory is private; create if possible. */
1488 /* It's okay to do this in "options_act_reversible()" even though it isn't
1489 * actually reversible, since you can't change the DataDirectory while
1490 * Tor is running. */
1491 if (check_and_create_data_directory(running_tor /* create */,
1492 options->DataDirectory,
1493 options->DataDirectoryGroupReadable,
1494 options->User,
1495 msg) < 0) {
1496 goto done;
1498 if (check_and_create_data_directory(running_tor /* create */,
1499 options->KeyDirectory,
1500 options->KeyDirectoryGroupReadable,
1501 options->User,
1502 msg) < 0) {
1503 goto done;
1505 if (check_and_create_data_directory(running_tor /* create */,
1506 options->CacheDirectory,
1507 options->CacheDirectoryGroupReadable,
1508 options->User,
1509 msg) < 0) {
1510 goto done;
1513 /* Bail out at this point if we're not going to be a client or server:
1514 * we don't run Tor itself. */
1515 if (!running_tor)
1516 goto commit;
1518 mark_logs_temp(); /* Close current logs once new logs are open. */
1519 logs_marked = 1;
1520 /* Configure the tor_log(s) */
1521 if (options_init_logs(old_options, options, 0)<0) {
1522 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1523 goto rollback;
1525 logs_initialized = 1;
1527 commit:
1528 r = 0;
1529 if (logs_marked) {
1530 log_severity_list_t *severity =
1531 tor_malloc_zero(sizeof(log_severity_list_t));
1532 close_temp_logs();
1533 add_callback_log(severity, control_event_logmsg);
1534 control_adjust_event_log_severity();
1535 tor_free(severity);
1536 tor_log_update_sigsafe_err_fds();
1538 if (logs_initialized) {
1539 flush_log_messages_from_startup();
1543 const char *badness = NULL;
1544 int bad_safelog = 0, bad_severity = 0, new_badness = 0;
1545 if (options->SafeLogging_ != SAFELOG_SCRUB_ALL) {
1546 bad_safelog = 1;
1547 if (!old_options || old_options->SafeLogging_ != options->SafeLogging_)
1548 new_badness = 1;
1550 if (get_min_log_level() >= LOG_INFO) {
1551 bad_severity = 1;
1552 if (get_min_log_level() != old_min_log_level)
1553 new_badness = 1;
1555 if (bad_safelog && bad_severity)
1556 badness = "you disabled SafeLogging, and "
1557 "you're logging more than \"notice\"";
1558 else if (bad_safelog)
1559 badness = "you disabled SafeLogging";
1560 else
1561 badness = "you're logging more than \"notice\"";
1562 if (new_badness)
1563 log_warn(LD_GENERAL, "Your log may contain sensitive information - %s. "
1564 "Don't log unless it serves an important reason. "
1565 "Overwrite the log afterwards.", badness);
1568 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1570 int marked = conn->marked_for_close;
1571 log_notice(LD_NET, "Closing old %s on %s:%d",
1572 conn_type_to_string(conn->type), conn->address, conn->port);
1573 connection_close_immediate(conn);
1574 if (!marked) {
1575 connection_mark_for_close(conn);
1579 if (set_conn_limit) {
1581 * If we adjusted the conn limit, recompute the OOS threshold too
1583 * How many possible sockets to keep in reserve? If we have lots of
1584 * possible sockets, keep this below a limit and set ConnLimit_high_thresh
1585 * very close to ConnLimit_, but if ConnLimit_ is low, shrink it in
1586 * proportion.
1588 * Somewhat arbitrarily, set socks_in_reserve to 5% of ConnLimit_, but
1589 * cap it at 64.
1591 int socks_in_reserve = options->ConnLimit_ / 20;
1592 if (socks_in_reserve > 64) socks_in_reserve = 64;
1594 options->ConnLimit_high_thresh = options->ConnLimit_ - socks_in_reserve;
1595 options->ConnLimit_low_thresh = (options->ConnLimit_ / 4) * 3;
1596 log_info(LD_GENERAL,
1597 "Recomputed OOS thresholds: ConnLimit %d, ConnLimit_ %d, "
1598 "ConnLimit_high_thresh %d, ConnLimit_low_thresh %d",
1599 options->ConnLimit, options->ConnLimit_,
1600 options->ConnLimit_high_thresh,
1601 options->ConnLimit_low_thresh);
1603 /* Give the OOS handler a chance with the new thresholds */
1604 connection_check_oos(get_n_open_sockets(), 0);
1607 goto done;
1609 rollback:
1610 r = -1;
1611 tor_assert(*msg);
1613 if (logs_marked) {
1614 rollback_log_changes();
1615 control_adjust_event_log_severity();
1618 if (set_conn_limit && old_options)
1619 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1620 &options->ConnLimit_);
1622 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1624 log_notice(LD_NET, "Closing partially-constructed %s on %s:%d",
1625 conn_type_to_string(conn->type), conn->address, conn->port);
1626 connection_close_immediate(conn);
1627 connection_mark_for_close(conn);
1630 done:
1631 smartlist_free(new_listeners);
1632 smartlist_free(replaced_listeners);
1633 return r;
1636 /** If we need to have a GEOIP ip-to-country map to run with our configured
1637 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1639 options_need_geoip_info(const or_options_t *options, const char **reason_out)
1641 int bridge_usage =
1642 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1643 int routerset_usage =
1644 routerset_needs_geoip(options->EntryNodes) ||
1645 routerset_needs_geoip(options->ExitNodes) ||
1646 routerset_needs_geoip(options->ExcludeExitNodes) ||
1647 routerset_needs_geoip(options->ExcludeNodes) ||
1648 routerset_needs_geoip(options->Tor2webRendezvousPoints);
1650 if (routerset_usage && reason_out) {
1651 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1652 "countries, and we need GEOIP information to figure out which ones they "
1653 "are.";
1654 } else if (bridge_usage && reason_out) {
1655 *reason_out = "We've been configured to see which countries can access "
1656 "us as a bridge, and we need GEOIP information to tell which countries "
1657 "clients are in.";
1659 return bridge_usage || routerset_usage;
1662 /** Return the bandwidthrate that we are going to report to the authorities
1663 * based on the config options. */
1664 uint32_t
1665 get_effective_bwrate(const or_options_t *options)
1667 uint64_t bw = options->BandwidthRate;
1668 if (bw > options->MaxAdvertisedBandwidth)
1669 bw = options->MaxAdvertisedBandwidth;
1670 if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1671 bw = options->RelayBandwidthRate;
1672 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1673 return (uint32_t)bw;
1676 /** Return the bandwidthburst that we are going to report to the authorities
1677 * based on the config options. */
1678 uint32_t
1679 get_effective_bwburst(const or_options_t *options)
1681 uint64_t bw = options->BandwidthBurst;
1682 if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1683 bw = options->RelayBandwidthBurst;
1684 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1685 return (uint32_t)bw;
1689 * Return true if changing the configuration from <b>old</b> to <b>new</b>
1690 * affects the guard susbsystem.
1692 static int
1693 options_transition_affects_guards(const or_options_t *old,
1694 const or_options_t *new)
1696 /* NOTE: Make sure this function stays in sync with
1697 * node_passes_guard_filter */
1699 tor_assert(old);
1700 tor_assert(new);
1702 return
1703 (old->UseEntryGuards != new->UseEntryGuards ||
1704 old->UseBridges != new->UseBridges ||
1705 old->ClientUseIPv4 != new->ClientUseIPv4 ||
1706 old->ClientUseIPv6 != new->ClientUseIPv6 ||
1707 old->FascistFirewall != new->FascistFirewall ||
1708 !routerset_equal(old->ExcludeNodes, new->ExcludeNodes) ||
1709 !routerset_equal(old->EntryNodes, new->EntryNodes) ||
1710 !smartlist_strings_eq(old->FirewallPorts, new->FirewallPorts) ||
1711 !config_lines_eq(old->Bridges, new->Bridges) ||
1712 !config_lines_eq(old->ReachableORAddresses, new->ReachableORAddresses) ||
1713 !config_lines_eq(old->ReachableDirAddresses, new->ReachableDirAddresses));
1716 /** Fetch the active option list, and take actions based on it. All of the
1717 * things we do should survive being done repeatedly. If present,
1718 * <b>old_options</b> contains the previous value of the options.
1720 * Return 0 if all goes well, return -1 if it's time to die.
1722 * Note: We haven't moved all the "act on new configuration" logic
1723 * here yet. Some is still in do_hup() and other places.
1725 STATIC int
1726 options_act(const or_options_t *old_options)
1728 config_line_t *cl;
1729 or_options_t *options = get_options_mutable();
1730 int running_tor = options->command == CMD_RUN_TOR;
1731 char *msg=NULL;
1732 const int transition_affects_workers =
1733 old_options && options_transition_affects_workers(old_options, options);
1734 int old_ewma_enabled;
1735 const int transition_affects_guards =
1736 old_options && options_transition_affects_guards(old_options, options);
1738 if (options->NoExec || options->Sandbox) {
1739 tor_disable_spawning_background_processes();
1742 /* disable ptrace and later, other basic debugging techniques */
1744 /* Remember if we already disabled debugger attachment */
1745 static int disabled_debugger_attach = 0;
1746 /* Remember if we already warned about being configured not to disable
1747 * debugger attachment */
1748 static int warned_debugger_attach = 0;
1749 /* Don't disable debugger attachment when we're running the unit tests. */
1750 if (options->DisableDebuggerAttachment && !disabled_debugger_attach &&
1751 running_tor) {
1752 int ok = tor_disable_debugger_attach();
1753 /* LCOV_EXCL_START the warned_debugger_attach is 0 can't reach inside. */
1754 if (warned_debugger_attach && ok == 1) {
1755 log_notice(LD_CONFIG, "Disabled attaching debuggers for unprivileged "
1756 "users.");
1758 /* LCOV_EXCL_STOP */
1759 disabled_debugger_attach = (ok == 1);
1760 } else if (!options->DisableDebuggerAttachment &&
1761 !warned_debugger_attach) {
1762 log_notice(LD_CONFIG, "Not disabling debugger attaching for "
1763 "unprivileged users.");
1764 warned_debugger_attach = 1;
1768 /* Write control ports to disk as appropriate */
1769 control_ports_write_to_file();
1771 if (running_tor && !have_lockfile()) {
1772 if (try_locking(options, 1) < 0)
1773 return -1;
1776 if (options->ProtocolWarnings)
1777 protocol_warning_severity_level = LOG_WARN;
1778 else
1779 protocol_warning_severity_level = LOG_INFO;
1781 if (consider_adding_dir_servers(options, old_options) < 0) {
1782 // XXXX This should get validated earlier, and committed here, to
1783 // XXXX lower opportunities for reaching an error case.
1784 return -1;
1787 if (rend_non_anonymous_mode_enabled(options)) {
1788 log_warn(LD_GENERAL, "This copy of Tor was compiled or configured to run "
1789 "in a non-anonymous mode. It will provide NO ANONYMITY.");
1792 #ifdef ENABLE_TOR2WEB_MODE
1793 /* LCOV_EXCL_START */
1794 // XXXX This should move into options_validate()
1795 if (!options->Tor2webMode) {
1796 log_err(LD_CONFIG, "This copy of Tor was compiled to run in "
1797 "'tor2web mode'. It can only be run with the Tor2webMode torrc "
1798 "option enabled.");
1799 return -1;
1801 /* LCOV_EXCL_STOP */
1802 #else /* !(defined(ENABLE_TOR2WEB_MODE)) */
1803 // XXXX This should move into options_validate()
1804 if (options->Tor2webMode) {
1805 log_err(LD_CONFIG, "This copy of Tor was not compiled to run in "
1806 "'tor2web mode'. It cannot be run with the Tor2webMode torrc "
1807 "option enabled. To enable Tor2webMode recompile with the "
1808 "--enable-tor2web-mode option.");
1809 return -1;
1811 #endif /* defined(ENABLE_TOR2WEB_MODE) */
1813 /* If we are a bridge with a pluggable transport proxy but no
1814 Extended ORPort, inform the user that they are missing out. */
1815 if (server_mode(options) && options->ServerTransportPlugin &&
1816 !options->ExtORPort_lines) {
1817 log_notice(LD_CONFIG, "We use pluggable transports but the Extended "
1818 "ORPort is disabled. Tor and your pluggable transports proxy "
1819 "communicate with each other via the Extended ORPort so it "
1820 "is suggested you enable it: it will also allow your Bridge "
1821 "to collect statistics about its clients that use pluggable "
1822 "transports. Please enable it using the ExtORPort torrc option "
1823 "(e.g. set 'ExtORPort auto').");
1826 if (options->Bridges) {
1827 mark_bridge_list();
1828 for (cl = options->Bridges; cl; cl = cl->next) {
1829 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
1830 if (!bridge_line) {
1831 // LCOV_EXCL_START
1832 log_warn(LD_BUG,
1833 "Previously validated Bridge line could not be added!");
1834 return -1;
1835 // LCOV_EXCL_STOP
1837 bridge_add_from_config(bridge_line);
1839 sweep_bridge_list();
1842 if (running_tor && hs_config_service_all(options, 0)<0) {
1843 // LCOV_EXCL_START
1844 log_warn(LD_BUG,
1845 "Previously validated hidden services line could not be added!");
1846 return -1;
1847 // LCOV_EXCL_STOP
1850 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1851 // LCOV_EXCL_START
1852 log_warn(LD_BUG, "Previously validated client authorization for "
1853 "hidden services could not be added!");
1854 return -1;
1855 // LCOV_EXCL_STOP
1858 if (running_tor && !old_options && options->OwningControllerFD != -1) {
1859 #ifdef _WIN32
1860 log_warn(LD_CONFIG, "OwningControllerFD is not supported on Windows. "
1861 "If you need it, tell the Tor developers.");
1862 return -1;
1863 #else
1864 const unsigned ctrl_flags =
1865 CC_LOCAL_FD_IS_OWNER |
1866 CC_LOCAL_FD_IS_AUTHENTICATED;
1867 tor_socket_t ctrl_sock = (tor_socket_t)options->OwningControllerFD;
1868 if (control_connection_add_local_fd(ctrl_sock, ctrl_flags) < 0) {
1869 log_warn(LD_CONFIG, "Could not add local controller connection with "
1870 "given FD.");
1871 return -1;
1873 #endif /* defined(_WIN32) */
1876 /* Load state */
1877 if (! or_state_loaded() && running_tor) {
1878 if (or_state_load())
1879 return -1;
1880 rep_hist_load_mtbf_data(time(NULL));
1883 /* If we have an ExtORPort, initialize its auth cookie. */
1884 if (running_tor &&
1885 init_ext_or_cookie_authentication(!!options->ExtORPort_lines) < 0) {
1886 log_warn(LD_CONFIG,"Error creating Extended ORPort cookie file.");
1887 return -1;
1890 mark_transport_list();
1891 pt_prepare_proxy_list_for_config_read();
1892 if (!options->DisableNetwork) {
1893 if (options->ClientTransportPlugin) {
1894 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
1895 if (parse_transport_line(options, cl->value, 0, 0) < 0) {
1896 // LCOV_EXCL_START
1897 log_warn(LD_BUG,
1898 "Previously validated ClientTransportPlugin line "
1899 "could not be added!");
1900 return -1;
1901 // LCOV_EXCL_STOP
1906 if (options->ServerTransportPlugin && server_mode(options)) {
1907 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
1908 if (parse_transport_line(options, cl->value, 0, 1) < 0) {
1909 // LCOV_EXCL_START
1910 log_warn(LD_BUG,
1911 "Previously validated ServerTransportPlugin line "
1912 "could not be added!");
1913 return -1;
1914 // LCOV_EXCL_STOP
1919 sweep_transport_list();
1920 sweep_proxy_list();
1922 /* Start the PT proxy configuration. By doing this configuration
1923 here, we also figure out which proxies need to be restarted and
1924 which not. */
1925 if (pt_proxies_configuration_pending() && !net_is_disabled())
1926 pt_configure_remaining_proxies();
1928 /* Bail out at this point if we're not going to be a client or server:
1929 * we want to not fork, and to log stuff to stderr. */
1930 if (!running_tor)
1931 return 0;
1933 /* Finish backgrounding the process */
1934 if (options->RunAsDaemon) {
1935 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1936 finish_daemon(options->DataDirectory);
1939 /* We want to reinit keys as needed before we do much of anything else:
1940 keys are important, and other things can depend on them. */
1941 if (transition_affects_workers ||
1942 (options->V3AuthoritativeDir && (!old_options ||
1943 !old_options->V3AuthoritativeDir))) {
1944 if (init_keys() < 0) {
1945 log_warn(LD_BUG,"Error initializing keys; exiting");
1946 return -1;
1950 /* Write our PID to the PID file. If we do not have write permissions we
1951 * will log a warning and exit. */
1952 if (options->PidFile && !sandbox_is_active()) {
1953 if (write_pidfile(options->PidFile) < 0) {
1954 log_err(LD_CONFIG, "Unable to write PIDFile %s",
1955 escaped(options->PidFile));
1956 return -1;
1960 /* Register addressmap directives */
1961 config_register_addressmaps(options);
1962 parse_virtual_addr_network(options->VirtualAddrNetworkIPv4, AF_INET,0,NULL);
1963 parse_virtual_addr_network(options->VirtualAddrNetworkIPv6, AF_INET6,0,NULL);
1965 /* Update address policies. */
1966 if (policies_parse_from_options(options) < 0) {
1967 /* This should be impossible, but let's be sure. */
1968 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1969 return -1;
1972 if (server_mode(options)) {
1973 static int cdm_initialized = 0;
1974 if (cdm_initialized == 0) {
1975 cdm_initialized = 1;
1976 consdiffmgr_configure(NULL);
1977 consdiffmgr_validate();
1981 if (init_control_cookie_authentication(options->CookieAuthentication) < 0) {
1982 log_warn(LD_CONFIG,"Error creating control cookie authentication file.");
1983 return -1;
1986 monitor_owning_controller_process(options->OwningControllerProcess);
1988 /* reload keys as needed for rendezvous services. */
1989 if (hs_service_load_all_keys() < 0) {
1990 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1991 return -1;
1994 /* Inform the scheduler subsystem that a configuration changed happened. It
1995 * might be a change of scheduler or parameter. */
1996 scheduler_conf_changed();
1998 /* Set up accounting */
1999 if (accounting_parse_options(options, 0)<0) {
2000 // LCOV_EXCL_START
2001 log_warn(LD_BUG,"Error in previously validated accounting options");
2002 return -1;
2003 // LCOV_EXCL_STOP
2005 if (accounting_is_enabled(options))
2006 configure_accounting(time(NULL));
2008 old_ewma_enabled = cell_ewma_enabled();
2009 /* Change the cell EWMA settings */
2010 cell_ewma_set_scale_factor(options, networkstatus_get_latest_consensus());
2011 /* If we just enabled ewma, set the cmux policy on all active channels */
2012 if (cell_ewma_enabled() && !old_ewma_enabled) {
2013 channel_set_cmux_policy_everywhere(&ewma_policy);
2014 } else if (!cell_ewma_enabled() && old_ewma_enabled) {
2015 /* Turn it off everywhere */
2016 channel_set_cmux_policy_everywhere(NULL);
2019 /* Update the BridgePassword's hashed version as needed. We store this as a
2020 * digest so that we can do side-channel-proof comparisons on it.
2022 if (options->BridgePassword) {
2023 char *http_authenticator;
2024 http_authenticator = alloc_http_authenticator(options->BridgePassword);
2025 if (!http_authenticator) {
2026 // XXXX This should get validated in options_validate().
2027 log_warn(LD_BUG, "Unable to allocate HTTP authenticator. Not setting "
2028 "BridgePassword.");
2029 return -1;
2031 options->BridgePassword_AuthDigest_ = tor_malloc(DIGEST256_LEN);
2032 crypto_digest256(options->BridgePassword_AuthDigest_,
2033 http_authenticator, strlen(http_authenticator),
2034 DIGEST_SHA256);
2035 tor_free(http_authenticator);
2038 if (parse_outbound_addresses(options, 0, &msg) < 0) {
2039 // LCOV_EXCL_START
2040 log_warn(LD_BUG, "Failed parsing previously validated outbound "
2041 "bind addresses: %s", msg);
2042 tor_free(msg);
2043 return -1;
2044 // LCOV_EXCL_STOP
2047 config_maybe_load_geoip_files_(options, old_options);
2049 if (geoip_is_loaded(AF_INET) && options->GeoIPExcludeUnknown) {
2050 /* ExcludeUnknown is true or "auto" */
2051 const int is_auto = options->GeoIPExcludeUnknown == -1;
2052 int changed;
2054 changed = routerset_add_unknown_ccs(&options->ExcludeNodes, is_auto);
2055 changed += routerset_add_unknown_ccs(&options->ExcludeExitNodes, is_auto);
2057 if (changed)
2058 routerset_add_unknown_ccs(&options->ExcludeExitNodesUnion_, is_auto);
2061 /* Check for transitions that need action. */
2062 if (old_options) {
2063 int revise_trackexithosts = 0;
2064 int revise_automap_entries = 0;
2065 int abandon_circuits = 0;
2066 if ((options->UseEntryGuards && !old_options->UseEntryGuards) ||
2067 options->UseBridges != old_options->UseBridges ||
2068 (options->UseBridges &&
2069 !config_lines_eq(options->Bridges, old_options->Bridges)) ||
2070 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes) ||
2071 !routerset_equal(old_options->ExcludeExitNodes,
2072 options->ExcludeExitNodes) ||
2073 !routerset_equal(old_options->EntryNodes, options->EntryNodes) ||
2074 !routerset_equal(old_options->ExitNodes, options->ExitNodes) ||
2075 !routerset_equal(old_options->Tor2webRendezvousPoints,
2076 options->Tor2webRendezvousPoints) ||
2077 options->StrictNodes != old_options->StrictNodes) {
2078 log_info(LD_CIRC,
2079 "Changed to using entry guards or bridges, or changed "
2080 "preferred or excluded node lists. "
2081 "Abandoning previous circuits.");
2082 abandon_circuits = 1;
2085 if (transition_affects_guards) {
2086 if (guards_update_all()) {
2087 abandon_circuits = 1;
2091 if (abandon_circuits) {
2092 circuit_mark_all_unused_circs();
2093 circuit_mark_all_dirty_circs_as_unusable();
2094 revise_trackexithosts = 1;
2097 if (!smartlist_strings_eq(old_options->TrackHostExits,
2098 options->TrackHostExits))
2099 revise_trackexithosts = 1;
2101 if (revise_trackexithosts)
2102 addressmap_clear_excluded_trackexithosts(options);
2104 if (!options->AutomapHostsOnResolve &&
2105 old_options->AutomapHostsOnResolve) {
2106 revise_automap_entries = 1;
2107 } else {
2108 if (!smartlist_strings_eq(old_options->AutomapHostsSuffixes,
2109 options->AutomapHostsSuffixes))
2110 revise_automap_entries = 1;
2111 else if (!opt_streq(old_options->VirtualAddrNetworkIPv4,
2112 options->VirtualAddrNetworkIPv4) ||
2113 !opt_streq(old_options->VirtualAddrNetworkIPv6,
2114 options->VirtualAddrNetworkIPv6))
2115 revise_automap_entries = 1;
2118 if (revise_automap_entries)
2119 addressmap_clear_invalid_automaps(options);
2121 /* How long should we delay counting bridge stats after becoming a bridge?
2122 * We use this so we don't count clients who used our bridge thinking it is
2123 * a relay. If you change this, don't forget to change the log message
2124 * below. It's 4 hours (the time it takes to stop being used by clients)
2125 * plus some extra time for clock skew. */
2126 #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
2128 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
2129 int was_relay = 0;
2130 if (options->BridgeRelay) {
2131 time_t int_start = time(NULL);
2132 if (config_lines_eq(old_options->ORPort_lines,options->ORPort_lines)) {
2133 int_start += RELAY_BRIDGE_STATS_DELAY;
2134 was_relay = 1;
2136 geoip_bridge_stats_init(int_start);
2137 log_info(LD_CONFIG, "We are acting as a bridge now. Starting new "
2138 "GeoIP stats interval%s.", was_relay ? " in 6 "
2139 "hours from now" : "");
2140 } else {
2141 geoip_bridge_stats_term();
2142 log_info(LD_GENERAL, "We are no longer acting as a bridge. "
2143 "Forgetting GeoIP stats.");
2147 if (transition_affects_workers) {
2148 log_info(LD_GENERAL,
2149 "Worker-related options changed. Rotating workers.");
2151 if (server_mode(options) && !server_mode(old_options)) {
2152 cpu_init();
2153 ip_address_changed(0);
2154 if (have_completed_a_circuit() || !any_predicted_circuits(time(NULL)))
2155 inform_testing_reachability();
2157 cpuworkers_rotate_keyinfo();
2158 if (dns_reset())
2159 return -1;
2160 } else {
2161 if (dns_reset())
2162 return -1;
2165 if (options->PerConnBWRate != old_options->PerConnBWRate ||
2166 options->PerConnBWBurst != old_options->PerConnBWBurst)
2167 connection_or_update_token_buckets(get_connection_array(), options);
2169 if (options->MainloopStats != old_options->MainloopStats) {
2170 reset_main_loop_counters();
2174 /* Only collect directory-request statistics on relays and bridges. */
2175 options->DirReqStatistics = options->DirReqStatistics_option &&
2176 server_mode(options);
2177 options->HiddenServiceStatistics =
2178 options->HiddenServiceStatistics_option && server_mode(options);
2180 if (options->CellStatistics || options->DirReqStatistics ||
2181 options->EntryStatistics || options->ExitPortStatistics ||
2182 options->ConnDirectionStatistics ||
2183 options->HiddenServiceStatistics ||
2184 options->BridgeAuthoritativeDir) {
2185 time_t now = time(NULL);
2186 int print_notice = 0;
2188 /* Only collect other relay-only statistics on relays. */
2189 if (!public_server_mode(options)) {
2190 options->CellStatistics = 0;
2191 options->EntryStatistics = 0;
2192 options->ConnDirectionStatistics = 0;
2193 options->ExitPortStatistics = 0;
2196 if ((!old_options || !old_options->CellStatistics) &&
2197 options->CellStatistics) {
2198 rep_hist_buffer_stats_init(now);
2199 print_notice = 1;
2201 if ((!old_options || !old_options->DirReqStatistics) &&
2202 options->DirReqStatistics) {
2203 if (geoip_is_loaded(AF_INET)) {
2204 geoip_dirreq_stats_init(now);
2205 print_notice = 1;
2206 } else {
2207 /* disable statistics collection since we have no geoip file */
2208 options->DirReqStatistics = 0;
2209 if (options->ORPort_set)
2210 log_notice(LD_CONFIG, "Configured to measure directory request "
2211 "statistics, but no GeoIP database found. "
2212 "Please specify a GeoIP database using the "
2213 "GeoIPFile option.");
2216 if ((!old_options || !old_options->EntryStatistics) &&
2217 options->EntryStatistics && !should_record_bridge_info(options)) {
2218 if (geoip_is_loaded(AF_INET) || geoip_is_loaded(AF_INET6)) {
2219 geoip_entry_stats_init(now);
2220 print_notice = 1;
2221 } else {
2222 options->EntryStatistics = 0;
2223 log_notice(LD_CONFIG, "Configured to measure entry node "
2224 "statistics, but no GeoIP database found. "
2225 "Please specify a GeoIP database using the "
2226 "GeoIPFile option.");
2229 if ((!old_options || !old_options->ExitPortStatistics) &&
2230 options->ExitPortStatistics) {
2231 rep_hist_exit_stats_init(now);
2232 print_notice = 1;
2234 if ((!old_options || !old_options->ConnDirectionStatistics) &&
2235 options->ConnDirectionStatistics) {
2236 rep_hist_conn_stats_init(now);
2238 if ((!old_options || !old_options->HiddenServiceStatistics) &&
2239 options->HiddenServiceStatistics) {
2240 log_info(LD_CONFIG, "Configured to measure hidden service statistics.");
2241 rep_hist_hs_stats_init(now);
2243 if ((!old_options || !old_options->BridgeAuthoritativeDir) &&
2244 options->BridgeAuthoritativeDir) {
2245 rep_hist_desc_stats_init(now);
2246 print_notice = 1;
2248 if (print_notice)
2249 log_notice(LD_CONFIG, "Configured to measure statistics. Look for "
2250 "the *-stats files that will first be written to the "
2251 "data directory in 24 hours from now.");
2254 /* If we used to have statistics enabled but we just disabled them,
2255 stop gathering them. */
2256 if (old_options && old_options->CellStatistics &&
2257 !options->CellStatistics)
2258 rep_hist_buffer_stats_term();
2259 if (old_options && old_options->DirReqStatistics &&
2260 !options->DirReqStatistics)
2261 geoip_dirreq_stats_term();
2262 if (old_options && old_options->EntryStatistics &&
2263 !options->EntryStatistics)
2264 geoip_entry_stats_term();
2265 if (old_options && old_options->HiddenServiceStatistics &&
2266 !options->HiddenServiceStatistics)
2267 rep_hist_hs_stats_term();
2268 if (old_options && old_options->ExitPortStatistics &&
2269 !options->ExitPortStatistics)
2270 rep_hist_exit_stats_term();
2271 if (old_options && old_options->ConnDirectionStatistics &&
2272 !options->ConnDirectionStatistics)
2273 rep_hist_conn_stats_term();
2274 if (old_options && old_options->BridgeAuthoritativeDir &&
2275 !options->BridgeAuthoritativeDir)
2276 rep_hist_desc_stats_term();
2278 /* Since our options changed, we might need to regenerate and upload our
2279 * server descriptor.
2281 if (!old_options ||
2282 options_transition_affects_descriptor(old_options, options))
2283 mark_my_descriptor_dirty("config change");
2285 /* We may need to reschedule some directory stuff if our status changed. */
2286 if (old_options) {
2287 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
2288 dirvote_recalculate_timing(options, time(NULL));
2289 if (!bool_eq(directory_fetches_dir_info_early(options),
2290 directory_fetches_dir_info_early(old_options)) ||
2291 !bool_eq(directory_fetches_dir_info_later(options),
2292 directory_fetches_dir_info_later(old_options))) {
2293 /* Make sure update_router_have_minimum_dir_info() gets called. */
2294 router_dir_info_changed();
2295 /* We might need to download a new consensus status later or sooner than
2296 * we had expected. */
2297 update_consensus_networkstatus_fetch_time(time(NULL));
2301 /* Load the webpage we're going to serve every time someone asks for '/' on
2302 our DirPort. */
2303 tor_free(global_dirfrontpagecontents);
2304 if (options->DirPortFrontPage) {
2305 global_dirfrontpagecontents =
2306 read_file_to_str(options->DirPortFrontPage, 0, NULL);
2307 if (!global_dirfrontpagecontents) {
2308 log_warn(LD_CONFIG,
2309 "DirPortFrontPage file '%s' not found. Continuing anyway.",
2310 options->DirPortFrontPage);
2314 return 0;
2317 typedef enum {
2318 TAKES_NO_ARGUMENT = 0,
2319 ARGUMENT_NECESSARY = 1,
2320 ARGUMENT_OPTIONAL = 2
2321 } takes_argument_t;
2323 static const struct {
2324 const char *name;
2325 takes_argument_t takes_argument;
2326 } CMDLINE_ONLY_OPTIONS[] = {
2327 { "-f", ARGUMENT_NECESSARY },
2328 { "--allow-missing-torrc", TAKES_NO_ARGUMENT },
2329 { "--defaults-torrc", ARGUMENT_NECESSARY },
2330 { "--hash-password", ARGUMENT_NECESSARY },
2331 { "--dump-config", ARGUMENT_OPTIONAL },
2332 { "--list-fingerprint", TAKES_NO_ARGUMENT },
2333 { "--keygen", TAKES_NO_ARGUMENT },
2334 { "--key-expiration", ARGUMENT_OPTIONAL },
2335 { "--newpass", TAKES_NO_ARGUMENT },
2336 { "--no-passphrase", TAKES_NO_ARGUMENT },
2337 { "--passphrase-fd", ARGUMENT_NECESSARY },
2338 { "--verify-config", TAKES_NO_ARGUMENT },
2339 { "--ignore-missing-torrc", TAKES_NO_ARGUMENT },
2340 { "--quiet", TAKES_NO_ARGUMENT },
2341 { "--hush", TAKES_NO_ARGUMENT },
2342 { "--version", TAKES_NO_ARGUMENT },
2343 { "--library-versions", TAKES_NO_ARGUMENT },
2344 { "-h", TAKES_NO_ARGUMENT },
2345 { "--help", TAKES_NO_ARGUMENT },
2346 { "--list-torrc-options", TAKES_NO_ARGUMENT },
2347 { "--list-deprecated-options",TAKES_NO_ARGUMENT },
2348 { "--nt-service", TAKES_NO_ARGUMENT },
2349 { "-nt-service", TAKES_NO_ARGUMENT },
2350 { NULL, 0 },
2353 /** Helper: Read a list of configuration options from the command line. If
2354 * successful, or if ignore_errors is set, put them in *<b>result</b>, put the
2355 * commandline-only options in *<b>cmdline_result</b>, and return 0;
2356 * otherwise, return -1 and leave *<b>result</b> and <b>cmdline_result</b>
2357 * alone. */
2359 config_parse_commandline(int argc, char **argv, int ignore_errors,
2360 config_line_t **result,
2361 config_line_t **cmdline_result)
2363 config_line_t *param = NULL;
2365 config_line_t *front = NULL;
2366 config_line_t **new = &front;
2368 config_line_t *front_cmdline = NULL;
2369 config_line_t **new_cmdline = &front_cmdline;
2371 char *s, *arg;
2372 int i = 1;
2374 while (i < argc) {
2375 unsigned command = CONFIG_LINE_NORMAL;
2376 takes_argument_t want_arg = ARGUMENT_NECESSARY;
2377 int is_cmdline = 0;
2378 int j;
2380 for (j = 0; CMDLINE_ONLY_OPTIONS[j].name != NULL; ++j) {
2381 if (!strcmp(argv[i], CMDLINE_ONLY_OPTIONS[j].name)) {
2382 is_cmdline = 1;
2383 want_arg = CMDLINE_ONLY_OPTIONS[j].takes_argument;
2384 break;
2388 s = argv[i];
2390 /* Each keyword may be prefixed with one or two dashes. */
2391 if (*s == '-')
2392 s++;
2393 if (*s == '-')
2394 s++;
2395 /* Figure out the command, if any. */
2396 if (*s == '+') {
2397 s++;
2398 command = CONFIG_LINE_APPEND;
2399 } else if (*s == '/') {
2400 s++;
2401 command = CONFIG_LINE_CLEAR;
2402 /* A 'clear' command has no argument. */
2403 want_arg = 0;
2406 const int is_last = (i == argc-1);
2408 if (want_arg == ARGUMENT_NECESSARY && is_last) {
2409 if (ignore_errors) {
2410 arg = tor_strdup("");
2411 } else {
2412 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
2413 argv[i]);
2414 config_free_lines(front);
2415 config_free_lines(front_cmdline);
2416 return -1;
2418 } else if (want_arg == ARGUMENT_OPTIONAL && is_last) {
2419 arg = tor_strdup("");
2420 } else {
2421 arg = (want_arg != TAKES_NO_ARGUMENT) ? tor_strdup(argv[i+1]) :
2422 tor_strdup("");
2425 param = tor_malloc_zero(sizeof(config_line_t));
2426 param->key = is_cmdline ? tor_strdup(argv[i]) :
2427 tor_strdup(config_expand_abbrev(&options_format, s, 1, 1));
2428 param->value = arg;
2429 param->command = command;
2430 param->next = NULL;
2431 log_debug(LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
2432 param->key, param->value);
2434 if (is_cmdline) {
2435 *new_cmdline = param;
2436 new_cmdline = &((*new_cmdline)->next);
2437 } else {
2438 *new = param;
2439 new = &((*new)->next);
2442 i += want_arg ? 2 : 1;
2444 *cmdline_result = front_cmdline;
2445 *result = front;
2446 return 0;
2449 /** Return true iff key is a valid configuration option. */
2451 option_is_recognized(const char *key)
2453 const config_var_t *var = config_find_option(&options_format, key);
2454 return (var != NULL);
2457 /** Return the canonical name of a configuration option, or NULL
2458 * if no such option exists. */
2459 const char *
2460 option_get_canonical_name(const char *key)
2462 const config_var_t *var = config_find_option(&options_format, key);
2463 return var ? var->name : NULL;
2466 /** Return a canonical list of the options assigned for key.
2468 config_line_t *
2469 option_get_assignment(const or_options_t *options, const char *key)
2471 return config_get_assigned_option(&options_format, options, key, 1);
2474 /** Try assigning <b>list</b> to the global options. You do this by duping
2475 * options, assigning list to the new one, then validating it. If it's
2476 * ok, then throw out the old one and stick with the new one. Else,
2477 * revert to old and return failure. Return SETOPT_OK on success, or
2478 * a setopt_err_t on failure.
2480 * If not success, point *<b>msg</b> to a newly allocated string describing
2481 * what went wrong.
2483 setopt_err_t
2484 options_trial_assign(config_line_t *list, unsigned flags, char **msg)
2486 int r;
2487 or_options_t *trial_options = config_dup(&options_format, get_options());
2489 if ((r=config_assign(&options_format, trial_options,
2490 list, flags, msg)) < 0) {
2491 or_options_free(trial_options);
2492 return r;
2495 setopt_err_t rv;
2496 or_options_t *cur_options = get_options_mutable();
2498 in_option_validation = 1;
2500 if (options_validate(cur_options, trial_options,
2501 global_default_options, 1, msg) < 0) {
2502 or_options_free(trial_options);
2503 rv = SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2504 goto done;
2507 if (options_transition_allowed(cur_options, trial_options, msg) < 0) {
2508 or_options_free(trial_options);
2509 rv = SETOPT_ERR_TRANSITION;
2510 goto done;
2512 in_option_validation = 0;
2514 if (set_options(trial_options, msg)<0) {
2515 or_options_free(trial_options);
2516 rv = SETOPT_ERR_SETTING;
2517 goto done;
2520 /* we liked it. put it in place. */
2521 rv = SETOPT_OK;
2522 done:
2523 in_option_validation = 0;
2524 return rv;
2527 /** Print a usage message for tor. */
2528 static void
2529 print_usage(void)
2531 printf(
2532 "Copyright (c) 2001-2004, Roger Dingledine\n"
2533 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2534 "Copyright (c) 2007-2017, The Tor Project, Inc.\n\n"
2535 "tor -f <torrc> [args]\n"
2536 "See man page for options, or https://www.torproject.org/ for "
2537 "documentation.\n");
2540 /** Print all non-obsolete torrc options. */
2541 static void
2542 list_torrc_options(void)
2544 int i;
2545 for (i = 0; option_vars_[i].name; ++i) {
2546 const config_var_t *var = &option_vars_[i];
2547 if (var->type == CONFIG_TYPE_OBSOLETE ||
2548 var->type == CONFIG_TYPE_LINELIST_V)
2549 continue;
2550 printf("%s\n", var->name);
2554 /** Print all deprecated but non-obsolete torrc options. */
2555 static void
2556 list_deprecated_options(void)
2558 const config_deprecation_t *d;
2559 for (d = option_deprecation_notes_; d->name; ++d) {
2560 printf("%s\n", d->name);
2564 /** Last value actually set by resolve_my_address. */
2565 static uint32_t last_resolved_addr = 0;
2567 /** Accessor for last_resolved_addr from outside this file. */
2568 uint32_t
2569 get_last_resolved_addr(void)
2571 return last_resolved_addr;
2574 /** Reset last_resolved_addr from outside this file. */
2575 void
2576 reset_last_resolved_addr(void)
2578 last_resolved_addr = 0;
2581 /* Return true if <b>options</b> is using the default authorities, and false
2582 * if any authority-related option has been overridden. */
2584 using_default_dir_authorities(const or_options_t *options)
2586 return (!options->DirAuthorities && !options->AlternateDirAuthority);
2590 * Attempt getting our non-local (as judged by tor_addr_is_internal()
2591 * function) IP address using following techniques, listed in
2592 * order from best (most desirable, try first) to worst (least
2593 * desirable, try if everything else fails).
2595 * First, attempt using <b>options-\>Address</b> to get our
2596 * non-local IP address.
2598 * If <b>options-\>Address</b> represents a non-local IP address,
2599 * consider it ours.
2601 * If <b>options-\>Address</b> is a DNS name that resolves to
2602 * a non-local IP address, consider this IP address ours.
2604 * If <b>options-\>Address</b> is NULL, fall back to getting local
2605 * hostname and using it in above-described ways to try and
2606 * get our IP address.
2608 * In case local hostname cannot be resolved to a non-local IP
2609 * address, try getting an IP address of network interface
2610 * in hopes it will be non-local one.
2612 * Fail if one or more of the following is true:
2613 * - DNS name in <b>options-\>Address</b> cannot be resolved.
2614 * - <b>options-\>Address</b> is a local host address.
2615 * - Attempt at getting local hostname fails.
2616 * - Attempt at getting network interface address fails.
2618 * Return 0 if all is well, or -1 if we can't find a suitable
2619 * public IP address.
2621 * If we are returning 0:
2622 * - Put our public IP address (in host order) into *<b>addr_out</b>.
2623 * - If <b>method_out</b> is non-NULL, set *<b>method_out</b> to a static
2624 * string describing how we arrived at our answer.
2625 * - "CONFIGURED" - parsed from IP address string in
2626 * <b>options-\>Address</b>
2627 * - "RESOLVED" - resolved from DNS name in <b>options-\>Address</b>
2628 * - "GETHOSTNAME" - resolved from a local hostname.
2629 * - "INTERFACE" - retrieved from a network interface.
2630 * - If <b>hostname_out</b> is non-NULL, and we resolved a hostname to
2631 * get our address, set *<b>hostname_out</b> to a newly allocated string
2632 * holding that hostname. (If we didn't get our address by resolving a
2633 * hostname, set *<b>hostname_out</b> to NULL.)
2635 * XXXX ipv6
2638 resolve_my_address(int warn_severity, const or_options_t *options,
2639 uint32_t *addr_out,
2640 const char **method_out, char **hostname_out)
2642 struct in_addr in;
2643 uint32_t addr; /* host order */
2644 char hostname[256];
2645 const char *method_used;
2646 const char *hostname_used;
2647 int explicit_ip=1;
2648 int explicit_hostname=1;
2649 int from_interface=0;
2650 char *addr_string = NULL;
2651 const char *address = options->Address;
2652 int notice_severity = warn_severity <= LOG_NOTICE ?
2653 LOG_NOTICE : warn_severity;
2655 tor_addr_t myaddr;
2656 tor_assert(addr_out);
2659 * Step one: Fill in 'hostname' to be our best guess.
2662 if (address && *address) {
2663 strlcpy(hostname, address, sizeof(hostname));
2664 } else { /* then we need to guess our address */
2665 explicit_ip = 0; /* it's implicit */
2666 explicit_hostname = 0; /* it's implicit */
2668 if (tor_gethostname(hostname, sizeof(hostname)) < 0) {
2669 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2670 return -1;
2672 log_debug(LD_CONFIG, "Guessed local host name as '%s'", hostname);
2676 * Step two: Now that we know 'hostname', parse it or resolve it. If
2677 * it doesn't parse or resolve, look at the interface address. Set 'addr'
2678 * to be our (host-order) 32-bit answer.
2681 if (tor_inet_aton(hostname, &in) == 0) {
2682 /* then we have to resolve it */
2683 explicit_ip = 0;
2684 if (tor_lookup_hostname(hostname, &addr)) { /* failed to resolve */
2685 uint32_t interface_ip; /* host order */
2687 if (explicit_hostname) {
2688 log_fn(warn_severity, LD_CONFIG,
2689 "Could not resolve local Address '%s'. Failing.", hostname);
2690 return -1;
2692 log_fn(notice_severity, LD_CONFIG,
2693 "Could not resolve guessed local hostname '%s'. "
2694 "Trying something else.", hostname);
2695 if (get_interface_address(warn_severity, &interface_ip)) {
2696 log_fn(warn_severity, LD_CONFIG,
2697 "Could not get local interface IP address. Failing.");
2698 return -1;
2700 from_interface = 1;
2701 addr = interface_ip;
2702 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2703 "local interface. Using that.", fmt_addr32(addr));
2704 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2705 } else { /* resolved hostname into addr */
2706 tor_addr_from_ipv4h(&myaddr, addr);
2708 if (!explicit_hostname &&
2709 tor_addr_is_internal(&myaddr, 0)) {
2710 tor_addr_t interface_ip;
2712 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2713 "resolves to a private IP address (%s). Trying something "
2714 "else.", hostname, fmt_addr32(addr));
2716 if (get_interface_address6(warn_severity, AF_INET, &interface_ip)<0) {
2717 log_fn(warn_severity, LD_CONFIG,
2718 "Could not get local interface IP address. Too bad.");
2719 } else if (tor_addr_is_internal(&interface_ip, 0)) {
2720 log_fn(notice_severity, LD_CONFIG,
2721 "Interface IP address '%s' is a private address too. "
2722 "Ignoring.", fmt_addr(&interface_ip));
2723 } else {
2724 from_interface = 1;
2725 addr = tor_addr_to_ipv4h(&interface_ip);
2726 log_fn(notice_severity, LD_CONFIG,
2727 "Learned IP address '%s' for local interface."
2728 " Using that.", fmt_addr32(addr));
2729 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2733 } else {
2734 addr = ntohl(in.s_addr); /* set addr so that addr_string is not
2735 * illformed */
2739 * Step three: Check whether 'addr' is an internal IP address, and error
2740 * out if it is and we don't want that.
2743 tor_addr_from_ipv4h(&myaddr,addr);
2745 addr_string = tor_dup_ip(addr);
2746 if (tor_addr_is_internal(&myaddr, 0)) {
2747 /* make sure we're ok with publishing an internal IP */
2748 if (using_default_dir_authorities(options)) {
2749 /* if they are using the default authorities, disallow internal IPs
2750 * always. */
2751 log_fn(warn_severity, LD_CONFIG,
2752 "Address '%s' resolves to private IP address '%s'. "
2753 "Tor servers that use the default DirAuthorities must have "
2754 "public IP addresses.", hostname, addr_string);
2755 tor_free(addr_string);
2756 return -1;
2758 if (!explicit_ip) {
2759 /* even if they've set their own authorities, require an explicit IP if
2760 * they're using an internal address. */
2761 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2762 "IP address '%s'. Please set the Address config option to be "
2763 "the IP address you want to use.", hostname, addr_string);
2764 tor_free(addr_string);
2765 return -1;
2770 * Step four: We have a winner! 'addr' is our answer for sure, and
2771 * 'addr_string' is its string form. Fill out the various fields to
2772 * say how we decided it.
2775 log_debug(LD_CONFIG, "Resolved Address to '%s'.", addr_string);
2777 if (explicit_ip) {
2778 method_used = "CONFIGURED";
2779 hostname_used = NULL;
2780 } else if (explicit_hostname) {
2781 method_used = "RESOLVED";
2782 hostname_used = hostname;
2783 } else if (from_interface) {
2784 method_used = "INTERFACE";
2785 hostname_used = NULL;
2786 } else {
2787 method_used = "GETHOSTNAME";
2788 hostname_used = hostname;
2791 *addr_out = addr;
2792 if (method_out)
2793 *method_out = method_used;
2794 if (hostname_out)
2795 *hostname_out = hostname_used ? tor_strdup(hostname_used) : NULL;
2798 * Step five: Check if the answer has changed since last time (or if
2799 * there was no last time), and if so call various functions to keep
2800 * us up-to-date.
2803 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2804 /* Leave this as a notice, regardless of the requested severity,
2805 * at least until dynamic IP address support becomes bulletproof. */
2806 log_notice(LD_NET,
2807 "Your IP address seems to have changed to %s "
2808 "(METHOD=%s%s%s). Updating.",
2809 addr_string, method_used,
2810 hostname_used ? " HOSTNAME=" : "",
2811 hostname_used ? hostname_used : "");
2812 ip_address_changed(0);
2815 if (last_resolved_addr != *addr_out) {
2816 control_event_server_status(LOG_NOTICE,
2817 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s%s%s",
2818 addr_string, method_used,
2819 hostname_used ? " HOSTNAME=" : "",
2820 hostname_used ? hostname_used : "");
2822 last_resolved_addr = *addr_out;
2825 * And finally, clean up and return success.
2828 tor_free(addr_string);
2829 return 0;
2832 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2833 * on a private network.
2835 MOCK_IMPL(int,
2836 is_local_addr, (const tor_addr_t *addr))
2838 if (tor_addr_is_internal(addr, 0))
2839 return 1;
2840 /* Check whether ip is on the same /24 as we are. */
2841 if (get_options()->EnforceDistinctSubnets == 0)
2842 return 0;
2843 if (tor_addr_family(addr) == AF_INET) {
2844 uint32_t ip = tor_addr_to_ipv4h(addr);
2846 /* It's possible that this next check will hit before the first time
2847 * resolve_my_address actually succeeds. (For clients, it is likely that
2848 * resolve_my_address will never be called at all). In those cases,
2849 * last_resolved_addr will be 0, and so checking to see whether ip is on
2850 * the same /24 as last_resolved_addr will be the same as checking whether
2851 * it was on net 0, which is already done by tor_addr_is_internal.
2853 if ((last_resolved_addr & (uint32_t)0xffffff00ul)
2854 == (ip & (uint32_t)0xffffff00ul))
2855 return 1;
2857 return 0;
2860 /** Return a new empty or_options_t. Used for testing. */
2861 or_options_t *
2862 options_new(void)
2864 return config_new(&options_format);
2867 /** Set <b>options</b> to hold reasonable defaults for most options.
2868 * Each option defaults to zero. */
2869 void
2870 options_init(or_options_t *options)
2872 config_init(&options_format, options);
2875 /** Return a string containing a possible configuration file that would give
2876 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2877 * include options that are the same as Tor's defaults.
2879 char *
2880 options_dump(const or_options_t *options, int how_to_dump)
2882 const or_options_t *use_defaults;
2883 int minimal;
2884 switch (how_to_dump) {
2885 case OPTIONS_DUMP_MINIMAL:
2886 use_defaults = global_default_options;
2887 minimal = 1;
2888 break;
2889 case OPTIONS_DUMP_DEFAULTS:
2890 use_defaults = NULL;
2891 minimal = 1;
2892 break;
2893 case OPTIONS_DUMP_ALL:
2894 use_defaults = NULL;
2895 minimal = 0;
2896 break;
2897 default:
2898 log_warn(LD_BUG, "Bogus value for how_to_dump==%d", how_to_dump);
2899 return NULL;
2902 return config_dump(&options_format, use_defaults, options, minimal, 0);
2905 /** Return 0 if every element of sl is a string holding a decimal
2906 * representation of a port number, or if sl is NULL.
2907 * Otherwise set *msg and return -1. */
2908 static int
2909 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2911 int i;
2912 tor_assert(name);
2914 if (!sl)
2915 return 0;
2917 SMARTLIST_FOREACH(sl, const char *, cp,
2919 i = atoi(cp);
2920 if (i < 1 || i > 65535) {
2921 tor_asprintf(msg, "Port '%s' out of range in %s", cp, name);
2922 return -1;
2925 return 0;
2928 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2929 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2930 * Else return 0.
2932 static int
2933 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2935 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2936 /* This handles an understandable special case where somebody says "2gb"
2937 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2938 --*value;
2940 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2941 tor_asprintf(msg, "%s ("U64_FORMAT") must be at most %d",
2942 desc, U64_PRINTF_ARG(*value),
2943 ROUTER_MAX_DECLARED_BANDWIDTH);
2944 return -1;
2946 return 0;
2949 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2950 * and write it to <b>options</b>-\>PublishServerDescriptor_. Treat "1"
2951 * as "v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2952 * Treat "0" as "".
2953 * Return 0 on success or -1 if not a recognized authority type (in which
2954 * case the value of PublishServerDescriptor_ is undefined). */
2955 static int
2956 compute_publishserverdescriptor(or_options_t *options)
2958 smartlist_t *list = options->PublishServerDescriptor;
2959 dirinfo_type_t *auth = &options->PublishServerDescriptor_;
2960 *auth = NO_DIRINFO;
2961 if (!list) /* empty list, answer is none */
2962 return 0;
2963 SMARTLIST_FOREACH_BEGIN(list, const char *, string) {
2964 if (!strcasecmp(string, "v1"))
2965 log_warn(LD_CONFIG, "PublishServerDescriptor v1 has no effect, because "
2966 "there are no v1 directory authorities anymore.");
2967 else if (!strcmp(string, "1"))
2968 if (options->BridgeRelay)
2969 *auth |= BRIDGE_DIRINFO;
2970 else
2971 *auth |= V3_DIRINFO;
2972 else if (!strcasecmp(string, "v2"))
2973 log_warn(LD_CONFIG, "PublishServerDescriptor v2 has no effect, because "
2974 "there are no v2 directory authorities anymore.");
2975 else if (!strcasecmp(string, "v3"))
2976 *auth |= V3_DIRINFO;
2977 else if (!strcasecmp(string, "bridge"))
2978 *auth |= BRIDGE_DIRINFO;
2979 else if (!strcasecmp(string, "hidserv"))
2980 log_warn(LD_CONFIG,
2981 "PublishServerDescriptor hidserv is invalid. See "
2982 "PublishHidServDescriptors.");
2983 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2984 /* no authority */;
2985 else
2986 return -1;
2987 } SMARTLIST_FOREACH_END(string);
2988 return 0;
2991 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2992 * services can overload the directory system. */
2993 #define MIN_REND_POST_PERIOD (10*60)
2994 #define MIN_REND_POST_PERIOD_TESTING (5)
2996 /** Highest allowable value for CircuitsAvailableTimeout.
2997 * If this is too large, client connections will stay open for too long,
2998 * incurring extra padding overhead. */
2999 #define MAX_CIRCS_AVAILABLE_TIME (24*60*60)
3001 /** Highest allowable value for RendPostPeriod. */
3002 #define MAX_DIR_PERIOD ((7*24*60*60)/2)
3004 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
3005 * will generate too many circuits and potentially overload the network. */
3006 #define MIN_MAX_CIRCUIT_DIRTINESS 10
3008 /** Highest allowable value for MaxCircuitDirtiness: prevents time_t
3009 * overflows. */
3010 #define MAX_MAX_CIRCUIT_DIRTINESS (30*24*60*60)
3012 /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
3013 * will generate too many circuits and potentially overload the network. */
3014 #define MIN_CIRCUIT_STREAM_TIMEOUT 10
3016 /** Lowest recommended value for CircuitBuildTimeout; if it is set too low
3017 * and LearnCircuitBuildTimeout is off, the failure rate for circuit
3018 * construction may be very high. In that case, if it is set below this
3019 * threshold emit a warning.
3020 * */
3021 #define RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT (10)
3023 static int
3024 options_validate_cb(void *old_options, void *options, void *default_options,
3025 int from_setconf, char **msg)
3027 in_option_validation = 1;
3028 int rv = options_validate(old_options, options, default_options,
3029 from_setconf, msg);
3030 in_option_validation = 0;
3031 return rv;
3034 #define REJECT(arg) \
3035 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
3036 #if defined(__GNUC__) && __GNUC__ <= 3
3037 #define COMPLAIN(args...) \
3038 STMT_BEGIN log_warn(LD_CONFIG, args); STMT_END
3039 #else
3040 #define COMPLAIN(args, ...) \
3041 STMT_BEGIN log_warn(LD_CONFIG, args, ##__VA_ARGS__); STMT_END
3042 #endif /* defined(__GNUC__) && __GNUC__ <= 3 */
3044 /** Log a warning message iff <b>filepath</b> is not absolute.
3045 * Warning message must contain option name <b>option</b> and
3046 * an absolute path that <b>filepath</b> will resolve to.
3048 * In case <b>filepath</b> is absolute, do nothing.
3050 * Return 1 if there were relative paths; 0 otherwise.
3052 static int
3053 warn_if_option_path_is_relative(const char *option,
3054 char *filepath)
3056 if (filepath && path_is_relative(filepath)) {
3057 char *abs_path = make_path_absolute(filepath);
3058 COMPLAIN("Path for %s (%s) is relative and will resolve to %s."
3059 " Is this what you wanted?", option, filepath, abs_path);
3060 tor_free(abs_path);
3061 return 1;
3063 return 0;
3066 /** Scan <b>options</b> for occurances of relative file/directory
3067 * path and log a warning whenever it is found.
3069 * Return 1 if there were relative paths; 0 otherwise.
3071 static int
3072 warn_about_relative_paths(or_options_t *options)
3074 tor_assert(options);
3075 int n = 0;
3077 n += warn_if_option_path_is_relative("CookieAuthFile",
3078 options->CookieAuthFile);
3079 n += warn_if_option_path_is_relative("ExtORPortCookieAuthFile",
3080 options->ExtORPortCookieAuthFile);
3081 n += warn_if_option_path_is_relative("DirPortFrontPage",
3082 options->DirPortFrontPage);
3083 n += warn_if_option_path_is_relative("V3BandwidthsFile",
3084 options->V3BandwidthsFile);
3085 n += warn_if_option_path_is_relative("ControlPortWriteToFile",
3086 options->ControlPortWriteToFile);
3087 n += warn_if_option_path_is_relative("GeoIPFile",options->GeoIPFile);
3088 n += warn_if_option_path_is_relative("GeoIPv6File",options->GeoIPv6File);
3089 n += warn_if_option_path_is_relative("Log",options->DebugLogFile);
3090 n += warn_if_option_path_is_relative("AccelDir",options->AccelDir);
3091 n += warn_if_option_path_is_relative("DataDirectory",options->DataDirectory);
3092 n += warn_if_option_path_is_relative("PidFile",options->PidFile);
3094 for (config_line_t *hs_line = options->RendConfigLines; hs_line;
3095 hs_line = hs_line->next) {
3096 if (!strcasecmp(hs_line->key, "HiddenServiceDir"))
3097 n += warn_if_option_path_is_relative("HiddenServiceDir",hs_line->value);
3099 return n != 0;
3102 /* Validate options related to the scheduler. From the Schedulers list, the
3103 * SchedulerTypes_ list is created with int values so once we select the
3104 * scheduler, which can happen anytime at runtime, we don't have to parse
3105 * strings and thus be quick.
3107 * Return 0 on success else -1 and msg is set with an error message. */
3108 static int
3109 options_validate_scheduler(or_options_t *options, char **msg)
3111 tor_assert(options);
3112 tor_assert(msg);
3114 if (!options->Schedulers || smartlist_len(options->Schedulers) == 0) {
3115 REJECT("Empty Schedulers list. Either remove the option so the defaults "
3116 "can be used or set at least one value.");
3118 /* Ok, we do have scheduler types, validate them. */
3119 options->SchedulerTypes_ = smartlist_new();
3120 SMARTLIST_FOREACH_BEGIN(options->Schedulers, const char *, type) {
3121 int *sched_type;
3122 if (!strcasecmp("KISTLite", type)) {
3123 sched_type = tor_malloc_zero(sizeof(int));
3124 *sched_type = SCHEDULER_KIST_LITE;
3125 smartlist_add(options->SchedulerTypes_, sched_type);
3126 } else if (!strcasecmp("KIST", type)) {
3127 sched_type = tor_malloc_zero(sizeof(int));
3128 *sched_type = SCHEDULER_KIST;
3129 smartlist_add(options->SchedulerTypes_, sched_type);
3130 } else if (!strcasecmp("Vanilla", type)) {
3131 sched_type = tor_malloc_zero(sizeof(int));
3132 *sched_type = SCHEDULER_VANILLA;
3133 smartlist_add(options->SchedulerTypes_, sched_type);
3134 } else {
3135 tor_asprintf(msg, "Unknown type %s in option Schedulers. "
3136 "Possible values are KIST, KISTLite and Vanilla.",
3137 escaped(type));
3138 return -1;
3140 } SMARTLIST_FOREACH_END(type);
3142 if (options->KISTSockBufSizeFactor < 0) {
3143 REJECT("KISTSockBufSizeFactor must be at least 0");
3146 /* Don't need to validate that the Interval is less than anything because
3147 * zero is valid and all negative values are valid. */
3148 if (options->KISTSchedRunInterval > KIST_SCHED_RUN_INTERVAL_MAX) {
3149 tor_asprintf(msg, "KISTSchedRunInterval must not be more than %d (ms)",
3150 KIST_SCHED_RUN_INTERVAL_MAX);
3151 return -1;
3154 return 0;
3157 /* Validate options related to single onion services.
3158 * Modifies some options that are incompatible with single onion services.
3159 * On failure returns -1, and sets *msg to an error string.
3160 * Returns 0 on success. */
3161 STATIC int
3162 options_validate_single_onion(or_options_t *options, char **msg)
3164 /* The two single onion service options must have matching values. */
3165 if (options->HiddenServiceSingleHopMode &&
3166 !options->HiddenServiceNonAnonymousMode) {
3167 REJECT("HiddenServiceSingleHopMode does not provide any server anonymity. "
3168 "It must be used with HiddenServiceNonAnonymousMode set to 1.");
3170 if (options->HiddenServiceNonAnonymousMode &&
3171 !options->HiddenServiceSingleHopMode) {
3172 REJECT("HiddenServiceNonAnonymousMode does not provide any server "
3173 "anonymity. It must be used with HiddenServiceSingleHopMode set to "
3174 "1.");
3177 /* Now that we've checked that the two options are consistent, we can safely
3178 * call the rend_service_* functions that abstract these options. */
3180 /* If you run an anonymous client with an active Single Onion service, the
3181 * client loses anonymity. */
3182 const int client_port_set = (options->SocksPort_set ||
3183 options->TransPort_set ||
3184 options->NATDPort_set ||
3185 options->DNSPort_set ||
3186 options->HTTPTunnelPort_set);
3187 if (rend_service_non_anonymous_mode_enabled(options) && client_port_set &&
3188 !options->Tor2webMode) {
3189 REJECT("HiddenServiceNonAnonymousMode is incompatible with using Tor as "
3190 "an anonymous client. Please set Socks/Trans/NATD/DNSPort to 0, or "
3191 "revert HiddenServiceNonAnonymousMode to 0.");
3194 /* If you run a hidden service in non-anonymous mode, the hidden service
3195 * loses anonymity, even if SOCKSPort / Tor2web mode isn't used. */
3196 if (!rend_service_non_anonymous_mode_enabled(options) &&
3197 options->RendConfigLines && options->Tor2webMode) {
3198 REJECT("Non-anonymous (Tor2web) mode is incompatible with using Tor as a "
3199 "hidden service. Please remove all HiddenServiceDir lines, or use "
3200 "a version of tor compiled without --enable-tor2web-mode, or use "
3201 "HiddenServiceNonAnonymousMode.");
3204 if (rend_service_allow_non_anonymous_connection(options)
3205 && options->UseEntryGuards) {
3206 /* Single Onion services only use entry guards when uploading descriptors;
3207 * all other connections are one-hop. Further, Single Onions causes the
3208 * hidden service code to do things which break the path bias
3209 * detector, and it's far easier to turn off entry guards (and
3210 * thus the path bias detector with it) than to figure out how to
3211 * make path bias compatible with single onions.
3213 log_notice(LD_CONFIG,
3214 "HiddenServiceSingleHopMode is enabled; disabling "
3215 "UseEntryGuards.");
3216 options->UseEntryGuards = 0;
3219 return 0;
3222 /** Return 0 if every setting in <b>options</b> is reasonable, is a
3223 * permissible transition from <b>old_options</b>, and none of the
3224 * testing-only settings differ from <b>default_options</b> unless in
3225 * testing mode. Else return -1. Should have no side effects, except for
3226 * normalizing the contents of <b>options</b>.
3228 * On error, tor_strdup an error explanation into *<b>msg</b>.
3230 * XXX
3231 * If <b>from_setconf</b>, we were called by the controller, and our
3232 * Log line should stay empty. If it's 0, then give us a default log
3233 * if there are no logs defined.
3235 STATIC int
3236 options_validate(or_options_t *old_options, or_options_t *options,
3237 or_options_t *default_options, int from_setconf, char **msg)
3239 int i;
3240 config_line_t *cl;
3241 const char *uname = get_uname();
3242 int n_ports=0;
3243 int world_writable_control_socket=0;
3245 tor_assert(msg);
3246 *msg = NULL;
3248 if (parse_ports(options, 1, msg, &n_ports,
3249 &world_writable_control_socket) < 0)
3250 return -1;
3252 /* Set UseEntryGuards from the configured value, before we check it below.
3253 * We change UseEntryGuards when it's incompatible with other options,
3254 * but leave UseEntryGuards_option with the original value.
3255 * Always use the value of UseEntryGuards, not UseEntryGuards_option. */
3256 options->UseEntryGuards = options->UseEntryGuards_option;
3258 if (warn_about_relative_paths(options) && options->RunAsDaemon) {
3259 REJECT("You have specified at least one relative path (see above) "
3260 "with the RunAsDaemon option. RunAsDaemon is not compatible "
3261 "with relative paths.");
3264 if (server_mode(options) &&
3265 (!strcmpstart(uname, "Windows 95") ||
3266 !strcmpstart(uname, "Windows 98") ||
3267 !strcmpstart(uname, "Windows Me"))) {
3268 log_warn(LD_CONFIG, "Tor is running as a server, but you are "
3269 "running %s; this probably won't work. See "
3270 "https://www.torproject.org/docs/faq.html#BestOSForRelay "
3271 "for details.", uname);
3274 if (parse_outbound_addresses(options, 1, msg) < 0)
3275 return -1;
3277 if (validate_data_directories(options)<0)
3278 REJECT("Invalid DataDirectory");
3280 if (options->Nickname == NULL) {
3281 if (server_mode(options)) {
3282 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
3284 } else {
3285 if (!is_legal_nickname(options->Nickname)) {
3286 tor_asprintf(msg,
3287 "Nickname '%s', nicknames must be between 1 and 19 characters "
3288 "inclusive, and must contain only the characters [a-zA-Z0-9].",
3289 options->Nickname);
3290 return -1;
3294 if (server_mode(options) && !options->ContactInfo)
3295 log_notice(LD_CONFIG, "Your ContactInfo config option is not set. "
3296 "Please consider setting it, so we can contact you if your server is "
3297 "misconfigured or something else goes wrong.");
3299 /* Special case on first boot if no Log options are given. */
3300 if (!options->Logs && !options->RunAsDaemon && !from_setconf) {
3301 if (quiet_level == 0)
3302 config_line_append(&options->Logs, "Log", "notice stdout");
3303 else if (quiet_level == 1)
3304 config_line_append(&options->Logs, "Log", "warn stdout");
3307 /* Validate the tor_log(s) */
3308 if (options_init_logs(old_options, options, 1)<0)
3309 REJECT("Failed to validate Log options. See logs for details.");
3311 if (authdir_mode(options)) {
3312 /* confirm that our address isn't broken, so we can complain now */
3313 uint32_t tmp;
3314 if (resolve_my_address(LOG_WARN, options, &tmp, NULL, NULL) < 0)
3315 REJECT("Failed to resolve/guess local address. See logs for details.");
3318 if (server_mode(options) && options->RendConfigLines)
3319 log_warn(LD_CONFIG,
3320 "Tor is currently configured as a relay and a hidden service. "
3321 "That's not very secure: you should probably run your hidden service "
3322 "in a separate Tor process, at least -- see "
3323 "https://trac.torproject.org/8742");
3325 /* XXXX require that the only port not be DirPort? */
3326 /* XXXX require that at least one port be listened-upon. */
3327 if (n_ports == 0 && !options->RendConfigLines)
3328 log_warn(LD_CONFIG,
3329 "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
3330 "undefined, and there aren't any hidden services configured. "
3331 "Tor will still run, but probably won't do anything.");
3333 options->TransProxyType_parsed = TPT_DEFAULT;
3334 #ifdef USE_TRANSPARENT
3335 if (options->TransProxyType) {
3336 if (!strcasecmp(options->TransProxyType, "default")) {
3337 options->TransProxyType_parsed = TPT_DEFAULT;
3338 } else if (!strcasecmp(options->TransProxyType, "pf-divert")) {
3339 #if !defined(OpenBSD) && !defined( DARWIN )
3340 /* Later versions of OS X have pf */
3341 REJECT("pf-divert is a OpenBSD-specific "
3342 "and OS X/Darwin-specific feature.");
3343 #else
3344 options->TransProxyType_parsed = TPT_PF_DIVERT;
3345 #endif /* !defined(OpenBSD) && !defined( DARWIN ) */
3346 } else if (!strcasecmp(options->TransProxyType, "tproxy")) {
3347 #if !defined(__linux__)
3348 REJECT("TPROXY is a Linux-specific feature.");
3349 #else
3350 options->TransProxyType_parsed = TPT_TPROXY;
3351 #endif
3352 } else if (!strcasecmp(options->TransProxyType, "ipfw")) {
3353 #ifndef KERNEL_MAY_SUPPORT_IPFW
3354 /* Earlier versions of OS X have ipfw */
3355 REJECT("ipfw is a FreeBSD-specific "
3356 "and OS X/Darwin-specific feature.");
3357 #else
3358 options->TransProxyType_parsed = TPT_IPFW;
3359 #endif /* !defined(KERNEL_MAY_SUPPORT_IPFW) */
3360 } else {
3361 REJECT("Unrecognized value for TransProxyType");
3364 if (strcasecmp(options->TransProxyType, "default") &&
3365 !options->TransPort_set) {
3366 REJECT("Cannot use TransProxyType without any valid TransPort.");
3369 #else /* !(defined(USE_TRANSPARENT)) */
3370 if (options->TransPort_set)
3371 REJECT("TransPort is disabled in this build.");
3372 #endif /* defined(USE_TRANSPARENT) */
3374 if (options->TokenBucketRefillInterval <= 0
3375 || options->TokenBucketRefillInterval > 1000) {
3376 REJECT("TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
3379 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3380 options->ExcludeExitNodesUnion_ = routerset_new();
3381 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeExitNodes);
3382 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeNodes);
3385 if (options->NodeFamilies) {
3386 options->NodeFamilySets = smartlist_new();
3387 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3388 routerset_t *rs = routerset_new();
3389 if (routerset_parse(rs, cl->value, cl->key) == 0) {
3390 smartlist_add(options->NodeFamilySets, rs);
3391 } else {
3392 routerset_free(rs);
3397 if (options->ExcludeNodes && options->StrictNodes) {
3398 COMPLAIN("You have asked to exclude certain relays from all positions "
3399 "in your circuits. Expect hidden services and other Tor "
3400 "features to be broken in unpredictable ways.");
3403 for (cl = options->RecommendedPackages; cl; cl = cl->next) {
3404 if (! validate_recommended_package_line(cl->value)) {
3405 log_warn(LD_CONFIG, "Invalid RecommendedPackage line %s will be ignored",
3406 escaped(cl->value));
3410 if (options->AuthoritativeDir) {
3411 if (!options->ContactInfo && !options->TestingTorNetwork)
3412 REJECT("Authoritative directory servers must set ContactInfo");
3413 if (!options->RecommendedClientVersions)
3414 options->RecommendedClientVersions =
3415 config_lines_dup(options->RecommendedVersions);
3416 if (!options->RecommendedServerVersions)
3417 options->RecommendedServerVersions =
3418 config_lines_dup(options->RecommendedVersions);
3419 if (options->VersioningAuthoritativeDir &&
3420 (!options->RecommendedClientVersions ||
3421 !options->RecommendedServerVersions))
3422 REJECT("Versioning authoritative dir servers must set "
3423 "Recommended*Versions.");
3424 if (options->UseEntryGuards) {
3425 log_info(LD_CONFIG, "Authoritative directory servers can't set "
3426 "UseEntryGuards. Disabling.");
3427 options->UseEntryGuards = 0;
3429 if (!options->DownloadExtraInfo && authdir_mode_v3(options)) {
3430 log_info(LD_CONFIG, "Authoritative directories always try to download "
3431 "extra-info documents. Setting DownloadExtraInfo.");
3432 options->DownloadExtraInfo = 1;
3434 if (!(options->BridgeAuthoritativeDir ||
3435 options->V3AuthoritativeDir))
3436 REJECT("AuthoritativeDir is set, but none of "
3437 "(Bridge/V3)AuthoritativeDir is set.");
3438 /* If we have a v3bandwidthsfile and it's broken, complain on startup */
3439 if (options->V3BandwidthsFile && !old_options) {
3440 dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
3442 /* same for guardfraction file */
3443 if (options->GuardfractionFile && !old_options) {
3444 dirserv_read_guardfraction_file(options->GuardfractionFile, NULL);
3448 if (options->AuthoritativeDir && !options->DirPort_set)
3449 REJECT("Running as authoritative directory, but no DirPort set.");
3451 if (options->AuthoritativeDir && !options->ORPort_set)
3452 REJECT("Running as authoritative directory, but no ORPort set.");
3454 if (options->AuthoritativeDir && options->ClientOnly)
3455 REJECT("Running as authoritative directory, but ClientOnly also set.");
3457 if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
3458 REJECT("FetchDirInfoExtraEarly requires that you also set "
3459 "FetchDirInfoEarly");
3461 if (options->ConnLimit <= 0) {
3462 tor_asprintf(msg,
3463 "ConnLimit must be greater than 0, but was set to %d",
3464 options->ConnLimit);
3465 return -1;
3468 if (options->PathsNeededToBuildCircuits >= 0.0) {
3469 if (options->PathsNeededToBuildCircuits < 0.25) {
3470 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too low. Increasing "
3471 "to 0.25");
3472 options->PathsNeededToBuildCircuits = 0.25;
3473 } else if (options->PathsNeededToBuildCircuits > 0.95) {
3474 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too high. Decreasing "
3475 "to 0.95");
3476 options->PathsNeededToBuildCircuits = 0.95;
3480 if (options->MaxClientCircuitsPending <= 0 ||
3481 options->MaxClientCircuitsPending > MAX_MAX_CLIENT_CIRCUITS_PENDING) {
3482 tor_asprintf(msg,
3483 "MaxClientCircuitsPending must be between 1 and %d, but "
3484 "was set to %d", MAX_MAX_CLIENT_CIRCUITS_PENDING,
3485 options->MaxClientCircuitsPending);
3486 return -1;
3489 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3490 return -1;
3492 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3493 return -1;
3495 if (validate_ports_csv(options->RejectPlaintextPorts,
3496 "RejectPlaintextPorts", msg) < 0)
3497 return -1;
3499 if (validate_ports_csv(options->WarnPlaintextPorts,
3500 "WarnPlaintextPorts", msg) < 0)
3501 return -1;
3503 if (options->FascistFirewall && !options->ReachableAddresses) {
3504 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3505 /* We already have firewall ports set, so migrate them to
3506 * ReachableAddresses, which will set ReachableORAddresses and
3507 * ReachableDirAddresses if they aren't set explicitly. */
3508 smartlist_t *instead = smartlist_new();
3509 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3510 new_line->key = tor_strdup("ReachableAddresses");
3511 /* If we're configured with the old format, we need to prepend some
3512 * open ports. */
3513 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3515 int p = atoi(portno);
3516 if (p<0) continue;
3517 smartlist_add_asprintf(instead, "*:%d", p);
3519 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3520 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3521 log_notice(LD_CONFIG,
3522 "Converting FascistFirewall and FirewallPorts "
3523 "config options to new format: \"ReachableAddresses %s\"",
3524 new_line->value);
3525 options->ReachableAddresses = new_line;
3526 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3527 smartlist_free(instead);
3528 } else {
3529 /* We do not have FirewallPorts set, so add 80 to
3530 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3531 if (!options->ReachableDirAddresses) {
3532 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3533 new_line->key = tor_strdup("ReachableDirAddresses");
3534 new_line->value = tor_strdup("*:80");
3535 options->ReachableDirAddresses = new_line;
3536 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3537 "to new format: \"ReachableDirAddresses *:80\"");
3539 if (!options->ReachableORAddresses) {
3540 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3541 new_line->key = tor_strdup("ReachableORAddresses");
3542 new_line->value = tor_strdup("*:443");
3543 options->ReachableORAddresses = new_line;
3544 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3545 "to new format: \"ReachableORAddresses *:443\"");
3550 /* Terminate Reachable*Addresses with reject *
3552 for (i=0; i<3; i++) {
3553 config_line_t **linep =
3554 (i==0) ? &options->ReachableAddresses :
3555 (i==1) ? &options->ReachableORAddresses :
3556 &options->ReachableDirAddresses;
3557 if (!*linep)
3558 continue;
3559 /* We need to end with a reject *:*, not an implicit accept *:* */
3560 for (;;) {
3561 linep = &((*linep)->next);
3562 if (!*linep) {
3563 *linep = tor_malloc_zero(sizeof(config_line_t));
3564 (*linep)->key = tor_strdup(
3565 (i==0) ? "ReachableAddresses" :
3566 (i==1) ? "ReachableORAddresses" :
3567 "ReachableDirAddresses");
3568 (*linep)->value = tor_strdup("reject *:*");
3569 break;
3574 if ((options->ReachableAddresses ||
3575 options->ReachableORAddresses ||
3576 options->ReachableDirAddresses ||
3577 options->ClientUseIPv4 == 0) &&
3578 server_mode(options))
3579 REJECT("Servers must be able to freely connect to the rest "
3580 "of the Internet, so they must not set Reachable*Addresses "
3581 "or FascistFirewall or FirewallPorts or ClientUseIPv4 0.");
3583 if (options->UseBridges &&
3584 server_mode(options))
3585 REJECT("Servers must be able to freely connect to the rest "
3586 "of the Internet, so they must not set UseBridges.");
3588 /* If both of these are set, we'll end up with funny behavior where we
3589 * demand enough entrynodes be up and running else we won't build
3590 * circuits, yet we never actually use them. */
3591 if (options->UseBridges && options->EntryNodes)
3592 REJECT("You cannot set both UseBridges and EntryNodes.");
3594 /* If we have UseBridges as 1 and UseEntryGuards as 0, we end up bypassing
3595 * the use of bridges */
3596 if (options->UseBridges && !options->UseEntryGuards)
3597 REJECT("Setting UseBridges requires also setting UseEntryGuards.");
3599 options->MaxMemInQueues =
3600 compute_real_max_mem_in_queues(options->MaxMemInQueues_raw,
3601 server_mode(options));
3602 options->MaxMemInQueues_low_threshold = (options->MaxMemInQueues / 4) * 3;
3604 if (!options->SafeLogging ||
3605 !strcasecmp(options->SafeLogging, "0")) {
3606 options->SafeLogging_ = SAFELOG_SCRUB_NONE;
3607 } else if (!strcasecmp(options->SafeLogging, "relay")) {
3608 options->SafeLogging_ = SAFELOG_SCRUB_RELAY;
3609 } else if (!strcasecmp(options->SafeLogging, "1")) {
3610 options->SafeLogging_ = SAFELOG_SCRUB_ALL;
3611 } else {
3612 tor_asprintf(msg,
3613 "Unrecognized value '%s' in SafeLogging",
3614 escaped(options->SafeLogging));
3615 return -1;
3618 if (compute_publishserverdescriptor(options) < 0) {
3619 tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
3620 return -1;
3623 if ((options->BridgeRelay
3624 || options->PublishServerDescriptor_ & BRIDGE_DIRINFO)
3625 && (options->PublishServerDescriptor_ & V3_DIRINFO)) {
3626 REJECT("Bridges are not supposed to publish router descriptors to the "
3627 "directory authorities. Please correct your "
3628 "PublishServerDescriptor line.");
3631 if (options->BridgeRelay && options->DirPort_set) {
3632 log_warn(LD_CONFIG, "Can't set a DirPort on a bridge relay; disabling "
3633 "DirPort");
3634 config_free_lines(options->DirPort_lines);
3635 options->DirPort_lines = NULL;
3636 options->DirPort_set = 0;
3639 if (server_mode(options) && options->ConnectionPadding != -1) {
3640 REJECT("Relays must use 'auto' for the ConnectionPadding setting.");
3643 if (server_mode(options) && options->ReducedConnectionPadding != 0) {
3644 REJECT("Relays cannot set ReducedConnectionPadding. ");
3647 if (options->BridgeDistribution) {
3648 if (!options->BridgeRelay) {
3649 REJECT("You set BridgeDistribution, but you didn't set BridgeRelay!");
3651 if (check_bridge_distribution_setting(options->BridgeDistribution) < 0) {
3652 REJECT("Invalid BridgeDistribution value.");
3656 if (options->MinUptimeHidServDirectoryV2 < 0) {
3657 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3658 "least 0 seconds. Changing to 0.");
3659 options->MinUptimeHidServDirectoryV2 = 0;
3662 const int min_rendpostperiod =
3663 options->TestingTorNetwork ?
3664 MIN_REND_POST_PERIOD_TESTING : MIN_REND_POST_PERIOD;
3665 if (options->RendPostPeriod < min_rendpostperiod) {
3666 log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
3667 "raising to %d seconds.", min_rendpostperiod);
3668 options->RendPostPeriod = min_rendpostperiod;
3671 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3672 log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3673 MAX_DIR_PERIOD);
3674 options->RendPostPeriod = MAX_DIR_PERIOD;
3677 /* Check the Single Onion Service options */
3678 if (options_validate_single_onion(options, msg) < 0)
3679 return -1;
3681 if (options->CircuitsAvailableTimeout > MAX_CIRCS_AVAILABLE_TIME) {
3682 // options_t is immutable for new code (the above code is older),
3683 // so just make the user fix the value themselves rather than
3684 // silently keep a shadow value lower than what they asked for.
3685 REJECT("CircuitsAvailableTimeout is too large. Max is 24 hours.");
3688 #ifdef ENABLE_TOR2WEB_MODE
3689 if (options->Tor2webMode && options->UseEntryGuards) {
3690 /* tor2web mode clients do not (and should not) use entry guards
3691 * in any meaningful way. Further, tor2web mode causes the hidden
3692 * service client code to do things which break the path bias
3693 * detector, and it's far easier to turn off entry guards (and
3694 * thus the path bias detector with it) than to figure out how to
3695 * make a piece of code which cannot possibly help tor2web mode
3696 * users compatible with tor2web mode.
3698 log_notice(LD_CONFIG,
3699 "Tor2WebMode is enabled; disabling UseEntryGuards.");
3700 options->UseEntryGuards = 0;
3702 #endif /* defined(ENABLE_TOR2WEB_MODE) */
3704 if (options->Tor2webRendezvousPoints && !options->Tor2webMode) {
3705 REJECT("Tor2webRendezvousPoints cannot be set without Tor2webMode.");
3708 if (options->EntryNodes && !options->UseEntryGuards) {
3709 REJECT("If EntryNodes is set, UseEntryGuards must be enabled.");
3712 if (!(options->UseEntryGuards) &&
3713 (options->RendConfigLines != NULL) &&
3714 !rend_service_allow_non_anonymous_connection(options)) {
3715 log_warn(LD_CONFIG,
3716 "UseEntryGuards is disabled, but you have configured one or more "
3717 "hidden services on this Tor instance. Your hidden services "
3718 "will be very easy to locate using a well-known attack -- see "
3719 "http://freehaven.net/anonbib/#hs-attack06 for details.");
3722 if (options->EntryNodes &&
3723 routerset_is_list(options->EntryNodes) &&
3724 (routerset_len(options->EntryNodes) == 1) &&
3725 (options->RendConfigLines != NULL)) {
3726 tor_asprintf(msg,
3727 "You have one single EntryNodes and at least one hidden service "
3728 "configured. This is bad because it's very easy to locate your "
3729 "entry guard which can then lead to the deanonymization of your "
3730 "hidden service -- for more details, see "
3731 "https://trac.torproject.org/projects/tor/ticket/14917. "
3732 "For this reason, the use of one EntryNodes with an hidden "
3733 "service is prohibited until a better solution is found.");
3734 return -1;
3737 /* Inform the hidden service operator that pinning EntryNodes can possibly
3738 * be harmful for the service anonymity. */
3739 if (options->EntryNodes &&
3740 routerset_is_list(options->EntryNodes) &&
3741 (options->RendConfigLines != NULL)) {
3742 log_warn(LD_CONFIG,
3743 "EntryNodes is set with multiple entries and at least one "
3744 "hidden service is configured. Pinning entry nodes can possibly "
3745 "be harmful to the service anonymity. Because of this, we "
3746 "recommend you either don't do that or make sure you know what "
3747 "you are doing. For more details, please look at "
3748 "https://trac.torproject.org/projects/tor/ticket/21155.");
3751 /* Single Onion Services: non-anonymous hidden services */
3752 if (rend_service_non_anonymous_mode_enabled(options)) {
3753 log_warn(LD_CONFIG,
3754 "HiddenServiceNonAnonymousMode is set. Every hidden service on "
3755 "this tor instance is NON-ANONYMOUS. If "
3756 "the HiddenServiceNonAnonymousMode option is changed, Tor will "
3757 "refuse to launch hidden services from the same directories, to "
3758 "protect your anonymity against config errors. This setting is "
3759 "for experimental use only.");
3762 if (!options->LearnCircuitBuildTimeout && options->CircuitBuildTimeout &&
3763 options->CircuitBuildTimeout < RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT) {
3764 log_warn(LD_CONFIG,
3765 "CircuitBuildTimeout is shorter (%d seconds) than the recommended "
3766 "minimum (%d seconds), and LearnCircuitBuildTimeout is disabled. "
3767 "If tor isn't working, raise this value or enable "
3768 "LearnCircuitBuildTimeout.",
3769 options->CircuitBuildTimeout,
3770 RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT );
3771 } else if (!options->LearnCircuitBuildTimeout &&
3772 !options->CircuitBuildTimeout) {
3773 int severity = LOG_NOTICE;
3774 /* Be a little quieter if we've deliberately disabled
3775 * LearnCircuitBuildTimeout. */
3776 if (circuit_build_times_disabled_(options, 1)) {
3777 severity = LOG_INFO;
3779 log_fn(severity, LD_CONFIG, "You disabled LearnCircuitBuildTimeout, but "
3780 "didn't specify a CircuitBuildTimeout. I'll pick a plausible "
3781 "default.");
3784 if (options->PathBiasNoticeRate > 1.0) {
3785 tor_asprintf(msg,
3786 "PathBiasNoticeRate is too high. "
3787 "It must be between 0 and 1.0");
3788 return -1;
3790 if (options->PathBiasWarnRate > 1.0) {
3791 tor_asprintf(msg,
3792 "PathBiasWarnRate is too high. "
3793 "It must be between 0 and 1.0");
3794 return -1;
3796 if (options->PathBiasExtremeRate > 1.0) {
3797 tor_asprintf(msg,
3798 "PathBiasExtremeRate is too high. "
3799 "It must be between 0 and 1.0");
3800 return -1;
3802 if (options->PathBiasNoticeUseRate > 1.0) {
3803 tor_asprintf(msg,
3804 "PathBiasNoticeUseRate is too high. "
3805 "It must be between 0 and 1.0");
3806 return -1;
3808 if (options->PathBiasExtremeUseRate > 1.0) {
3809 tor_asprintf(msg,
3810 "PathBiasExtremeUseRate is too high. "
3811 "It must be between 0 and 1.0");
3812 return -1;
3815 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3816 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3817 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3818 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3821 if (options->MaxCircuitDirtiness > MAX_MAX_CIRCUIT_DIRTINESS) {
3822 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too high; "
3823 "setting to %d days.", MAX_MAX_CIRCUIT_DIRTINESS/86400);
3824 options->MaxCircuitDirtiness = MAX_MAX_CIRCUIT_DIRTINESS;
3827 if (options->CircuitStreamTimeout &&
3828 options->CircuitStreamTimeout < MIN_CIRCUIT_STREAM_TIMEOUT) {
3829 log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
3830 "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
3831 options->CircuitStreamTimeout = MIN_CIRCUIT_STREAM_TIMEOUT;
3834 if (options->HeartbeatPeriod &&
3835 options->HeartbeatPeriod < MIN_HEARTBEAT_PERIOD) {
3836 log_warn(LD_CONFIG, "HeartbeatPeriod option is too short; "
3837 "raising to %d seconds.", MIN_HEARTBEAT_PERIOD);
3838 options->HeartbeatPeriod = MIN_HEARTBEAT_PERIOD;
3841 if (options->KeepalivePeriod < 1)
3842 REJECT("KeepalivePeriod option must be positive.");
3844 if (options->PortForwarding && options->Sandbox) {
3845 REJECT("PortForwarding is not compatible with Sandbox; at most one can "
3846 "be set");
3848 if (options->PortForwarding && options->NoExec) {
3849 COMPLAIN("Both PortForwarding and NoExec are set; PortForwarding will "
3850 "be ignored.");
3853 if (ensure_bandwidth_cap(&options->BandwidthRate,
3854 "BandwidthRate", msg) < 0)
3855 return -1;
3856 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3857 "BandwidthBurst", msg) < 0)
3858 return -1;
3859 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3860 "MaxAdvertisedBandwidth", msg) < 0)
3861 return -1;
3862 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3863 "RelayBandwidthRate", msg) < 0)
3864 return -1;
3865 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3866 "RelayBandwidthBurst", msg) < 0)
3867 return -1;
3868 if (ensure_bandwidth_cap(&options->PerConnBWRate,
3869 "PerConnBWRate", msg) < 0)
3870 return -1;
3871 if (ensure_bandwidth_cap(&options->PerConnBWBurst,
3872 "PerConnBWBurst", msg) < 0)
3873 return -1;
3874 if (ensure_bandwidth_cap(&options->AuthDirFastGuarantee,
3875 "AuthDirFastGuarantee", msg) < 0)
3876 return -1;
3877 if (ensure_bandwidth_cap(&options->AuthDirGuardBWGuarantee,
3878 "AuthDirGuardBWGuarantee", msg) < 0)
3879 return -1;
3881 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3882 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3883 if (options->RelayBandwidthBurst && !options->RelayBandwidthRate)
3884 options->RelayBandwidthRate = options->RelayBandwidthBurst;
3886 if (server_mode(options)) {
3887 const unsigned required_min_bw =
3888 public_server_mode(options) ?
3889 RELAY_REQUIRED_MIN_BANDWIDTH : BRIDGE_REQUIRED_MIN_BANDWIDTH;
3890 const char * const optbridge =
3891 public_server_mode(options) ? "" : "bridge ";
3892 if (options->BandwidthRate < required_min_bw) {
3893 tor_asprintf(msg,
3894 "BandwidthRate is set to %d bytes/second. "
3895 "For %sservers, it must be at least %u.",
3896 (int)options->BandwidthRate, optbridge,
3897 required_min_bw);
3898 return -1;
3899 } else if (options->MaxAdvertisedBandwidth <
3900 required_min_bw/2) {
3901 tor_asprintf(msg,
3902 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3903 "For %sservers, it must be at least %u.",
3904 (int)options->MaxAdvertisedBandwidth, optbridge,
3905 required_min_bw/2);
3906 return -1;
3908 if (options->RelayBandwidthRate &&
3909 options->RelayBandwidthRate < required_min_bw) {
3910 tor_asprintf(msg,
3911 "RelayBandwidthRate is set to %d bytes/second. "
3912 "For %sservers, it must be at least %u.",
3913 (int)options->RelayBandwidthRate, optbridge,
3914 required_min_bw);
3915 return -1;
3919 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3920 REJECT("RelayBandwidthBurst must be at least equal "
3921 "to RelayBandwidthRate.");
3923 if (options->BandwidthRate > options->BandwidthBurst)
3924 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3926 /* if they set relaybandwidth* really high but left bandwidth*
3927 * at the default, raise the defaults. */
3928 if (options->RelayBandwidthRate > options->BandwidthRate)
3929 options->BandwidthRate = options->RelayBandwidthRate;
3930 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3931 options->BandwidthBurst = options->RelayBandwidthBurst;
3933 if (accounting_parse_options(options, 1)<0)
3934 REJECT("Failed to parse accounting options. See logs for details.");
3936 if (options->AccountingMax) {
3937 if (options->RendConfigLines && server_mode(options)) {
3938 log_warn(LD_CONFIG, "Using accounting with a hidden service and an "
3939 "ORPort is risky: your hidden service(s) and your public "
3940 "address will all turn off at the same time, which may alert "
3941 "observers that they are being run by the same party.");
3942 } else if (config_count_key(options->RendConfigLines,
3943 "HiddenServiceDir") > 1) {
3944 log_warn(LD_CONFIG, "Using accounting with multiple hidden services is "
3945 "risky: they will all turn off at the same time, which may "
3946 "alert observers that they are being run by the same party.");
3950 options->AccountingRule = ACCT_MAX;
3951 if (options->AccountingRule_option) {
3952 if (!strcmp(options->AccountingRule_option, "sum"))
3953 options->AccountingRule = ACCT_SUM;
3954 else if (!strcmp(options->AccountingRule_option, "max"))
3955 options->AccountingRule = ACCT_MAX;
3956 else if (!strcmp(options->AccountingRule_option, "in"))
3957 options->AccountingRule = ACCT_IN;
3958 else if (!strcmp(options->AccountingRule_option, "out"))
3959 options->AccountingRule = ACCT_OUT;
3960 else
3961 REJECT("AccountingRule must be 'sum', 'max', 'in', or 'out'");
3964 if (options->DirPort_set && !options->DirCache) {
3965 REJECT("DirPort configured but DirCache disabled. DirPort requires "
3966 "DirCache.");
3969 if (options->BridgeRelay && !options->DirCache) {
3970 REJECT("We're a bridge but DirCache is disabled. BridgeRelay requires "
3971 "DirCache.");
3974 if (server_mode(options)) {
3975 char *dircache_msg = NULL;
3976 if (have_enough_mem_for_dircache(options, 0, &dircache_msg)) {
3977 log_warn(LD_CONFIG, "%s", dircache_msg);
3978 tor_free(dircache_msg);
3982 if (options->HTTPProxy) { /* parse it now */
3983 if (tor_addr_port_lookup(options->HTTPProxy,
3984 &options->HTTPProxyAddr, &options->HTTPProxyPort) < 0)
3985 REJECT("HTTPProxy failed to parse or resolve. Please fix.");
3986 if (options->HTTPProxyPort == 0) { /* give it a default */
3987 options->HTTPProxyPort = 80;
3991 if (options->HTTPProxyAuthenticator) {
3992 if (strlen(options->HTTPProxyAuthenticator) >= 512)
3993 REJECT("HTTPProxyAuthenticator is too long (>= 512 chars).");
3996 if (options->HTTPSProxy) { /* parse it now */
3997 if (tor_addr_port_lookup(options->HTTPSProxy,
3998 &options->HTTPSProxyAddr, &options->HTTPSProxyPort) <0)
3999 REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
4000 if (options->HTTPSProxyPort == 0) { /* give it a default */
4001 options->HTTPSProxyPort = 443;
4005 if (options->HTTPSProxyAuthenticator) {
4006 if (strlen(options->HTTPSProxyAuthenticator) >= 512)
4007 REJECT("HTTPSProxyAuthenticator is too long (>= 512 chars).");
4010 if (options->Socks4Proxy) { /* parse it now */
4011 if (tor_addr_port_lookup(options->Socks4Proxy,
4012 &options->Socks4ProxyAddr,
4013 &options->Socks4ProxyPort) <0)
4014 REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
4015 if (options->Socks4ProxyPort == 0) { /* give it a default */
4016 options->Socks4ProxyPort = 1080;
4020 if (options->Socks5Proxy) { /* parse it now */
4021 if (tor_addr_port_lookup(options->Socks5Proxy,
4022 &options->Socks5ProxyAddr,
4023 &options->Socks5ProxyPort) <0)
4024 REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
4025 if (options->Socks5ProxyPort == 0) { /* give it a default */
4026 options->Socks5ProxyPort = 1080;
4030 /* Check if more than one exclusive proxy type has been enabled. */
4031 if (!!options->Socks4Proxy + !!options->Socks5Proxy +
4032 !!options->HTTPSProxy > 1)
4033 REJECT("You have configured more than one proxy type. "
4034 "(Socks4Proxy|Socks5Proxy|HTTPSProxy)");
4036 /* Check if the proxies will give surprising behavior. */
4037 if (options->HTTPProxy && !(options->Socks4Proxy ||
4038 options->Socks5Proxy ||
4039 options->HTTPSProxy)) {
4040 log_warn(LD_CONFIG, "HTTPProxy configured, but no SOCKS proxy or "
4041 "HTTPS proxy configured. Watch out: this configuration will "
4042 "proxy unencrypted directory connections only.");
4045 if (options->Socks5ProxyUsername) {
4046 size_t len;
4048 len = strlen(options->Socks5ProxyUsername);
4049 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
4050 REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
4052 if (!options->Socks5ProxyPassword)
4053 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
4055 len = strlen(options->Socks5ProxyPassword);
4056 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
4057 REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
4058 } else if (options->Socks5ProxyPassword)
4059 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
4061 if (options->HashedControlPassword) {
4062 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
4063 if (!sl) {
4064 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
4065 } else {
4066 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
4067 smartlist_free(sl);
4071 if (options->HashedControlSessionPassword) {
4072 smartlist_t *sl = decode_hashed_passwords(
4073 options->HashedControlSessionPassword);
4074 if (!sl) {
4075 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
4076 } else {
4077 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
4078 smartlist_free(sl);
4082 if (options->OwningControllerProcess) {
4083 const char *validate_pspec_msg = NULL;
4084 if (tor_validate_process_specifier(options->OwningControllerProcess,
4085 &validate_pspec_msg)) {
4086 tor_asprintf(msg, "Bad OwningControllerProcess: %s",
4087 validate_pspec_msg);
4088 return -1;
4092 if ((options->ControlPort_set || world_writable_control_socket) &&
4093 !options->HashedControlPassword &&
4094 !options->HashedControlSessionPassword &&
4095 !options->CookieAuthentication) {
4096 log_warn(LD_CONFIG, "Control%s is %s, but no authentication method "
4097 "has been configured. This means that any program on your "
4098 "computer can reconfigure your Tor. That's bad! You should "
4099 "upgrade your Tor controller as soon as possible.",
4100 options->ControlPort_set ? "Port" : "Socket",
4101 options->ControlPort_set ? "open" : "world writable");
4104 if (options->CookieAuthFileGroupReadable && !options->CookieAuthFile) {
4105 log_warn(LD_CONFIG, "CookieAuthFileGroupReadable is set, but will have "
4106 "no effect: you must specify an explicit CookieAuthFile to "
4107 "have it group-readable.");
4110 if (options->MyFamily_lines && options->BridgeRelay) {
4111 log_warn(LD_CONFIG, "Listing a family for a bridge relay is not "
4112 "supported: it can reveal bridge fingerprints to censors. "
4113 "You should also make sure you aren't listing this bridge's "
4114 "fingerprint in any other MyFamily.");
4116 if (normalize_nickname_list(&options->MyFamily,
4117 options->MyFamily_lines, "MyFamily", msg))
4118 return -1;
4119 for (cl = options->NodeFamilies; cl; cl = cl->next) {
4120 routerset_t *rs = routerset_new();
4121 if (routerset_parse(rs, cl->value, cl->key)) {
4122 routerset_free(rs);
4123 return -1;
4125 routerset_free(rs);
4128 if (validate_addr_policies(options, msg) < 0)
4129 return -1;
4131 /* If FallbackDir is set, we don't UseDefaultFallbackDirs */
4132 if (options->UseDefaultFallbackDirs && options->FallbackDir) {
4133 log_info(LD_CONFIG, "You have set UseDefaultFallbackDirs 1 and "
4134 "FallbackDir(s). Ignoring UseDefaultFallbackDirs, and "
4135 "using the FallbackDir(s) you have set.");
4138 if (validate_dir_servers(options, old_options) < 0)
4139 REJECT("Directory authority/fallback line did not parse. See logs "
4140 "for details.");
4142 if (options->UseBridges && !options->Bridges)
4143 REJECT("If you set UseBridges, you must specify at least one bridge.");
4145 for (cl = options->Bridges; cl; cl = cl->next) {
4146 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
4147 if (!bridge_line)
4148 REJECT("Bridge line did not parse. See logs for details.");
4149 bridge_line_free(bridge_line);
4152 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
4153 if (parse_transport_line(options, cl->value, 1, 0) < 0)
4154 REJECT("Invalid client transport line. See logs for details.");
4157 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
4158 if (parse_transport_line(options, cl->value, 1, 1) < 0)
4159 REJECT("Invalid server transport line. See logs for details.");
4162 if (options->ServerTransportPlugin && !server_mode(options)) {
4163 log_notice(LD_GENERAL, "Tor is not configured as a relay but you specified"
4164 " a ServerTransportPlugin line (%s). The ServerTransportPlugin "
4165 "line will be ignored.",
4166 escaped(options->ServerTransportPlugin->value));
4169 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
4170 /** If get_bindaddr_from_transport_listen_line() fails with
4171 'transport' being NULL, it means that something went wrong
4172 while parsing the ServerTransportListenAddr line. */
4173 char *bindaddr = get_bindaddr_from_transport_listen_line(cl->value, NULL);
4174 if (!bindaddr)
4175 REJECT("ServerTransportListenAddr did not parse. See logs for details.");
4176 tor_free(bindaddr);
4179 if (options->ServerTransportListenAddr && !options->ServerTransportPlugin) {
4180 log_notice(LD_GENERAL, "You need at least a single managed-proxy to "
4181 "specify a transport listen address. The "
4182 "ServerTransportListenAddr line will be ignored.");
4185 for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
4186 /** If get_options_from_transport_options_line() fails with
4187 'transport' being NULL, it means that something went wrong
4188 while parsing the ServerTransportOptions line. */
4189 smartlist_t *options_sl =
4190 get_options_from_transport_options_line(cl->value, NULL);
4191 if (!options_sl)
4192 REJECT("ServerTransportOptions did not parse. See logs for details.");
4194 SMARTLIST_FOREACH(options_sl, char *, cp, tor_free(cp));
4195 smartlist_free(options_sl);
4198 if (options->ConstrainedSockets) {
4199 /* If the user wants to constrain socket buffer use, make sure the desired
4200 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
4201 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
4202 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
4203 options->ConstrainedSockSize % 1024) {
4204 tor_asprintf(msg,
4205 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
4206 "in 1024 byte increments.",
4207 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
4208 return -1;
4210 if (options->DirPort_set) {
4211 /* Providing cached directory entries while system TCP buffers are scarce
4212 * will exacerbate the socket errors. Suggest that this be disabled. */
4213 COMPLAIN("You have requested constrained socket buffers while also "
4214 "serving directory entries via DirPort. It is strongly "
4215 "suggested that you disable serving directory requests when "
4216 "system TCP buffer resources are scarce.");
4220 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
4221 options->V3AuthVotingInterval/2) {
4223 This doesn't work, but it seems like it should:
4224 what code is preventing the interval being less than twice the lead-up?
4225 if (options->TestingTorNetwork) {
4226 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
4227 options->V3AuthVotingInterval) {
4228 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than "
4229 "V3AuthVotingInterval");
4230 } else {
4231 COMPLAIN("V3AuthVoteDelay plus V3AuthDistDelay is more than half "
4232 "V3AuthVotingInterval. This may lead to "
4233 "consensus instability, particularly if clocks drift.");
4235 } else {
4237 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
4238 "V3AuthVotingInterval");
4244 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS) {
4245 if (options->TestingTorNetwork) {
4246 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS_TESTING) {
4247 REJECT("V3AuthVoteDelay is way too low.");
4248 } else {
4249 COMPLAIN("V3AuthVoteDelay is very low. "
4250 "This may lead to failure to vote for a consensus.");
4252 } else {
4253 REJECT("V3AuthVoteDelay is way too low.");
4257 if (options->V3AuthDistDelay < MIN_DIST_SECONDS) {
4258 if (options->TestingTorNetwork) {
4259 if (options->V3AuthDistDelay < MIN_DIST_SECONDS_TESTING) {
4260 REJECT("V3AuthDistDelay is way too low.");
4261 } else {
4262 COMPLAIN("V3AuthDistDelay is very low. "
4263 "This may lead to missing votes in a consensus.");
4265 } else {
4266 REJECT("V3AuthDistDelay is way too low.");
4270 if (options->V3AuthNIntervalsValid < 2)
4271 REJECT("V3AuthNIntervalsValid must be at least 2.");
4273 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
4274 if (options->TestingTorNetwork) {
4275 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL_TESTING) {
4276 REJECT("V3AuthVotingInterval is insanely low.");
4277 } else {
4278 COMPLAIN("V3AuthVotingInterval is very low. "
4279 "This may lead to failure to synchronise for a consensus.");
4281 } else {
4282 REJECT("V3AuthVotingInterval is insanely low.");
4284 } else if (options->V3AuthVotingInterval > 24*60*60) {
4285 REJECT("V3AuthVotingInterval is insanely high.");
4286 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
4287 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
4290 if (hs_config_service_all(options, 1) < 0)
4291 REJECT("Failed to configure rendezvous options. See logs for details.");
4293 /* Parse client-side authorization for hidden services. */
4294 if (rend_parse_service_authorization(options, 1) < 0)
4295 REJECT("Failed to configure client authorization for hidden services. "
4296 "See logs for details.");
4298 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv4,
4299 AF_INET, 1, msg)<0)
4300 return -1;
4301 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv6,
4302 AF_INET6, 1, msg)<0)
4303 return -1;
4305 if (options->TestingTorNetwork &&
4306 !(options->DirAuthorities ||
4307 (options->AlternateDirAuthority &&
4308 options->AlternateBridgeAuthority))) {
4309 REJECT("TestingTorNetwork may only be configured in combination with "
4310 "a non-default set of DirAuthority or both of "
4311 "AlternateDirAuthority and AlternateBridgeAuthority configured.");
4314 #define CHECK_DEFAULT(arg) \
4315 STMT_BEGIN \
4316 if (!options->TestingTorNetwork && \
4317 !options->UsingTestNetworkDefaults_ && \
4318 !config_is_same(&options_format,options, \
4319 default_options,#arg)) { \
4320 REJECT(#arg " may only be changed in testing Tor " \
4321 "networks!"); \
4322 } STMT_END
4323 CHECK_DEFAULT(TestingV3AuthInitialVotingInterval);
4324 CHECK_DEFAULT(TestingV3AuthInitialVoteDelay);
4325 CHECK_DEFAULT(TestingV3AuthInitialDistDelay);
4326 CHECK_DEFAULT(TestingV3AuthVotingStartOffset);
4327 CHECK_DEFAULT(TestingAuthDirTimeToLearnReachability);
4328 CHECK_DEFAULT(TestingEstimatedDescriptorPropagationTime);
4329 CHECK_DEFAULT(TestingServerDownloadSchedule);
4330 CHECK_DEFAULT(TestingClientDownloadSchedule);
4331 CHECK_DEFAULT(TestingServerConsensusDownloadSchedule);
4332 CHECK_DEFAULT(TestingClientConsensusDownloadSchedule);
4333 CHECK_DEFAULT(TestingBridgeDownloadSchedule);
4334 CHECK_DEFAULT(TestingBridgeBootstrapDownloadSchedule);
4335 CHECK_DEFAULT(TestingClientMaxIntervalWithoutRequest);
4336 CHECK_DEFAULT(TestingDirConnectionMaxStall);
4337 CHECK_DEFAULT(TestingConsensusMaxDownloadTries);
4338 CHECK_DEFAULT(TestingDescriptorMaxDownloadTries);
4339 CHECK_DEFAULT(TestingMicrodescMaxDownloadTries);
4340 CHECK_DEFAULT(TestingCertMaxDownloadTries);
4341 CHECK_DEFAULT(TestingAuthKeyLifetime);
4342 CHECK_DEFAULT(TestingLinkCertLifetime);
4343 CHECK_DEFAULT(TestingSigningKeySlop);
4344 CHECK_DEFAULT(TestingAuthKeySlop);
4345 CHECK_DEFAULT(TestingLinkKeySlop);
4346 #undef CHECK_DEFAULT
4348 if (!options->ClientDNSRejectInternalAddresses &&
4349 !(options->DirAuthorities ||
4350 (options->AlternateDirAuthority && options->AlternateBridgeAuthority)))
4351 REJECT("ClientDNSRejectInternalAddresses used for default network.");
4352 if (options->SigningKeyLifetime < options->TestingSigningKeySlop*2)
4353 REJECT("SigningKeyLifetime is too short.");
4354 if (options->TestingLinkCertLifetime < options->TestingAuthKeySlop*2)
4355 REJECT("LinkCertLifetime is too short.");
4356 if (options->TestingAuthKeyLifetime < options->TestingLinkKeySlop*2)
4357 REJECT("TestingAuthKeyLifetime is too short.");
4359 if (options->TestingV3AuthInitialVotingInterval
4360 < MIN_VOTE_INTERVAL_TESTING_INITIAL) {
4361 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
4362 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
4363 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
4364 "30 minutes.");
4367 if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS_TESTING) {
4368 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
4371 if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS_TESTING) {
4372 REJECT("TestingV3AuthInitialDistDelay is way too low.");
4375 if (options->TestingV3AuthInitialVoteDelay +
4376 options->TestingV3AuthInitialDistDelay >=
4377 options->TestingV3AuthInitialVotingInterval) {
4378 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
4379 "must be less than TestingV3AuthInitialVotingInterval");
4382 if (options->TestingV3AuthVotingStartOffset >
4383 MIN(options->TestingV3AuthInitialVotingInterval,
4384 options->V3AuthVotingInterval)) {
4385 REJECT("TestingV3AuthVotingStartOffset is higher than the voting "
4386 "interval.");
4387 } else if (options->TestingV3AuthVotingStartOffset < 0) {
4388 REJECT("TestingV3AuthVotingStartOffset must be non-negative.");
4391 if (options->TestingAuthDirTimeToLearnReachability < 0) {
4392 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
4393 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
4394 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
4397 if (options->TestingEstimatedDescriptorPropagationTime < 0) {
4398 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
4399 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
4400 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
4403 if (options->TestingClientMaxIntervalWithoutRequest < 1) {
4404 REJECT("TestingClientMaxIntervalWithoutRequest is way too low.");
4405 } else if (options->TestingClientMaxIntervalWithoutRequest > 3600) {
4406 COMPLAIN("TestingClientMaxIntervalWithoutRequest is insanely high.");
4409 if (options->TestingDirConnectionMaxStall < 5) {
4410 REJECT("TestingDirConnectionMaxStall is way too low.");
4411 } else if (options->TestingDirConnectionMaxStall > 3600) {
4412 COMPLAIN("TestingDirConnectionMaxStall is insanely high.");
4415 if (options->TestingConsensusMaxDownloadTries < 2) {
4416 REJECT("TestingConsensusMaxDownloadTries must be greater than 2.");
4417 } else if (options->TestingConsensusMaxDownloadTries > 800) {
4418 COMPLAIN("TestingConsensusMaxDownloadTries is insanely high.");
4421 if (options->ClientBootstrapConsensusMaxDownloadTries < 2) {
4422 REJECT("ClientBootstrapConsensusMaxDownloadTries must be greater "
4423 "than 2."
4425 } else if (options->ClientBootstrapConsensusMaxDownloadTries > 800) {
4426 COMPLAIN("ClientBootstrapConsensusMaxDownloadTries is insanely "
4427 "high.");
4430 if (options->ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries
4431 < 2) {
4432 REJECT("ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries must "
4433 "be greater than 2."
4435 } else if (
4436 options->ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries
4437 > 800) {
4438 COMPLAIN("ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries is "
4439 "insanely high.");
4442 if (options->ClientBootstrapConsensusMaxInProgressTries < 1) {
4443 REJECT("ClientBootstrapConsensusMaxInProgressTries must be greater "
4444 "than 0.");
4445 } else if (options->ClientBootstrapConsensusMaxInProgressTries
4446 > 100) {
4447 COMPLAIN("ClientBootstrapConsensusMaxInProgressTries is insanely "
4448 "high.");
4451 if (options->TestingDescriptorMaxDownloadTries < 2) {
4452 REJECT("TestingDescriptorMaxDownloadTries must be greater than 1.");
4453 } else if (options->TestingDescriptorMaxDownloadTries > 800) {
4454 COMPLAIN("TestingDescriptorMaxDownloadTries is insanely high.");
4457 if (options->TestingMicrodescMaxDownloadTries < 2) {
4458 REJECT("TestingMicrodescMaxDownloadTries must be greater than 1.");
4459 } else if (options->TestingMicrodescMaxDownloadTries > 800) {
4460 COMPLAIN("TestingMicrodescMaxDownloadTries is insanely high.");
4463 if (options->TestingCertMaxDownloadTries < 2) {
4464 REJECT("TestingCertMaxDownloadTries must be greater than 1.");
4465 } else if (options->TestingCertMaxDownloadTries > 800) {
4466 COMPLAIN("TestingCertMaxDownloadTries is insanely high.");
4469 if (options->TestingEnableConnBwEvent &&
4470 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4471 REJECT("TestingEnableConnBwEvent may only be changed in testing "
4472 "Tor networks!");
4475 if (options->TestingEnableCellStatsEvent &&
4476 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4477 REJECT("TestingEnableCellStatsEvent may only be changed in testing "
4478 "Tor networks!");
4481 if (options->TestingEnableTbEmptyEvent &&
4482 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4483 REJECT("TestingEnableTbEmptyEvent may only be changed in testing "
4484 "Tor networks!");
4487 if (options->TestingTorNetwork) {
4488 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
4489 "almost unusable in the public Tor network, and is "
4490 "therefore only advised if you are building a "
4491 "testing Tor network!");
4494 if (options->AccelName && !options->HardwareAccel)
4495 options->HardwareAccel = 1;
4496 if (options->AccelDir && !options->AccelName)
4497 REJECT("Can't use hardware crypto accelerator dir without engine name.");
4499 if (options->PublishServerDescriptor)
4500 SMARTLIST_FOREACH(options->PublishServerDescriptor, const char *, pubdes, {
4501 if (!strcmp(pubdes, "1") || !strcmp(pubdes, "0"))
4502 if (smartlist_len(options->PublishServerDescriptor) > 1) {
4503 COMPLAIN("You have passed a list of multiple arguments to the "
4504 "PublishServerDescriptor option that includes 0 or 1. "
4505 "0 or 1 should only be used as the sole argument. "
4506 "This configuration will be rejected in a future release.");
4507 break;
4511 if (options->BridgeRelay == 1 && ! options->ORPort_set)
4512 REJECT("BridgeRelay is 1, ORPort is not set. This is an invalid "
4513 "combination.");
4515 if (options_validate_scheduler(options, msg) < 0) {
4516 return -1;
4519 return 0;
4522 #undef REJECT
4523 #undef COMPLAIN
4525 /* Given the value that the user has set for MaxMemInQueues, compute the
4526 * actual maximum value. We clip this value if it's too low, and autodetect
4527 * it if it's set to 0. */
4528 static uint64_t
4529 compute_real_max_mem_in_queues(const uint64_t val, int log_guess)
4531 uint64_t result;
4533 if (val == 0) {
4534 #define ONE_GIGABYTE (U64_LITERAL(1) << 30)
4535 #define ONE_MEGABYTE (U64_LITERAL(1) << 20)
4536 #if SIZEOF_VOID_P >= 8
4537 #define MAX_DEFAULT_MAXMEM (8*ONE_GIGABYTE)
4538 #else
4539 #define MAX_DEFAULT_MAXMEM (2*ONE_GIGABYTE)
4540 #endif
4541 /* The user didn't pick a memory limit. Choose a very large one
4542 * that is still smaller than the system memory */
4543 static int notice_sent = 0;
4544 size_t ram = 0;
4545 if (get_total_system_memory(&ram) < 0) {
4546 /* We couldn't determine our total system memory! */
4547 #if SIZEOF_VOID_P >= 8
4548 /* 64-bit system. Let's hope for 8 GB. */
4549 result = 8 * ONE_GIGABYTE;
4550 #else
4551 /* (presumably) 32-bit system. Let's hope for 1 GB. */
4552 result = ONE_GIGABYTE;
4553 #endif /* SIZEOF_VOID_P >= 8 */
4554 } else {
4555 /* We detected it, so let's pick 3/4 of the total RAM as our limit. */
4556 const uint64_t avail = (ram / 4) * 3;
4558 /* Make sure it's in range from 0.25 GB to 8 GB. */
4559 if (avail > MAX_DEFAULT_MAXMEM) {
4560 /* If you want to use more than this much RAM, you need to configure
4561 it yourself */
4562 result = MAX_DEFAULT_MAXMEM;
4563 } else if (avail < ONE_GIGABYTE / 4) {
4564 result = ONE_GIGABYTE / 4;
4565 } else {
4566 result = avail;
4569 if (log_guess && ! notice_sent) {
4570 log_notice(LD_CONFIG, "%sMaxMemInQueues is set to "U64_FORMAT" MB. "
4571 "You can override this by setting MaxMemInQueues by hand.",
4572 ram ? "Based on detected system memory, " : "",
4573 U64_PRINTF_ARG(result / ONE_MEGABYTE));
4574 notice_sent = 1;
4576 return result;
4577 } else if (val < ONE_GIGABYTE / 4) {
4578 log_warn(LD_CONFIG, "MaxMemInQueues must be at least 256 MB for now. "
4579 "Ideally, have it as large as you can afford.");
4580 return ONE_GIGABYTE / 4;
4581 } else {
4582 /* The value was fine all along */
4583 return val;
4587 /* If we have less than 300 MB suggest disabling dircache */
4588 #define DIRCACHE_MIN_MEM_MB 300
4589 #define DIRCACHE_MIN_MEM_BYTES (DIRCACHE_MIN_MEM_MB*ONE_MEGABYTE)
4590 #define STRINGIFY(val) #val
4592 /** Create a warning message for emitting if we are a dircache but may not have
4593 * enough system memory, or if we are not a dircache but probably should be.
4594 * Return -1 when a message is returned in *msg*, else return 0. */
4595 STATIC int
4596 have_enough_mem_for_dircache(const or_options_t *options, size_t total_mem,
4597 char **msg)
4599 *msg = NULL;
4600 /* XXX We should possibly be looking at MaxMemInQueues here
4601 * unconditionally. Or we should believe total_mem unconditionally. */
4602 if (total_mem == 0) {
4603 if (get_total_system_memory(&total_mem) < 0) {
4604 total_mem = options->MaxMemInQueues >= SIZE_MAX ?
4605 SIZE_MAX : (size_t)options->MaxMemInQueues;
4608 if (options->DirCache) {
4609 if (total_mem < DIRCACHE_MIN_MEM_BYTES) {
4610 if (options->BridgeRelay) {
4611 *msg = tor_strdup("Running a Bridge with less than "
4612 STRINGIFY(DIRCACHE_MIN_MEM_MB) " MB of memory is not "
4613 "recommended.");
4614 } else {
4615 *msg = tor_strdup("Being a directory cache (default) with less than "
4616 STRINGIFY(DIRCACHE_MIN_MEM_MB) " MB of memory is not "
4617 "recommended and may consume most of the available "
4618 "resources, consider disabling this functionality by "
4619 "setting the DirCache option to 0.");
4622 } else {
4623 if (total_mem >= DIRCACHE_MIN_MEM_BYTES) {
4624 *msg = tor_strdup("DirCache is disabled and we are configured as a "
4625 "relay. This may disqualify us from becoming a guard in the "
4626 "future.");
4629 return *msg == NULL ? 0 : -1;
4631 #undef STRINGIFY
4633 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
4634 * equal strings. */
4635 static int
4636 opt_streq(const char *s1, const char *s2)
4638 return 0 == strcmp_opt(s1, s2);
4641 /** Check if any of the previous options have changed but aren't allowed to. */
4642 static int
4643 options_transition_allowed(const or_options_t *old,
4644 const or_options_t *new_val,
4645 char **msg)
4647 if (!old)
4648 return 0;
4650 if (!opt_streq(old->PidFile, new_val->PidFile)) {
4651 *msg = tor_strdup("PidFile is not allowed to change.");
4652 return -1;
4655 if (old->RunAsDaemon != new_val->RunAsDaemon) {
4656 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
4657 "is not allowed.");
4658 return -1;
4661 if (old->Sandbox != new_val->Sandbox) {
4662 *msg = tor_strdup("While Tor is running, changing Sandbox "
4663 "is not allowed.");
4664 return -1;
4667 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
4668 tor_asprintf(msg,
4669 "While Tor is running, changing DataDirectory "
4670 "(\"%s\"->\"%s\") is not allowed.",
4671 old->DataDirectory, new_val->DataDirectory);
4672 return -1;
4675 if (!opt_streq(old->KeyDirectory, new_val->KeyDirectory)) {
4676 tor_asprintf(msg,
4677 "While Tor is running, changing KeyDirectory "
4678 "(\"%s\"->\"%s\") is not allowed.",
4679 old->KeyDirectory, new_val->KeyDirectory);
4680 return -1;
4683 if (!opt_streq(old->CacheDirectory, new_val->CacheDirectory)) {
4684 tor_asprintf(msg,
4685 "While Tor is running, changing CacheDirectory "
4686 "(\"%s\"->\"%s\") is not allowed.",
4687 old->CacheDirectory, new_val->CacheDirectory);
4688 return -1;
4691 if (!opt_streq(old->User, new_val->User)) {
4692 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
4693 return -1;
4696 if (old->KeepBindCapabilities != new_val->KeepBindCapabilities) {
4697 *msg = tor_strdup("While Tor is running, changing KeepBindCapabilities is "
4698 "not allowed.");
4699 return -1;
4702 if (!opt_streq(old->SyslogIdentityTag, new_val->SyslogIdentityTag)) {
4703 *msg = tor_strdup("While Tor is running, changing "
4704 "SyslogIdentityTag is not allowed.");
4705 return -1;
4708 if (!opt_streq(old->AndroidIdentityTag, new_val->AndroidIdentityTag)) {
4709 *msg = tor_strdup("While Tor is running, changing "
4710 "AndroidIdentityTag is not allowed.");
4711 return -1;
4714 if ((old->HardwareAccel != new_val->HardwareAccel)
4715 || !opt_streq(old->AccelName, new_val->AccelName)
4716 || !opt_streq(old->AccelDir, new_val->AccelDir)) {
4717 *msg = tor_strdup("While Tor is running, changing OpenSSL hardware "
4718 "acceleration engine is not allowed.");
4719 return -1;
4722 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
4723 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
4724 "is not allowed.");
4725 return -1;
4728 if (old->DisableAllSwap != new_val->DisableAllSwap) {
4729 *msg = tor_strdup("While Tor is running, changing DisableAllSwap "
4730 "is not allowed.");
4731 return -1;
4734 if (old->TokenBucketRefillInterval != new_val->TokenBucketRefillInterval) {
4735 *msg = tor_strdup("While Tor is running, changing TokenBucketRefill"
4736 "Interval is not allowed");
4737 return -1;
4740 if (old->HiddenServiceSingleHopMode != new_val->HiddenServiceSingleHopMode) {
4741 *msg = tor_strdup("While Tor is running, changing "
4742 "HiddenServiceSingleHopMode is not allowed.");
4743 return -1;
4746 if (old->HiddenServiceNonAnonymousMode !=
4747 new_val->HiddenServiceNonAnonymousMode) {
4748 *msg = tor_strdup("While Tor is running, changing "
4749 "HiddenServiceNonAnonymousMode is not allowed.");
4750 return -1;
4753 if (old->DisableDebuggerAttachment &&
4754 !new_val->DisableDebuggerAttachment) {
4755 *msg = tor_strdup("While Tor is running, disabling "
4756 "DisableDebuggerAttachment is not allowed.");
4757 return -1;
4760 if (old->NoExec && !new_val->NoExec) {
4761 *msg = tor_strdup("While Tor is running, disabling "
4762 "NoExec is not allowed.");
4763 return -1;
4766 if (old->OwningControllerFD != new_val->OwningControllerFD) {
4767 *msg = tor_strdup("While Tor is running, changing OwningControllerFD "
4768 "is not allowed.");
4769 return -1;
4772 if (sandbox_is_active()) {
4773 #define SB_NOCHANGE_STR(opt) \
4774 do { \
4775 if (! opt_streq(old->opt, new_val->opt)) { \
4776 *msg = tor_strdup("Can't change " #opt " while Sandbox is active"); \
4777 return -1; \
4779 } while (0)
4781 SB_NOCHANGE_STR(Address);
4782 SB_NOCHANGE_STR(ServerDNSResolvConfFile);
4783 SB_NOCHANGE_STR(DirPortFrontPage);
4784 SB_NOCHANGE_STR(CookieAuthFile);
4785 SB_NOCHANGE_STR(ExtORPortCookieAuthFile);
4787 #undef SB_NOCHANGE_STR
4789 if (! config_lines_eq(old->Logs, new_val->Logs)) {
4790 *msg = tor_strdup("Can't change Logs while Sandbox is active");
4791 return -1;
4793 if (old->ConnLimit != new_val->ConnLimit) {
4794 *msg = tor_strdup("Can't change ConnLimit while Sandbox is active");
4795 return -1;
4797 if (server_mode(old) != server_mode(new_val)) {
4798 *msg = tor_strdup("Can't start/stop being a server while "
4799 "Sandbox is active");
4800 return -1;
4804 return 0;
4807 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
4808 * will require us to rotate the CPU and DNS workers; else return 0. */
4809 static int
4810 options_transition_affects_workers(const or_options_t *old_options,
4811 const or_options_t *new_options)
4813 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
4814 old_options->NumCPUs != new_options->NumCPUs ||
4815 !config_lines_eq(old_options->ORPort_lines, new_options->ORPort_lines) ||
4816 old_options->ServerDNSSearchDomains !=
4817 new_options->ServerDNSSearchDomains ||
4818 old_options->SafeLogging_ != new_options->SafeLogging_ ||
4819 old_options->ClientOnly != new_options->ClientOnly ||
4820 server_mode(old_options) != server_mode(new_options) ||
4821 public_server_mode(old_options) != public_server_mode(new_options) ||
4822 !config_lines_eq(old_options->Logs, new_options->Logs) ||
4823 old_options->LogMessageDomains != new_options->LogMessageDomains)
4824 return 1;
4826 /* Check whether log options match. */
4828 /* Nothing that changed matters. */
4829 return 0;
4832 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
4833 * will require us to generate a new descriptor; else return 0. */
4834 static int
4835 options_transition_affects_descriptor(const or_options_t *old_options,
4836 const or_options_t *new_options)
4838 /* XXX We can be smarter here. If your DirPort isn't being
4839 * published and you just turned it off, no need to republish. Etc. */
4840 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
4841 !opt_streq(old_options->Nickname,new_options->Nickname) ||
4842 !opt_streq(old_options->Address,new_options->Address) ||
4843 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
4844 old_options->ExitRelay != new_options->ExitRelay ||
4845 old_options->ExitPolicyRejectPrivate !=
4846 new_options->ExitPolicyRejectPrivate ||
4847 old_options->ExitPolicyRejectLocalInterfaces !=
4848 new_options->ExitPolicyRejectLocalInterfaces ||
4849 old_options->IPv6Exit != new_options->IPv6Exit ||
4850 !config_lines_eq(old_options->ORPort_lines,
4851 new_options->ORPort_lines) ||
4852 !config_lines_eq(old_options->DirPort_lines,
4853 new_options->DirPort_lines) ||
4854 old_options->ClientOnly != new_options->ClientOnly ||
4855 old_options->DisableNetwork != new_options->DisableNetwork ||
4856 old_options->PublishServerDescriptor_ !=
4857 new_options->PublishServerDescriptor_ ||
4858 get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
4859 get_effective_bwburst(old_options) !=
4860 get_effective_bwburst(new_options) ||
4861 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
4862 !opt_streq(old_options->BridgeDistribution,
4863 new_options->BridgeDistribution) ||
4864 !config_lines_eq(old_options->MyFamily, new_options->MyFamily) ||
4865 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
4866 old_options->AccountingMax != new_options->AccountingMax ||
4867 old_options->AccountingRule != new_options->AccountingRule ||
4868 public_server_mode(old_options) != public_server_mode(new_options) ||
4869 old_options->DirCache != new_options->DirCache ||
4870 old_options->AssumeReachable != new_options->AssumeReachable)
4871 return 1;
4873 return 0;
4876 #ifdef _WIN32
4877 /** Return the directory on windows where we expect to find our application
4878 * data. */
4879 static char *
4880 get_windows_conf_root(void)
4882 static int is_set = 0;
4883 static char path[MAX_PATH*2+1];
4884 TCHAR tpath[MAX_PATH] = {0};
4886 LPITEMIDLIST idl;
4887 IMalloc *m;
4888 HRESULT result;
4890 if (is_set)
4891 return path;
4893 /* Find X:\documents and settings\username\application data\ .
4894 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
4896 #ifdef ENABLE_LOCAL_APPDATA
4897 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
4898 #else
4899 #define APPDATA_PATH CSIDL_APPDATA
4900 #endif
4901 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
4902 getcwd(path,MAX_PATH);
4903 is_set = 1;
4904 log_warn(LD_CONFIG,
4905 "I couldn't find your application data folder: are you "
4906 "running an ancient version of Windows 95? Defaulting to \"%s\"",
4907 path);
4908 return path;
4910 /* Convert the path from an "ID List" (whatever that is!) to a path. */
4911 result = SHGetPathFromIDList(idl, tpath);
4912 #ifdef UNICODE
4913 wcstombs(path,tpath,sizeof(path));
4914 path[sizeof(path)-1] = '\0';
4915 #else
4916 strlcpy(path,tpath,sizeof(path));
4917 #endif /* defined(UNICODE) */
4919 /* Now we need to free the memory that the path-idl was stored in. In
4920 * typical Windows fashion, we can't just call 'free()' on it. */
4921 SHGetMalloc(&m);
4922 if (m) {
4923 m->lpVtbl->Free(m, idl);
4924 m->lpVtbl->Release(m);
4926 if (!SUCCEEDED(result)) {
4927 return NULL;
4929 strlcat(path,"\\tor",MAX_PATH);
4930 is_set = 1;
4931 return path;
4933 #endif /* defined(_WIN32) */
4935 /** Return the default location for our torrc file (if <b>defaults_file</b> is
4936 * false), or for the torrc-defaults file (if <b>defaults_file</b> is true). */
4937 static const char *
4938 get_default_conf_file(int defaults_file)
4940 #ifdef DISABLE_SYSTEM_TORRC
4941 (void) defaults_file;
4942 return NULL;
4943 #elif defined(_WIN32)
4944 if (defaults_file) {
4945 static char defaults_path[MAX_PATH+1];
4946 tor_snprintf(defaults_path, MAX_PATH, "%s\\torrc-defaults",
4947 get_windows_conf_root());
4948 return defaults_path;
4949 } else {
4950 static char path[MAX_PATH+1];
4951 tor_snprintf(path, MAX_PATH, "%s\\torrc",
4952 get_windows_conf_root());
4953 return path;
4955 #else
4956 return defaults_file ? CONFDIR "/torrc-defaults" : CONFDIR "/torrc";
4957 #endif /* defined(DISABLE_SYSTEM_TORRC) || ... */
4960 /** Verify whether lst is a list of strings containing valid-looking
4961 * comma-separated nicknames, or NULL. Will normalise <b>lst</b> to prefix '$'
4962 * to any nickname or fingerprint that needs it. Also splits comma-separated
4963 * list elements into multiple elements. Return 0 on success.
4964 * Warn and return -1 on failure.
4966 static int
4967 normalize_nickname_list(config_line_t **normalized_out,
4968 const config_line_t *lst, const char *name,
4969 char **msg)
4971 if (!lst)
4972 return 0;
4974 config_line_t *new_nicknames = NULL;
4975 config_line_t **new_nicknames_next = &new_nicknames;
4977 const config_line_t *cl;
4978 for (cl = lst; cl; cl = cl->next) {
4979 const char *line = cl->value;
4980 if (!line)
4981 continue;
4983 int valid_line = 1;
4984 smartlist_t *sl = smartlist_new();
4985 smartlist_split_string(sl, line, ",",
4986 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
4987 SMARTLIST_FOREACH_BEGIN(sl, char *, s)
4989 char *normalized = NULL;
4990 if (!is_legal_nickname_or_hexdigest(s)) {
4991 // check if first char is dollar
4992 if (s[0] != '$') {
4993 // Try again but with a dollar symbol prepended
4994 char *prepended;
4995 tor_asprintf(&prepended, "$%s", s);
4997 if (is_legal_nickname_or_hexdigest(prepended)) {
4998 // The nickname is valid when it's prepended, set it as the
4999 // normalized version
5000 normalized = prepended;
5001 } else {
5002 // Still not valid, free and fallback to error message
5003 tor_free(prepended);
5007 if (!normalized) {
5008 tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
5009 valid_line = 0;
5010 break;
5012 } else {
5013 normalized = tor_strdup(s);
5016 config_line_t *next = tor_malloc_zero(sizeof(*next));
5017 next->key = tor_strdup(cl->key);
5018 next->value = normalized;
5019 next->next = NULL;
5021 *new_nicknames_next = next;
5022 new_nicknames_next = &next->next;
5023 } SMARTLIST_FOREACH_END(s);
5025 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
5026 smartlist_free(sl);
5028 if (!valid_line) {
5029 config_free_lines(new_nicknames);
5030 return -1;
5034 *normalized_out = new_nicknames;
5036 return 0;
5039 /** Learn config file name from command line arguments, or use the default.
5041 * If <b>defaults_file</b> is true, we're looking for torrc-defaults;
5042 * otherwise, we're looking for the regular torrc_file.
5044 * Set *<b>using_default_fname</b> to true if we're using the default
5045 * configuration file name; or false if we've set it from the command line.
5047 * Set *<b>ignore_missing_torrc</b> to true if we should ignore the resulting
5048 * filename if it doesn't exist.
5050 static char *
5051 find_torrc_filename(config_line_t *cmd_arg,
5052 int defaults_file,
5053 int *using_default_fname, int *ignore_missing_torrc)
5055 char *fname=NULL;
5056 config_line_t *p_index;
5057 const char *fname_opt = defaults_file ? "--defaults-torrc" : "-f";
5058 const char *ignore_opt = defaults_file ? NULL : "--ignore-missing-torrc";
5060 if (defaults_file)
5061 *ignore_missing_torrc = 1;
5063 for (p_index = cmd_arg; p_index; p_index = p_index->next) {
5064 if (!strcmp(p_index->key, fname_opt)) {
5065 if (fname) {
5066 log_warn(LD_CONFIG, "Duplicate %s options on command line.",
5067 fname_opt);
5068 tor_free(fname);
5070 fname = expand_filename(p_index->value);
5073 char *absfname;
5074 absfname = make_path_absolute(fname);
5075 tor_free(fname);
5076 fname = absfname;
5079 *using_default_fname = 0;
5080 } else if (ignore_opt && !strcmp(p_index->key,ignore_opt)) {
5081 *ignore_missing_torrc = 1;
5085 if (*using_default_fname) {
5086 /* didn't find one, try CONFDIR */
5087 const char *dflt = get_default_conf_file(defaults_file);
5088 file_status_t st = file_status(dflt);
5089 if (dflt && (st == FN_FILE || st == FN_EMPTY)) {
5090 fname = tor_strdup(dflt);
5091 } else {
5092 #ifndef _WIN32
5093 char *fn = NULL;
5094 if (!defaults_file) {
5095 fn = expand_filename("~/.torrc");
5097 if (fn) {
5098 file_status_t hmst = file_status(fn);
5099 if (hmst == FN_FILE || hmst == FN_EMPTY || dflt == NULL) {
5100 fname = fn;
5101 } else {
5102 tor_free(fn);
5103 fname = tor_strdup(dflt);
5105 } else {
5106 fname = dflt ? tor_strdup(dflt) : NULL;
5108 #else /* !(!defined(_WIN32)) */
5109 fname = dflt ? tor_strdup(dflt) : NULL;
5110 #endif /* !defined(_WIN32) */
5113 return fname;
5116 /** Read the torrc from standard input and return it as a string.
5117 * Upon failure, return NULL.
5119 static char *
5120 load_torrc_from_stdin(void)
5122 size_t sz_out;
5124 return read_file_to_str_until_eof(STDIN_FILENO,SIZE_MAX,&sz_out);
5127 /** Load a configuration file from disk, setting torrc_fname or
5128 * torrc_defaults_fname if successful.
5130 * If <b>defaults_file</b> is true, load torrc-defaults; otherwise load torrc.
5132 * Return the contents of the file on success, and NULL on failure.
5134 static char *
5135 load_torrc_from_disk(config_line_t *cmd_arg, int defaults_file)
5137 char *fname=NULL;
5138 char *cf = NULL;
5139 int using_default_torrc = 1;
5140 int ignore_missing_torrc = 0;
5141 char **fname_var = defaults_file ? &torrc_defaults_fname : &torrc_fname;
5143 if (*fname_var == NULL) {
5144 fname = find_torrc_filename(cmd_arg, defaults_file,
5145 &using_default_torrc, &ignore_missing_torrc);
5146 tor_free(*fname_var);
5147 *fname_var = fname;
5148 } else {
5149 fname = *fname_var;
5151 log_debug(LD_CONFIG, "Opening config file \"%s\"", fname?fname:"<NULL>");
5153 /* Open config file */
5154 file_status_t st = fname ? file_status(fname) : FN_EMPTY;
5155 if (fname == NULL ||
5156 !(st == FN_FILE || st == FN_EMPTY) ||
5157 !(cf = read_file_to_str(fname,0,NULL))) {
5158 if (using_default_torrc == 1 || ignore_missing_torrc) {
5159 if (!defaults_file)
5160 log_notice(LD_CONFIG, "Configuration file \"%s\" not present, "
5161 "using reasonable defaults.", fname);
5162 tor_free(fname); /* sets fname to NULL */
5163 *fname_var = NULL;
5164 cf = tor_strdup("");
5165 } else {
5166 log_warn(LD_CONFIG,
5167 "Unable to open configuration file \"%s\".", fname);
5168 goto err;
5170 } else {
5171 log_notice(LD_CONFIG, "Read configuration file \"%s\".", fname);
5174 return cf;
5175 err:
5176 tor_free(fname);
5177 *fname_var = NULL;
5178 return NULL;
5181 /** Read a configuration file into <b>options</b>, finding the configuration
5182 * file location based on the command line. After loading the file
5183 * call options_init_from_string() to load the config.
5184 * Return 0 if success, -1 if failure, and 1 if we succeeded but should exit
5185 * anyway. */
5187 options_init_from_torrc(int argc, char **argv)
5189 char *cf=NULL, *cf_defaults=NULL;
5190 int command;
5191 int retval = -1;
5192 char *command_arg = NULL;
5193 char *errmsg=NULL;
5194 config_line_t *p_index = NULL;
5195 config_line_t *cmdline_only_options = NULL;
5197 /* Go through command-line variables */
5198 if (! have_parsed_cmdline) {
5199 /* Or we could redo the list every time we pass this place.
5200 * It does not really matter */
5201 if (config_parse_commandline(argc, argv, 0, &global_cmdline_options,
5202 &global_cmdline_only_options) < 0) {
5203 goto err;
5205 have_parsed_cmdline = 1;
5207 cmdline_only_options = global_cmdline_only_options;
5209 if (config_line_find(cmdline_only_options, "-h") ||
5210 config_line_find(cmdline_only_options, "--help")) {
5211 print_usage();
5212 return 1;
5214 if (config_line_find(cmdline_only_options, "--list-torrc-options")) {
5215 /* For validating whether we've documented everything. */
5216 list_torrc_options();
5217 return 1;
5219 if (config_line_find(cmdline_only_options, "--list-deprecated-options")) {
5220 /* For validating whether what we have deprecated really exists. */
5221 list_deprecated_options();
5222 return 1;
5225 if (config_line_find(cmdline_only_options, "--version")) {
5226 printf("Tor version %s.\n",get_version());
5227 return 1;
5230 if (config_line_find(cmdline_only_options, "--library-versions")) {
5231 printf("Tor version %s. \n", get_version());
5232 printf("Library versions\tCompiled\t\tRuntime\n");
5233 printf("Libevent\t\t%-15s\t\t%s\n",
5234 tor_libevent_get_header_version_str(),
5235 tor_libevent_get_version_str());
5236 printf("OpenSSL \t\t%-15s\t\t%s\n",
5237 crypto_openssl_get_header_version_str(),
5238 crypto_openssl_get_version_str());
5239 if (tor_compress_supports_method(ZLIB_METHOD)) {
5240 printf("Zlib \t\t%-15s\t\t%s\n",
5241 tor_compress_version_str(ZLIB_METHOD),
5242 tor_compress_header_version_str(ZLIB_METHOD));
5244 if (tor_compress_supports_method(LZMA_METHOD)) {
5245 printf("Liblzma \t\t%-15s\t\t%s\n",
5246 tor_compress_version_str(LZMA_METHOD),
5247 tor_compress_header_version_str(LZMA_METHOD));
5249 if (tor_compress_supports_method(ZSTD_METHOD)) {
5250 printf("Libzstd \t\t%-15s\t\t%s\n",
5251 tor_compress_version_str(ZSTD_METHOD),
5252 tor_compress_header_version_str(ZSTD_METHOD));
5254 //TODO: Hex versions?
5255 return 1;
5258 command = CMD_RUN_TOR;
5259 for (p_index = cmdline_only_options; p_index; p_index = p_index->next) {
5260 if (!strcmp(p_index->key,"--keygen")) {
5261 command = CMD_KEYGEN;
5262 } else if (!strcmp(p_index->key, "--key-expiration")) {
5263 command = CMD_KEY_EXPIRATION;
5264 command_arg = p_index->value;
5265 } else if (!strcmp(p_index->key,"--list-fingerprint")) {
5266 command = CMD_LIST_FINGERPRINT;
5267 } else if (!strcmp(p_index->key, "--hash-password")) {
5268 command = CMD_HASH_PASSWORD;
5269 command_arg = p_index->value;
5270 } else if (!strcmp(p_index->key, "--dump-config")) {
5271 command = CMD_DUMP_CONFIG;
5272 command_arg = p_index->value;
5273 } else if (!strcmp(p_index->key, "--verify-config")) {
5274 command = CMD_VERIFY_CONFIG;
5278 if (command == CMD_HASH_PASSWORD) {
5279 cf_defaults = tor_strdup("");
5280 cf = tor_strdup("");
5281 } else {
5282 cf_defaults = load_torrc_from_disk(cmdline_only_options, 1);
5284 const config_line_t *f_line = config_line_find(cmdline_only_options,
5285 "-f");
5287 const int read_torrc_from_stdin =
5288 (f_line != NULL && strcmp(f_line->value, "-") == 0);
5290 if (read_torrc_from_stdin) {
5291 cf = load_torrc_from_stdin();
5292 } else {
5293 cf = load_torrc_from_disk(cmdline_only_options, 0);
5296 if (!cf) {
5297 if (config_line_find(cmdline_only_options, "--allow-missing-torrc")) {
5298 cf = tor_strdup("");
5299 } else {
5300 goto err;
5305 retval = options_init_from_string(cf_defaults, cf, command, command_arg,
5306 &errmsg);
5308 if (retval < 0)
5309 goto err;
5311 if (config_line_find(cmdline_only_options, "--no-passphrase")) {
5312 if (command == CMD_KEYGEN) {
5313 get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_OFF;
5314 } else {
5315 log_err(LD_CONFIG, "--no-passphrase specified without --keygen!");
5316 retval = -1;
5317 goto err;
5321 if (config_line_find(cmdline_only_options, "--newpass")) {
5322 if (command == CMD_KEYGEN) {
5323 get_options_mutable()->change_key_passphrase = 1;
5324 } else {
5325 log_err(LD_CONFIG, "--newpass specified without --keygen!");
5326 retval = -1;
5327 goto err;
5332 const config_line_t *fd_line = config_line_find(cmdline_only_options,
5333 "--passphrase-fd");
5334 if (fd_line) {
5335 if (get_options()->keygen_force_passphrase == FORCE_PASSPHRASE_OFF) {
5336 log_err(LD_CONFIG, "--no-passphrase specified with --passphrase-fd!");
5337 retval = -1;
5338 goto err;
5339 } else if (command != CMD_KEYGEN) {
5340 log_err(LD_CONFIG, "--passphrase-fd specified without --keygen!");
5341 retval = -1;
5342 goto err;
5343 } else {
5344 const char *v = fd_line->value;
5345 int ok = 1;
5346 long fd = tor_parse_long(v, 10, 0, INT_MAX, &ok, NULL);
5347 if (fd < 0 || ok == 0) {
5348 log_err(LD_CONFIG, "Invalid --passphrase-fd value %s", escaped(v));
5349 retval = -1;
5350 goto err;
5352 get_options_mutable()->keygen_passphrase_fd = (int)fd;
5353 get_options_mutable()->use_keygen_passphrase_fd = 1;
5354 get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_ON;
5360 const config_line_t *key_line = config_line_find(cmdline_only_options,
5361 "--master-key");
5362 if (key_line) {
5363 if (command != CMD_KEYGEN) {
5364 log_err(LD_CONFIG, "--master-key without --keygen!");
5365 retval = -1;
5366 goto err;
5367 } else {
5368 get_options_mutable()->master_key_fname = tor_strdup(key_line->value);
5373 err:
5375 tor_free(cf);
5376 tor_free(cf_defaults);
5377 if (errmsg) {
5378 log_warn(LD_CONFIG,"%s", errmsg);
5379 tor_free(errmsg);
5381 return retval < 0 ? -1 : 0;
5384 /** Load the options from the configuration in <b>cf</b>, validate
5385 * them for consistency and take actions based on them.
5387 * Return 0 if success, negative on error:
5388 * * -1 for general errors.
5389 * * -2 for failure to parse/validate,
5390 * * -3 for transition not allowed
5391 * * -4 for error while setting the new options
5393 setopt_err_t
5394 options_init_from_string(const char *cf_defaults, const char *cf,
5395 int command, const char *command_arg,
5396 char **msg)
5398 or_options_t *oldoptions, *newoptions, *newdefaultoptions=NULL;
5399 config_line_t *cl;
5400 int retval;
5401 setopt_err_t err = SETOPT_ERR_MISC;
5402 int cf_has_include = 0;
5403 tor_assert(msg);
5405 oldoptions = global_options; /* get_options unfortunately asserts if
5406 this is the first time we run*/
5408 newoptions = tor_malloc_zero(sizeof(or_options_t));
5409 newoptions->magic_ = OR_OPTIONS_MAGIC;
5410 options_init(newoptions);
5411 newoptions->command = command;
5412 newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
5414 smartlist_t *opened_files = smartlist_new();
5415 for (int i = 0; i < 2; ++i) {
5416 const char *body = i==0 ? cf_defaults : cf;
5417 if (!body)
5418 continue;
5420 /* get config lines, assign them */
5421 retval = config_get_lines_include(body, &cl, 1,
5422 body == cf ? &cf_has_include : NULL,
5423 opened_files);
5424 if (retval < 0) {
5425 err = SETOPT_ERR_PARSE;
5426 goto err;
5428 retval = config_assign(&options_format, newoptions, cl,
5429 CAL_WARN_DEPRECATIONS, msg);
5430 config_free_lines(cl);
5431 if (retval < 0) {
5432 err = SETOPT_ERR_PARSE;
5433 goto err;
5435 if (i==0)
5436 newdefaultoptions = config_dup(&options_format, newoptions);
5439 if (newdefaultoptions == NULL) {
5440 newdefaultoptions = config_dup(&options_format, global_default_options);
5443 /* Go through command-line variables too */
5444 retval = config_assign(&options_format, newoptions,
5445 global_cmdline_options, CAL_WARN_DEPRECATIONS, msg);
5446 if (retval < 0) {
5447 err = SETOPT_ERR_PARSE;
5448 goto err;
5451 newoptions->IncludeUsed = cf_has_include;
5452 newoptions->FilesOpenedByIncludes = opened_files;
5454 /* If this is a testing network configuration, change defaults
5455 * for a list of dependent config options, re-initialize newoptions
5456 * with the new defaults, and assign all options to it second time. */
5457 if (newoptions->TestingTorNetwork) {
5458 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
5459 * this? We could, for example, make the parsing algorithm do two passes
5460 * over the configuration. If it finds any "suite" options like
5461 * TestingTorNetwork, it could change the defaults before its second pass.
5462 * Not urgent so long as this seems to work, but at any sign of trouble,
5463 * let's clean it up. -NM */
5465 /* Change defaults. */
5466 for (int i = 0; testing_tor_network_defaults[i].name; ++i) {
5467 const config_var_t *new_var = &testing_tor_network_defaults[i];
5468 config_var_t *old_var =
5469 config_find_option_mutable(&options_format, new_var->name);
5470 tor_assert(new_var);
5471 tor_assert(old_var);
5472 old_var->initvalue = new_var->initvalue;
5474 if ((config_find_deprecation(&options_format, new_var->name))) {
5475 log_warn(LD_GENERAL, "Testing options override the deprecated "
5476 "option %s. Is that intentional?",
5477 new_var->name);
5481 /* Clear newoptions and re-initialize them with new defaults. */
5482 or_options_free(newoptions);
5483 or_options_free(newdefaultoptions);
5484 newdefaultoptions = NULL;
5485 newoptions = tor_malloc_zero(sizeof(or_options_t));
5486 newoptions->magic_ = OR_OPTIONS_MAGIC;
5487 options_init(newoptions);
5488 newoptions->command = command;
5489 newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
5491 /* Assign all options a second time. */
5492 opened_files = smartlist_new();
5493 for (int i = 0; i < 2; ++i) {
5494 const char *body = i==0 ? cf_defaults : cf;
5495 if (!body)
5496 continue;
5498 /* get config lines, assign them */
5499 retval = config_get_lines_include(body, &cl, 1,
5500 body == cf ? &cf_has_include : NULL,
5501 opened_files);
5502 if (retval < 0) {
5503 err = SETOPT_ERR_PARSE;
5504 goto err;
5506 retval = config_assign(&options_format, newoptions, cl, 0, msg);
5507 config_free_lines(cl);
5508 if (retval < 0) {
5509 err = SETOPT_ERR_PARSE;
5510 goto err;
5512 if (i==0)
5513 newdefaultoptions = config_dup(&options_format, newoptions);
5515 /* Assign command-line variables a second time too */
5516 retval = config_assign(&options_format, newoptions,
5517 global_cmdline_options, 0, msg);
5518 if (retval < 0) {
5519 err = SETOPT_ERR_PARSE;
5520 goto err;
5524 newoptions->IncludeUsed = cf_has_include;
5525 in_option_validation = 1;
5526 newoptions->FilesOpenedByIncludes = opened_files;
5528 /* Validate newoptions */
5529 if (options_validate(oldoptions, newoptions, newdefaultoptions,
5530 0, msg) < 0) {
5531 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
5532 goto err;
5535 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
5536 err = SETOPT_ERR_TRANSITION;
5537 goto err;
5539 in_option_validation = 0;
5541 if (set_options(newoptions, msg)) {
5542 err = SETOPT_ERR_SETTING;
5543 goto err; /* frees and replaces old options */
5546 or_options_free(global_default_options);
5547 global_default_options = newdefaultoptions;
5549 return SETOPT_OK;
5551 err:
5552 in_option_validation = 0;
5553 if (opened_files) {
5554 SMARTLIST_FOREACH(opened_files, char *, f, tor_free(f));
5555 smartlist_free(opened_files);
5557 // may have been set to opened_files, avoid double free
5558 newoptions->FilesOpenedByIncludes = NULL;
5559 or_options_free(newoptions);
5560 or_options_free(newdefaultoptions);
5561 if (*msg) {
5562 char *old_msg = *msg;
5563 tor_asprintf(msg, "Failed to parse/validate config: %s", old_msg);
5564 tor_free(old_msg);
5566 return err;
5569 /** Return the location for our configuration file. May return NULL.
5571 const char *
5572 get_torrc_fname(int defaults_fname)
5574 const char *fname = defaults_fname ? torrc_defaults_fname : torrc_fname;
5576 if (fname)
5577 return fname;
5578 else
5579 return get_default_conf_file(defaults_fname);
5582 /** Adjust the address map based on the MapAddress elements in the
5583 * configuration <b>options</b>
5585 void
5586 config_register_addressmaps(const or_options_t *options)
5588 smartlist_t *elts;
5589 config_line_t *opt;
5590 const char *from, *to, *msg;
5592 addressmap_clear_configured();
5593 elts = smartlist_new();
5594 for (opt = options->AddressMap; opt; opt = opt->next) {
5595 smartlist_split_string(elts, opt->value, NULL,
5596 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
5597 if (smartlist_len(elts) < 2) {
5598 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
5599 opt->value);
5600 goto cleanup;
5603 from = smartlist_get(elts,0);
5604 to = smartlist_get(elts,1);
5606 if (to[0] == '.' || from[0] == '.') {
5607 log_warn(LD_CONFIG,"MapAddress '%s' is ambiguous - address starts with a"
5608 "'.'. Ignoring.",opt->value);
5609 goto cleanup;
5612 if (addressmap_register_auto(from, to, 0, ADDRMAPSRC_TORRC, &msg) < 0) {
5613 log_warn(LD_CONFIG,"MapAddress '%s' failed: %s. Ignoring.", opt->value,
5614 msg);
5615 goto cleanup;
5618 if (smartlist_len(elts) > 2)
5619 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
5621 cleanup:
5622 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
5623 smartlist_clear(elts);
5625 smartlist_free(elts);
5628 /** As addressmap_register(), but detect the wildcarded status of "from" and
5629 * "to", and do not steal a reference to <b>to</b>. */
5630 /* XXXX move to connection_edge.c */
5632 addressmap_register_auto(const char *from, const char *to,
5633 time_t expires,
5634 addressmap_entry_source_t addrmap_source,
5635 const char **msg)
5637 int from_wildcard = 0, to_wildcard = 0;
5639 *msg = "whoops, forgot the error message";
5641 if (!strcmp(to, "*") || !strcmp(from, "*")) {
5642 *msg = "can't remap from or to *";
5643 return -1;
5645 /* Detect asterisks in expressions of type: '*.example.com' */
5646 if (!strncmp(from,"*.",2)) {
5647 from += 2;
5648 from_wildcard = 1;
5650 if (!strncmp(to,"*.",2)) {
5651 to += 2;
5652 to_wildcard = 1;
5655 if (to_wildcard && !from_wildcard) {
5656 *msg = "can only use wildcard (i.e. '*.') if 'from' address "
5657 "uses wildcard also";
5658 return -1;
5661 if (address_is_invalid_destination(to, 1)) {
5662 *msg = "destination is invalid";
5663 return -1;
5666 addressmap_register(from, tor_strdup(to), expires, addrmap_source,
5667 from_wildcard, to_wildcard);
5669 return 0;
5673 * Initialize the logs based on the configuration file.
5675 static int
5676 options_init_logs(const or_options_t *old_options, or_options_t *options,
5677 int validate_only)
5679 config_line_t *opt;
5680 int ok;
5681 smartlist_t *elts;
5682 int run_as_daemon =
5683 #ifdef _WIN32
5685 #else
5686 options->RunAsDaemon;
5687 #endif
5689 if (options->LogTimeGranularity <= 0) {
5690 log_warn(LD_CONFIG, "Log time granularity '%d' has to be positive.",
5691 options->LogTimeGranularity);
5692 return -1;
5693 } else if (1000 % options->LogTimeGranularity != 0 &&
5694 options->LogTimeGranularity % 1000 != 0) {
5695 int granularity = options->LogTimeGranularity;
5696 if (granularity < 40) {
5697 do granularity++;
5698 while (1000 % granularity != 0);
5699 } else if (granularity < 1000) {
5700 granularity = 1000 / granularity;
5701 while (1000 % granularity != 0)
5702 granularity--;
5703 granularity = 1000 / granularity;
5704 } else {
5705 granularity = 1000 * ((granularity / 1000) + 1);
5707 log_warn(LD_CONFIG, "Log time granularity '%d' has to be either a "
5708 "divisor or a multiple of 1 second. Changing to "
5709 "'%d'.",
5710 options->LogTimeGranularity, granularity);
5711 if (!validate_only)
5712 set_log_time_granularity(granularity);
5713 } else {
5714 if (!validate_only)
5715 set_log_time_granularity(options->LogTimeGranularity);
5718 ok = 1;
5719 elts = smartlist_new();
5721 for (opt = options->Logs; opt; opt = opt->next) {
5722 log_severity_list_t *severity;
5723 const char *cfg = opt->value;
5724 severity = tor_malloc_zero(sizeof(log_severity_list_t));
5725 if (parse_log_severity_config(&cfg, severity) < 0) {
5726 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
5727 opt->value);
5728 ok = 0; goto cleanup;
5731 smartlist_split_string(elts, cfg, NULL,
5732 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
5734 if (smartlist_len(elts) == 0)
5735 smartlist_add_strdup(elts, "stdout");
5737 if (smartlist_len(elts) == 1 &&
5738 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
5739 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
5740 int err = smartlist_len(elts) &&
5741 !strcasecmp(smartlist_get(elts,0), "stderr");
5742 if (!validate_only) {
5743 if (run_as_daemon) {
5744 log_warn(LD_CONFIG,
5745 "Can't log to %s with RunAsDaemon set; skipping stdout",
5746 err?"stderr":"stdout");
5747 } else {
5748 add_stream_log(severity, err?"<stderr>":"<stdout>",
5749 fileno(err?stderr:stdout));
5752 goto cleanup;
5754 if (smartlist_len(elts) == 1) {
5755 if (!strcasecmp(smartlist_get(elts,0), "syslog")) {
5756 #ifdef HAVE_SYSLOG_H
5757 if (!validate_only) {
5758 add_syslog_log(severity, options->SyslogIdentityTag);
5760 #else
5761 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
5762 #endif /* defined(HAVE_SYSLOG_H) */
5763 goto cleanup;
5766 if (!strcasecmp(smartlist_get(elts, 0), "android")) {
5767 #ifdef HAVE_ANDROID_LOG_H
5768 if (!validate_only) {
5769 add_android_log(severity, options->AndroidIdentityTag);
5771 #else
5772 log_warn(LD_CONFIG, "Android logging is not supported"
5773 " on this system. Sorry.");
5774 #endif // HAVE_ANDROID_LOG_H.
5775 goto cleanup;
5779 if (smartlist_len(elts) == 2 &&
5780 !strcasecmp(smartlist_get(elts,0), "file")) {
5781 if (!validate_only) {
5782 char *fname = expand_filename(smartlist_get(elts, 1));
5783 /* Truncate if TruncateLogFile is set and we haven't seen this option
5784 line before. */
5785 int truncate_log = 0;
5786 if (options->TruncateLogFile) {
5787 truncate_log = 1;
5788 if (old_options) {
5789 config_line_t *opt2;
5790 for (opt2 = old_options->Logs; opt2; opt2 = opt2->next)
5791 if (!strcmp(opt->value, opt2->value)) {
5792 truncate_log = 0;
5793 break;
5797 if (add_file_log(severity, fname, truncate_log) < 0) {
5798 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
5799 opt->value, strerror(errno));
5800 ok = 0;
5802 tor_free(fname);
5804 goto cleanup;
5807 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
5808 opt->value);
5809 ok = 0; goto cleanup;
5811 cleanup:
5812 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
5813 smartlist_clear(elts);
5814 tor_free(severity);
5816 smartlist_free(elts);
5818 if (ok && !validate_only)
5819 logs_set_domain_logging(options->LogMessageDomains);
5821 return ok?0:-1;
5824 /** Given a smartlist of SOCKS arguments to be passed to a transport
5825 * proxy in <b>args</b>, validate them and return -1 if they are
5826 * corrupted. Return 0 if they seem OK. */
5827 static int
5828 validate_transport_socks_arguments(const smartlist_t *args)
5830 char *socks_string = NULL;
5831 size_t socks_string_len;
5833 tor_assert(args);
5834 tor_assert(smartlist_len(args) > 0);
5836 SMARTLIST_FOREACH_BEGIN(args, const char *, s) {
5837 if (!string_is_key_value(LOG_WARN, s)) { /* items should be k=v items */
5838 log_warn(LD_CONFIG, "'%s' is not a k=v item.", s);
5839 return -1;
5841 } SMARTLIST_FOREACH_END(s);
5843 socks_string = pt_stringify_socks_args(args);
5844 if (!socks_string)
5845 return -1;
5847 socks_string_len = strlen(socks_string);
5848 tor_free(socks_string);
5850 if (socks_string_len > MAX_SOCKS5_AUTH_SIZE_TOTAL) {
5851 log_warn(LD_CONFIG, "SOCKS arguments can't be more than %u bytes (%lu).",
5852 MAX_SOCKS5_AUTH_SIZE_TOTAL,
5853 (unsigned long) socks_string_len);
5854 return -1;
5857 return 0;
5860 /** Deallocate a bridge_line_t structure. */
5861 /* private */ void
5862 bridge_line_free_(bridge_line_t *bridge_line)
5864 if (!bridge_line)
5865 return;
5867 if (bridge_line->socks_args) {
5868 SMARTLIST_FOREACH(bridge_line->socks_args, char*, s, tor_free(s));
5869 smartlist_free(bridge_line->socks_args);
5871 tor_free(bridge_line->transport_name);
5872 tor_free(bridge_line);
5875 /** Parse the contents of a string, <b>line</b>, containing a Bridge line,
5876 * into a bridge_line_t.
5878 * Validates that the IP:PORT, fingerprint, and SOCKS arguments (given to the
5879 * Pluggable Transport, if a one was specified) are well-formed.
5881 * Returns NULL If the Bridge line could not be validated, and returns a
5882 * bridge_line_t containing the parsed information otherwise.
5884 * Bridge line format:
5885 * Bridge [transport] IP:PORT [id-fingerprint] [k=v] [k=v] ...
5887 /* private */ bridge_line_t *
5888 parse_bridge_line(const char *line)
5890 smartlist_t *items = NULL;
5891 char *addrport=NULL, *fingerprint=NULL;
5892 char *field=NULL;
5893 bridge_line_t *bridge_line = tor_malloc_zero(sizeof(bridge_line_t));
5895 items = smartlist_new();
5896 smartlist_split_string(items, line, NULL,
5897 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5898 if (smartlist_len(items) < 1) {
5899 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
5900 goto err;
5903 /* first field is either a transport name or addrport */
5904 field = smartlist_get(items, 0);
5905 smartlist_del_keeporder(items, 0);
5907 if (string_is_C_identifier(field)) {
5908 /* It's a transport name. */
5909 bridge_line->transport_name = field;
5910 if (smartlist_len(items) < 1) {
5911 log_warn(LD_CONFIG, "Too few items to Bridge line.");
5912 goto err;
5914 addrport = smartlist_get(items, 0); /* Next field is addrport then. */
5915 smartlist_del_keeporder(items, 0);
5916 } else {
5917 addrport = field;
5920 if (tor_addr_port_parse(LOG_INFO, addrport,
5921 &bridge_line->addr, &bridge_line->port, 443)<0) {
5922 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
5923 goto err;
5926 /* If transports are enabled, next field could be a fingerprint or a
5927 socks argument. If transports are disabled, next field must be
5928 a fingerprint. */
5929 if (smartlist_len(items)) {
5930 if (bridge_line->transport_name) { /* transports enabled: */
5931 field = smartlist_get(items, 0);
5932 smartlist_del_keeporder(items, 0);
5934 /* If it's a key=value pair, then it's a SOCKS argument for the
5935 transport proxy... */
5936 if (string_is_key_value(LOG_DEBUG, field)) {
5937 bridge_line->socks_args = smartlist_new();
5938 smartlist_add(bridge_line->socks_args, field);
5939 } else { /* ...otherwise, it's the bridge fingerprint. */
5940 fingerprint = field;
5943 } else { /* transports disabled: */
5944 fingerprint = smartlist_join_strings(items, "", 0, NULL);
5948 /* Handle fingerprint, if it was provided. */
5949 if (fingerprint) {
5950 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
5951 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
5952 goto err;
5954 if (base16_decode(bridge_line->digest, DIGEST_LEN,
5955 fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
5956 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
5957 goto err;
5961 /* If we are using transports, any remaining items in the smartlist
5962 should be k=v values. */
5963 if (bridge_line->transport_name && smartlist_len(items)) {
5964 if (!bridge_line->socks_args)
5965 bridge_line->socks_args = smartlist_new();
5967 /* append remaining items of 'items' to 'socks_args' */
5968 smartlist_add_all(bridge_line->socks_args, items);
5969 smartlist_clear(items);
5971 tor_assert(smartlist_len(bridge_line->socks_args) > 0);
5974 if (bridge_line->socks_args) {
5975 if (validate_transport_socks_arguments(bridge_line->socks_args) < 0)
5976 goto err;
5979 goto done;
5981 err:
5982 bridge_line_free(bridge_line);
5983 bridge_line = NULL;
5985 done:
5986 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5987 smartlist_free(items);
5988 tor_free(addrport);
5989 tor_free(fingerprint);
5991 return bridge_line;
5994 /** Read the contents of a ClientTransportPlugin or ServerTransportPlugin
5995 * line from <b>line</b>, depending on the value of <b>server</b>. Return 0
5996 * if the line is well-formed, and -1 if it isn't.
5998 * If <b>validate_only</b> is 0, the line is well-formed, and the transport is
5999 * needed by some bridge:
6000 * - If it's an external proxy line, add the transport described in the line to
6001 * our internal transport list.
6002 * - If it's a managed proxy line, launch the managed proxy.
6005 STATIC int
6006 parse_transport_line(const or_options_t *options,
6007 const char *line, int validate_only,
6008 int server)
6011 smartlist_t *items = NULL;
6012 int r;
6013 const char *transports = NULL;
6014 smartlist_t *transport_list = NULL;
6015 char *type = NULL;
6016 char *addrport = NULL;
6017 tor_addr_t addr;
6018 uint16_t port = 0;
6019 int socks_ver = PROXY_NONE;
6021 /* managed proxy options */
6022 int is_managed = 0;
6023 char **proxy_argv = NULL;
6024 char **tmp = NULL;
6025 int proxy_argc, i;
6026 int is_useless_proxy = 1;
6028 int line_length;
6030 /* Split the line into space-separated tokens */
6031 items = smartlist_new();
6032 smartlist_split_string(items, line, NULL,
6033 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6034 line_length = smartlist_len(items);
6036 if (line_length < 3) {
6037 log_warn(LD_CONFIG,
6038 "Too few arguments on %sTransportPlugin line.",
6039 server ? "Server" : "Client");
6040 goto err;
6043 /* Get the first line element, split it to commas into
6044 transport_list (in case it's multiple transports) and validate
6045 the transport names. */
6046 transports = smartlist_get(items, 0);
6047 transport_list = smartlist_new();
6048 smartlist_split_string(transport_list, transports, ",",
6049 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
6050 SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
6051 /* validate transport names */
6052 if (!string_is_C_identifier(transport_name)) {
6053 log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
6054 transport_name);
6055 goto err;
6058 /* see if we actually need the transports provided by this proxy */
6059 if (!validate_only && transport_is_needed(transport_name))
6060 is_useless_proxy = 0;
6061 } SMARTLIST_FOREACH_END(transport_name);
6063 type = smartlist_get(items, 1);
6064 if (!strcmp(type, "exec")) {
6065 is_managed = 1;
6066 } else if (server && !strcmp(type, "proxy")) {
6067 /* 'proxy' syntax only with ServerTransportPlugin */
6068 is_managed = 0;
6069 } else if (!server && !strcmp(type, "socks4")) {
6070 /* 'socks4' syntax only with ClientTransportPlugin */
6071 is_managed = 0;
6072 socks_ver = PROXY_SOCKS4;
6073 } else if (!server && !strcmp(type, "socks5")) {
6074 /* 'socks5' syntax only with ClientTransportPlugin */
6075 is_managed = 0;
6076 socks_ver = PROXY_SOCKS5;
6077 } else {
6078 log_warn(LD_CONFIG,
6079 "Strange %sTransportPlugin type '%s'",
6080 server ? "Server" : "Client", type);
6081 goto err;
6084 if (is_managed && options->Sandbox) {
6085 log_warn(LD_CONFIG,
6086 "Managed proxies are not compatible with Sandbox mode."
6087 "(%sTransportPlugin line was %s)",
6088 server ? "Server" : "Client", escaped(line));
6089 goto err;
6092 if (is_managed && options->NoExec) {
6093 log_warn(LD_CONFIG,
6094 "Managed proxies are not compatible with NoExec mode; ignoring."
6095 "(%sTransportPlugin line was %s)",
6096 server ? "Server" : "Client", escaped(line));
6097 r = 0;
6098 goto done;
6101 if (is_managed) {
6102 /* managed */
6104 if (!server && !validate_only && is_useless_proxy) {
6105 log_info(LD_GENERAL,
6106 "Pluggable transport proxy (%s) does not provide "
6107 "any needed transports and will not be launched.",
6108 line);
6112 * If we are not just validating, use the rest of the line as the
6113 * argv of the proxy to be launched. Also, make sure that we are
6114 * only launching proxies that contribute useful transports.
6117 if (!validate_only && (server || !is_useless_proxy)) {
6118 proxy_argc = line_length - 2;
6119 tor_assert(proxy_argc > 0);
6120 proxy_argv = tor_calloc((proxy_argc + 1), sizeof(char *));
6121 tmp = proxy_argv;
6123 for (i = 0; i < proxy_argc; i++) {
6124 /* store arguments */
6125 *tmp++ = smartlist_get(items, 2);
6126 smartlist_del_keeporder(items, 2);
6128 *tmp = NULL; /* terminated with NULL, just like execve() likes it */
6130 /* kickstart the thing */
6131 if (server) {
6132 pt_kickstart_server_proxy(transport_list, proxy_argv);
6133 } else {
6134 pt_kickstart_client_proxy(transport_list, proxy_argv);
6137 } else {
6138 /* external */
6140 /* ClientTransportPlugins connecting through a proxy is managed only. */
6141 if (!server && (options->Socks4Proxy || options->Socks5Proxy ||
6142 options->HTTPSProxy)) {
6143 log_warn(LD_CONFIG, "You have configured an external proxy with another "
6144 "proxy type. (Socks4Proxy|Socks5Proxy|HTTPSProxy)");
6145 goto err;
6148 if (smartlist_len(transport_list) != 1) {
6149 log_warn(LD_CONFIG,
6150 "You can't have an external proxy with more than "
6151 "one transport.");
6152 goto err;
6155 addrport = smartlist_get(items, 2);
6157 if (tor_addr_port_lookup(addrport, &addr, &port) < 0) {
6158 log_warn(LD_CONFIG,
6159 "Error parsing transport address '%s'", addrport);
6160 goto err;
6163 if (!port) {
6164 log_warn(LD_CONFIG,
6165 "Transport address '%s' has no port.", addrport);
6166 goto err;
6169 if (!validate_only) {
6170 log_info(LD_DIR, "%s '%s' at %s.",
6171 server ? "Server transport" : "Transport",
6172 transports, fmt_addrport(&addr, port));
6174 if (!server) {
6175 transport_add_from_config(&addr, port,
6176 smartlist_get(transport_list, 0),
6177 socks_ver);
6182 r = 0;
6183 goto done;
6185 err:
6186 r = -1;
6188 done:
6189 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
6190 smartlist_free(items);
6191 if (transport_list) {
6192 SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
6193 smartlist_free(transport_list);
6196 return r;
6199 /** Given a ServerTransportListenAddr <b>line</b>, return its
6200 * <address:port> string. Return NULL if the line was not
6201 * well-formed.
6203 * If <b>transport</b> is set, return NULL if the line is not
6204 * referring to <b>transport</b>.
6206 * The returned string is allocated on the heap and it's the
6207 * responsibility of the caller to free it. */
6208 static char *
6209 get_bindaddr_from_transport_listen_line(const char *line,const char *transport)
6211 smartlist_t *items = NULL;
6212 const char *parsed_transport = NULL;
6213 char *addrport = NULL;
6214 tor_addr_t addr;
6215 uint16_t port = 0;
6217 items = smartlist_new();
6218 smartlist_split_string(items, line, NULL,
6219 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6221 if (smartlist_len(items) < 2) {
6222 log_warn(LD_CONFIG,"Too few arguments on ServerTransportListenAddr line.");
6223 goto err;
6226 parsed_transport = smartlist_get(items, 0);
6227 addrport = tor_strdup(smartlist_get(items, 1));
6229 /* If 'transport' is given, check if it matches the one on the line */
6230 if (transport && strcmp(transport, parsed_transport))
6231 goto err;
6233 /* Validate addrport */
6234 if (tor_addr_port_parse(LOG_WARN, addrport, &addr, &port, -1)<0) {
6235 log_warn(LD_CONFIG, "Error parsing ServerTransportListenAddr "
6236 "address '%s'", addrport);
6237 goto err;
6240 goto done;
6242 err:
6243 tor_free(addrport);
6244 addrport = NULL;
6246 done:
6247 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
6248 smartlist_free(items);
6250 return addrport;
6253 /** Given a ServerTransportOptions <b>line</b>, return a smartlist
6254 * with the options. Return NULL if the line was not well-formed.
6256 * If <b>transport</b> is set, return NULL if the line is not
6257 * referring to <b>transport</b>.
6259 * The returned smartlist and its strings are allocated on the heap
6260 * and it's the responsibility of the caller to free it. */
6261 smartlist_t *
6262 get_options_from_transport_options_line(const char *line,const char *transport)
6264 smartlist_t *items = smartlist_new();
6265 smartlist_t *options = smartlist_new();
6266 const char *parsed_transport = NULL;
6268 smartlist_split_string(items, line, NULL,
6269 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6271 if (smartlist_len(items) < 2) {
6272 log_warn(LD_CONFIG,"Too few arguments on ServerTransportOptions line.");
6273 goto err;
6276 parsed_transport = smartlist_get(items, 0);
6277 /* If 'transport' is given, check if it matches the one on the line */
6278 if (transport && strcmp(transport, parsed_transport))
6279 goto err;
6281 SMARTLIST_FOREACH_BEGIN(items, const char *, option) {
6282 if (option_sl_idx == 0) /* skip the transport field (first field)*/
6283 continue;
6285 /* validate that it's a k=v value */
6286 if (!string_is_key_value(LOG_WARN, option)) {
6287 log_warn(LD_CONFIG, "%s is not a k=v value.", escaped(option));
6288 goto err;
6291 /* add it to the options smartlist */
6292 smartlist_add_strdup(options, option);
6293 log_debug(LD_CONFIG, "Added %s to the list of options", escaped(option));
6294 } SMARTLIST_FOREACH_END(option);
6296 goto done;
6298 err:
6299 SMARTLIST_FOREACH(options, char*, s, tor_free(s));
6300 smartlist_free(options);
6301 options = NULL;
6303 done:
6304 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
6305 smartlist_free(items);
6307 return options;
6310 /** Given the name of a pluggable transport in <b>transport</b>, check
6311 * the configuration file to see if the user has explicitly asked for
6312 * it to listen on a specific port. Return a <address:port> string if
6313 * so, otherwise NULL. */
6314 char *
6315 get_transport_bindaddr_from_config(const char *transport)
6317 config_line_t *cl;
6318 const or_options_t *options = get_options();
6320 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
6321 char *bindaddr =
6322 get_bindaddr_from_transport_listen_line(cl->value, transport);
6323 if (bindaddr)
6324 return bindaddr;
6327 return NULL;
6330 /** Given the name of a pluggable transport in <b>transport</b>, check
6331 * the configuration file to see if the user has asked us to pass any
6332 * parameters to the pluggable transport. Return a smartlist
6333 * containing the parameters, otherwise NULL. */
6334 smartlist_t *
6335 get_options_for_server_transport(const char *transport)
6337 config_line_t *cl;
6338 const or_options_t *options = get_options();
6340 for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
6341 smartlist_t *options_sl =
6342 get_options_from_transport_options_line(cl->value, transport);
6343 if (options_sl)
6344 return options_sl;
6347 return NULL;
6350 /** Read the contents of a DirAuthority line from <b>line</b>. If
6351 * <b>validate_only</b> is 0, and the line is well-formed, and it
6352 * shares any bits with <b>required_type</b> or <b>required_type</b>
6353 * is NO_DIRINFO (zero), then add the dirserver described in the line
6354 * (minus whatever bits it's missing) as a valid authority.
6355 * Return 0 on success or filtering out by type,
6356 * or -1 if the line isn't well-formed or if we can't add it. */
6357 STATIC int
6358 parse_dir_authority_line(const char *line, dirinfo_type_t required_type,
6359 int validate_only)
6361 smartlist_t *items = NULL;
6362 int r;
6363 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
6364 tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
6365 uint16_t dir_port = 0, or_port = 0;
6366 char digest[DIGEST_LEN];
6367 char v3_digest[DIGEST_LEN];
6368 dirinfo_type_t type = 0;
6369 double weight = 1.0;
6371 memset(v3_digest, 0, sizeof(v3_digest));
6373 items = smartlist_new();
6374 smartlist_split_string(items, line, NULL,
6375 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6376 if (smartlist_len(items) < 1) {
6377 log_warn(LD_CONFIG, "No arguments on DirAuthority line.");
6378 goto err;
6381 if (is_legal_nickname(smartlist_get(items, 0))) {
6382 nickname = smartlist_get(items, 0);
6383 smartlist_del_keeporder(items, 0);
6386 while (smartlist_len(items)) {
6387 char *flag = smartlist_get(items, 0);
6388 if (TOR_ISDIGIT(flag[0]))
6389 break;
6390 if (!strcasecmp(flag, "hs") ||
6391 !strcasecmp(flag, "no-hs")) {
6392 log_warn(LD_CONFIG, "The DirAuthority options 'hs' and 'no-hs' are "
6393 "obsolete; you don't need them any more.");
6394 } else if (!strcasecmp(flag, "bridge")) {
6395 type |= BRIDGE_DIRINFO;
6396 } else if (!strcasecmp(flag, "no-v2")) {
6397 /* obsolete, but may still be contained in DirAuthority lines generated
6398 by various tools */;
6399 } else if (!strcasecmpstart(flag, "orport=")) {
6400 int ok;
6401 char *portstring = flag + strlen("orport=");
6402 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
6403 if (!ok)
6404 log_warn(LD_CONFIG, "Invalid orport '%s' on DirAuthority line.",
6405 portstring);
6406 } else if (!strcmpstart(flag, "weight=")) {
6407 int ok;
6408 const char *wstring = flag + strlen("weight=");
6409 weight = tor_parse_double(wstring, 0, (double)UINT64_MAX, &ok, NULL);
6410 if (!ok) {
6411 log_warn(LD_CONFIG, "Invalid weight '%s' on DirAuthority line.",flag);
6412 weight=1.0;
6414 } else if (!strcasecmpstart(flag, "v3ident=")) {
6415 char *idstr = flag + strlen("v3ident=");
6416 if (strlen(idstr) != HEX_DIGEST_LEN ||
6417 base16_decode(v3_digest, DIGEST_LEN,
6418 idstr, HEX_DIGEST_LEN) != DIGEST_LEN) {
6419 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirAuthority line",
6420 flag);
6421 } else {
6422 type |= V3_DIRINFO|EXTRAINFO_DIRINFO|MICRODESC_DIRINFO;
6424 } else if (!strcasecmpstart(flag, "ipv6=")) {
6425 if (ipv6_addrport_ptr) {
6426 log_warn(LD_CONFIG, "Redundant ipv6 addr/port on DirAuthority line");
6427 } else {
6428 if (tor_addr_port_parse(LOG_WARN, flag+strlen("ipv6="),
6429 &ipv6_addrport.addr, &ipv6_addrport.port,
6430 -1) < 0
6431 || tor_addr_family(&ipv6_addrport.addr) != AF_INET6) {
6432 log_warn(LD_CONFIG, "Bad ipv6 addr/port %s on DirAuthority line",
6433 escaped(flag));
6434 goto err;
6436 ipv6_addrport_ptr = &ipv6_addrport;
6438 } else {
6439 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirAuthority line",
6440 flag);
6442 tor_free(flag);
6443 smartlist_del_keeporder(items, 0);
6446 if (smartlist_len(items) < 2) {
6447 log_warn(LD_CONFIG, "Too few arguments to DirAuthority line.");
6448 goto err;
6450 addrport = smartlist_get(items, 0);
6451 smartlist_del_keeporder(items, 0);
6452 if (addr_port_lookup(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
6453 log_warn(LD_CONFIG, "Error parsing DirAuthority address '%s'", addrport);
6454 goto err;
6456 if (!dir_port) {
6457 log_warn(LD_CONFIG, "Missing port in DirAuthority address '%s'",addrport);
6458 goto err;
6461 fingerprint = smartlist_join_strings(items, "", 0, NULL);
6462 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
6463 log_warn(LD_CONFIG, "Key digest '%s' for DirAuthority is wrong length %d.",
6464 fingerprint, (int)strlen(fingerprint));
6465 goto err;
6467 if (base16_decode(digest, DIGEST_LEN,
6468 fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
6469 log_warn(LD_CONFIG, "Unable to decode DirAuthority key digest.");
6470 goto err;
6473 if (!validate_only && (!required_type || required_type & type)) {
6474 dir_server_t *ds;
6475 if (required_type)
6476 type &= required_type; /* pare down what we think of them as an
6477 * authority for. */
6478 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
6479 address, (int)dir_port, (char*)smartlist_get(items,0));
6480 if (!(ds = trusted_dir_server_new(nickname, address, dir_port, or_port,
6481 ipv6_addrport_ptr,
6482 digest, v3_digest, type, weight)))
6483 goto err;
6484 dir_server_add(ds);
6487 r = 0;
6488 goto done;
6490 err:
6491 r = -1;
6493 done:
6494 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
6495 smartlist_free(items);
6496 tor_free(addrport);
6497 tor_free(address);
6498 tor_free(nickname);
6499 tor_free(fingerprint);
6500 return r;
6503 /** Read the contents of a FallbackDir line from <b>line</b>. If
6504 * <b>validate_only</b> is 0, and the line is well-formed, then add the
6505 * dirserver described in the line as a fallback directory. Return 0 on
6506 * success, or -1 if the line isn't well-formed or if we can't add it. */
6508 parse_dir_fallback_line(const char *line,
6509 int validate_only)
6511 int r = -1;
6512 smartlist_t *items = smartlist_new(), *positional = smartlist_new();
6513 int orport = -1;
6514 uint16_t dirport;
6515 tor_addr_t addr;
6516 int ok;
6517 char id[DIGEST_LEN];
6518 char *address=NULL;
6519 tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
6520 double weight=1.0;
6522 memset(id, 0, sizeof(id));
6523 smartlist_split_string(items, line, NULL,
6524 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6525 SMARTLIST_FOREACH_BEGIN(items, const char *, cp) {
6526 const char *eq = strchr(cp, '=');
6527 ok = 1;
6528 if (! eq) {
6529 smartlist_add(positional, (char*)cp);
6530 continue;
6532 if (!strcmpstart(cp, "orport=")) {
6533 orport = (int)tor_parse_long(cp+strlen("orport="), 10,
6534 1, 65535, &ok, NULL);
6535 } else if (!strcmpstart(cp, "id=")) {
6536 ok = base16_decode(id, DIGEST_LEN, cp+strlen("id="),
6537 strlen(cp)-strlen("id=")) == DIGEST_LEN;
6538 } else if (!strcasecmpstart(cp, "ipv6=")) {
6539 if (ipv6_addrport_ptr) {
6540 log_warn(LD_CONFIG, "Redundant ipv6 addr/port on FallbackDir line");
6541 } else {
6542 if (tor_addr_port_parse(LOG_WARN, cp+strlen("ipv6="),
6543 &ipv6_addrport.addr, &ipv6_addrport.port,
6544 -1) < 0
6545 || tor_addr_family(&ipv6_addrport.addr) != AF_INET6) {
6546 log_warn(LD_CONFIG, "Bad ipv6 addr/port %s on FallbackDir line",
6547 escaped(cp));
6548 goto end;
6550 ipv6_addrport_ptr = &ipv6_addrport;
6552 } else if (!strcmpstart(cp, "weight=")) {
6553 int num_ok;
6554 const char *wstring = cp + strlen("weight=");
6555 weight = tor_parse_double(wstring, 0, (double)UINT64_MAX, &num_ok, NULL);
6556 if (!num_ok) {
6557 log_warn(LD_CONFIG, "Invalid weight '%s' on FallbackDir line.", cp);
6558 weight=1.0;
6562 if (!ok) {
6563 log_warn(LD_CONFIG, "Bad FallbackDir option %s", escaped(cp));
6564 goto end;
6566 } SMARTLIST_FOREACH_END(cp);
6568 if (smartlist_len(positional) != 1) {
6569 log_warn(LD_CONFIG, "Couldn't parse FallbackDir line %s", escaped(line));
6570 goto end;
6573 if (tor_digest_is_zero(id)) {
6574 log_warn(LD_CONFIG, "Missing identity on FallbackDir line");
6575 goto end;
6578 if (orport <= 0) {
6579 log_warn(LD_CONFIG, "Missing orport on FallbackDir line");
6580 goto end;
6583 if (tor_addr_port_split(LOG_INFO, smartlist_get(positional, 0),
6584 &address, &dirport) < 0 ||
6585 tor_addr_parse(&addr, address)<0) {
6586 log_warn(LD_CONFIG, "Couldn't parse address:port %s on FallbackDir line",
6587 (const char*)smartlist_get(positional, 0));
6588 goto end;
6591 if (!validate_only) {
6592 dir_server_t *ds;
6593 ds = fallback_dir_server_new(&addr, dirport, orport, ipv6_addrport_ptr,
6594 id, weight);
6595 if (!ds) {
6596 log_warn(LD_CONFIG, "Couldn't create FallbackDir %s", escaped(line));
6597 goto end;
6599 dir_server_add(ds);
6602 r = 0;
6604 end:
6605 SMARTLIST_FOREACH(items, char *, cp, tor_free(cp));
6606 smartlist_free(items);
6607 smartlist_free(positional);
6608 tor_free(address);
6609 return r;
6612 /** Allocate and return a new port_cfg_t with reasonable defaults. */
6613 STATIC port_cfg_t *
6614 port_cfg_new(size_t namelen)
6616 tor_assert(namelen <= SIZE_T_CEILING - sizeof(port_cfg_t) - 1);
6617 port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t) + namelen + 1);
6618 cfg->entry_cfg.ipv4_traffic = 1;
6619 cfg->entry_cfg.ipv6_traffic = 1;
6620 cfg->entry_cfg.dns_request = 1;
6621 cfg->entry_cfg.onion_traffic = 1;
6622 cfg->entry_cfg.prefer_ipv6_virtaddr = 1;
6623 return cfg;
6626 /** Free all storage held in <b>port</b> */
6627 STATIC void
6628 port_cfg_free_(port_cfg_t *port)
6630 tor_free(port);
6633 /** Warn for every port in <b>ports</b> of type <b>listener_type</b> that is
6634 * on a publicly routable address. */
6635 static void
6636 warn_nonlocal_client_ports(const smartlist_t *ports,
6637 const char *portname,
6638 const int listener_type)
6640 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
6641 if (port->type != listener_type)
6642 continue;
6643 if (port->is_unix_addr) {
6644 /* Unix sockets aren't accessible over a network. */
6645 } else if (!tor_addr_is_internal(&port->addr, 1)) {
6646 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
6647 "Other people on the Internet might find your computer and "
6648 "use it as an open proxy. Please don't allow this unless you "
6649 "have a good reason.",
6650 fmt_addrport(&port->addr, port->port), portname);
6651 } else if (!tor_addr_is_loopback(&port->addr)) {
6652 log_notice(LD_CONFIG, "You configured a non-loopback address '%s' "
6653 "for %sPort. This allows everybody on your local network to "
6654 "use your machine as a proxy. Make sure this is what you "
6655 "wanted.",
6656 fmt_addrport(&port->addr, port->port), portname);
6658 } SMARTLIST_FOREACH_END(port);
6661 /** Warn for every Extended ORPort port in <b>ports</b> that is on a
6662 * publicly routable address. */
6663 static void
6664 warn_nonlocal_ext_orports(const smartlist_t *ports, const char *portname)
6666 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
6667 if (port->type != CONN_TYPE_EXT_OR_LISTENER)
6668 continue;
6669 if (port->is_unix_addr)
6670 continue;
6671 /* XXX maybe warn even if address is RFC1918? */
6672 if (!tor_addr_is_internal(&port->addr, 1)) {
6673 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
6674 "This is not advised; this address is supposed to only be "
6675 "exposed on localhost so that your pluggable transport "
6676 "proxies can connect to it.",
6677 fmt_addrport(&port->addr, port->port), portname);
6679 } SMARTLIST_FOREACH_END(port);
6682 /** Given a list of port_cfg_t in <b>ports</b>, warn if any controller port
6683 * there is listening on any non-loopback address. If <b>forbid_nonlocal</b>
6684 * is true, then emit a stronger warning and remove the port from the list.
6686 static void
6687 warn_nonlocal_controller_ports(smartlist_t *ports, unsigned forbid_nonlocal)
6689 int warned = 0;
6690 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
6691 if (port->type != CONN_TYPE_CONTROL_LISTENER)
6692 continue;
6693 if (port->is_unix_addr)
6694 continue;
6695 if (!tor_addr_is_loopback(&port->addr)) {
6696 if (forbid_nonlocal) {
6697 if (!warned)
6698 log_warn(LD_CONFIG,
6699 "You have a ControlPort set to accept "
6700 "unauthenticated connections from a non-local address. "
6701 "This means that programs not running on your computer "
6702 "can reconfigure your Tor, without even having to guess a "
6703 "password. That's so bad that I'm closing your ControlPort "
6704 "for you. If you need to control your Tor remotely, try "
6705 "enabling authentication and using a tool like stunnel or "
6706 "ssh to encrypt remote access.");
6707 warned = 1;
6708 port_cfg_free(port);
6709 SMARTLIST_DEL_CURRENT(ports, port);
6710 } else {
6711 log_warn(LD_CONFIG, "You have a ControlPort set to accept "
6712 "connections from a non-local address. This means that "
6713 "programs not running on your computer can reconfigure your "
6714 "Tor. That's pretty bad, since the controller "
6715 "protocol isn't encrypted! Maybe you should just listen on "
6716 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
6717 "remote connections to your control port.");
6718 return; /* No point in checking the rest */
6721 } SMARTLIST_FOREACH_END(port);
6725 * Take a string (<b>line</b>) that begins with either an address:port, a
6726 * port, or an AF_UNIX address, optionally quoted, prefixed with
6727 * "unix:". Parse that line, and on success, set <b>addrport_out</b> to a new
6728 * string containing the beginning portion (without prefix). Iff there was a
6729 * unix: prefix, set <b>is_unix_out</b> to true. On success, also set
6730 * <b>rest_out</b> to point to the part of the line after the address portion.
6732 * Return 0 on success, -1 on failure.
6735 port_cfg_line_extract_addrport(const char *line,
6736 char **addrport_out,
6737 int *is_unix_out,
6738 const char **rest_out)
6740 tor_assert(line);
6741 tor_assert(addrport_out);
6742 tor_assert(is_unix_out);
6743 tor_assert(rest_out);
6745 line = eat_whitespace(line);
6747 if (!strcmpstart(line, unix_q_socket_prefix)) {
6748 // It starts with unix:"
6749 size_t sz;
6750 *is_unix_out = 1;
6751 *addrport_out = NULL;
6752 line += strlen(unix_socket_prefix); /*No q: Keep the quote */
6753 *rest_out = unescape_string(line, addrport_out, &sz);
6754 if (!*rest_out || (*addrport_out && sz != strlen(*addrport_out))) {
6755 tor_free(*addrport_out);
6756 return -1;
6758 *rest_out = eat_whitespace(*rest_out);
6759 return 0;
6760 } else {
6761 // Is there a unix: prefix?
6762 if (!strcmpstart(line, unix_socket_prefix)) {
6763 line += strlen(unix_socket_prefix);
6764 *is_unix_out = 1;
6765 } else {
6766 *is_unix_out = 0;
6769 const char *end = find_whitespace(line);
6770 if (BUG(!end)) {
6771 end = strchr(line, '\0'); // LCOV_EXCL_LINE -- this can't be NULL
6773 tor_assert(end && end >= line);
6774 *addrport_out = tor_strndup(line, end - line);
6775 *rest_out = eat_whitespace(end);
6776 return 0;
6780 static void
6781 warn_client_dns_cache(const char *option, int disabling)
6783 if (disabling)
6784 return;
6786 warn_deprecated_option(option,
6787 "Client-side DNS cacheing enables a wide variety of route-"
6788 "capture attacks. If a single bad exit node lies to you about "
6789 "an IP address, cacheing that address would make you visit "
6790 "an address of the attacker's choice every time you connected "
6791 "to your destination.");
6795 * Validate the configured bridge distribution method from a BridgeDistribution
6796 * config line.
6798 * The input <b>bd</b>, is a string taken from the BridgeDistribution config
6799 * line (if present). If the option wasn't set, return 0 immediately. The
6800 * BridgeDistribution option is then validated. Currently valid, recognised
6801 * options are:
6803 * - "none"
6804 * - "any"
6805 * - "https"
6806 * - "email"
6807 * - "moat"
6808 * - "hyphae"
6810 * If the option string is unrecognised, a warning will be logged and 0 is
6811 * returned. If the option string contains an invalid character, -1 is
6812 * returned.
6814 STATIC int
6815 check_bridge_distribution_setting(const char *bd)
6817 if (bd == NULL)
6818 return 0;
6820 const char *RECOGNIZED[] = {
6821 "none", "any", "https", "email", "moat", "hyphae"
6823 unsigned i;
6824 for (i = 0; i < ARRAY_LENGTH(RECOGNIZED); ++i) {
6825 if (!strcmp(bd, RECOGNIZED[i]))
6826 return 0;
6829 const char *cp = bd;
6830 // Method = (KeywordChar | "_") +
6831 while (TOR_ISALNUM(*cp) || *cp == '-' || *cp == '_')
6832 ++cp;
6834 if (*cp == 0) {
6835 log_warn(LD_CONFIG, "Unrecognized BridgeDistribution value %s. I'll "
6836 "assume you know what you are doing...", escaped(bd));
6837 return 0; // we reached the end of the string; all is well
6838 } else {
6839 return -1; // we found a bad character in the string.
6844 * Parse port configuration for a single port type.
6846 * Read entries of the "FooPort" type from the list <b>ports</b>. Syntax is
6847 * that FooPort can have any number of entries of the format
6848 * "[Address:][Port] IsolationOptions".
6850 * In log messages, describe the port type as <b>portname</b>.
6852 * If no address is specified, default to <b>defaultaddr</b>. If no
6853 * FooPort is given, default to defaultport (if 0, there is no default).
6855 * If CL_PORT_NO_STREAM_OPTIONS is set in <b>flags</b>, do not allow stream
6856 * isolation options in the FooPort entries.
6858 * If CL_PORT_WARN_NONLOCAL is set in <b>flags</b>, warn if any of the
6859 * ports are not on a local address. If CL_PORT_FORBID_NONLOCAL is set,
6860 * this is a control port with no password set: don't even allow it.
6862 * If CL_PORT_SERVER_OPTIONS is set in <b>flags</b>, do not allow stream
6863 * isolation options in the FooPort entries; instead allow the
6864 * server-port option set.
6866 * If CL_PORT_TAKES_HOSTNAMES is set in <b>flags</b>, allow the options
6867 * {No,}IPv{4,6}Traffic.
6869 * On success, if <b>out</b> is given, add a new port_cfg_t entry to
6870 * <b>out</b> for every port that the client should listen on. Return 0
6871 * on success, -1 on failure.
6873 STATIC int
6874 parse_port_config(smartlist_t *out,
6875 const config_line_t *ports,
6876 const char *portname,
6877 int listener_type,
6878 const char *defaultaddr,
6879 int defaultport,
6880 const unsigned flags)
6882 smartlist_t *elts;
6883 int retval = -1;
6884 const unsigned is_control = (listener_type == CONN_TYPE_CONTROL_LISTENER);
6885 const unsigned is_ext_orport = (listener_type == CONN_TYPE_EXT_OR_LISTENER);
6886 const unsigned allow_no_stream_options = flags & CL_PORT_NO_STREAM_OPTIONS;
6887 const unsigned use_server_options = flags & CL_PORT_SERVER_OPTIONS;
6888 const unsigned warn_nonlocal = flags & CL_PORT_WARN_NONLOCAL;
6889 const unsigned forbid_nonlocal = flags & CL_PORT_FORBID_NONLOCAL;
6890 const unsigned default_to_group_writable =
6891 flags & CL_PORT_DFLT_GROUP_WRITABLE;
6892 const unsigned takes_hostnames = flags & CL_PORT_TAKES_HOSTNAMES;
6893 const unsigned is_unix_socket = flags & CL_PORT_IS_UNIXSOCKET;
6894 int got_zero_port=0, got_nonzero_port=0;
6895 char *unix_socket_path = NULL;
6897 /* If there's no FooPort, then maybe make a default one. */
6898 if (! ports) {
6899 if (defaultport && defaultaddr && out) {
6900 port_cfg_t *cfg = port_cfg_new(is_unix_socket ? strlen(defaultaddr) : 0);
6901 cfg->type = listener_type;
6902 if (is_unix_socket) {
6903 tor_addr_make_unspec(&cfg->addr);
6904 memcpy(cfg->unix_addr, defaultaddr, strlen(defaultaddr) + 1);
6905 cfg->is_unix_addr = 1;
6906 } else {
6907 cfg->port = defaultport;
6908 tor_addr_parse(&cfg->addr, defaultaddr);
6910 cfg->entry_cfg.session_group = SESSION_GROUP_UNSET;
6911 cfg->entry_cfg.isolation_flags = ISO_DEFAULT;
6912 smartlist_add(out, cfg);
6914 return 0;
6917 /* At last we can actually parse the FooPort lines. The syntax is:
6918 * [Addr:](Port|auto) [Options].*/
6919 elts = smartlist_new();
6920 char *addrport = NULL;
6922 for (; ports; ports = ports->next) {
6923 tor_addr_t addr;
6924 int port;
6925 int sessiongroup = SESSION_GROUP_UNSET;
6926 unsigned isolation = ISO_DEFAULT;
6927 int prefer_no_auth = 0;
6928 int socks_iso_keep_alive = 0;
6930 uint16_t ptmp=0;
6931 int ok;
6932 /* This must be kept in sync with port_cfg_new's defaults */
6933 int no_listen = 0, no_advertise = 0, all_addrs = 0,
6934 bind_ipv4_only = 0, bind_ipv6_only = 0,
6935 ipv4_traffic = 1, ipv6_traffic = 1, prefer_ipv6 = 0, dns_request = 1,
6936 onion_traffic = 1,
6937 cache_ipv4 = 0, use_cached_ipv4 = 0,
6938 cache_ipv6 = 0, use_cached_ipv6 = 0,
6939 prefer_ipv6_automap = 1, world_writable = 0, group_writable = 0,
6940 relax_dirmode_check = 0,
6941 has_used_unix_socket_only_option = 0;
6943 int is_unix_tagged_addr = 0;
6944 const char *rest_of_line = NULL;
6945 if (port_cfg_line_extract_addrport(ports->value,
6946 &addrport, &is_unix_tagged_addr, &rest_of_line)<0) {
6947 log_warn(LD_CONFIG, "Invalid %sPort line with unparsable address",
6948 portname);
6949 goto err;
6951 if (strlen(addrport) == 0) {
6952 log_warn(LD_CONFIG, "Invalid %sPort line with no address", portname);
6953 goto err;
6956 /* Split the remainder... */
6957 smartlist_split_string(elts, rest_of_line, NULL,
6958 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
6960 /* Let's start to check if it's a Unix socket path. */
6961 if (is_unix_tagged_addr) {
6962 #ifndef HAVE_SYS_UN_H
6963 log_warn(LD_CONFIG, "Unix sockets not supported on this system.");
6964 goto err;
6965 #endif
6966 unix_socket_path = addrport;
6967 addrport = NULL;
6970 if (unix_socket_path &&
6971 ! conn_listener_type_supports_af_unix(listener_type)) {
6972 log_warn(LD_CONFIG, "%sPort does not support unix sockets", portname);
6973 goto err;
6976 if (unix_socket_path) {
6977 port = 1;
6978 } else if (is_unix_socket) {
6979 if (BUG(!addrport))
6980 goto err; // LCOV_EXCL_LINE unreachable, but coverity can't tell that
6981 unix_socket_path = tor_strdup(addrport);
6982 if (!strcmp(addrport, "0"))
6983 port = 0;
6984 else
6985 port = 1;
6986 } else if (!strcmp(addrport, "auto")) {
6987 port = CFG_AUTO_PORT;
6988 int af = tor_addr_parse(&addr, defaultaddr);
6989 tor_assert(af >= 0);
6990 } else if (!strcasecmpend(addrport, ":auto")) {
6991 char *addrtmp = tor_strndup(addrport, strlen(addrport)-5);
6992 port = CFG_AUTO_PORT;
6993 if (tor_addr_port_lookup(addrtmp, &addr, &ptmp)<0 || ptmp) {
6994 log_warn(LD_CONFIG, "Invalid address '%s' for %sPort",
6995 escaped(addrport), portname);
6996 tor_free(addrtmp);
6997 goto err;
6999 tor_free(addrtmp);
7000 } else {
7001 /* Try parsing integer port before address, because, who knows?
7002 "9050" might be a valid address. */
7003 port = (int) tor_parse_long(addrport, 10, 0, 65535, &ok, NULL);
7004 if (ok) {
7005 int af = tor_addr_parse(&addr, defaultaddr);
7006 tor_assert(af >= 0);
7007 } else if (tor_addr_port_lookup(addrport, &addr, &ptmp) == 0) {
7008 if (ptmp == 0) {
7009 log_warn(LD_CONFIG, "%sPort line has address but no port", portname);
7010 goto err;
7012 port = ptmp;
7013 } else {
7014 log_warn(LD_CONFIG, "Couldn't parse address %s for %sPort",
7015 escaped(addrport), portname);
7016 goto err;
7020 if (unix_socket_path && default_to_group_writable)
7021 group_writable = 1;
7023 /* Now parse the rest of the options, if any. */
7024 if (use_server_options) {
7025 /* This is a server port; parse advertising options */
7026 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
7027 if (!strcasecmp(elt, "NoAdvertise")) {
7028 no_advertise = 1;
7029 } else if (!strcasecmp(elt, "NoListen")) {
7030 no_listen = 1;
7031 #if 0
7032 /* not implemented yet. */
7033 } else if (!strcasecmp(elt, "AllAddrs")) {
7035 all_addrs = 1;
7036 #endif /* 0 */
7037 } else if (!strcasecmp(elt, "IPv4Only")) {
7038 bind_ipv4_only = 1;
7039 } else if (!strcasecmp(elt, "IPv6Only")) {
7040 bind_ipv6_only = 1;
7041 } else {
7042 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
7043 portname, escaped(elt));
7045 } SMARTLIST_FOREACH_END(elt);
7047 if (no_advertise && no_listen) {
7048 log_warn(LD_CONFIG, "Tried to set both NoListen and NoAdvertise "
7049 "on %sPort line '%s'",
7050 portname, escaped(ports->value));
7051 goto err;
7053 if (bind_ipv4_only && bind_ipv6_only) {
7054 log_warn(LD_CONFIG, "Tried to set both IPv4Only and IPv6Only "
7055 "on %sPort line '%s'",
7056 portname, escaped(ports->value));
7057 goto err;
7059 if (bind_ipv4_only && tor_addr_family(&addr) == AF_INET6) {
7060 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv6",
7061 portname);
7062 goto err;
7064 if (bind_ipv6_only && tor_addr_family(&addr) == AF_INET) {
7065 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv4",
7066 portname);
7067 goto err;
7069 } else {
7070 /* This is a client port; parse isolation options */
7071 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
7072 int no = 0, isoflag = 0;
7073 const char *elt_orig = elt;
7075 if (!strcasecmpstart(elt, "SessionGroup=")) {
7076 int group = (int)tor_parse_long(elt+strlen("SessionGroup="),
7077 10, 0, INT_MAX, &ok, NULL);
7078 if (!ok || !allow_no_stream_options) {
7079 log_warn(LD_CONFIG, "Invalid %sPort option '%s'",
7080 portname, escaped(elt));
7081 goto err;
7083 if (sessiongroup >= 0) {
7084 log_warn(LD_CONFIG, "Multiple SessionGroup options on %sPort",
7085 portname);
7086 goto err;
7088 sessiongroup = group;
7089 continue;
7092 if (!strcasecmpstart(elt, "No")) {
7093 no = 1;
7094 elt += 2;
7097 if (!strcasecmp(elt, "GroupWritable")) {
7098 group_writable = !no;
7099 has_used_unix_socket_only_option = 1;
7100 continue;
7101 } else if (!strcasecmp(elt, "WorldWritable")) {
7102 world_writable = !no;
7103 has_used_unix_socket_only_option = 1;
7104 continue;
7105 } else if (!strcasecmp(elt, "RelaxDirModeCheck")) {
7106 relax_dirmode_check = !no;
7107 has_used_unix_socket_only_option = 1;
7108 continue;
7111 if (allow_no_stream_options) {
7112 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
7113 portname, escaped(elt));
7114 continue;
7117 if (takes_hostnames) {
7118 if (!strcasecmp(elt, "IPv4Traffic")) {
7119 ipv4_traffic = ! no;
7120 continue;
7121 } else if (!strcasecmp(elt, "IPv6Traffic")) {
7122 ipv6_traffic = ! no;
7123 continue;
7124 } else if (!strcasecmp(elt, "PreferIPv6")) {
7125 prefer_ipv6 = ! no;
7126 continue;
7127 } else if (!strcasecmp(elt, "DNSRequest")) {
7128 dns_request = ! no;
7129 continue;
7130 } else if (!strcasecmp(elt, "OnionTraffic")) {
7131 onion_traffic = ! no;
7132 continue;
7133 } else if (!strcasecmp(elt, "OnionTrafficOnly")) {
7134 /* Only connect to .onion addresses. Equivalent to
7135 * NoDNSRequest, NoIPv4Traffic, NoIPv6Traffic. The option
7136 * NoOnionTrafficOnly is not supported, it's too confusing. */
7137 if (no) {
7138 log_warn(LD_CONFIG, "Unsupported %sPort option 'No%s'. Use "
7139 "DNSRequest, IPv4Traffic, and/or IPv6Traffic instead.",
7140 portname, escaped(elt));
7141 } else {
7142 ipv4_traffic = ipv6_traffic = dns_request = 0;
7144 continue;
7147 if (!strcasecmp(elt, "CacheIPv4DNS")) {
7148 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
7149 cache_ipv4 = ! no;
7150 continue;
7151 } else if (!strcasecmp(elt, "CacheIPv6DNS")) {
7152 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
7153 cache_ipv6 = ! no;
7154 continue;
7155 } else if (!strcasecmp(elt, "CacheDNS")) {
7156 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
7157 cache_ipv4 = cache_ipv6 = ! no;
7158 continue;
7159 } else if (!strcasecmp(elt, "UseIPv4Cache")) {
7160 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
7161 use_cached_ipv4 = ! no;
7162 continue;
7163 } else if (!strcasecmp(elt, "UseIPv6Cache")) {
7164 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
7165 use_cached_ipv6 = ! no;
7166 continue;
7167 } else if (!strcasecmp(elt, "UseDNSCache")) {
7168 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
7169 use_cached_ipv4 = use_cached_ipv6 = ! no;
7170 continue;
7171 } else if (!strcasecmp(elt, "PreferIPv6Automap")) {
7172 prefer_ipv6_automap = ! no;
7173 continue;
7174 } else if (!strcasecmp(elt, "PreferSOCKSNoAuth")) {
7175 prefer_no_auth = ! no;
7176 continue;
7177 } else if (!strcasecmp(elt, "KeepAliveIsolateSOCKSAuth")) {
7178 socks_iso_keep_alive = ! no;
7179 continue;
7182 if (!strcasecmpend(elt, "s"))
7183 elt[strlen(elt)-1] = '\0'; /* kill plurals. */
7185 if (!strcasecmp(elt, "IsolateDestPort")) {
7186 isoflag = ISO_DESTPORT;
7187 } else if (!strcasecmp(elt, "IsolateDestAddr")) {
7188 isoflag = ISO_DESTADDR;
7189 } else if (!strcasecmp(elt, "IsolateSOCKSAuth")) {
7190 isoflag = ISO_SOCKSAUTH;
7191 } else if (!strcasecmp(elt, "IsolateClientProtocol")) {
7192 isoflag = ISO_CLIENTPROTO;
7193 } else if (!strcasecmp(elt, "IsolateClientAddr")) {
7194 isoflag = ISO_CLIENTADDR;
7195 } else {
7196 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
7197 portname, escaped(elt_orig));
7200 if (no) {
7201 isolation &= ~isoflag;
7202 } else {
7203 isolation |= isoflag;
7205 } SMARTLIST_FOREACH_END(elt);
7208 if (port)
7209 got_nonzero_port = 1;
7210 else
7211 got_zero_port = 1;
7213 if (dns_request == 0 && listener_type == CONN_TYPE_AP_DNS_LISTENER) {
7214 log_warn(LD_CONFIG, "You have a %sPort entry with DNS disabled; that "
7215 "won't work.", portname);
7216 goto err;
7219 if (ipv4_traffic == 0 && ipv6_traffic == 0 && onion_traffic == 0
7220 && listener_type != CONN_TYPE_AP_DNS_LISTENER) {
7221 log_warn(LD_CONFIG, "You have a %sPort entry with all of IPv4 and "
7222 "IPv6 and .onion disabled; that won't work.", portname);
7223 goto err;
7226 if (dns_request == 1 && ipv4_traffic == 0 && ipv6_traffic == 0
7227 && listener_type != CONN_TYPE_AP_DNS_LISTENER) {
7228 log_warn(LD_CONFIG, "You have a %sPort entry with DNSRequest enabled, "
7229 "but IPv4 and IPv6 disabled; DNS-based sites won't work.",
7230 portname);
7231 goto err;
7234 if ( has_used_unix_socket_only_option && ! unix_socket_path) {
7235 log_warn(LD_CONFIG, "You have a %sPort entry with GroupWritable, "
7236 "WorldWritable, or RelaxDirModeCheck, but it is not a "
7237 "unix socket.", portname);
7238 goto err;
7241 if (!(isolation & ISO_SOCKSAUTH) && socks_iso_keep_alive) {
7242 log_warn(LD_CONFIG, "You have a %sPort entry with both "
7243 "NoIsolateSOCKSAuth and KeepAliveIsolateSOCKSAuth set.",
7244 portname);
7245 goto err;
7248 if (unix_socket_path && (isolation & ISO_CLIENTADDR)) {
7249 /* `IsolateClientAddr` is nonsensical in the context of AF_LOCAL.
7250 * just silently remove the isolation flag.
7252 isolation &= ~ISO_CLIENTADDR;
7255 if (out && port) {
7256 size_t namelen = unix_socket_path ? strlen(unix_socket_path) : 0;
7257 port_cfg_t *cfg = port_cfg_new(namelen);
7258 if (unix_socket_path) {
7259 tor_addr_make_unspec(&cfg->addr);
7260 memcpy(cfg->unix_addr, unix_socket_path, namelen + 1);
7261 cfg->is_unix_addr = 1;
7262 tor_free(unix_socket_path);
7263 } else {
7264 tor_addr_copy(&cfg->addr, &addr);
7265 cfg->port = port;
7267 cfg->type = listener_type;
7268 cfg->is_world_writable = world_writable;
7269 cfg->is_group_writable = group_writable;
7270 cfg->relax_dirmode_check = relax_dirmode_check;
7271 cfg->entry_cfg.isolation_flags = isolation;
7272 cfg->entry_cfg.session_group = sessiongroup;
7273 cfg->server_cfg.no_advertise = no_advertise;
7274 cfg->server_cfg.no_listen = no_listen;
7275 cfg->server_cfg.all_addrs = all_addrs;
7276 cfg->server_cfg.bind_ipv4_only = bind_ipv4_only;
7277 cfg->server_cfg.bind_ipv6_only = bind_ipv6_only;
7278 cfg->entry_cfg.ipv4_traffic = ipv4_traffic;
7279 cfg->entry_cfg.ipv6_traffic = ipv6_traffic;
7280 cfg->entry_cfg.prefer_ipv6 = prefer_ipv6;
7281 cfg->entry_cfg.dns_request = dns_request;
7282 cfg->entry_cfg.onion_traffic = onion_traffic;
7283 cfg->entry_cfg.cache_ipv4_answers = cache_ipv4;
7284 cfg->entry_cfg.cache_ipv6_answers = cache_ipv6;
7285 cfg->entry_cfg.use_cached_ipv4_answers = use_cached_ipv4;
7286 cfg->entry_cfg.use_cached_ipv6_answers = use_cached_ipv6;
7287 cfg->entry_cfg.prefer_ipv6_virtaddr = prefer_ipv6_automap;
7288 cfg->entry_cfg.socks_prefer_no_auth = prefer_no_auth;
7289 if (! (isolation & ISO_SOCKSAUTH))
7290 cfg->entry_cfg.socks_prefer_no_auth = 1;
7291 cfg->entry_cfg.socks_iso_keep_alive = socks_iso_keep_alive;
7293 smartlist_add(out, cfg);
7295 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
7296 smartlist_clear(elts);
7297 tor_free(addrport);
7298 tor_free(unix_socket_path);
7301 if (warn_nonlocal && out) {
7302 if (is_control)
7303 warn_nonlocal_controller_ports(out, forbid_nonlocal);
7304 else if (is_ext_orport)
7305 warn_nonlocal_ext_orports(out, portname);
7306 else
7307 warn_nonlocal_client_ports(out, portname, listener_type);
7310 if (got_zero_port && got_nonzero_port) {
7311 log_warn(LD_CONFIG, "You specified a nonzero %sPort along with '%sPort 0' "
7312 "in the same configuration. Did you mean to disable %sPort or "
7313 "not?", portname, portname, portname);
7314 goto err;
7317 retval = 0;
7318 err:
7319 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
7320 smartlist_free(elts);
7321 tor_free(unix_socket_path);
7322 tor_free(addrport);
7323 return retval;
7326 /** Return the number of ports which are actually going to listen with type
7327 * <b>listenertype</b>. Do not count no_listen ports. Only count unix
7328 * sockets if count_sockets is true. */
7329 static int
7330 count_real_listeners(const smartlist_t *ports, int listenertype,
7331 int count_sockets)
7333 int n = 0;
7334 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
7335 if (port->server_cfg.no_listen)
7336 continue;
7337 if (!count_sockets && port->is_unix_addr)
7338 continue;
7339 if (port->type != listenertype)
7340 continue;
7341 ++n;
7342 } SMARTLIST_FOREACH_END(port);
7343 return n;
7346 /** Parse all ports from <b>options</b>. On success, set *<b>n_ports_out</b>
7347 * to the number of ports that are listed, update the *Port_set values in
7348 * <b>options</b>, and return 0. On failure, set *<b>msg</b> to a
7349 * description of the problem and return -1.
7351 * If <b>validate_only</b> is false, set configured_client_ports to the
7352 * new list of ports parsed from <b>options</b>.
7354 static int
7355 parse_ports(or_options_t *options, int validate_only,
7356 char **msg, int *n_ports_out,
7357 int *world_writable_control_socket)
7359 smartlist_t *ports;
7360 int retval = -1;
7362 ports = smartlist_new();
7364 *n_ports_out = 0;
7366 const unsigned gw_flag = options->SocksSocketsGroupWritable ?
7367 CL_PORT_DFLT_GROUP_WRITABLE : 0;
7368 if (parse_port_config(ports,
7369 options->SocksPort_lines,
7370 "Socks", CONN_TYPE_AP_LISTENER,
7371 "127.0.0.1", 9050,
7372 ((validate_only ? 0 : CL_PORT_WARN_NONLOCAL)
7373 | CL_PORT_TAKES_HOSTNAMES | gw_flag)) < 0) {
7374 *msg = tor_strdup("Invalid SocksPort configuration");
7375 goto err;
7377 if (parse_port_config(ports,
7378 options->DNSPort_lines,
7379 "DNS", CONN_TYPE_AP_DNS_LISTENER,
7380 "127.0.0.1", 0,
7381 CL_PORT_WARN_NONLOCAL|CL_PORT_TAKES_HOSTNAMES) < 0) {
7382 *msg = tor_strdup("Invalid DNSPort configuration");
7383 goto err;
7385 if (parse_port_config(ports,
7386 options->TransPort_lines,
7387 "Trans", CONN_TYPE_AP_TRANS_LISTENER,
7388 "127.0.0.1", 0,
7389 CL_PORT_WARN_NONLOCAL) < 0) {
7390 *msg = tor_strdup("Invalid TransPort configuration");
7391 goto err;
7393 if (parse_port_config(ports,
7394 options->NATDPort_lines,
7395 "NATD", CONN_TYPE_AP_NATD_LISTENER,
7396 "127.0.0.1", 0,
7397 CL_PORT_WARN_NONLOCAL) < 0) {
7398 *msg = tor_strdup("Invalid NatdPort configuration");
7399 goto err;
7401 if (parse_port_config(ports,
7402 options->HTTPTunnelPort_lines,
7403 "HTTP Tunnel", CONN_TYPE_AP_HTTP_CONNECT_LISTENER,
7404 "127.0.0.1", 0,
7405 ((validate_only ? 0 : CL_PORT_WARN_NONLOCAL)
7406 | CL_PORT_TAKES_HOSTNAMES | gw_flag)) < 0) {
7407 *msg = tor_strdup("Invalid HTTPTunnelPort configuration");
7408 goto err;
7411 unsigned control_port_flags = CL_PORT_NO_STREAM_OPTIONS |
7412 CL_PORT_WARN_NONLOCAL;
7413 const int any_passwords = (options->HashedControlPassword ||
7414 options->HashedControlSessionPassword ||
7415 options->CookieAuthentication);
7416 if (! any_passwords)
7417 control_port_flags |= CL_PORT_FORBID_NONLOCAL;
7418 if (options->ControlSocketsGroupWritable)
7419 control_port_flags |= CL_PORT_DFLT_GROUP_WRITABLE;
7421 if (parse_port_config(ports,
7422 options->ControlPort_lines,
7423 "Control", CONN_TYPE_CONTROL_LISTENER,
7424 "127.0.0.1", 0,
7425 control_port_flags) < 0) {
7426 *msg = tor_strdup("Invalid ControlPort configuration");
7427 goto err;
7430 if (parse_port_config(ports, options->ControlSocket,
7431 "ControlSocket",
7432 CONN_TYPE_CONTROL_LISTENER, NULL, 0,
7433 control_port_flags | CL_PORT_IS_UNIXSOCKET) < 0) {
7434 *msg = tor_strdup("Invalid ControlSocket configuration");
7435 goto err;
7438 if (! options->ClientOnly) {
7439 if (parse_port_config(ports,
7440 options->ORPort_lines,
7441 "OR", CONN_TYPE_OR_LISTENER,
7442 "0.0.0.0", 0,
7443 CL_PORT_SERVER_OPTIONS) < 0) {
7444 *msg = tor_strdup("Invalid ORPort configuration");
7445 goto err;
7447 if (parse_port_config(ports,
7448 options->ExtORPort_lines,
7449 "ExtOR", CONN_TYPE_EXT_OR_LISTENER,
7450 "127.0.0.1", 0,
7451 CL_PORT_SERVER_OPTIONS|CL_PORT_WARN_NONLOCAL) < 0) {
7452 *msg = tor_strdup("Invalid ExtORPort configuration");
7453 goto err;
7455 if (parse_port_config(ports,
7456 options->DirPort_lines,
7457 "Dir", CONN_TYPE_DIR_LISTENER,
7458 "0.0.0.0", 0,
7459 CL_PORT_SERVER_OPTIONS) < 0) {
7460 *msg = tor_strdup("Invalid DirPort configuration");
7461 goto err;
7465 int n_low_ports = 0;
7466 if (check_server_ports(ports, options, &n_low_ports) < 0) {
7467 *msg = tor_strdup("Misconfigured server ports");
7468 goto err;
7470 if (have_low_ports < 0)
7471 have_low_ports = (n_low_ports > 0);
7473 *n_ports_out = smartlist_len(ports);
7475 retval = 0;
7477 /* Update the *Port_set options. The !! here is to force a boolean out of
7478 an integer. */
7479 options->ORPort_set =
7480 !! count_real_listeners(ports, CONN_TYPE_OR_LISTENER, 0);
7481 options->SocksPort_set =
7482 !! count_real_listeners(ports, CONN_TYPE_AP_LISTENER, 1);
7483 options->TransPort_set =
7484 !! count_real_listeners(ports, CONN_TYPE_AP_TRANS_LISTENER, 1);
7485 options->NATDPort_set =
7486 !! count_real_listeners(ports, CONN_TYPE_AP_NATD_LISTENER, 1);
7487 options->HTTPTunnelPort_set =
7488 !! count_real_listeners(ports, CONN_TYPE_AP_HTTP_CONNECT_LISTENER, 1);
7489 /* Use options->ControlSocket to test if a control socket is set */
7490 options->ControlPort_set =
7491 !! count_real_listeners(ports, CONN_TYPE_CONTROL_LISTENER, 0);
7492 options->DirPort_set =
7493 !! count_real_listeners(ports, CONN_TYPE_DIR_LISTENER, 0);
7494 options->DNSPort_set =
7495 !! count_real_listeners(ports, CONN_TYPE_AP_DNS_LISTENER, 1);
7496 options->ExtORPort_set =
7497 !! count_real_listeners(ports, CONN_TYPE_EXT_OR_LISTENER, 0);
7499 if (world_writable_control_socket) {
7500 SMARTLIST_FOREACH(ports, port_cfg_t *, p,
7501 if (p->type == CONN_TYPE_CONTROL_LISTENER &&
7502 p->is_unix_addr &&
7503 p->is_world_writable) {
7504 *world_writable_control_socket = 1;
7505 break;
7509 if (!validate_only) {
7510 if (configured_ports) {
7511 SMARTLIST_FOREACH(configured_ports,
7512 port_cfg_t *, p, port_cfg_free(p));
7513 smartlist_free(configured_ports);
7515 configured_ports = ports;
7516 ports = NULL; /* prevent free below. */
7519 err:
7520 if (ports) {
7521 SMARTLIST_FOREACH(ports, port_cfg_t *, p, port_cfg_free(p));
7522 smartlist_free(ports);
7524 return retval;
7527 /* Does port bind to IPv4? */
7528 static int
7529 port_binds_ipv4(const port_cfg_t *port)
7531 return tor_addr_family(&port->addr) == AF_INET ||
7532 (tor_addr_family(&port->addr) == AF_UNSPEC
7533 && !port->server_cfg.bind_ipv6_only);
7536 /* Does port bind to IPv6? */
7537 static int
7538 port_binds_ipv6(const port_cfg_t *port)
7540 return tor_addr_family(&port->addr) == AF_INET6 ||
7541 (tor_addr_family(&port->addr) == AF_UNSPEC
7542 && !port->server_cfg.bind_ipv4_only);
7545 /** Given a list of <b>port_cfg_t</b> in <b>ports</b>, check them for internal
7546 * consistency and warn as appropriate. Set *<b>n_low_ports_out</b> to the
7547 * number of sub-1024 ports we will be binding. */
7548 static int
7549 check_server_ports(const smartlist_t *ports,
7550 const or_options_t *options,
7551 int *n_low_ports_out)
7553 int n_orport_advertised = 0;
7554 int n_orport_advertised_ipv4 = 0;
7555 int n_orport_listeners = 0;
7556 int n_dirport_advertised = 0;
7557 int n_dirport_listeners = 0;
7558 int n_low_port = 0;
7559 int r = 0;
7561 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
7562 if (port->type == CONN_TYPE_DIR_LISTENER) {
7563 if (! port->server_cfg.no_advertise)
7564 ++n_dirport_advertised;
7565 if (! port->server_cfg.no_listen)
7566 ++n_dirport_listeners;
7567 } else if (port->type == CONN_TYPE_OR_LISTENER) {
7568 if (! port->server_cfg.no_advertise) {
7569 ++n_orport_advertised;
7570 if (port_binds_ipv4(port))
7571 ++n_orport_advertised_ipv4;
7573 if (! port->server_cfg.no_listen)
7574 ++n_orport_listeners;
7575 } else {
7576 continue;
7578 #ifndef _WIN32
7579 if (!port->server_cfg.no_listen && port->port < 1024)
7580 ++n_low_port;
7581 #endif
7582 } SMARTLIST_FOREACH_END(port);
7584 if (n_orport_advertised && !n_orport_listeners) {
7585 log_warn(LD_CONFIG, "We are advertising an ORPort, but not actually "
7586 "listening on one.");
7587 r = -1;
7589 if (n_orport_listeners && !n_orport_advertised) {
7590 log_warn(LD_CONFIG, "We are listening on an ORPort, but not advertising "
7591 "any ORPorts. This will keep us from building a %s "
7592 "descriptor, and make us impossible to use.",
7593 options->BridgeRelay ? "bridge" : "router");
7594 r = -1;
7596 if (n_dirport_advertised && !n_dirport_listeners) {
7597 log_warn(LD_CONFIG, "We are advertising a DirPort, but not actually "
7598 "listening on one.");
7599 r = -1;
7601 if (n_dirport_advertised > 1) {
7602 log_warn(LD_CONFIG, "Can't advertise more than one DirPort.");
7603 r = -1;
7605 if (n_orport_advertised && !n_orport_advertised_ipv4 &&
7606 !options->BridgeRelay) {
7607 log_warn(LD_CONFIG, "Configured non-bridge only to listen on an IPv6 "
7608 "address.");
7609 r = -1;
7612 if (n_low_port && options->AccountingMax &&
7613 (!have_capability_support() || options->KeepBindCapabilities == 0)) {
7614 const char *extra = "";
7615 if (options->KeepBindCapabilities == 0 && have_capability_support())
7616 extra = ", and you have disabled KeepBindCapabilities.";
7617 log_warn(LD_CONFIG,
7618 "You have set AccountingMax to use hibernation. You have also "
7619 "chosen a low DirPort or OrPort%s."
7620 "This combination can make Tor stop "
7621 "working when it tries to re-attach the port after a period of "
7622 "hibernation. Please choose a different port or turn off "
7623 "hibernation unless you know this combination will work on your "
7624 "platform.", extra);
7627 if (n_low_ports_out)
7628 *n_low_ports_out = n_low_port;
7630 return r;
7633 /** Return a list of port_cfg_t for client ports parsed from the
7634 * options. */
7635 MOCK_IMPL(const smartlist_t *,
7636 get_configured_ports,(void))
7638 if (!configured_ports)
7639 configured_ports = smartlist_new();
7640 return configured_ports;
7643 /** Return an address:port string representation of the address
7644 * where the first <b>listener_type</b> listener waits for
7645 * connections. Return NULL if we couldn't find a listener. The
7646 * string is allocated on the heap and it's the responsibility of the
7647 * caller to free it after use.
7649 * This function is meant to be used by the pluggable transport proxy
7650 * spawning code, please make sure that it fits your purposes before
7651 * using it. */
7652 char *
7653 get_first_listener_addrport_string(int listener_type)
7655 static const char *ipv4_localhost = "127.0.0.1";
7656 static const char *ipv6_localhost = "[::1]";
7657 const char *address;
7658 uint16_t port;
7659 char *string = NULL;
7661 if (!configured_ports)
7662 return NULL;
7664 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
7665 if (cfg->server_cfg.no_listen)
7666 continue;
7668 if (cfg->type == listener_type &&
7669 tor_addr_family(&cfg->addr) != AF_UNSPEC) {
7671 /* We found the first listener of the type we are interested in! */
7673 /* If a listener is listening on INADDR_ANY, assume that it's
7674 also listening on 127.0.0.1, and point the transport proxy
7675 there: */
7676 if (tor_addr_is_null(&cfg->addr))
7677 address = tor_addr_is_v4(&cfg->addr) ? ipv4_localhost : ipv6_localhost;
7678 else
7679 address = fmt_and_decorate_addr(&cfg->addr);
7681 /* If a listener is configured with port 'auto', we are forced
7682 to iterate all listener connections and find out in which
7683 port it ended up listening: */
7684 if (cfg->port == CFG_AUTO_PORT) {
7685 port = router_get_active_listener_port_by_type_af(listener_type,
7686 tor_addr_family(&cfg->addr));
7687 if (!port)
7688 return NULL;
7689 } else {
7690 port = cfg->port;
7693 tor_asprintf(&string, "%s:%u", address, port);
7695 return string;
7698 } SMARTLIST_FOREACH_END(cfg);
7700 return NULL;
7703 /** Return the first advertised port of type <b>listener_type</b> in
7704 * <b>address_family</b>. Returns 0 when no port is found, and when passed
7705 * AF_UNSPEC. */
7707 get_first_advertised_port_by_type_af(int listener_type, int address_family)
7709 if (address_family == AF_UNSPEC)
7710 return 0;
7712 const smartlist_t *conf_ports = get_configured_ports();
7713 SMARTLIST_FOREACH_BEGIN(conf_ports, const port_cfg_t *, cfg) {
7714 if (cfg->type == listener_type &&
7715 !cfg->server_cfg.no_advertise) {
7716 if ((address_family == AF_INET && port_binds_ipv4(cfg)) ||
7717 (address_family == AF_INET6 && port_binds_ipv6(cfg))) {
7718 return cfg->port;
7721 } SMARTLIST_FOREACH_END(cfg);
7722 return 0;
7725 /** Return the first advertised address of type <b>listener_type</b> in
7726 * <b>address_family</b>. Returns NULL if there is no advertised address,
7727 * and when passed AF_UNSPEC. */
7728 const tor_addr_t *
7729 get_first_advertised_addr_by_type_af(int listener_type, int address_family)
7731 if (address_family == AF_UNSPEC)
7732 return NULL;
7733 if (!configured_ports)
7734 return NULL;
7735 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
7736 if (cfg->type == listener_type &&
7737 !cfg->server_cfg.no_advertise) {
7738 if ((address_family == AF_INET && port_binds_ipv4(cfg)) ||
7739 (address_family == AF_INET6 && port_binds_ipv6(cfg))) {
7740 return &cfg->addr;
7743 } SMARTLIST_FOREACH_END(cfg);
7744 return NULL;
7747 /** Return 1 if a port exists of type <b>listener_type</b> on <b>addr</b> and
7748 * <b>port</b>. If <b>check_wildcard</b> is true, INADDR[6]_ANY and AF_UNSPEC
7749 * addresses match any address of the appropriate family; and port -1 matches
7750 * any port.
7751 * To match auto ports, pass CFG_PORT_AUTO. (Does not match on the actual
7752 * automatically chosen listener ports.) */
7754 port_exists_by_type_addr_port(int listener_type, const tor_addr_t *addr,
7755 int port, int check_wildcard)
7757 if (!configured_ports || !addr)
7758 return 0;
7759 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
7760 if (cfg->type == listener_type) {
7761 if (cfg->port == port || (check_wildcard && port == -1)) {
7762 /* Exact match */
7763 if (tor_addr_eq(&cfg->addr, addr)) {
7764 return 1;
7766 /* Skip wildcard matches if we're not doing them */
7767 if (!check_wildcard) {
7768 continue;
7770 /* Wildcard matches IPv4 */
7771 const int cfg_v4 = port_binds_ipv4(cfg);
7772 const int cfg_any_v4 = tor_addr_is_null(&cfg->addr) && cfg_v4;
7773 const int addr_v4 = tor_addr_family(addr) == AF_INET ||
7774 tor_addr_family(addr) == AF_UNSPEC;
7775 const int addr_any_v4 = tor_addr_is_null(&cfg->addr) && addr_v4;
7776 if ((cfg_any_v4 && addr_v4) || (cfg_v4 && addr_any_v4)) {
7777 return 1;
7779 /* Wildcard matches IPv6 */
7780 const int cfg_v6 = port_binds_ipv6(cfg);
7781 const int cfg_any_v6 = tor_addr_is_null(&cfg->addr) && cfg_v6;
7782 const int addr_v6 = tor_addr_family(addr) == AF_INET6 ||
7783 tor_addr_family(addr) == AF_UNSPEC;
7784 const int addr_any_v6 = tor_addr_is_null(&cfg->addr) && addr_v6;
7785 if ((cfg_any_v6 && addr_v6) || (cfg_v6 && addr_any_v6)) {
7786 return 1;
7790 } SMARTLIST_FOREACH_END(cfg);
7791 return 0;
7794 /* Like port_exists_by_type_addr_port, but accepts a host-order IPv4 address
7795 * instead. */
7797 port_exists_by_type_addr32h_port(int listener_type, uint32_t addr_ipv4h,
7798 int port, int check_wildcard)
7800 tor_addr_t ipv4;
7801 tor_addr_from_ipv4h(&ipv4, addr_ipv4h);
7802 return port_exists_by_type_addr_port(listener_type, &ipv4, port,
7803 check_wildcard);
7806 /** Allocate and return a good value for the DataDirectory based on
7807 * <b>val</b>, which may be NULL. Return NULL on failure. */
7808 static char *
7809 get_data_directory(const char *val)
7811 #ifdef _WIN32
7812 if (val) {
7813 return tor_strdup(val);
7814 } else {
7815 return tor_strdup(get_windows_conf_root());
7817 #else /* !(defined(_WIN32)) */
7818 const char *d = val;
7819 if (!d)
7820 d = "~/.tor";
7822 if (!strcmpstart(d, "~/")) {
7823 char *fn = expand_filename(d);
7824 if (!fn) {
7825 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
7826 return NULL;
7828 if (!val && !strcmp(fn,"/.tor")) {
7829 /* If our homedir is /, we probably don't want to use it. */
7830 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
7831 * want. */
7832 log_warn(LD_CONFIG,
7833 "Default DataDirectory is \"~/.tor\". This expands to "
7834 "\"%s\", which is probably not what you want. Using "
7835 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
7836 tor_free(fn);
7837 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
7839 return fn;
7841 return tor_strdup(d);
7842 #endif /* defined(_WIN32) */
7845 /** Check and normalize the values of options->{Key,Data,Cache}Directory;
7846 * return 0 if it is sane, -1 otherwise. */
7847 static int
7848 validate_data_directories(or_options_t *options)
7850 tor_free(options->DataDirectory);
7851 options->DataDirectory = get_data_directory(options->DataDirectory_option);
7852 if (!options->DataDirectory)
7853 return -1;
7854 if (strlen(options->DataDirectory) > (512-128)) {
7855 log_warn(LD_CONFIG, "DataDirectory is too long.");
7856 return -1;
7859 tor_free(options->KeyDirectory);
7860 if (options->KeyDirectory_option) {
7861 options->KeyDirectory = get_data_directory(options->KeyDirectory_option);
7862 if (!options->KeyDirectory)
7863 return -1;
7864 } else {
7865 /* Default to the data directory's keys subdir */
7866 tor_asprintf(&options->KeyDirectory, "%s"PATH_SEPARATOR"keys",
7867 options->DataDirectory);
7870 tor_free(options->CacheDirectory);
7871 if (options->CacheDirectory_option) {
7872 options->CacheDirectory = get_data_directory(
7873 options->CacheDirectory_option);
7874 if (!options->CacheDirectory)
7875 return -1;
7876 } else {
7877 /* Default to the data directory. */
7878 options->CacheDirectory = tor_strdup(options->DataDirectory);
7881 return 0;
7884 /** This string must remain the same forevermore. It is how we
7885 * recognize that the torrc file doesn't need to be backed up. */
7886 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
7887 "if you edit it, comments will not be preserved"
7888 /** This string can change; it tries to give the reader an idea
7889 * that editing this file by hand is not a good plan. */
7890 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
7891 "to torrc.orig.1 or similar, and Tor will ignore it"
7893 /** Save a configuration file for the configuration in <b>options</b>
7894 * into the file <b>fname</b>. If the file already exists, and
7895 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
7896 * replace it. Return 0 on success, -1 on failure. */
7897 static int
7898 write_configuration_file(const char *fname, const or_options_t *options)
7900 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
7901 int rename_old = 0, r;
7903 if (!fname)
7904 return -1;
7906 switch (file_status(fname)) {
7907 /* create backups of old config files, even if they're empty */
7908 case FN_FILE:
7909 case FN_EMPTY:
7910 old_val = read_file_to_str(fname, 0, NULL);
7911 if (!old_val || strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
7912 rename_old = 1;
7914 tor_free(old_val);
7915 break;
7916 case FN_NOENT:
7917 break;
7918 case FN_ERROR:
7919 case FN_DIR:
7920 default:
7921 log_warn(LD_CONFIG,
7922 "Config file \"%s\" is not a file? Failing.", fname);
7923 return -1;
7926 if (!(new_conf = options_dump(options, OPTIONS_DUMP_MINIMAL))) {
7927 log_warn(LD_BUG, "Couldn't get configuration string");
7928 goto err;
7931 tor_asprintf(&new_val, "%s\n%s\n\n%s",
7932 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
7934 if (rename_old) {
7935 int i = 1;
7936 char *fn_tmp = NULL;
7937 while (1) {
7938 tor_asprintf(&fn_tmp, "%s.orig.%d", fname, i);
7939 if (file_status(fn_tmp) == FN_NOENT)
7940 break;
7941 tor_free(fn_tmp);
7942 ++i;
7944 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
7945 if (tor_rename(fname, fn_tmp) < 0) {//XXXX sandbox doesn't allow
7946 log_warn(LD_FS,
7947 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
7948 fname, fn_tmp, strerror(errno));
7949 tor_free(fn_tmp);
7950 goto err;
7952 tor_free(fn_tmp);
7955 if (write_str_to_file(fname, new_val, 0) < 0)
7956 goto err;
7958 r = 0;
7959 goto done;
7960 err:
7961 r = -1;
7962 done:
7963 tor_free(new_val);
7964 tor_free(new_conf);
7965 return r;
7969 * Save the current configuration file value to disk. Return 0 on
7970 * success, -1 on failure.
7973 options_save_current(void)
7975 /* This fails if we can't write to our configuration file.
7977 * If we try falling back to datadirectory or something, we have a better
7978 * chance of saving the configuration, but a better chance of doing
7979 * something the user never expected. */
7980 return write_configuration_file(get_torrc_fname(0), get_options());
7983 /** Return the number of cpus configured in <b>options</b>. If we are
7984 * told to auto-detect the number of cpus, return the auto-detected number. */
7986 get_num_cpus(const or_options_t *options)
7988 if (options->NumCPUs == 0) {
7989 int n = compute_num_cpus();
7990 return (n >= 1) ? n : 1;
7991 } else {
7992 return options->NumCPUs;
7997 * Initialize the libevent library.
7999 static void
8000 init_libevent(const or_options_t *options)
8002 tor_libevent_cfg cfg;
8004 tor_assert(options);
8006 configure_libevent_logging();
8007 /* If the kernel complains that some method (say, epoll) doesn't
8008 * exist, we don't care about it, since libevent will cope.
8010 suppress_libevent_log_msg("Function not implemented");
8012 memset(&cfg, 0, sizeof(cfg));
8013 cfg.num_cpus = get_num_cpus(options);
8014 cfg.msec_per_tick = options->TokenBucketRefillInterval;
8016 tor_libevent_initialize(&cfg);
8018 suppress_libevent_log_msg(NULL);
8021 /** Return a newly allocated string holding a filename relative to the
8022 * directory in <b>options</b> specified by <b>roottype</b>.
8023 * If <b>sub1</b> is present, it is the first path component after
8024 * the data directory. If <b>sub2</b> is also present, it is the second path
8025 * component after the data directory. If <b>suffix</b> is present, it
8026 * is appended to the filename.
8028 * Note: Consider using macros in config.h that wrap this function;
8029 * you should probably never need to call it as-is.
8031 MOCK_IMPL(char *,
8032 options_get_dir_fname2_suffix,(const or_options_t *options,
8033 directory_root_t roottype,
8034 const char *sub1, const char *sub2,
8035 const char *suffix))
8037 tor_assert(options);
8039 const char *rootdir = NULL;
8040 switch (roottype) {
8041 case DIRROOT_DATADIR:
8042 rootdir = options->DataDirectory;
8043 break;
8044 case DIRROOT_CACHEDIR:
8045 rootdir = options->CacheDirectory;
8046 break;
8047 case DIRROOT_KEYDIR:
8048 rootdir = options->KeyDirectory;
8049 break;
8050 default:
8051 tor_assert_unreached();
8052 break;
8054 tor_assert(rootdir);
8056 if (!suffix)
8057 suffix = "";
8059 char *fname = NULL;
8061 if (sub1 == NULL) {
8062 tor_asprintf(&fname, "%s%s", rootdir, suffix);
8063 tor_assert(!sub2); /* If sub2 is present, sub1 must be present. */
8064 } else if (sub2 == NULL) {
8065 tor_asprintf(&fname, "%s"PATH_SEPARATOR"%s%s", rootdir, sub1, suffix);
8066 } else {
8067 tor_asprintf(&fname, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s%s",
8068 rootdir, sub1, sub2, suffix);
8071 return fname;
8074 /** Check wether the data directory has a private subdirectory
8075 * <b>subdir</b>. If not, try to create it. Return 0 on success,
8076 * -1 otherwise. */
8078 check_or_create_data_subdir(const char *subdir)
8080 char *statsdir = get_datadir_fname(subdir);
8081 int return_val = 0;
8083 if (check_private_dir(statsdir, CPD_CREATE, get_options()->User) < 0) {
8084 log_warn(LD_HIST, "Unable to create %s/ directory!", subdir);
8085 return_val = -1;
8087 tor_free(statsdir);
8088 return return_val;
8091 /** Create a file named <b>fname</b> with contents <b>str</b> in the
8092 * subdirectory <b>subdir</b> of the data directory. <b>descr</b>
8093 * should be a short description of the file's content and will be
8094 * used for the warning message, if it's present and the write process
8095 * fails. Return 0 on success, -1 otherwise.*/
8097 write_to_data_subdir(const char* subdir, const char* fname,
8098 const char* str, const char* descr)
8100 char *filename = get_datadir_fname2(subdir, fname);
8101 int return_val = 0;
8103 if (write_str_to_file(filename, str, 0) < 0) {
8104 log_warn(LD_HIST, "Unable to write %s to disk!", descr ? descr : fname);
8105 return_val = -1;
8107 tor_free(filename);
8108 return return_val;
8111 /** Return a smartlist of ports that must be forwarded by
8112 * tor-fw-helper. The smartlist contains the ports in a string format
8113 * that is understandable by tor-fw-helper. */
8114 smartlist_t *
8115 get_list_of_ports_to_forward(void)
8117 smartlist_t *ports_to_forward = smartlist_new();
8118 int port = 0;
8120 /** XXX TODO tor-fw-helper does not support forwarding ports to
8121 other hosts than the local one. If the user is binding to a
8122 different IP address, tor-fw-helper won't work. */
8123 port = router_get_advertised_or_port(get_options()); /* Get ORPort */
8124 if (port)
8125 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
8127 port = router_get_advertised_dir_port(get_options(), 0); /* Get DirPort */
8128 if (port)
8129 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
8131 /* Get ports of transport proxies */
8133 smartlist_t *transport_ports = get_transport_proxy_ports();
8134 if (transport_ports) {
8135 smartlist_add_all(ports_to_forward, transport_ports);
8136 smartlist_free(transport_ports);
8140 if (!smartlist_len(ports_to_forward)) {
8141 smartlist_free(ports_to_forward);
8142 ports_to_forward = NULL;
8145 return ports_to_forward;
8148 /** Helper to implement GETINFO functions about configuration variables (not
8149 * their values). Given a "config/names" question, set *<b>answer</b> to a
8150 * new string describing the supported configuration variables and their
8151 * types. */
8153 getinfo_helper_config(control_connection_t *conn,
8154 const char *question, char **answer,
8155 const char **errmsg)
8157 (void) conn;
8158 (void) errmsg;
8159 if (!strcmp(question, "config/names")) {
8160 smartlist_t *sl = smartlist_new();
8161 int i;
8162 for (i = 0; option_vars_[i].name; ++i) {
8163 const config_var_t *var = &option_vars_[i];
8164 const char *type;
8165 /* don't tell controller about triple-underscore options */
8166 if (!strncmp(option_vars_[i].name, "___", 3))
8167 continue;
8168 switch (var->type) {
8169 case CONFIG_TYPE_STRING: type = "String"; break;
8170 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
8171 case CONFIG_TYPE_UINT: type = "Integer"; break;
8172 case CONFIG_TYPE_INT: type = "SignedInteger"; break;
8173 case CONFIG_TYPE_PORT: type = "Port"; break;
8174 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
8175 case CONFIG_TYPE_MSEC_INTERVAL: type = "TimeMsecInterval"; break;
8176 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
8177 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
8178 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
8179 case CONFIG_TYPE_AUTOBOOL: type = "Boolean+Auto"; break;
8180 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
8181 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
8182 case CONFIG_TYPE_CSV: type = "CommaList"; break;
8183 case CONFIG_TYPE_CSV_INTERVAL: type = "TimeIntervalCommaList"; break;
8184 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
8185 case CONFIG_TYPE_LINELIST_S: type = "Dependent"; break;
8186 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
8187 default:
8188 case CONFIG_TYPE_OBSOLETE:
8189 type = NULL; break;
8191 if (!type)
8192 continue;
8193 smartlist_add_asprintf(sl, "%s %s\n",var->name,type);
8195 *answer = smartlist_join_strings(sl, "", 0, NULL);
8196 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
8197 smartlist_free(sl);
8198 } else if (!strcmp(question, "config/defaults")) {
8199 smartlist_t *sl = smartlist_new();
8200 int dirauth_lines_seen = 0, fallback_lines_seen = 0;
8201 for (int i = 0; option_vars_[i].name; ++i) {
8202 const config_var_t *var = &option_vars_[i];
8203 if (var->initvalue != NULL) {
8204 if (strcmp(option_vars_[i].name, "DirAuthority") == 0) {
8206 * Count dirauth lines we have a default for; we'll use the
8207 * count later to decide whether to add the defaults manually
8209 ++dirauth_lines_seen;
8211 if (strcmp(option_vars_[i].name, "FallbackDir") == 0) {
8213 * Similarly count fallback lines, so that we can decided later
8214 * to add the defaults manually.
8216 ++fallback_lines_seen;
8218 char *val = esc_for_log(var->initvalue);
8219 smartlist_add_asprintf(sl, "%s %s\n",var->name,val);
8220 tor_free(val);
8224 if (dirauth_lines_seen == 0) {
8226 * We didn't see any directory authorities with default values,
8227 * so add the list of default authorities manually.
8231 * default_authorities is defined earlier in this file and
8232 * is a const char ** NULL-terminated array of dirauth config
8233 * lines.
8235 for (const char **i = default_authorities; *i != NULL; ++i) {
8236 char *val = esc_for_log(*i);
8237 smartlist_add_asprintf(sl, "DirAuthority %s\n", val);
8238 tor_free(val);
8242 if (fallback_lines_seen == 0 &&
8243 get_options()->UseDefaultFallbackDirs == 1) {
8245 * We didn't see any explicitly configured fallback mirrors,
8246 * so add the defaults to the list manually.
8248 * default_fallbacks is included earlier in this file and
8249 * is a const char ** NULL-terminated array of fallback config lines.
8251 const char **i;
8253 for (i = default_fallbacks; *i != NULL; ++i) {
8254 char *val = esc_for_log(*i);
8255 smartlist_add_asprintf(sl, "FallbackDir %s\n", val);
8256 tor_free(val);
8260 *answer = smartlist_join_strings(sl, "", 0, NULL);
8261 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
8262 smartlist_free(sl);
8264 return 0;
8267 /* Check whether an address has already been set against the options
8268 * depending on address family and destination type. Any exsting
8269 * value will lead to a fail, even if it is the same value. If not
8270 * set and not only validating, copy it into this location too.
8271 * Returns 0 on success or -1 if this address is already set.
8273 static int
8274 verify_and_store_outbound_address(sa_family_t family, tor_addr_t *addr,
8275 outbound_addr_t type, or_options_t *options, int validate_only)
8277 if (type>=OUTBOUND_ADDR_MAX || (family!=AF_INET && family!=AF_INET6)) {
8278 return -1;
8280 int fam_index=0;
8281 if (family==AF_INET6) {
8282 fam_index=1;
8284 tor_addr_t *dest=&options->OutboundBindAddresses[type][fam_index];
8285 if (!tor_addr_is_null(dest)) {
8286 return -1;
8288 if (!validate_only) {
8289 tor_addr_copy(dest, addr);
8291 return 0;
8294 /* Parse a list of address lines for a specific destination type.
8295 * Will store them into the options if not validate_only. If a
8296 * problem occurs, a suitable error message is store in msg.
8297 * Returns 0 on success or -1 if any address is already set.
8299 static int
8300 parse_outbound_address_lines(const config_line_t *lines, outbound_addr_t type,
8301 or_options_t *options, int validate_only, char **msg)
8303 tor_addr_t addr;
8304 sa_family_t family;
8305 while (lines) {
8306 family = tor_addr_parse(&addr, lines->value);
8307 if (verify_and_store_outbound_address(family, &addr, type,
8308 options, validate_only)) {
8309 if (msg)
8310 tor_asprintf(msg, "Multiple%s%s outbound bind addresses "
8311 "configured: %s",
8312 family==AF_INET?" IPv4":(family==AF_INET6?" IPv6":""),
8313 type==OUTBOUND_ADDR_OR?" OR":
8314 (type==OUTBOUND_ADDR_EXIT?" exit":""), lines->value);
8315 return -1;
8317 lines = lines->next;
8319 return 0;
8322 /** Parse outbound bind address option lines. If <b>validate_only</b>
8323 * is not 0 update OutboundBindAddresses in <b>options</b>.
8324 * Only one address can be set for any of these values.
8325 * On failure, set <b>msg</b> (if provided) to a newly allocated string
8326 * containing a description of the problem and return -1.
8328 static int
8329 parse_outbound_addresses(or_options_t *options, int validate_only, char **msg)
8331 if (!validate_only) {
8332 memset(&options->OutboundBindAddresses, 0,
8333 sizeof(options->OutboundBindAddresses));
8336 if (parse_outbound_address_lines(options->OutboundBindAddress,
8337 OUTBOUND_ADDR_EXIT_AND_OR, options,
8338 validate_only, msg) < 0) {
8339 goto err;
8342 if (parse_outbound_address_lines(options->OutboundBindAddressOR,
8343 OUTBOUND_ADDR_OR, options, validate_only,
8344 msg) < 0) {
8345 goto err;
8348 if (parse_outbound_address_lines(options->OutboundBindAddressExit,
8349 OUTBOUND_ADDR_EXIT, options, validate_only,
8350 msg) < 0) {
8351 goto err;
8354 return 0;
8355 err:
8356 return -1;
8359 /** Load one of the geoip files, <a>family</a> determining which
8360 * one. <a>default_fname</a> is used if on Windows and
8361 * <a>fname</a> equals "<default>". */
8362 static void
8363 config_load_geoip_file_(sa_family_t family,
8364 const char *fname,
8365 const char *default_fname)
8367 #ifdef _WIN32
8368 char *free_fname = NULL; /* Used to hold any temporary-allocated value */
8369 /* XXXX Don't use this "<default>" junk; make our filename options
8370 * understand prefixes somehow. -NM */
8371 if (!strcmp(fname, "<default>")) {
8372 const char *conf_root = get_windows_conf_root();
8373 tor_asprintf(&free_fname, "%s\\%s", conf_root, default_fname);
8374 fname = free_fname;
8376 geoip_load_file(family, fname);
8377 tor_free(free_fname);
8378 #else /* !(defined(_WIN32)) */
8379 (void)default_fname;
8380 geoip_load_file(family, fname);
8381 #endif /* defined(_WIN32) */
8384 /** Load geoip files for IPv4 and IPv6 if <a>options</a> and
8385 * <a>old_options</a> indicate we should. */
8386 static void
8387 config_maybe_load_geoip_files_(const or_options_t *options,
8388 const or_options_t *old_options)
8390 /* XXXX Reload GeoIPFile on SIGHUP. -NM */
8392 if (options->GeoIPFile &&
8393 ((!old_options || !opt_streq(old_options->GeoIPFile,
8394 options->GeoIPFile))
8395 || !geoip_is_loaded(AF_INET)))
8396 config_load_geoip_file_(AF_INET, options->GeoIPFile, "geoip");
8397 if (options->GeoIPv6File &&
8398 ((!old_options || !opt_streq(old_options->GeoIPv6File,
8399 options->GeoIPv6File))
8400 || !geoip_is_loaded(AF_INET6)))
8401 config_load_geoip_file_(AF_INET6, options->GeoIPv6File, "geoip6");
8404 /** Initialize cookie authentication (used so far by the ControlPort
8405 * and Extended ORPort).
8407 * Allocate memory and create a cookie (of length <b>cookie_len</b>)
8408 * in <b>cookie_out</b>.
8409 * Then write it down to <b>fname</b> and prepend it with <b>header</b>.
8411 * If <b>group_readable</b> is set, set <b>fname</b> to be readable
8412 * by the default GID.
8414 * If the whole procedure was successful, set
8415 * <b>cookie_is_set_out</b> to True. */
8417 init_cookie_authentication(const char *fname, const char *header,
8418 int cookie_len, int group_readable,
8419 uint8_t **cookie_out, int *cookie_is_set_out)
8421 char cookie_file_str_len = strlen(header) + cookie_len;
8422 char *cookie_file_str = tor_malloc(cookie_file_str_len);
8423 int retval = -1;
8425 /* We don't want to generate a new cookie every time we call
8426 * options_act(). One should be enough. */
8427 if (*cookie_is_set_out) {
8428 retval = 0; /* we are all set */
8429 goto done;
8432 /* If we've already set the cookie, free it before re-setting
8433 it. This can happen if we previously generated a cookie, but
8434 couldn't write it to a disk. */
8435 if (*cookie_out)
8436 tor_free(*cookie_out);
8438 /* Generate the cookie */
8439 *cookie_out = tor_malloc(cookie_len);
8440 crypto_rand((char *)*cookie_out, cookie_len);
8442 /* Create the string that should be written on the file. */
8443 memcpy(cookie_file_str, header, strlen(header));
8444 memcpy(cookie_file_str+strlen(header), *cookie_out, cookie_len);
8445 if (write_bytes_to_file(fname, cookie_file_str, cookie_file_str_len, 1)) {
8446 log_warn(LD_FS,"Error writing auth cookie to %s.", escaped(fname));
8447 goto done;
8450 #ifndef _WIN32
8451 if (group_readable) {
8452 if (chmod(fname, 0640)) {
8453 log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
8456 #else /* !(!defined(_WIN32)) */
8457 (void) group_readable;
8458 #endif /* !defined(_WIN32) */
8460 /* Success! */
8461 log_info(LD_GENERAL, "Generated auth cookie file in '%s'.", escaped(fname));
8462 *cookie_is_set_out = 1;
8463 retval = 0;
8465 done:
8466 memwipe(cookie_file_str, 0, cookie_file_str_len);
8467 tor_free(cookie_file_str);
8468 return retval;