Add Coccinelle patch for replacing NULL/non-NULL tt_assert().
[tor.git] / src / or / config.c
blob30853724e499b88cda4fcad22603b2814a9ec0bc
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 "geoip.h"
86 #include "hibernate.h"
87 #include "main.h"
88 #include "networkstatus.h"
89 #include "nodelist.h"
90 #include "policies.h"
91 #include "relay.h"
92 #include "rendclient.h"
93 #include "rendservice.h"
94 #include "hs_config.h"
95 #include "rephist.h"
96 #include "router.h"
97 #include "sandbox.h"
98 #include "util.h"
99 #include "routerlist.h"
100 #include "routerset.h"
101 #include "scheduler.h"
102 #include "statefile.h"
103 #include "transports.h"
104 #include "ext_orport.h"
105 #ifdef _WIN32
106 #include <shlobj.h>
107 #endif
109 #include "procmon.h"
111 #ifdef HAVE_SYSTEMD
112 # if defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__)
113 /* Systemd's use of gcc's __INCLUDE_LEVEL__ extension macro appears to confuse
114 * Coverity. Here's a kludge to unconfuse it.
116 # define __INCLUDE_LEVEL__ 2
117 # endif
118 #include <systemd/sd-daemon.h>
119 #endif
121 /* Prefix used to indicate a Unix socket in a FooPort configuration. */
122 static const char unix_socket_prefix[] = "unix:";
123 /* Prefix used to indicate a Unix socket with spaces in it, in a FooPort
124 * configuration. */
125 static const char unix_q_socket_prefix[] = "unix:\"";
127 /** A list of abbreviations and aliases to map command-line options, obsolete
128 * option names, or alternative option names, to their current values. */
129 static config_abbrev_t option_abbrevs_[] = {
130 PLURAL(AuthDirBadDirCC),
131 PLURAL(AuthDirBadExitCC),
132 PLURAL(AuthDirInvalidCC),
133 PLURAL(AuthDirRejectCC),
134 PLURAL(EntryNode),
135 PLURAL(ExcludeNode),
136 PLURAL(Tor2webRendezvousPoint),
137 PLURAL(FirewallPort),
138 PLURAL(LongLivedPort),
139 PLURAL(HiddenServiceNode),
140 PLURAL(HiddenServiceExcludeNode),
141 PLURAL(NumCPU),
142 PLURAL(RendNode),
143 PLURAL(RecommendedPackage),
144 PLURAL(RendExcludeNode),
145 PLURAL(StrictEntryNode),
146 PLURAL(StrictExitNode),
147 PLURAL(StrictNode),
148 { "l", "Log", 1, 0},
149 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
150 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
151 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
152 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
153 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
154 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
155 { "DirServer", "DirAuthority", 0, 0}, /* XXXX later, make this warn? */
156 { "MaxConn", "ConnLimit", 0, 1},
157 { "MaxMemInCellQueues", "MaxMemInQueues", 0, 0},
158 { "ORBindAddress", "ORListenAddress", 0, 0},
159 { "DirBindAddress", "DirListenAddress", 0, 0},
160 { "SocksBindAddress", "SocksListenAddress", 0, 0},
161 { "UseHelperNodes", "UseEntryGuards", 0, 0},
162 { "NumHelperNodes", "NumEntryGuards", 0, 0},
163 { "UseEntryNodes", "UseEntryGuards", 0, 0},
164 { "NumEntryNodes", "NumEntryGuards", 0, 0},
165 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
166 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
167 { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0},
168 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
169 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
170 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
171 { "VirtualAddrNetwork", "VirtualAddrNetworkIPv4", 0, 0},
172 { NULL, NULL, 0, 0},
175 /** An entry for config_vars: "The option <b>name</b> has type
176 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
177 * or_options_t.<b>member</b>"
179 #define VAR(name,conftype,member,initvalue) \
180 { name, CONFIG_TYPE_ ## conftype, offsetof(or_options_t, member), \
181 initvalue }
182 /** As VAR, but the option name and member name are the same. */
183 #define V(member,conftype,initvalue) \
184 VAR(#member, conftype, member, initvalue)
185 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
186 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
189 * Macro to declare *Port options. Each one comes in three entries.
190 * For example, most users should use "SocksPort" to configure the
191 * socks port, but TorBrowser wants to use __SocksPort so that it
192 * isn't stored by SAVECONF. The SocksPortLines virtual option is
193 * used to query both options from the controller.
195 #define VPORT(member) \
196 VAR(#member "Lines", LINELIST_V, member ## _lines, NULL), \
197 VAR(#member, LINELIST_S, member ## _lines, NULL), \
198 VAR("__" #member, LINELIST_S, member ## _lines, NULL)
200 /** Array of configuration options. Until we disallow nonstandard
201 * abbreviations, order is significant, since the first matching option will
202 * be chosen first.
204 static config_var_t option_vars_[] = {
205 V(AccountingMax, MEMUNIT, "0 bytes"),
206 VAR("AccountingRule", STRING, AccountingRule_option, "max"),
207 V(AccountingStart, STRING, NULL),
208 V(Address, STRING, NULL),
209 V(AllowDotExit, BOOL, "0"),
210 OBSOLETE("AllowInvalidNodes"),
211 V(AllowNonRFC953Hostnames, BOOL, "0"),
212 OBSOLETE("AllowSingleHopCircuits"),
213 OBSOLETE("AllowSingleHopExits"),
214 V(AlternateBridgeAuthority, LINELIST, NULL),
215 V(AlternateDirAuthority, LINELIST, NULL),
216 OBSOLETE("AlternateHSAuthority"),
217 V(AssumeReachable, BOOL, "0"),
218 OBSOLETE("AuthDirBadDir"),
219 OBSOLETE("AuthDirBadDirCCs"),
220 V(AuthDirBadExit, LINELIST, NULL),
221 V(AuthDirBadExitCCs, CSV, ""),
222 V(AuthDirInvalid, LINELIST, NULL),
223 V(AuthDirInvalidCCs, CSV, ""),
224 V(AuthDirFastGuarantee, MEMUNIT, "100 KB"),
225 V(AuthDirGuardBWGuarantee, MEMUNIT, "2 MB"),
226 V(AuthDirPinKeys, BOOL, "1"),
227 V(AuthDirReject, LINELIST, NULL),
228 V(AuthDirRejectCCs, CSV, ""),
229 OBSOLETE("AuthDirRejectUnlisted"),
230 OBSOLETE("AuthDirListBadDirs"),
231 V(AuthDirListBadExits, BOOL, "0"),
232 V(AuthDirMaxServersPerAddr, UINT, "2"),
233 OBSOLETE("AuthDirMaxServersPerAuthAddr"),
234 V(AuthDirHasIPv6Connectivity, BOOL, "0"),
235 VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
236 V(AutomapHostsOnResolve, BOOL, "0"),
237 V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
238 V(AvoidDiskWrites, BOOL, "0"),
239 V(BandwidthBurst, MEMUNIT, "1 GB"),
240 V(BandwidthRate, MEMUNIT, "1 GB"),
241 V(BridgeAuthoritativeDir, BOOL, "0"),
242 VAR("Bridge", LINELIST, Bridges, NULL),
243 V(BridgePassword, STRING, NULL),
244 V(BridgeRecordUsageByCountry, BOOL, "1"),
245 V(BridgeRelay, BOOL, "0"),
246 V(CellStatistics, BOOL, "0"),
247 V(PaddingStatistics, BOOL, "1"),
248 V(LearnCircuitBuildTimeout, BOOL, "1"),
249 V(CircuitBuildTimeout, INTERVAL, "0"),
250 OBSOLETE("CircuitIdleTimeout"),
251 V(CircuitsAvailableTimeout, INTERVAL, "0"),
252 V(CircuitStreamTimeout, INTERVAL, "0"),
253 V(CircuitPriorityHalflife, DOUBLE, "-100.0"), /*negative:'Use default'*/
254 V(ClientDNSRejectInternalAddresses, BOOL,"1"),
255 V(ClientOnly, BOOL, "0"),
256 V(ClientPreferIPv6ORPort, AUTOBOOL, "auto"),
257 V(ClientPreferIPv6DirPort, AUTOBOOL, "auto"),
258 V(ClientRejectInternalAddresses, BOOL, "1"),
259 V(ClientTransportPlugin, LINELIST, NULL),
260 V(ClientUseIPv6, BOOL, "0"),
261 V(ClientUseIPv4, BOOL, "1"),
262 V(ConsensusParams, STRING, NULL),
263 V(ConnLimit, UINT, "1000"),
264 V(ConnDirectionStatistics, BOOL, "0"),
265 V(ConstrainedSockets, BOOL, "0"),
266 V(ConstrainedSockSize, MEMUNIT, "8192"),
267 V(ContactInfo, STRING, NULL),
268 OBSOLETE("ControlListenAddress"),
269 VPORT(ControlPort),
270 V(ControlPortFileGroupReadable,BOOL, "0"),
271 V(ControlPortWriteToFile, FILENAME, NULL),
272 V(ControlSocket, LINELIST, NULL),
273 V(ControlSocketsGroupWritable, BOOL, "0"),
274 V(SocksSocketsGroupWritable, BOOL, "0"),
275 V(CookieAuthentication, BOOL, "0"),
276 V(CookieAuthFileGroupReadable, BOOL, "0"),
277 V(CookieAuthFile, STRING, NULL),
278 V(CountPrivateBandwidth, BOOL, "0"),
279 V(DataDirectory, FILENAME, NULL),
280 V(DataDirectoryGroupReadable, BOOL, "0"),
281 V(DisableOOSCheck, BOOL, "1"),
282 V(DisableNetwork, BOOL, "0"),
283 V(DirAllowPrivateAddresses, BOOL, "0"),
284 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
285 OBSOLETE("DirListenAddress"),
286 V(DirPolicy, LINELIST, NULL),
287 VPORT(DirPort),
288 V(DirPortFrontPage, FILENAME, NULL),
289 VAR("DirReqStatistics", BOOL, DirReqStatistics_option, "1"),
290 VAR("DirAuthority", LINELIST, DirAuthorities, NULL),
291 V(DirCache, BOOL, "1"),
292 V(DirAuthorityFallbackRate, DOUBLE, "1.0"),
293 V(DisableAllSwap, BOOL, "0"),
294 V(DisableDebuggerAttachment, BOOL, "1"),
295 OBSOLETE("DisableIOCP"),
296 OBSOLETE("DisableV2DirectoryInfo_"),
297 OBSOLETE("DynamicDHGroups"),
298 VPORT(DNSPort),
299 OBSOLETE("DNSListenAddress"),
300 V(DownloadExtraInfo, BOOL, "0"),
301 V(TestingEnableConnBwEvent, BOOL, "0"),
302 V(TestingEnableCellStatsEvent, BOOL, "0"),
303 V(TestingEnableTbEmptyEvent, BOOL, "0"),
304 V(EnforceDistinctSubnets, BOOL, "1"),
305 V(EntryNodes, ROUTERSET, NULL),
306 V(EntryStatistics, BOOL, "0"),
307 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
308 V(ExcludeNodes, ROUTERSET, NULL),
309 V(ExcludeExitNodes, ROUTERSET, NULL),
310 OBSOLETE("ExcludeSingleHopRelays"),
311 V(ExitNodes, ROUTERSET, NULL),
312 V(ExitPolicy, LINELIST, NULL),
313 V(ExitPolicyRejectPrivate, BOOL, "1"),
314 V(ExitPolicyRejectLocalInterfaces, BOOL, "0"),
315 V(ExitPortStatistics, BOOL, "0"),
316 V(ExtendAllowPrivateAddresses, BOOL, "0"),
317 V(ExitRelay, AUTOBOOL, "auto"),
318 VPORT(ExtORPort),
319 V(ExtORPortCookieAuthFile, STRING, NULL),
320 V(ExtORPortCookieAuthFileGroupReadable, BOOL, "0"),
321 V(ExtraInfoStatistics, BOOL, "1"),
322 V(ExtendByEd25519ID, AUTOBOOL, "auto"),
323 V(FallbackDir, LINELIST, NULL),
325 V(UseDefaultFallbackDirs, BOOL, "1"),
327 OBSOLETE("FallbackNetworkstatusFile"),
328 V(FascistFirewall, BOOL, "0"),
329 V(FirewallPorts, CSV, ""),
330 OBSOLETE("FastFirstHopPK"),
331 V(FetchDirInfoEarly, BOOL, "0"),
332 V(FetchDirInfoExtraEarly, BOOL, "0"),
333 V(FetchServerDescriptors, BOOL, "1"),
334 V(FetchHidServDescriptors, BOOL, "1"),
335 V(FetchUselessDescriptors, BOOL, "0"),
336 OBSOLETE("FetchV2Networkstatus"),
337 V(GeoIPExcludeUnknown, AUTOBOOL, "auto"),
338 #ifdef _WIN32
339 V(GeoIPFile, FILENAME, "<default>"),
340 V(GeoIPv6File, FILENAME, "<default>"),
341 #else
342 V(GeoIPFile, FILENAME,
343 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
344 V(GeoIPv6File, FILENAME,
345 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip6"),
346 #endif
347 OBSOLETE("Group"),
348 V(GuardLifetime, INTERVAL, "0 minutes"),
349 V(HardwareAccel, BOOL, "0"),
350 V(HeartbeatPeriod, INTERVAL, "6 hours"),
351 V(AccelName, STRING, NULL),
352 V(AccelDir, FILENAME, NULL),
353 V(HashedControlPassword, LINELIST, NULL),
354 OBSOLETE("HidServDirectoryV2"),
355 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
356 VAR("HiddenServiceDirGroupReadable", LINELIST_S, RendConfigLines, NULL),
357 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
358 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
359 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
360 VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
361 VAR("HiddenServiceAllowUnknownPorts",LINELIST_S, RendConfigLines, NULL),
362 VAR("HiddenServiceMaxStreams",LINELIST_S, RendConfigLines, NULL),
363 VAR("HiddenServiceMaxStreamsCloseCircuit",LINELIST_S, RendConfigLines, NULL),
364 VAR("HiddenServiceNumIntroductionPoints", LINELIST_S, RendConfigLines, NULL),
365 VAR("HiddenServiceStatistics", BOOL, HiddenServiceStatistics_option, "1"),
366 V(HidServAuth, LINELIST, NULL),
367 OBSOLETE("CloseHSClientCircuitsImmediatelyOnTimeout"),
368 OBSOLETE("CloseHSServiceRendCircuitsImmediatelyOnTimeout"),
369 V(HiddenServiceSingleHopMode, BOOL, "0"),
370 V(HiddenServiceNonAnonymousMode,BOOL, "0"),
371 V(HTTPProxy, STRING, NULL),
372 V(HTTPProxyAuthenticator, STRING, NULL),
373 V(HTTPSProxy, STRING, NULL),
374 V(HTTPSProxyAuthenticator, STRING, NULL),
375 V(IPv6Exit, BOOL, "0"),
376 VAR("ServerTransportPlugin", LINELIST, ServerTransportPlugin, NULL),
377 V(ServerTransportListenAddr, LINELIST, NULL),
378 V(ServerTransportOptions, LINELIST, NULL),
379 V(SigningKeyLifetime, INTERVAL, "30 days"),
380 V(Socks4Proxy, STRING, NULL),
381 V(Socks5Proxy, STRING, NULL),
382 V(Socks5ProxyUsername, STRING, NULL),
383 V(Socks5ProxyPassword, STRING, NULL),
384 V(KeepalivePeriod, INTERVAL, "5 minutes"),
385 V(KeepBindCapabilities, AUTOBOOL, "auto"),
386 VAR("Log", LINELIST, Logs, NULL),
387 V(LogMessageDomains, BOOL, "0"),
388 V(LogTimeGranularity, MSEC_INTERVAL, "1 second"),
389 V(TruncateLogFile, BOOL, "0"),
390 V(SyslogIdentityTag, STRING, NULL),
391 V(LongLivedPorts, CSV,
392 "21,22,706,1863,5050,5190,5222,5223,6523,6667,6697,8300"),
393 VAR("MapAddress", LINELIST, AddressMap, NULL),
394 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
395 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
396 V(MaxClientCircuitsPending, UINT, "32"),
397 V(MaxConsensusAgeForDiffs, INTERVAL, "0 seconds"),
398 VAR("MaxMemInQueues", MEMUNIT, MaxMemInQueues_raw, "0"),
399 OBSOLETE("MaxOnionsPending"),
400 V(MaxOnionQueueDelay, MSEC_INTERVAL, "1750 msec"),
401 V(MaxUnparseableDescSizeToLog, MEMUNIT, "10 MB"),
402 V(MinMeasuredBWsForAuthToIgnoreAdvertised, INT, "500"),
403 VAR("MyFamily", LINELIST, MyFamily_lines, NULL),
404 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
405 OBSOLETE("NamingAuthoritativeDirectory"),
406 OBSOLETE("NATDListenAddress"),
407 VPORT(NATDPort),
408 V(Nickname, STRING, NULL),
409 OBSOLETE("PredictedPortsRelevanceTime"),
410 OBSOLETE("WarnUnsafeSocks"),
411 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
412 V(NoExec, BOOL, "0"),
413 V(NumCPUs, UINT, "0"),
414 V(NumDirectoryGuards, UINT, "0"),
415 V(NumEntryGuards, UINT, "0"),
416 V(OfflineMasterKey, BOOL, "0"),
417 OBSOLETE("ORListenAddress"),
418 VPORT(ORPort),
419 V(OutboundBindAddress, LINELIST, NULL),
420 V(OutboundBindAddressOR, LINELIST, NULL),
421 V(OutboundBindAddressExit, LINELIST, NULL),
423 OBSOLETE("PathBiasDisableRate"),
424 V(PathBiasCircThreshold, INT, "-1"),
425 V(PathBiasNoticeRate, DOUBLE, "-1"),
426 V(PathBiasWarnRate, DOUBLE, "-1"),
427 V(PathBiasExtremeRate, DOUBLE, "-1"),
428 V(PathBiasScaleThreshold, INT, "-1"),
429 OBSOLETE("PathBiasScaleFactor"),
430 OBSOLETE("PathBiasMultFactor"),
431 V(PathBiasDropGuards, AUTOBOOL, "0"),
432 OBSOLETE("PathBiasUseCloseCounts"),
434 V(PathBiasUseThreshold, INT, "-1"),
435 V(PathBiasNoticeUseRate, DOUBLE, "-1"),
436 V(PathBiasExtremeUseRate, DOUBLE, "-1"),
437 V(PathBiasScaleUseThreshold, INT, "-1"),
439 V(PathsNeededToBuildCircuits, DOUBLE, "-1"),
440 V(PerConnBWBurst, MEMUNIT, "0"),
441 V(PerConnBWRate, MEMUNIT, "0"),
442 V(PidFile, STRING, NULL),
443 V(TestingTorNetwork, BOOL, "0"),
444 V(TestingMinExitFlagThreshold, MEMUNIT, "0"),
445 V(TestingMinFastFlagThreshold, MEMUNIT, "0"),
447 V(TestingLinkCertLifetime, INTERVAL, "2 days"),
448 V(TestingAuthKeyLifetime, INTERVAL, "2 days"),
449 V(TestingLinkKeySlop, INTERVAL, "3 hours"),
450 V(TestingAuthKeySlop, INTERVAL, "3 hours"),
451 V(TestingSigningKeySlop, INTERVAL, "1 day"),
453 V(OptimisticData, AUTOBOOL, "auto"),
454 V(PortForwarding, BOOL, "0"),
455 V(PortForwardingHelper, FILENAME, "tor-fw-helper"),
456 OBSOLETE("PreferTunneledDirConns"),
457 V(ProtocolWarnings, BOOL, "0"),
458 V(PublishServerDescriptor, CSV, "1"),
459 V(PublishHidServDescriptors, BOOL, "1"),
460 V(ReachableAddresses, LINELIST, NULL),
461 V(ReachableDirAddresses, LINELIST, NULL),
462 V(ReachableORAddresses, LINELIST, NULL),
463 V(RecommendedVersions, LINELIST, NULL),
464 V(RecommendedClientVersions, LINELIST, NULL),
465 V(RecommendedServerVersions, LINELIST, NULL),
466 V(RecommendedPackages, LINELIST, NULL),
467 V(ReducedConnectionPadding, BOOL, "0"),
468 V(ConnectionPadding, AUTOBOOL, "auto"),
469 V(RefuseUnknownExits, AUTOBOOL, "auto"),
470 V(RejectPlaintextPorts, CSV, ""),
471 V(RelayBandwidthBurst, MEMUNIT, "0"),
472 V(RelayBandwidthRate, MEMUNIT, "0"),
473 V(RendPostPeriod, INTERVAL, "1 hour"),
474 V(RephistTrackTime, INTERVAL, "24 hours"),
475 V(RunAsDaemon, BOOL, "0"),
476 OBSOLETE("RunTesting"), // currently unused
477 V(Sandbox, BOOL, "0"),
478 V(SafeLogging, STRING, "1"),
479 V(SafeSocks, BOOL, "0"),
480 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
481 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
482 V(ServerDNSDetectHijacking, BOOL, "1"),
483 V(ServerDNSRandomizeCase, BOOL, "1"),
484 V(ServerDNSResolvConfFile, STRING, NULL),
485 V(ServerDNSSearchDomains, BOOL, "0"),
486 V(ServerDNSTestAddresses, CSV,
487 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
488 V(SchedulerLowWaterMark__, MEMUNIT, "100 MB"),
489 V(SchedulerHighWaterMark__, MEMUNIT, "101 MB"),
490 V(SchedulerMaxFlushCells__, UINT, "1000"),
491 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
492 OBSOLETE("SocksListenAddress"),
493 V(SocksPolicy, LINELIST, NULL),
494 VPORT(SocksPort),
495 V(SocksTimeout, INTERVAL, "2 minutes"),
496 V(SSLKeyLifetime, INTERVAL, "0"),
497 OBSOLETE("StrictEntryNodes"),
498 OBSOLETE("StrictExitNodes"),
499 V(StrictNodes, BOOL, "0"),
500 OBSOLETE("Support022HiddenServices"),
501 V(TestSocks, BOOL, "0"),
502 V(TokenBucketRefillInterval, MSEC_INTERVAL, "100 msec"),
503 V(Tor2webMode, BOOL, "0"),
504 V(Tor2webRendezvousPoints, ROUTERSET, NULL),
505 OBSOLETE("TLSECGroup"),
506 V(TrackHostExits, CSV, NULL),
507 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
508 OBSOLETE("TransListenAddress"),
509 VPORT(TransPort),
510 V(TransProxyType, STRING, "default"),
511 OBSOLETE("TunnelDirConns"),
512 V(UpdateBridgesFromAuthority, BOOL, "0"),
513 V(UseBridges, BOOL, "0"),
514 VAR("UseEntryGuards", BOOL, UseEntryGuards_option, "1"),
515 OBSOLETE("UseEntryGuardsAsDirGuards"),
516 V(UseGuardFraction, AUTOBOOL, "auto"),
517 V(UseMicrodescriptors, AUTOBOOL, "auto"),
518 OBSOLETE("UseNTorHandshake"),
519 V(User, STRING, NULL),
520 OBSOLETE("UserspaceIOCPBuffers"),
521 V(AuthDirSharedRandomness, BOOL, "1"),
522 V(AuthDirTestEd25519LinkKeys, BOOL, "1"),
523 OBSOLETE("V1AuthoritativeDirectory"),
524 OBSOLETE("V2AuthoritativeDirectory"),
525 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
526 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
527 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
528 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
529 V(TestingV3AuthVotingStartOffset, INTERVAL, "0"),
530 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
531 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
532 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
533 V(V3AuthNIntervalsValid, UINT, "3"),
534 V(V3AuthUseLegacyKey, BOOL, "0"),
535 V(V3BandwidthsFile, FILENAME, NULL),
536 V(GuardfractionFile, FILENAME, NULL),
537 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
538 OBSOLETE("VoteOnHidServDirectoriesV2"),
539 V(VirtualAddrNetworkIPv4, STRING, "127.192.0.0/10"),
540 V(VirtualAddrNetworkIPv6, STRING, "[FE80::]/10"),
541 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
542 OBSOLETE("UseFilteringSSLBufferevents"),
543 OBSOLETE("__UseFilteringSSLBufferevents"),
544 VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
545 VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
546 VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
547 VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
548 VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
549 NULL),
550 VAR("__OwningControllerProcess",STRING,OwningControllerProcess, NULL),
551 V(MinUptimeHidServDirectoryV2, INTERVAL, "96 hours"),
552 V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 60, 60, 120, "
553 "300, 900, 2147483647"),
554 V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 60, 300, 600, "
555 "2147483647"),
556 V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
557 "300, 600, 1800, 1800, 1800, 1800, "
558 "1800, 3600, 7200"),
559 V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
560 "300, 600, 1800, 3600, 3600, 3600, "
561 "10800, 21600, 43200"),
562 /* With the ClientBootstrapConsensus*Download* below:
563 * Clients with only authorities will try:
564 * - at least 3 authorities over 10 seconds, then exponentially backoff,
565 * with the next attempt 3-21 seconds later,
566 * Clients with authorities and fallbacks will try:
567 * - at least 2 authorities and 4 fallbacks over 21 seconds, then
568 * exponentially backoff, with the next attempts 4-33 seconds later,
569 * Clients will also retry when an application request arrives.
570 * After a number of failed requests, clients retry every 3 days + 1 hour.
572 * Clients used to try 2 authorities over 10 seconds, then wait for
573 * 60 minutes or an application request.
575 * When clients have authorities and fallbacks available, they use these
576 * schedules: (we stagger the times to avoid thundering herds) */
577 V(ClientBootstrapConsensusAuthorityDownloadSchedule, CSV_INTERVAL,
578 "6, 11, 3600, 10800, 25200, 54000, 111600, 262800" /* 3 days + 1 hour */),
579 V(ClientBootstrapConsensusFallbackDownloadSchedule, CSV_INTERVAL,
580 "0, 1, 4, 11, 3600, 10800, 25200, 54000, 111600, 262800"),
581 /* When clients only have authorities available, they use this schedule: */
582 V(ClientBootstrapConsensusAuthorityOnlyDownloadSchedule, CSV_INTERVAL,
583 "0, 3, 7, 3600, 10800, 25200, 54000, 111600, 262800"),
584 /* We don't want to overwhelm slow networks (or mirrors whose replies are
585 * blocked), but we also don't want to fail if only some mirrors are
586 * blackholed. Clients will try 3 directories simultaneously.
587 * (Relays never use simultaneous connections.) */
588 V(ClientBootstrapConsensusMaxInProgressTries, UINT, "3"),
589 V(TestingBridgeDownloadSchedule, CSV_INTERVAL, "1200, 900, 900, 3600"),
590 V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "10 minutes"),
591 V(TestingDirConnectionMaxStall, INTERVAL, "5 minutes"),
592 V(TestingConsensusMaxDownloadTries, UINT, "8"),
593 /* Since we try connections rapidly and simultaneously, we can afford
594 * to give up earlier. (This protects against overloading directories.) */
595 V(ClientBootstrapConsensusMaxDownloadTries, UINT, "7"),
596 /* We want to give up much earlier if we're only using authorities. */
597 V(ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries, UINT, "4"),
598 V(TestingDescriptorMaxDownloadTries, UINT, "8"),
599 V(TestingMicrodescMaxDownloadTries, UINT, "8"),
600 V(TestingCertMaxDownloadTries, UINT, "8"),
601 V(TestingDirAuthVoteExit, ROUTERSET, NULL),
602 V(TestingDirAuthVoteExitIsStrict, BOOL, "0"),
603 V(TestingDirAuthVoteGuard, ROUTERSET, NULL),
604 V(TestingDirAuthVoteGuardIsStrict, BOOL, "0"),
605 V(TestingDirAuthVoteHSDir, ROUTERSET, NULL),
606 V(TestingDirAuthVoteHSDirIsStrict, BOOL, "0"),
607 VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "0"),
609 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
612 /** Override default values with these if the user sets the TestingTorNetwork
613 * option. */
614 static const config_var_t testing_tor_network_defaults[] = {
615 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
616 V(DirAllowPrivateAddresses, BOOL, "1"),
617 V(EnforceDistinctSubnets, BOOL, "0"),
618 V(AssumeReachable, BOOL, "1"),
619 V(AuthDirMaxServersPerAddr, UINT, "0"),
620 V(ClientBootstrapConsensusAuthorityDownloadSchedule, CSV_INTERVAL,
621 "0, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
622 V(ClientBootstrapConsensusFallbackDownloadSchedule, CSV_INTERVAL,
623 "0, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
624 V(ClientBootstrapConsensusAuthorityOnlyDownloadSchedule, CSV_INTERVAL,
625 "0, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
626 V(ClientBootstrapConsensusMaxDownloadTries, UINT, "80"),
627 V(ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries, UINT, "80"),
628 V(ClientDNSRejectInternalAddresses, BOOL,"0"), // deprecated in 0.2.9.2-alpha
629 V(ClientRejectInternalAddresses, BOOL, "0"),
630 V(CountPrivateBandwidth, BOOL, "1"),
631 V(ExitPolicyRejectPrivate, BOOL, "0"),
632 V(ExtendAllowPrivateAddresses, BOOL, "1"),
633 V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
634 V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
635 V(V3AuthDistDelay, INTERVAL, "20 seconds"),
636 V(TestingV3AuthInitialVotingInterval, INTERVAL, "150 seconds"),
637 V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
638 V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
639 V(TestingV3AuthVotingStartOffset, INTERVAL, "0"),
640 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
641 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
642 V(MinUptimeHidServDirectoryV2, INTERVAL, "0 minutes"),
643 V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 5, 10, 15, "
644 "20, 30, 60"),
645 V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, 15, 20, "
646 "30, 60"),
647 V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
648 "15, 20, 30, 60"),
649 V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
650 "15, 20, 30, 60"),
651 V(TestingBridgeDownloadSchedule, CSV_INTERVAL, "60, 30, 30, 60"),
652 V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "5 seconds"),
653 V(TestingDirConnectionMaxStall, INTERVAL, "30 seconds"),
654 V(TestingConsensusMaxDownloadTries, UINT, "80"),
655 V(TestingDescriptorMaxDownloadTries, UINT, "80"),
656 V(TestingMicrodescMaxDownloadTries, UINT, "80"),
657 V(TestingCertMaxDownloadTries, UINT, "80"),
658 V(TestingEnableConnBwEvent, BOOL, "1"),
659 V(TestingEnableCellStatsEvent, BOOL, "1"),
660 V(TestingEnableTbEmptyEvent, BOOL, "1"),
661 VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "1"),
662 V(RendPostPeriod, INTERVAL, "2 minutes"),
664 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
667 #undef VAR
668 #undef V
669 #undef OBSOLETE
671 static const config_deprecation_t option_deprecation_notes_[] = {
672 /* Deprecated since 0.2.9.2-alpha... */
673 { "AllowDotExit", "Unrestricted use of the .exit notation can be used for "
674 "a wide variety of application-level attacks." },
675 { "ClientDNSRejectInternalAddresses", "Turning this on makes your client "
676 "easier to fingerprint, and may open you to esoteric attacks." },
677 /* End of options deprecated since 0.2.9.2-alpha. */
679 /* Deprecated since 0.3.2.0-alpha. */
680 { "HTTPProxy", "It only applies to direct unencrypted HTTP connections "
681 "to your directory server, which your Tor probably wasn't using." },
682 { "HTTPProxyAuthenticator", "HTTPProxy is deprecated in favor of HTTPSProxy "
683 "which should be used with HTTPSProxyAuthenticator." },
684 /* End of options deprecated since 0.3.2.0-alpha. */
686 { NULL, NULL }
689 #ifdef _WIN32
690 static char *get_windows_conf_root(void);
691 #endif
692 static int options_act_reversible(const or_options_t *old_options, char **msg);
693 static int options_transition_allowed(const or_options_t *old,
694 const or_options_t *new,
695 char **msg);
696 static int options_transition_affects_workers(
697 const or_options_t *old_options, const or_options_t *new_options);
698 static int options_transition_affects_descriptor(
699 const or_options_t *old_options, const or_options_t *new_options);
700 static int normalize_nickname_list(config_line_t **normalized_out,
701 const config_line_t *lst, const char *name,
702 char **msg);
703 static char *get_bindaddr_from_transport_listen_line(const char *line,
704 const char *transport);
705 static int parse_ports(or_options_t *options, int validate_only,
706 char **msg_out, int *n_ports_out,
707 int *world_writable_control_socket);
708 static int check_server_ports(const smartlist_t *ports,
709 const or_options_t *options,
710 int *num_low_ports_out);
712 static int validate_data_directory(or_options_t *options);
713 static int write_configuration_file(const char *fname,
714 const or_options_t *options);
715 static int options_init_logs(const or_options_t *old_options,
716 or_options_t *options, int validate_only);
718 static void init_libevent(const or_options_t *options);
719 static int opt_streq(const char *s1, const char *s2);
720 static int parse_outbound_addresses(or_options_t *options, int validate_only,
721 char **msg);
722 static void config_maybe_load_geoip_files_(const or_options_t *options,
723 const or_options_t *old_options);
724 static int options_validate_cb(void *old_options, void *options,
725 void *default_options,
726 int from_setconf, char **msg);
727 static uint64_t compute_real_max_mem_in_queues(const uint64_t val,
728 int log_guess);
730 /** Magic value for or_options_t. */
731 #define OR_OPTIONS_MAGIC 9090909
733 /** Configuration format for or_options_t. */
734 STATIC config_format_t options_format = {
735 sizeof(or_options_t),
736 OR_OPTIONS_MAGIC,
737 offsetof(or_options_t, magic_),
738 option_abbrevs_,
739 option_deprecation_notes_,
740 option_vars_,
741 options_validate_cb,
742 NULL
746 * Functions to read and write the global options pointer.
749 /** Command-line and config-file options. */
750 static or_options_t *global_options = NULL;
751 /** The fallback options_t object; this is where we look for options not
752 * in torrc before we fall back to Tor's defaults. */
753 static or_options_t *global_default_options = NULL;
754 /** Name of most recently read torrc file. */
755 static char *torrc_fname = NULL;
756 /** Name of the most recently read torrc-defaults file.*/
757 static char *torrc_defaults_fname;
758 /** Configuration options set by command line. */
759 static config_line_t *global_cmdline_options = NULL;
760 /** Non-configuration options set by the command line */
761 static config_line_t *global_cmdline_only_options = NULL;
762 /** Boolean: Have we parsed the command line? */
763 static int have_parsed_cmdline = 0;
764 /** Contents of most recently read DirPortFrontPage file. */
765 static char *global_dirfrontpagecontents = NULL;
766 /** List of port_cfg_t for all configured ports. */
767 static smartlist_t *configured_ports = NULL;
769 /** Return the contents of our frontpage string, or NULL if not configured. */
770 MOCK_IMPL(const char*,
771 get_dirportfrontpage, (void))
773 return global_dirfrontpagecontents;
776 /** Returns the currently configured options. */
777 MOCK_IMPL(or_options_t *,
778 get_options_mutable, (void))
780 tor_assert(global_options);
781 return global_options;
784 /** Returns the currently configured options */
785 MOCK_IMPL(const or_options_t *,
786 get_options,(void))
788 return get_options_mutable();
791 /** Change the current global options to contain <b>new_val</b> instead of
792 * their current value; take action based on the new value; free the old value
793 * as necessary. Returns 0 on success, -1 on failure.
796 set_options(or_options_t *new_val, char **msg)
798 int i;
799 smartlist_t *elements;
800 config_line_t *line;
801 or_options_t *old_options = global_options;
802 global_options = new_val;
803 /* Note that we pass the *old* options below, for comparison. It
804 * pulls the new options directly out of global_options. */
805 if (options_act_reversible(old_options, msg)<0) {
806 tor_assert(*msg);
807 global_options = old_options;
808 return -1;
810 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
811 log_err(LD_BUG,
812 "Acting on config options left us in a broken state. Dying.");
813 exit(1);
815 /* Issues a CONF_CHANGED event to notify controller of the change. If Tor is
816 * just starting up then the old_options will be undefined. */
817 if (old_options && old_options != global_options) {
818 elements = smartlist_new();
819 for (i=0; options_format.vars[i].name; ++i) {
820 const config_var_t *var = &options_format.vars[i];
821 const char *var_name = var->name;
822 if (var->type == CONFIG_TYPE_LINELIST_S ||
823 var->type == CONFIG_TYPE_OBSOLETE) {
824 continue;
826 if (!config_is_same(&options_format, new_val, old_options, var_name)) {
827 line = config_get_assigned_option(&options_format, new_val,
828 var_name, 1);
830 if (line) {
831 config_line_t *next;
832 for (; line; line = next) {
833 next = line->next;
834 smartlist_add(elements, line->key);
835 smartlist_add(elements, line->value);
836 tor_free(line);
838 } else {
839 smartlist_add_strdup(elements, options_format.vars[i].name);
840 smartlist_add(elements, NULL);
844 control_event_conf_changed(elements);
845 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
846 smartlist_free(elements);
849 if (old_options != global_options)
850 or_options_free(old_options);
852 return 0;
855 extern const char tor_git_revision[]; /* from tor_main.c */
857 /** The version of this Tor process, as parsed. */
858 static char *the_tor_version = NULL;
859 /** A shorter version of this Tor process's version, for export in our router
860 * descriptor. (Does not include the git version, if any.) */
861 static char *the_short_tor_version = NULL;
863 /** Return the current Tor version. */
864 const char *
865 get_version(void)
867 if (the_tor_version == NULL) {
868 if (strlen(tor_git_revision)) {
869 tor_asprintf(&the_tor_version, "%s (git-%s)", get_short_version(),
870 tor_git_revision);
871 } else {
872 the_tor_version = tor_strdup(get_short_version());
875 return the_tor_version;
878 /** Return the current Tor version, without any git tag. */
879 const char *
880 get_short_version(void)
883 if (the_short_tor_version == NULL) {
884 #ifdef TOR_BUILD_TAG
885 tor_asprintf(&the_short_tor_version, "%s (%s)", VERSION, TOR_BUILD_TAG);
886 #else
887 the_short_tor_version = tor_strdup(VERSION);
888 #endif
890 return the_short_tor_version;
893 /** Release additional memory allocated in options
895 STATIC void
896 or_options_free(or_options_t *options)
898 if (!options)
899 return;
901 routerset_free(options->ExcludeExitNodesUnion_);
902 if (options->NodeFamilySets) {
903 SMARTLIST_FOREACH(options->NodeFamilySets, routerset_t *,
904 rs, routerset_free(rs));
905 smartlist_free(options->NodeFamilySets);
907 tor_free(options->BridgePassword_AuthDigest_);
908 tor_free(options->command_arg);
909 tor_free(options->master_key_fname);
910 config_free_lines(options->MyFamily);
911 config_free(&options_format, options);
914 /** Release all memory and resources held by global configuration structures.
916 void
917 config_free_all(void)
919 or_options_free(global_options);
920 global_options = NULL;
921 or_options_free(global_default_options);
922 global_default_options = NULL;
924 config_free_lines(global_cmdline_options);
925 global_cmdline_options = NULL;
927 config_free_lines(global_cmdline_only_options);
928 global_cmdline_only_options = NULL;
930 if (configured_ports) {
931 SMARTLIST_FOREACH(configured_ports,
932 port_cfg_t *, p, port_cfg_free(p));
933 smartlist_free(configured_ports);
934 configured_ports = NULL;
937 tor_free(torrc_fname);
938 tor_free(torrc_defaults_fname);
939 tor_free(global_dirfrontpagecontents);
941 tor_free(the_short_tor_version);
942 tor_free(the_tor_version);
945 /** Make <b>address</b> -- a piece of information related to our operation as
946 * a client -- safe to log according to the settings in options->SafeLogging,
947 * and return it.
949 * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
951 const char *
952 safe_str_client(const char *address)
954 tor_assert(address);
955 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
956 return "[scrubbed]";
957 else
958 return address;
961 /** Make <b>address</b> -- a piece of information of unspecified sensitivity
962 * -- safe to log according to the settings in options->SafeLogging, and
963 * return it.
965 * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
966 * otherwise.)
968 const char *
969 safe_str(const char *address)
971 tor_assert(address);
972 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
973 return "[scrubbed]";
974 else
975 return address;
978 /** Equivalent to escaped(safe_str_client(address)). See reentrancy note on
979 * escaped(): don't use this outside the main thread, or twice in the same
980 * log statement. */
981 const char *
982 escaped_safe_str_client(const char *address)
984 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
985 return "[scrubbed]";
986 else
987 return escaped(address);
990 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
991 * escaped(): don't use this outside the main thread, or twice in the same
992 * log statement. */
993 const char *
994 escaped_safe_str(const char *address)
996 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
997 return "[scrubbed]";
998 else
999 return escaped(address);
1002 /** List of default directory authorities */
1004 static const char *default_authorities[] = {
1005 "moria1 orport=9101 "
1006 "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
1007 "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
1008 "tor26 orport=443 "
1009 "v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
1010 "ipv6=[2001:858:2:2:aabb:0:563b:1526]:443 "
1011 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
1012 "dizum orport=443 "
1013 "v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
1014 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
1015 "Bifroest orport=443 bridge "
1016 "37.218.247.217:80 1D8F 3A91 C37C 5D1C 4C19 B1AD 1D0C FBE8 BF72 D8E1",
1017 "gabelmoo orport=443 "
1018 "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
1019 "ipv6=[2001:638:a000:4140::ffff:189]:443 "
1020 "131.188.40.189:80 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
1021 "dannenberg orport=443 "
1022 "v3ident=0232AF901C31A04EE9848595AF9BB7620D4C5B2E "
1023 "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
1024 "maatuska orport=80 "
1025 "v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
1026 "ipv6=[2001:67c:289c::9]:80 "
1027 "171.25.193.9:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
1028 "Faravahar orport=443 "
1029 "v3ident=EFCBE720AB3A82B99F9E953CD5BF50F7EEFC7B97 "
1030 "154.35.175.225:80 CF6D 0AAF B385 BE71 B8E1 11FC 5CFF 4B47 9237 33BC",
1031 "longclaw orport=443 "
1032 "v3ident=23D15D965BC35114467363C165C4F724B64B4F66 "
1033 "ipv6=[2620:13:4000:8000:60:f3ff:fea1:7cff]:443 "
1034 "199.254.238.52:80 74A9 1064 6BCE EFBC D2E8 74FC 1DC9 9743 0F96 8145",
1035 NULL
1038 /** List of fallback directory authorities. The list is generated by opt-in of
1039 * relays that meet certain stability criteria.
1041 static const char *default_fallbacks[] = {
1042 #include "fallback_dirs.inc"
1043 NULL
1046 /** Add the default directory authorities directly into the trusted dir list,
1047 * but only add them insofar as they share bits with <b>type</b>.
1048 * Each authority's bits are restricted to the bits shared with <b>type</b>.
1049 * If <b>type</b> is ALL_DIRINFO or NO_DIRINFO (zero), add all authorities. */
1050 STATIC void
1051 add_default_trusted_dir_authorities(dirinfo_type_t type)
1053 int i;
1054 for (i=0; default_authorities[i]; i++) {
1055 if (parse_dir_authority_line(default_authorities[i], type, 0)<0) {
1056 log_err(LD_BUG, "Couldn't parse internal DirAuthority line %s",
1057 default_authorities[i]);
1062 /** Add the default fallback directory servers into the fallback directory
1063 * server list. */
1064 MOCK_IMPL(void,
1065 add_default_fallback_dir_servers,(void))
1067 int i;
1068 for (i=0; default_fallbacks[i]; i++) {
1069 if (parse_dir_fallback_line(default_fallbacks[i], 0)<0) {
1070 log_err(LD_BUG, "Couldn't parse internal FallbackDir line %s",
1071 default_fallbacks[i]);
1076 /** Look at all the config options for using alternate directory
1077 * authorities, and make sure none of them are broken. Also, warn the
1078 * user if we changed any dangerous ones.
1080 static int
1081 validate_dir_servers(or_options_t *options, or_options_t *old_options)
1083 config_line_t *cl;
1085 if (options->DirAuthorities &&
1086 (options->AlternateDirAuthority || options->AlternateBridgeAuthority)) {
1087 log_warn(LD_CONFIG,
1088 "You cannot set both DirAuthority and Alternate*Authority.");
1089 return -1;
1092 /* do we want to complain to the user about being partitionable? */
1093 if ((options->DirAuthorities &&
1094 (!old_options ||
1095 !config_lines_eq(options->DirAuthorities,
1096 old_options->DirAuthorities))) ||
1097 (options->AlternateDirAuthority &&
1098 (!old_options ||
1099 !config_lines_eq(options->AlternateDirAuthority,
1100 old_options->AlternateDirAuthority)))) {
1101 log_warn(LD_CONFIG,
1102 "You have used DirAuthority or AlternateDirAuthority to "
1103 "specify alternate directory authorities in "
1104 "your configuration. This is potentially dangerous: it can "
1105 "make you look different from all other Tor users, and hurt "
1106 "your anonymity. Even if you've specified the same "
1107 "authorities as Tor uses by default, the defaults could "
1108 "change in the future. Be sure you know what you're doing.");
1111 /* Now go through the four ways you can configure an alternate
1112 * set of directory authorities, and make sure none are broken. */
1113 for (cl = options->DirAuthorities; cl; cl = cl->next)
1114 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1115 return -1;
1116 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1117 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1118 return -1;
1119 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1120 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1121 return -1;
1122 for (cl = options->FallbackDir; cl; cl = cl->next)
1123 if (parse_dir_fallback_line(cl->value, 1)<0)
1124 return -1;
1125 return 0;
1128 /** Look at all the config options and assign new dir authorities
1129 * as appropriate.
1132 consider_adding_dir_servers(const or_options_t *options,
1133 const or_options_t *old_options)
1135 config_line_t *cl;
1136 int need_to_update =
1137 !smartlist_len(router_get_trusted_dir_servers()) ||
1138 !smartlist_len(router_get_fallback_dir_servers()) || !old_options ||
1139 !config_lines_eq(options->DirAuthorities, old_options->DirAuthorities) ||
1140 !config_lines_eq(options->FallbackDir, old_options->FallbackDir) ||
1141 (options->UseDefaultFallbackDirs != old_options->UseDefaultFallbackDirs) ||
1142 !config_lines_eq(options->AlternateBridgeAuthority,
1143 old_options->AlternateBridgeAuthority) ||
1144 !config_lines_eq(options->AlternateDirAuthority,
1145 old_options->AlternateDirAuthority);
1147 if (!need_to_update)
1148 return 0; /* all done */
1150 /* "You cannot set both DirAuthority and Alternate*Authority."
1151 * Checking that this restriction holds allows us to simplify
1152 * the unit tests. */
1153 tor_assert(!(options->DirAuthorities &&
1154 (options->AlternateDirAuthority
1155 || options->AlternateBridgeAuthority)));
1157 /* Start from a clean slate. */
1158 clear_dir_servers();
1160 if (!options->DirAuthorities) {
1161 /* then we may want some of the defaults */
1162 dirinfo_type_t type = NO_DIRINFO;
1163 if (!options->AlternateBridgeAuthority) {
1164 type |= BRIDGE_DIRINFO;
1166 if (!options->AlternateDirAuthority) {
1167 type |= V3_DIRINFO | EXTRAINFO_DIRINFO | MICRODESC_DIRINFO;
1168 /* Only add the default fallback directories when the DirAuthorities,
1169 * AlternateDirAuthority, and FallbackDir directory config options
1170 * are set to their defaults, and when UseDefaultFallbackDirs is 1. */
1171 if (!options->FallbackDir && options->UseDefaultFallbackDirs) {
1172 add_default_fallback_dir_servers();
1175 /* if type == NO_DIRINFO, we don't want to add any of the
1176 * default authorities, because we've replaced them all */
1177 if (type != NO_DIRINFO)
1178 add_default_trusted_dir_authorities(type);
1181 for (cl = options->DirAuthorities; cl; cl = cl->next)
1182 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1183 return -1;
1184 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1185 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1186 return -1;
1187 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1188 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1189 return -1;
1190 for (cl = options->FallbackDir; cl; cl = cl->next)
1191 if (parse_dir_fallback_line(cl->value, 0)<0)
1192 return -1;
1193 return 0;
1196 /* Helps determine flags to pass to switch_id. */
1197 static int have_low_ports = -1;
1199 /** Fetch the active option list, and take actions based on it. All of the
1200 * things we do should survive being done repeatedly. If present,
1201 * <b>old_options</b> contains the previous value of the options.
1203 * Return 0 if all goes well, return -1 if things went badly.
1205 static int
1206 options_act_reversible(const or_options_t *old_options, char **msg)
1208 smartlist_t *new_listeners = smartlist_new();
1209 smartlist_t *replaced_listeners = smartlist_new();
1210 static int libevent_initialized = 0;
1211 or_options_t *options = get_options_mutable();
1212 int running_tor = options->command == CMD_RUN_TOR;
1213 int set_conn_limit = 0;
1214 int r = -1;
1215 int logs_marked = 0, logs_initialized = 0;
1216 int old_min_log_level = get_min_log_level();
1218 /* Daemonize _first_, since we only want to open most of this stuff in
1219 * the subprocess. Libevent bases can't be reliably inherited across
1220 * processes. */
1221 if (running_tor && options->RunAsDaemon) {
1222 /* No need to roll back, since you can't change the value. */
1223 start_daemon();
1226 #ifdef HAVE_SYSTEMD
1227 /* Our PID may have changed, inform supervisor */
1228 sd_notifyf(0, "MAINPID=%ld\n", (long int)getpid());
1229 #endif
1231 #ifndef HAVE_SYS_UN_H
1232 if (options->ControlSocket || options->ControlSocketsGroupWritable) {
1233 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported "
1234 "on this OS/with this build.");
1235 goto rollback;
1237 #else
1238 if (options->ControlSocketsGroupWritable && !options->ControlSocket) {
1239 *msg = tor_strdup("Setting ControlSocketGroupWritable without setting"
1240 "a ControlSocket makes no sense.");
1241 goto rollback;
1243 #endif
1245 if (running_tor) {
1246 int n_ports=0;
1247 /* We need to set the connection limit before we can open the listeners. */
1248 if (! sandbox_is_active()) {
1249 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1250 &options->ConnLimit_) < 0) {
1251 *msg = tor_strdup("Problem with ConnLimit value. "
1252 "See logs for details.");
1253 goto rollback;
1255 set_conn_limit = 1;
1256 } else {
1257 tor_assert(old_options);
1258 options->ConnLimit_ = old_options->ConnLimit_;
1261 /* Set up libevent. (We need to do this before we can register the
1262 * listeners as listeners.) */
1263 if (running_tor && !libevent_initialized) {
1264 init_libevent(options);
1265 libevent_initialized = 1;
1267 /* This has to come up after libevent is initialized. */
1268 control_initialize_event_queue();
1271 * Initialize the scheduler - this has to come after
1272 * options_init_from_torrc() sets up libevent - why yes, that seems
1273 * completely sensible to hide the libevent setup in the option parsing
1274 * code! It also needs to happen before init_keys(), so it needs to
1275 * happen here too. How yucky. */
1276 scheduler_init();
1279 /* Adjust the port configuration so we can launch listeners. */
1280 if (parse_ports(options, 0, msg, &n_ports, NULL)) {
1281 if (!*msg)
1282 *msg = tor_strdup("Unexpected problem parsing port config");
1283 goto rollback;
1286 /* Set the hibernation state appropriately.*/
1287 consider_hibernation(time(NULL));
1289 /* Launch the listeners. (We do this before we setuid, so we can bind to
1290 * ports under 1024.) We don't want to rebind if we're hibernating. If
1291 * networking is disabled, this will close all but the control listeners,
1292 * but disable those. */
1293 if (!we_are_hibernating()) {
1294 if (retry_all_listeners(replaced_listeners, new_listeners,
1295 options->DisableNetwork) < 0) {
1296 *msg = tor_strdup("Failed to bind one of the listener ports.");
1297 goto rollback;
1300 if (options->DisableNetwork) {
1301 /* Aggressively close non-controller stuff, NOW */
1302 log_notice(LD_NET, "DisableNetwork is set. Tor will not make or accept "
1303 "non-control network connections. Shutting down all existing "
1304 "connections.");
1305 connection_mark_all_noncontrol_connections();
1306 /* We can't complete circuits until the network is re-enabled. */
1307 note_that_we_maybe_cant_complete_circuits();
1311 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1312 /* Open /dev/pf before dropping privileges. */
1313 if (options->TransPort_set &&
1314 options->TransProxyType_parsed == TPT_DEFAULT) {
1315 if (get_pf_socket() < 0) {
1316 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1317 goto rollback;
1320 #endif
1322 /* Attempt to lock all current and future memory with mlockall() only once */
1323 if (options->DisableAllSwap) {
1324 if (tor_mlockall() == -1) {
1325 *msg = tor_strdup("DisableAllSwap failure. Do you have proper "
1326 "permissions?");
1327 goto done;
1331 /* Setuid/setgid as appropriate */
1332 if (options->User) {
1333 tor_assert(have_low_ports != -1);
1334 unsigned switch_id_flags = 0;
1335 if (options->KeepBindCapabilities == 1) {
1336 switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
1337 switch_id_flags |= SWITCH_ID_WARN_IF_NO_CAPS;
1339 if (options->KeepBindCapabilities == -1 && have_low_ports) {
1340 switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
1342 if (switch_id(options->User, switch_id_flags) != 0) {
1343 /* No need to roll back, since you can't change the value. */
1344 *msg = tor_strdup("Problem with User value. See logs for details.");
1345 goto done;
1349 /* Ensure data directory is private; create if possible. */
1350 cpd_check_t cpd_opts = running_tor ? CPD_CREATE : CPD_CHECK;
1351 if (options->DataDirectoryGroupReadable)
1352 cpd_opts |= CPD_GROUP_READ;
1353 if (check_private_dir(options->DataDirectory,
1354 cpd_opts,
1355 options->User)<0) {
1356 tor_asprintf(msg,
1357 "Couldn't access/create private data directory \"%s\"",
1358 options->DataDirectory);
1360 goto done;
1361 /* No need to roll back, since you can't change the value. */
1364 #ifndef _WIN32
1365 if (options->DataDirectoryGroupReadable) {
1366 /* Only new dirs created get new opts, also enforce group read. */
1367 if (chmod(options->DataDirectory, 0750)) {
1368 log_warn(LD_FS,"Unable to make %s group-readable: %s",
1369 options->DataDirectory, strerror(errno));
1372 #endif
1374 /* Bail out at this point if we're not going to be a client or server:
1375 * we don't run Tor itself. */
1376 if (!running_tor)
1377 goto commit;
1379 mark_logs_temp(); /* Close current logs once new logs are open. */
1380 logs_marked = 1;
1381 /* Configure the tor_log(s) */
1382 if (options_init_logs(old_options, options, 0)<0) {
1383 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1384 goto rollback;
1386 logs_initialized = 1;
1388 commit:
1389 r = 0;
1390 if (logs_marked) {
1391 log_severity_list_t *severity =
1392 tor_malloc_zero(sizeof(log_severity_list_t));
1393 close_temp_logs();
1394 add_callback_log(severity, control_event_logmsg);
1395 control_adjust_event_log_severity();
1396 tor_free(severity);
1397 tor_log_update_sigsafe_err_fds();
1399 if (logs_initialized) {
1400 flush_log_messages_from_startup();
1404 const char *badness = NULL;
1405 int bad_safelog = 0, bad_severity = 0, new_badness = 0;
1406 if (options->SafeLogging_ != SAFELOG_SCRUB_ALL) {
1407 bad_safelog = 1;
1408 if (!old_options || old_options->SafeLogging_ != options->SafeLogging_)
1409 new_badness = 1;
1411 if (get_min_log_level() >= LOG_INFO) {
1412 bad_severity = 1;
1413 if (get_min_log_level() != old_min_log_level)
1414 new_badness = 1;
1416 if (bad_safelog && bad_severity)
1417 badness = "you disabled SafeLogging, and "
1418 "you're logging more than \"notice\"";
1419 else if (bad_safelog)
1420 badness = "you disabled SafeLogging";
1421 else
1422 badness = "you're logging more than \"notice\"";
1423 if (new_badness)
1424 log_warn(LD_GENERAL, "Your log may contain sensitive information - %s. "
1425 "Don't log unless it serves an important reason. "
1426 "Overwrite the log afterwards.", badness);
1429 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1431 int marked = conn->marked_for_close;
1432 log_notice(LD_NET, "Closing old %s on %s:%d",
1433 conn_type_to_string(conn->type), conn->address, conn->port);
1434 connection_close_immediate(conn);
1435 if (!marked) {
1436 connection_mark_for_close(conn);
1440 if (set_conn_limit) {
1442 * If we adjusted the conn limit, recompute the OOS threshold too
1444 * How many possible sockets to keep in reserve? If we have lots of
1445 * possible sockets, keep this below a limit and set ConnLimit_high_thresh
1446 * very close to ConnLimit_, but if ConnLimit_ is low, shrink it in
1447 * proportion.
1449 * Somewhat arbitrarily, set socks_in_reserve to 5% of ConnLimit_, but
1450 * cap it at 64.
1452 int socks_in_reserve = options->ConnLimit_ / 20;
1453 if (socks_in_reserve > 64) socks_in_reserve = 64;
1455 options->ConnLimit_high_thresh = options->ConnLimit_ - socks_in_reserve;
1456 options->ConnLimit_low_thresh = (options->ConnLimit_ / 4) * 3;
1457 log_info(LD_GENERAL,
1458 "Recomputed OOS thresholds: ConnLimit %d, ConnLimit_ %d, "
1459 "ConnLimit_high_thresh %d, ConnLimit_low_thresh %d",
1460 options->ConnLimit, options->ConnLimit_,
1461 options->ConnLimit_high_thresh,
1462 options->ConnLimit_low_thresh);
1464 /* Give the OOS handler a chance with the new thresholds */
1465 connection_check_oos(get_n_open_sockets(), 0);
1468 goto done;
1470 rollback:
1471 r = -1;
1472 tor_assert(*msg);
1474 if (logs_marked) {
1475 rollback_log_changes();
1476 control_adjust_event_log_severity();
1479 if (set_conn_limit && old_options)
1480 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1481 &options->ConnLimit_);
1483 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1485 log_notice(LD_NET, "Closing partially-constructed %s on %s:%d",
1486 conn_type_to_string(conn->type), conn->address, conn->port);
1487 connection_close_immediate(conn);
1488 connection_mark_for_close(conn);
1491 done:
1492 smartlist_free(new_listeners);
1493 smartlist_free(replaced_listeners);
1494 return r;
1497 /** If we need to have a GEOIP ip-to-country map to run with our configured
1498 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1500 options_need_geoip_info(const or_options_t *options, const char **reason_out)
1502 int bridge_usage =
1503 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1504 int routerset_usage =
1505 routerset_needs_geoip(options->EntryNodes) ||
1506 routerset_needs_geoip(options->ExitNodes) ||
1507 routerset_needs_geoip(options->ExcludeExitNodes) ||
1508 routerset_needs_geoip(options->ExcludeNodes) ||
1509 routerset_needs_geoip(options->Tor2webRendezvousPoints);
1511 if (routerset_usage && reason_out) {
1512 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1513 "countries, and we need GEOIP information to figure out which ones they "
1514 "are.";
1515 } else if (bridge_usage && reason_out) {
1516 *reason_out = "We've been configured to see which countries can access "
1517 "us as a bridge, and we need GEOIP information to tell which countries "
1518 "clients are in.";
1520 return bridge_usage || routerset_usage;
1523 /** Return the bandwidthrate that we are going to report to the authorities
1524 * based on the config options. */
1525 uint32_t
1526 get_effective_bwrate(const or_options_t *options)
1528 uint64_t bw = options->BandwidthRate;
1529 if (bw > options->MaxAdvertisedBandwidth)
1530 bw = options->MaxAdvertisedBandwidth;
1531 if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1532 bw = options->RelayBandwidthRate;
1533 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1534 return (uint32_t)bw;
1537 /** Return the bandwidthburst that we are going to report to the authorities
1538 * based on the config options. */
1539 uint32_t
1540 get_effective_bwburst(const or_options_t *options)
1542 uint64_t bw = options->BandwidthBurst;
1543 if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1544 bw = options->RelayBandwidthBurst;
1545 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1546 return (uint32_t)bw;
1550 * Return true if changing the configuration from <b>old</b> to <b>new</b>
1551 * affects the guard susbsystem.
1553 static int
1554 options_transition_affects_guards(const or_options_t *old,
1555 const or_options_t *new)
1557 /* NOTE: Make sure this function stays in sync with
1558 * entry_guards_set_filtered_flags */
1560 tor_assert(old);
1561 tor_assert(new);
1563 return
1564 (old->UseEntryGuards != new->UseEntryGuards ||
1565 old->UseBridges != new->UseBridges ||
1566 old->ClientUseIPv4 != new->ClientUseIPv4 ||
1567 old->ClientUseIPv6 != new->ClientUseIPv6 ||
1568 old->FascistFirewall != new->FascistFirewall ||
1569 !routerset_equal(old->ExcludeNodes, new->ExcludeNodes) ||
1570 !routerset_equal(old->EntryNodes, new->EntryNodes) ||
1571 !smartlist_strings_eq(old->FirewallPorts, new->FirewallPorts) ||
1572 !config_lines_eq(old->Bridges, new->Bridges) ||
1573 !config_lines_eq(old->ReachableORAddresses, new->ReachableORAddresses) ||
1574 !config_lines_eq(old->ReachableDirAddresses, new->ReachableDirAddresses));
1577 /** Fetch the active option list, and take actions based on it. All of the
1578 * things we do should survive being done repeatedly. If present,
1579 * <b>old_options</b> contains the previous value of the options.
1581 * Return 0 if all goes well, return -1 if it's time to die.
1583 * Note: We haven't moved all the "act on new configuration" logic
1584 * here yet. Some is still in do_hup() and other places.
1586 STATIC int
1587 options_act(const or_options_t *old_options)
1589 config_line_t *cl;
1590 or_options_t *options = get_options_mutable();
1591 int running_tor = options->command == CMD_RUN_TOR;
1592 char *msg=NULL;
1593 const int transition_affects_workers =
1594 old_options && options_transition_affects_workers(old_options, options);
1595 int old_ewma_enabled;
1596 const int transition_affects_guards =
1597 old_options && options_transition_affects_guards(old_options, options);
1599 if (options->NoExec || options->Sandbox) {
1600 tor_disable_spawning_background_processes();
1603 /* disable ptrace and later, other basic debugging techniques */
1605 /* Remember if we already disabled debugger attachment */
1606 static int disabled_debugger_attach = 0;
1607 /* Remember if we already warned about being configured not to disable
1608 * debugger attachment */
1609 static int warned_debugger_attach = 0;
1610 /* Don't disable debugger attachment when we're running the unit tests. */
1611 if (options->DisableDebuggerAttachment && !disabled_debugger_attach &&
1612 running_tor) {
1613 int ok = tor_disable_debugger_attach();
1614 /* LCOV_EXCL_START the warned_debugger_attach is 0 can't reach inside. */
1615 if (warned_debugger_attach && ok == 1) {
1616 log_notice(LD_CONFIG, "Disabled attaching debuggers for unprivileged "
1617 "users.");
1619 /* LCOV_EXCL_STOP */
1620 disabled_debugger_attach = (ok == 1);
1621 } else if (!options->DisableDebuggerAttachment &&
1622 !warned_debugger_attach) {
1623 log_notice(LD_CONFIG, "Not disabling debugger attaching for "
1624 "unprivileged users.");
1625 warned_debugger_attach = 1;
1629 /* Write control ports to disk as appropriate */
1630 control_ports_write_to_file();
1632 if (running_tor && !have_lockfile()) {
1633 if (try_locking(options, 1) < 0)
1634 return -1;
1637 if (consider_adding_dir_servers(options, old_options) < 0)
1638 return -1;
1640 if (rend_non_anonymous_mode_enabled(options)) {
1641 log_warn(LD_GENERAL, "This copy of Tor was compiled or configured to run "
1642 "in a non-anonymous mode. It will provide NO ANONYMITY.");
1645 #ifdef ENABLE_TOR2WEB_MODE
1646 /* LCOV_EXCL_START */
1647 if (!options->Tor2webMode) {
1648 log_err(LD_CONFIG, "This copy of Tor was compiled to run in "
1649 "'tor2web mode'. It can only be run with the Tor2webMode torrc "
1650 "option enabled.");
1651 return -1;
1653 /* LCOV_EXCL_STOP */
1654 #else
1655 if (options->Tor2webMode) {
1656 log_err(LD_CONFIG, "This copy of Tor was not compiled to run in "
1657 "'tor2web mode'. It cannot be run with the Tor2webMode torrc "
1658 "option enabled. To enable Tor2webMode recompile with the "
1659 "--enable-tor2web-mode option.");
1660 return -1;
1662 #endif
1664 /* If we are a bridge with a pluggable transport proxy but no
1665 Extended ORPort, inform the user that they are missing out. */
1666 if (server_mode(options) && options->ServerTransportPlugin &&
1667 !options->ExtORPort_lines) {
1668 log_notice(LD_CONFIG, "We use pluggable transports but the Extended "
1669 "ORPort is disabled. Tor and your pluggable transports proxy "
1670 "communicate with each other via the Extended ORPort so it "
1671 "is suggested you enable it: it will also allow your Bridge "
1672 "to collect statistics about its clients that use pluggable "
1673 "transports. Please enable it using the ExtORPort torrc option "
1674 "(e.g. set 'ExtORPort auto').");
1677 if (options->Bridges) {
1678 mark_bridge_list();
1679 for (cl = options->Bridges; cl; cl = cl->next) {
1680 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
1681 if (!bridge_line) {
1682 log_warn(LD_BUG,
1683 "Previously validated Bridge line could not be added!");
1684 return -1;
1686 bridge_add_from_config(bridge_line);
1688 sweep_bridge_list();
1691 if (running_tor && hs_config_service_all(options, 0)<0) {
1692 log_warn(LD_BUG,
1693 "Previously validated hidden services line could not be added!");
1694 return -1;
1697 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1698 log_warn(LD_BUG, "Previously validated client authorization for "
1699 "hidden services could not be added!");
1700 return -1;
1703 /* Load state */
1704 if (! or_state_loaded() && running_tor) {
1705 if (or_state_load())
1706 return -1;
1707 rep_hist_load_mtbf_data(time(NULL));
1710 /* If we have an ExtORPort, initialize its auth cookie. */
1711 if (running_tor &&
1712 init_ext_or_cookie_authentication(!!options->ExtORPort_lines) < 0) {
1713 log_warn(LD_CONFIG,"Error creating Extended ORPort cookie file.");
1714 return -1;
1717 mark_transport_list();
1718 pt_prepare_proxy_list_for_config_read();
1719 if (!options->DisableNetwork) {
1720 if (options->ClientTransportPlugin) {
1721 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
1722 if (parse_transport_line(options, cl->value, 0, 0) < 0) {
1723 log_warn(LD_BUG,
1724 "Previously validated ClientTransportPlugin line "
1725 "could not be added!");
1726 return -1;
1731 if (options->ServerTransportPlugin && server_mode(options)) {
1732 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
1733 if (parse_transport_line(options, cl->value, 0, 1) < 0) {
1734 log_warn(LD_BUG,
1735 "Previously validated ServerTransportPlugin line "
1736 "could not be added!");
1737 return -1;
1742 sweep_transport_list();
1743 sweep_proxy_list();
1745 /* Start the PT proxy configuration. By doing this configuration
1746 here, we also figure out which proxies need to be restarted and
1747 which not. */
1748 if (pt_proxies_configuration_pending() && !net_is_disabled())
1749 pt_configure_remaining_proxies();
1751 /* Bail out at this point if we're not going to be a client or server:
1752 * we want to not fork, and to log stuff to stderr. */
1753 if (!running_tor)
1754 return 0;
1756 /* Finish backgrounding the process */
1757 if (options->RunAsDaemon) {
1758 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1759 finish_daemon(options->DataDirectory);
1762 /* We want to reinit keys as needed before we do much of anything else:
1763 keys are important, and other things can depend on them. */
1764 if (transition_affects_workers ||
1765 (options->V3AuthoritativeDir && (!old_options ||
1766 !old_options->V3AuthoritativeDir))) {
1767 if (init_keys() < 0) {
1768 log_warn(LD_BUG,"Error initializing keys; exiting");
1769 return -1;
1773 /* Write our PID to the PID file. If we do not have write permissions we
1774 * will log a warning */
1775 if (options->PidFile && !sandbox_is_active()) {
1776 write_pidfile(options->PidFile);
1779 /* Register addressmap directives */
1780 config_register_addressmaps(options);
1781 parse_virtual_addr_network(options->VirtualAddrNetworkIPv4, AF_INET,0,NULL);
1782 parse_virtual_addr_network(options->VirtualAddrNetworkIPv6, AF_INET6,0,NULL);
1784 /* Update address policies. */
1785 if (policies_parse_from_options(options) < 0) {
1786 /* This should be impossible, but let's be sure. */
1787 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1788 return -1;
1791 if (server_mode(options)) {
1792 static int cdm_initialized = 0;
1793 if (cdm_initialized == 0) {
1794 cdm_initialized = 1;
1795 consdiffmgr_configure(NULL);
1796 consdiffmgr_validate();
1800 if (init_control_cookie_authentication(options->CookieAuthentication) < 0) {
1801 log_warn(LD_CONFIG,"Error creating control cookie authentication file.");
1802 return -1;
1805 monitor_owning_controller_process(options->OwningControllerProcess);
1807 /* reload keys as needed for rendezvous services. */
1808 if (hs_service_load_all_keys() < 0) {
1809 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1810 return -1;
1813 /* Set up scheduler thresholds */
1814 scheduler_set_watermarks((uint32_t)options->SchedulerLowWaterMark__,
1815 (uint32_t)options->SchedulerHighWaterMark__,
1816 (options->SchedulerMaxFlushCells__ > 0) ?
1817 options->SchedulerMaxFlushCells__ : 1000);
1819 /* Set up accounting */
1820 if (accounting_parse_options(options, 0)<0) {
1821 log_warn(LD_CONFIG,"Error in accounting options");
1822 return -1;
1824 if (accounting_is_enabled(options))
1825 configure_accounting(time(NULL));
1827 old_ewma_enabled = cell_ewma_enabled();
1828 /* Change the cell EWMA settings */
1829 cell_ewma_set_scale_factor(options, networkstatus_get_latest_consensus());
1830 /* If we just enabled ewma, set the cmux policy on all active channels */
1831 if (cell_ewma_enabled() && !old_ewma_enabled) {
1832 channel_set_cmux_policy_everywhere(&ewma_policy);
1833 } else if (!cell_ewma_enabled() && old_ewma_enabled) {
1834 /* Turn it off everywhere */
1835 channel_set_cmux_policy_everywhere(NULL);
1838 /* Update the BridgePassword's hashed version as needed. We store this as a
1839 * digest so that we can do side-channel-proof comparisons on it.
1841 if (options->BridgePassword) {
1842 char *http_authenticator;
1843 http_authenticator = alloc_http_authenticator(options->BridgePassword);
1844 if (!http_authenticator) {
1845 log_warn(LD_BUG, "Unable to allocate HTTP authenticator. Not setting "
1846 "BridgePassword.");
1847 return -1;
1849 options->BridgePassword_AuthDigest_ = tor_malloc(DIGEST256_LEN);
1850 crypto_digest256(options->BridgePassword_AuthDigest_,
1851 http_authenticator, strlen(http_authenticator),
1852 DIGEST_SHA256);
1853 tor_free(http_authenticator);
1856 if (parse_outbound_addresses(options, 0, &msg) < 0) {
1857 log_warn(LD_BUG, "Failed parsing outbound bind addresses: %s", msg);
1858 tor_free(msg);
1859 return -1;
1862 config_maybe_load_geoip_files_(options, old_options);
1864 if (geoip_is_loaded(AF_INET) && options->GeoIPExcludeUnknown) {
1865 /* ExcludeUnknown is true or "auto" */
1866 const int is_auto = options->GeoIPExcludeUnknown == -1;
1867 int changed;
1869 changed = routerset_add_unknown_ccs(&options->ExcludeNodes, is_auto);
1870 changed += routerset_add_unknown_ccs(&options->ExcludeExitNodes, is_auto);
1872 if (changed)
1873 routerset_add_unknown_ccs(&options->ExcludeExitNodesUnion_, is_auto);
1876 /* Check for transitions that need action. */
1877 if (old_options) {
1878 int revise_trackexithosts = 0;
1879 int revise_automap_entries = 0;
1880 int abandon_circuits = 0;
1881 if ((options->UseEntryGuards && !old_options->UseEntryGuards) ||
1882 options->UseBridges != old_options->UseBridges ||
1883 (options->UseBridges &&
1884 !config_lines_eq(options->Bridges, old_options->Bridges)) ||
1885 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes) ||
1886 !routerset_equal(old_options->ExcludeExitNodes,
1887 options->ExcludeExitNodes) ||
1888 !routerset_equal(old_options->EntryNodes, options->EntryNodes) ||
1889 !routerset_equal(old_options->ExitNodes, options->ExitNodes) ||
1890 !routerset_equal(old_options->Tor2webRendezvousPoints,
1891 options->Tor2webRendezvousPoints) ||
1892 options->StrictNodes != old_options->StrictNodes) {
1893 log_info(LD_CIRC,
1894 "Changed to using entry guards or bridges, or changed "
1895 "preferred or excluded node lists. "
1896 "Abandoning previous circuits.");
1897 abandon_circuits = 1;
1900 if (transition_affects_guards) {
1901 if (guards_update_all()) {
1902 abandon_circuits = 1;
1906 if (abandon_circuits) {
1907 circuit_mark_all_unused_circs();
1908 circuit_mark_all_dirty_circs_as_unusable();
1909 revise_trackexithosts = 1;
1912 if (!smartlist_strings_eq(old_options->TrackHostExits,
1913 options->TrackHostExits))
1914 revise_trackexithosts = 1;
1916 if (revise_trackexithosts)
1917 addressmap_clear_excluded_trackexithosts(options);
1919 if (!options->AutomapHostsOnResolve &&
1920 old_options->AutomapHostsOnResolve) {
1921 revise_automap_entries = 1;
1922 } else {
1923 if (!smartlist_strings_eq(old_options->AutomapHostsSuffixes,
1924 options->AutomapHostsSuffixes))
1925 revise_automap_entries = 1;
1926 else if (!opt_streq(old_options->VirtualAddrNetworkIPv4,
1927 options->VirtualAddrNetworkIPv4) ||
1928 !opt_streq(old_options->VirtualAddrNetworkIPv6,
1929 options->VirtualAddrNetworkIPv6))
1930 revise_automap_entries = 1;
1933 if (revise_automap_entries)
1934 addressmap_clear_invalid_automaps(options);
1936 /* How long should we delay counting bridge stats after becoming a bridge?
1937 * We use this so we don't count clients who used our bridge thinking it is
1938 * a relay. If you change this, don't forget to change the log message
1939 * below. It's 4 hours (the time it takes to stop being used by clients)
1940 * plus some extra time for clock skew. */
1941 #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
1943 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
1944 int was_relay = 0;
1945 if (options->BridgeRelay) {
1946 time_t int_start = time(NULL);
1947 if (config_lines_eq(old_options->ORPort_lines,options->ORPort_lines)) {
1948 int_start += RELAY_BRIDGE_STATS_DELAY;
1949 was_relay = 1;
1951 geoip_bridge_stats_init(int_start);
1952 log_info(LD_CONFIG, "We are acting as a bridge now. Starting new "
1953 "GeoIP stats interval%s.", was_relay ? " in 6 "
1954 "hours from now" : "");
1955 } else {
1956 geoip_bridge_stats_term();
1957 log_info(LD_GENERAL, "We are no longer acting as a bridge. "
1958 "Forgetting GeoIP stats.");
1962 if (transition_affects_workers) {
1963 log_info(LD_GENERAL,
1964 "Worker-related options changed. Rotating workers.");
1966 if (server_mode(options) && !server_mode(old_options)) {
1967 cpu_init();
1968 ip_address_changed(0);
1969 if (have_completed_a_circuit() || !any_predicted_circuits(time(NULL)))
1970 inform_testing_reachability();
1972 cpuworkers_rotate_keyinfo();
1973 if (dns_reset())
1974 return -1;
1975 } else {
1976 if (dns_reset())
1977 return -1;
1980 if (options->PerConnBWRate != old_options->PerConnBWRate ||
1981 options->PerConnBWBurst != old_options->PerConnBWBurst)
1982 connection_or_update_token_buckets(get_connection_array(), options);
1985 /* Only collect directory-request statistics on relays and bridges. */
1986 options->DirReqStatistics = options->DirReqStatistics_option &&
1987 server_mode(options);
1988 options->HiddenServiceStatistics =
1989 options->HiddenServiceStatistics_option && server_mode(options);
1991 if (options->CellStatistics || options->DirReqStatistics ||
1992 options->EntryStatistics || options->ExitPortStatistics ||
1993 options->ConnDirectionStatistics ||
1994 options->HiddenServiceStatistics ||
1995 options->BridgeAuthoritativeDir) {
1996 time_t now = time(NULL);
1997 int print_notice = 0;
1999 /* Only collect other relay-only statistics on relays. */
2000 if (!public_server_mode(options)) {
2001 options->CellStatistics = 0;
2002 options->EntryStatistics = 0;
2003 options->ConnDirectionStatistics = 0;
2004 options->ExitPortStatistics = 0;
2007 if ((!old_options || !old_options->CellStatistics) &&
2008 options->CellStatistics) {
2009 rep_hist_buffer_stats_init(now);
2010 print_notice = 1;
2012 if ((!old_options || !old_options->DirReqStatistics) &&
2013 options->DirReqStatistics) {
2014 if (geoip_is_loaded(AF_INET)) {
2015 geoip_dirreq_stats_init(now);
2016 print_notice = 1;
2017 } else {
2018 /* disable statistics collection since we have no geoip file */
2019 options->DirReqStatistics = 0;
2020 if (options->ORPort_set)
2021 log_notice(LD_CONFIG, "Configured to measure directory request "
2022 "statistics, but no GeoIP database found. "
2023 "Please specify a GeoIP database using the "
2024 "GeoIPFile option.");
2027 if ((!old_options || !old_options->EntryStatistics) &&
2028 options->EntryStatistics && !should_record_bridge_info(options)) {
2029 if (geoip_is_loaded(AF_INET) || geoip_is_loaded(AF_INET6)) {
2030 geoip_entry_stats_init(now);
2031 print_notice = 1;
2032 } else {
2033 options->EntryStatistics = 0;
2034 log_notice(LD_CONFIG, "Configured to measure entry node "
2035 "statistics, but no GeoIP database found. "
2036 "Please specify a GeoIP database using the "
2037 "GeoIPFile option.");
2040 if ((!old_options || !old_options->ExitPortStatistics) &&
2041 options->ExitPortStatistics) {
2042 rep_hist_exit_stats_init(now);
2043 print_notice = 1;
2045 if ((!old_options || !old_options->ConnDirectionStatistics) &&
2046 options->ConnDirectionStatistics) {
2047 rep_hist_conn_stats_init(now);
2049 if ((!old_options || !old_options->HiddenServiceStatistics) &&
2050 options->HiddenServiceStatistics) {
2051 log_info(LD_CONFIG, "Configured to measure hidden service statistics.");
2052 rep_hist_hs_stats_init(now);
2054 if ((!old_options || !old_options->BridgeAuthoritativeDir) &&
2055 options->BridgeAuthoritativeDir) {
2056 rep_hist_desc_stats_init(now);
2057 print_notice = 1;
2059 if (print_notice)
2060 log_notice(LD_CONFIG, "Configured to measure statistics. Look for "
2061 "the *-stats files that will first be written to the "
2062 "data directory in 24 hours from now.");
2065 /* If we used to have statistics enabled but we just disabled them,
2066 stop gathering them. */
2067 if (old_options && old_options->CellStatistics &&
2068 !options->CellStatistics)
2069 rep_hist_buffer_stats_term();
2070 if (old_options && old_options->DirReqStatistics &&
2071 !options->DirReqStatistics)
2072 geoip_dirreq_stats_term();
2073 if (old_options && old_options->EntryStatistics &&
2074 !options->EntryStatistics)
2075 geoip_entry_stats_term();
2076 if (old_options && old_options->HiddenServiceStatistics &&
2077 !options->HiddenServiceStatistics)
2078 rep_hist_hs_stats_term();
2079 if (old_options && old_options->ExitPortStatistics &&
2080 !options->ExitPortStatistics)
2081 rep_hist_exit_stats_term();
2082 if (old_options && old_options->ConnDirectionStatistics &&
2083 !options->ConnDirectionStatistics)
2084 rep_hist_conn_stats_term();
2085 if (old_options && old_options->BridgeAuthoritativeDir &&
2086 !options->BridgeAuthoritativeDir)
2087 rep_hist_desc_stats_term();
2089 /* Since our options changed, we might need to regenerate and upload our
2090 * server descriptor.
2092 if (!old_options ||
2093 options_transition_affects_descriptor(old_options, options))
2094 mark_my_descriptor_dirty("config change");
2096 /* We may need to reschedule some directory stuff if our status changed. */
2097 if (old_options) {
2098 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
2099 dirvote_recalculate_timing(options, time(NULL));
2100 if (!bool_eq(directory_fetches_dir_info_early(options),
2101 directory_fetches_dir_info_early(old_options)) ||
2102 !bool_eq(directory_fetches_dir_info_later(options),
2103 directory_fetches_dir_info_later(old_options))) {
2104 /* Make sure update_router_have_minimum_dir_info() gets called. */
2105 router_dir_info_changed();
2106 /* We might need to download a new consensus status later or sooner than
2107 * we had expected. */
2108 update_consensus_networkstatus_fetch_time(time(NULL));
2112 /* Load the webpage we're going to serve every time someone asks for '/' on
2113 our DirPort. */
2114 tor_free(global_dirfrontpagecontents);
2115 if (options->DirPortFrontPage) {
2116 global_dirfrontpagecontents =
2117 read_file_to_str(options->DirPortFrontPage, 0, NULL);
2118 if (!global_dirfrontpagecontents) {
2119 log_warn(LD_CONFIG,
2120 "DirPortFrontPage file '%s' not found. Continuing anyway.",
2121 options->DirPortFrontPage);
2125 return 0;
2128 typedef enum {
2129 TAKES_NO_ARGUMENT = 0,
2130 ARGUMENT_NECESSARY = 1,
2131 ARGUMENT_OPTIONAL = 2
2132 } takes_argument_t;
2134 static const struct {
2135 const char *name;
2136 takes_argument_t takes_argument;
2137 } CMDLINE_ONLY_OPTIONS[] = {
2138 { "-f", ARGUMENT_NECESSARY },
2139 { "--allow-missing-torrc", TAKES_NO_ARGUMENT },
2140 { "--defaults-torrc", ARGUMENT_NECESSARY },
2141 { "--hash-password", ARGUMENT_NECESSARY },
2142 { "--dump-config", ARGUMENT_OPTIONAL },
2143 { "--list-fingerprint", TAKES_NO_ARGUMENT },
2144 { "--keygen", TAKES_NO_ARGUMENT },
2145 { "--key-expiration", ARGUMENT_OPTIONAL },
2146 { "--newpass", TAKES_NO_ARGUMENT },
2147 { "--no-passphrase", TAKES_NO_ARGUMENT },
2148 { "--passphrase-fd", ARGUMENT_NECESSARY },
2149 { "--verify-config", TAKES_NO_ARGUMENT },
2150 { "--ignore-missing-torrc", TAKES_NO_ARGUMENT },
2151 { "--quiet", TAKES_NO_ARGUMENT },
2152 { "--hush", TAKES_NO_ARGUMENT },
2153 { "--version", TAKES_NO_ARGUMENT },
2154 { "--library-versions", TAKES_NO_ARGUMENT },
2155 { "-h", TAKES_NO_ARGUMENT },
2156 { "--help", TAKES_NO_ARGUMENT },
2157 { "--list-torrc-options", TAKES_NO_ARGUMENT },
2158 { "--list-deprecated-options",TAKES_NO_ARGUMENT },
2159 { "--nt-service", TAKES_NO_ARGUMENT },
2160 { "-nt-service", TAKES_NO_ARGUMENT },
2161 { NULL, 0 },
2164 /** Helper: Read a list of configuration options from the command line. If
2165 * successful, or if ignore_errors is set, put them in *<b>result</b>, put the
2166 * commandline-only options in *<b>cmdline_result</b>, and return 0;
2167 * otherwise, return -1 and leave *<b>result</b> and <b>cmdline_result</b>
2168 * alone. */
2170 config_parse_commandline(int argc, char **argv, int ignore_errors,
2171 config_line_t **result,
2172 config_line_t **cmdline_result)
2174 config_line_t *param = NULL;
2176 config_line_t *front = NULL;
2177 config_line_t **new = &front;
2179 config_line_t *front_cmdline = NULL;
2180 config_line_t **new_cmdline = &front_cmdline;
2182 char *s, *arg;
2183 int i = 1;
2185 while (i < argc) {
2186 unsigned command = CONFIG_LINE_NORMAL;
2187 takes_argument_t want_arg = ARGUMENT_NECESSARY;
2188 int is_cmdline = 0;
2189 int j;
2191 for (j = 0; CMDLINE_ONLY_OPTIONS[j].name != NULL; ++j) {
2192 if (!strcmp(argv[i], CMDLINE_ONLY_OPTIONS[j].name)) {
2193 is_cmdline = 1;
2194 want_arg = CMDLINE_ONLY_OPTIONS[j].takes_argument;
2195 break;
2199 s = argv[i];
2201 /* Each keyword may be prefixed with one or two dashes. */
2202 if (*s == '-')
2203 s++;
2204 if (*s == '-')
2205 s++;
2206 /* Figure out the command, if any. */
2207 if (*s == '+') {
2208 s++;
2209 command = CONFIG_LINE_APPEND;
2210 } else if (*s == '/') {
2211 s++;
2212 command = CONFIG_LINE_CLEAR;
2213 /* A 'clear' command has no argument. */
2214 want_arg = 0;
2217 const int is_last = (i == argc-1);
2219 if (want_arg == ARGUMENT_NECESSARY && is_last) {
2220 if (ignore_errors) {
2221 arg = tor_strdup("");
2222 } else {
2223 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
2224 argv[i]);
2225 config_free_lines(front);
2226 config_free_lines(front_cmdline);
2227 return -1;
2229 } else if (want_arg == ARGUMENT_OPTIONAL && is_last) {
2230 arg = tor_strdup("");
2231 } else {
2232 arg = (want_arg != TAKES_NO_ARGUMENT) ? tor_strdup(argv[i+1]) :
2233 tor_strdup("");
2236 param = tor_malloc_zero(sizeof(config_line_t));
2237 param->key = is_cmdline ? tor_strdup(argv[i]) :
2238 tor_strdup(config_expand_abbrev(&options_format, s, 1, 1));
2239 param->value = arg;
2240 param->command = command;
2241 param->next = NULL;
2242 log_debug(LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
2243 param->key, param->value);
2245 if (is_cmdline) {
2246 *new_cmdline = param;
2247 new_cmdline = &((*new_cmdline)->next);
2248 } else {
2249 *new = param;
2250 new = &((*new)->next);
2253 i += want_arg ? 2 : 1;
2255 *cmdline_result = front_cmdline;
2256 *result = front;
2257 return 0;
2260 /** Return true iff key is a valid configuration option. */
2262 option_is_recognized(const char *key)
2264 const config_var_t *var = config_find_option(&options_format, key);
2265 return (var != NULL);
2268 /** Return the canonical name of a configuration option, or NULL
2269 * if no such option exists. */
2270 const char *
2271 option_get_canonical_name(const char *key)
2273 const config_var_t *var = config_find_option(&options_format, key);
2274 return var ? var->name : NULL;
2277 /** Return a canonical list of the options assigned for key.
2279 config_line_t *
2280 option_get_assignment(const or_options_t *options, const char *key)
2282 return config_get_assigned_option(&options_format, options, key, 1);
2285 /** Try assigning <b>list</b> to the global options. You do this by duping
2286 * options, assigning list to the new one, then validating it. If it's
2287 * ok, then throw out the old one and stick with the new one. Else,
2288 * revert to old and return failure. Return SETOPT_OK on success, or
2289 * a setopt_err_t on failure.
2291 * If not success, point *<b>msg</b> to a newly allocated string describing
2292 * what went wrong.
2294 setopt_err_t
2295 options_trial_assign(config_line_t *list, unsigned flags, char **msg)
2297 int r;
2298 or_options_t *trial_options = config_dup(&options_format, get_options());
2300 if ((r=config_assign(&options_format, trial_options,
2301 list, flags, msg)) < 0) {
2302 or_options_free(trial_options);
2303 return r;
2306 if (options_validate(get_options_mutable(), trial_options,
2307 global_default_options, 1, msg) < 0) {
2308 or_options_free(trial_options);
2309 return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2312 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2313 or_options_free(trial_options);
2314 return SETOPT_ERR_TRANSITION;
2317 if (set_options(trial_options, msg)<0) {
2318 or_options_free(trial_options);
2319 return SETOPT_ERR_SETTING;
2322 /* we liked it. put it in place. */
2323 return SETOPT_OK;
2326 /** Print a usage message for tor. */
2327 static void
2328 print_usage(void)
2330 printf(
2331 "Copyright (c) 2001-2004, Roger Dingledine\n"
2332 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2333 "Copyright (c) 2007-2017, The Tor Project, Inc.\n\n"
2334 "tor -f <torrc> [args]\n"
2335 "See man page for options, or https://www.torproject.org/ for "
2336 "documentation.\n");
2339 /** Print all non-obsolete torrc options. */
2340 static void
2341 list_torrc_options(void)
2343 int i;
2344 for (i = 0; option_vars_[i].name; ++i) {
2345 const config_var_t *var = &option_vars_[i];
2346 if (var->type == CONFIG_TYPE_OBSOLETE ||
2347 var->type == CONFIG_TYPE_LINELIST_V)
2348 continue;
2349 printf("%s\n", var->name);
2353 /** Print all deprecated but non-obsolete torrc options. */
2354 static void
2355 list_deprecated_options(void)
2357 const config_deprecation_t *d;
2358 for (d = option_deprecation_notes_; d->name; ++d) {
2359 printf("%s\n", d->name);
2363 /** Last value actually set by resolve_my_address. */
2364 static uint32_t last_resolved_addr = 0;
2366 /** Accessor for last_resolved_addr from outside this file. */
2367 uint32_t
2368 get_last_resolved_addr(void)
2370 return last_resolved_addr;
2373 /** Reset last_resolved_addr from outside this file. */
2374 void
2375 reset_last_resolved_addr(void)
2377 last_resolved_addr = 0;
2380 /* Return true if <b>options</b> is using the default authorities, and false
2381 * if any authority-related option has been overridden. */
2383 using_default_dir_authorities(const or_options_t *options)
2385 return (!options->DirAuthorities && !options->AlternateDirAuthority);
2389 * Attempt getting our non-local (as judged by tor_addr_is_internal()
2390 * function) IP address using following techniques, listed in
2391 * order from best (most desirable, try first) to worst (least
2392 * desirable, try if everything else fails).
2394 * First, attempt using <b>options-\>Address</b> to get our
2395 * non-local IP address.
2397 * If <b>options-\>Address</b> represents a non-local IP address,
2398 * consider it ours.
2400 * If <b>options-\>Address</b> is a DNS name that resolves to
2401 * a non-local IP address, consider this IP address ours.
2403 * If <b>options-\>Address</b> is NULL, fall back to getting local
2404 * hostname and using it in above-described ways to try and
2405 * get our IP address.
2407 * In case local hostname cannot be resolved to a non-local IP
2408 * address, try getting an IP address of network interface
2409 * in hopes it will be non-local one.
2411 * Fail if one or more of the following is true:
2412 * - DNS name in <b>options-\>Address</b> cannot be resolved.
2413 * - <b>options-\>Address</b> is a local host address.
2414 * - Attempt at getting local hostname fails.
2415 * - Attempt at getting network interface address fails.
2417 * Return 0 if all is well, or -1 if we can't find a suitable
2418 * public IP address.
2420 * If we are returning 0:
2421 * - Put our public IP address (in host order) into *<b>addr_out</b>.
2422 * - If <b>method_out</b> is non-NULL, set *<b>method_out</b> to a static
2423 * string describing how we arrived at our answer.
2424 * - "CONFIGURED" - parsed from IP address string in
2425 * <b>options-\>Address</b>
2426 * - "RESOLVED" - resolved from DNS name in <b>options-\>Address</b>
2427 * - "GETHOSTNAME" - resolved from a local hostname.
2428 * - "INTERFACE" - retrieved from a network interface.
2429 * - If <b>hostname_out</b> is non-NULL, and we resolved a hostname to
2430 * get our address, set *<b>hostname_out</b> to a newly allocated string
2431 * holding that hostname. (If we didn't get our address by resolving a
2432 * hostname, set *<b>hostname_out</b> to NULL.)
2434 * XXXX ipv6
2437 resolve_my_address(int warn_severity, const or_options_t *options,
2438 uint32_t *addr_out,
2439 const char **method_out, char **hostname_out)
2441 struct in_addr in;
2442 uint32_t addr; /* host order */
2443 char hostname[256];
2444 const char *method_used;
2445 const char *hostname_used;
2446 int explicit_ip=1;
2447 int explicit_hostname=1;
2448 int from_interface=0;
2449 char *addr_string = NULL;
2450 const char *address = options->Address;
2451 int notice_severity = warn_severity <= LOG_NOTICE ?
2452 LOG_NOTICE : warn_severity;
2454 tor_addr_t myaddr;
2455 tor_assert(addr_out);
2458 * Step one: Fill in 'hostname' to be our best guess.
2461 if (address && *address) {
2462 strlcpy(hostname, address, sizeof(hostname));
2463 } else { /* then we need to guess our address */
2464 explicit_ip = 0; /* it's implicit */
2465 explicit_hostname = 0; /* it's implicit */
2467 if (tor_gethostname(hostname, sizeof(hostname)) < 0) {
2468 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2469 return -1;
2471 log_debug(LD_CONFIG, "Guessed local host name as '%s'", hostname);
2475 * Step two: Now that we know 'hostname', parse it or resolve it. If
2476 * it doesn't parse or resolve, look at the interface address. Set 'addr'
2477 * to be our (host-order) 32-bit answer.
2480 if (tor_inet_aton(hostname, &in) == 0) {
2481 /* then we have to resolve it */
2482 explicit_ip = 0;
2483 if (tor_lookup_hostname(hostname, &addr)) { /* failed to resolve */
2484 uint32_t interface_ip; /* host order */
2486 if (explicit_hostname) {
2487 log_fn(warn_severity, LD_CONFIG,
2488 "Could not resolve local Address '%s'. Failing.", hostname);
2489 return -1;
2491 log_fn(notice_severity, LD_CONFIG,
2492 "Could not resolve guessed local hostname '%s'. "
2493 "Trying something else.", hostname);
2494 if (get_interface_address(warn_severity, &interface_ip)) {
2495 log_fn(warn_severity, LD_CONFIG,
2496 "Could not get local interface IP address. Failing.");
2497 return -1;
2499 from_interface = 1;
2500 addr = interface_ip;
2501 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2502 "local interface. Using that.", fmt_addr32(addr));
2503 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2504 } else { /* resolved hostname into addr */
2505 tor_addr_from_ipv4h(&myaddr, addr);
2507 if (!explicit_hostname &&
2508 tor_addr_is_internal(&myaddr, 0)) {
2509 tor_addr_t interface_ip;
2511 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2512 "resolves to a private IP address (%s). Trying something "
2513 "else.", hostname, fmt_addr32(addr));
2515 if (get_interface_address6(warn_severity, AF_INET, &interface_ip)<0) {
2516 log_fn(warn_severity, LD_CONFIG,
2517 "Could not get local interface IP address. Too bad.");
2518 } else if (tor_addr_is_internal(&interface_ip, 0)) {
2519 log_fn(notice_severity, LD_CONFIG,
2520 "Interface IP address '%s' is a private address too. "
2521 "Ignoring.", fmt_addr(&interface_ip));
2522 } else {
2523 from_interface = 1;
2524 addr = tor_addr_to_ipv4h(&interface_ip);
2525 log_fn(notice_severity, LD_CONFIG,
2526 "Learned IP address '%s' for local interface."
2527 " Using that.", fmt_addr32(addr));
2528 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2532 } else {
2533 addr = ntohl(in.s_addr); /* set addr so that addr_string is not
2534 * illformed */
2538 * Step three: Check whether 'addr' is an internal IP address, and error
2539 * out if it is and we don't want that.
2542 tor_addr_from_ipv4h(&myaddr,addr);
2544 addr_string = tor_dup_ip(addr);
2545 if (tor_addr_is_internal(&myaddr, 0)) {
2546 /* make sure we're ok with publishing an internal IP */
2547 if (using_default_dir_authorities(options)) {
2548 /* if they are using the default authorities, disallow internal IPs
2549 * always. */
2550 log_fn(warn_severity, LD_CONFIG,
2551 "Address '%s' resolves to private IP address '%s'. "
2552 "Tor servers that use the default DirAuthorities must have "
2553 "public IP addresses.", hostname, addr_string);
2554 tor_free(addr_string);
2555 return -1;
2557 if (!explicit_ip) {
2558 /* even if they've set their own authorities, require an explicit IP if
2559 * they're using an internal address. */
2560 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2561 "IP address '%s'. Please set the Address config option to be "
2562 "the IP address you want to use.", hostname, addr_string);
2563 tor_free(addr_string);
2564 return -1;
2569 * Step four: We have a winner! 'addr' is our answer for sure, and
2570 * 'addr_string' is its string form. Fill out the various fields to
2571 * say how we decided it.
2574 log_debug(LD_CONFIG, "Resolved Address to '%s'.", addr_string);
2576 if (explicit_ip) {
2577 method_used = "CONFIGURED";
2578 hostname_used = NULL;
2579 } else if (explicit_hostname) {
2580 method_used = "RESOLVED";
2581 hostname_used = hostname;
2582 } else if (from_interface) {
2583 method_used = "INTERFACE";
2584 hostname_used = NULL;
2585 } else {
2586 method_used = "GETHOSTNAME";
2587 hostname_used = hostname;
2590 *addr_out = addr;
2591 if (method_out)
2592 *method_out = method_used;
2593 if (hostname_out)
2594 *hostname_out = hostname_used ? tor_strdup(hostname_used) : NULL;
2597 * Step five: Check if the answer has changed since last time (or if
2598 * there was no last time), and if so call various functions to keep
2599 * us up-to-date.
2602 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2603 /* Leave this as a notice, regardless of the requested severity,
2604 * at least until dynamic IP address support becomes bulletproof. */
2605 log_notice(LD_NET,
2606 "Your IP address seems to have changed to %s "
2607 "(METHOD=%s%s%s). Updating.",
2608 addr_string, method_used,
2609 hostname_used ? " HOSTNAME=" : "",
2610 hostname_used ? hostname_used : "");
2611 ip_address_changed(0);
2614 if (last_resolved_addr != *addr_out) {
2615 control_event_server_status(LOG_NOTICE,
2616 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s%s%s",
2617 addr_string, method_used,
2618 hostname_used ? " HOSTNAME=" : "",
2619 hostname_used ? hostname_used : "");
2621 last_resolved_addr = *addr_out;
2624 * And finally, clean up and return success.
2627 tor_free(addr_string);
2628 return 0;
2631 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2632 * on a private network.
2634 MOCK_IMPL(int,
2635 is_local_addr, (const tor_addr_t *addr))
2637 if (tor_addr_is_internal(addr, 0))
2638 return 1;
2639 /* Check whether ip is on the same /24 as we are. */
2640 if (get_options()->EnforceDistinctSubnets == 0)
2641 return 0;
2642 if (tor_addr_family(addr) == AF_INET) {
2643 uint32_t ip = tor_addr_to_ipv4h(addr);
2645 /* It's possible that this next check will hit before the first time
2646 * resolve_my_address actually succeeds. (For clients, it is likely that
2647 * resolve_my_address will never be called at all). In those cases,
2648 * last_resolved_addr will be 0, and so checking to see whether ip is on
2649 * the same /24 as last_resolved_addr will be the same as checking whether
2650 * it was on net 0, which is already done by tor_addr_is_internal.
2652 if ((last_resolved_addr & (uint32_t)0xffffff00ul)
2653 == (ip & (uint32_t)0xffffff00ul))
2654 return 1;
2656 return 0;
2659 /** Return a new empty or_options_t. Used for testing. */
2660 or_options_t *
2661 options_new(void)
2663 return config_new(&options_format);
2666 /** Set <b>options</b> to hold reasonable defaults for most options.
2667 * Each option defaults to zero. */
2668 void
2669 options_init(or_options_t *options)
2671 config_init(&options_format, options);
2674 /** Return a string containing a possible configuration file that would give
2675 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2676 * include options that are the same as Tor's defaults.
2678 char *
2679 options_dump(const or_options_t *options, int how_to_dump)
2681 const or_options_t *use_defaults;
2682 int minimal;
2683 switch (how_to_dump) {
2684 case OPTIONS_DUMP_MINIMAL:
2685 use_defaults = global_default_options;
2686 minimal = 1;
2687 break;
2688 case OPTIONS_DUMP_DEFAULTS:
2689 use_defaults = NULL;
2690 minimal = 1;
2691 break;
2692 case OPTIONS_DUMP_ALL:
2693 use_defaults = NULL;
2694 minimal = 0;
2695 break;
2696 default:
2697 log_warn(LD_BUG, "Bogus value for how_to_dump==%d", how_to_dump);
2698 return NULL;
2701 return config_dump(&options_format, use_defaults, options, minimal, 0);
2704 /** Return 0 if every element of sl is a string holding a decimal
2705 * representation of a port number, or if sl is NULL.
2706 * Otherwise set *msg and return -1. */
2707 static int
2708 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2710 int i;
2711 tor_assert(name);
2713 if (!sl)
2714 return 0;
2716 SMARTLIST_FOREACH(sl, const char *, cp,
2718 i = atoi(cp);
2719 if (i < 1 || i > 65535) {
2720 tor_asprintf(msg, "Port '%s' out of range in %s", cp, name);
2721 return -1;
2724 return 0;
2727 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2728 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2729 * Else return 0.
2731 static int
2732 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2734 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2735 /* This handles an understandable special case where somebody says "2gb"
2736 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2737 --*value;
2739 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2740 tor_asprintf(msg, "%s ("U64_FORMAT") must be at most %d",
2741 desc, U64_PRINTF_ARG(*value),
2742 ROUTER_MAX_DECLARED_BANDWIDTH);
2743 return -1;
2745 return 0;
2748 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2749 * and write it to <b>options</b>-\>PublishServerDescriptor_. Treat "1"
2750 * as "v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2751 * Treat "0" as "".
2752 * Return 0 on success or -1 if not a recognized authority type (in which
2753 * case the value of PublishServerDescriptor_ is undefined). */
2754 static int
2755 compute_publishserverdescriptor(or_options_t *options)
2757 smartlist_t *list = options->PublishServerDescriptor;
2758 dirinfo_type_t *auth = &options->PublishServerDescriptor_;
2759 *auth = NO_DIRINFO;
2760 if (!list) /* empty list, answer is none */
2761 return 0;
2762 SMARTLIST_FOREACH_BEGIN(list, const char *, string) {
2763 if (!strcasecmp(string, "v1"))
2764 log_warn(LD_CONFIG, "PublishServerDescriptor v1 has no effect, because "
2765 "there are no v1 directory authorities anymore.");
2766 else if (!strcmp(string, "1"))
2767 if (options->BridgeRelay)
2768 *auth |= BRIDGE_DIRINFO;
2769 else
2770 *auth |= V3_DIRINFO;
2771 else if (!strcasecmp(string, "v2"))
2772 log_warn(LD_CONFIG, "PublishServerDescriptor v2 has no effect, because "
2773 "there are no v2 directory authorities anymore.");
2774 else if (!strcasecmp(string, "v3"))
2775 *auth |= V3_DIRINFO;
2776 else if (!strcasecmp(string, "bridge"))
2777 *auth |= BRIDGE_DIRINFO;
2778 else if (!strcasecmp(string, "hidserv"))
2779 log_warn(LD_CONFIG,
2780 "PublishServerDescriptor hidserv is invalid. See "
2781 "PublishHidServDescriptors.");
2782 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2783 /* no authority */;
2784 else
2785 return -1;
2786 } SMARTLIST_FOREACH_END(string);
2787 return 0;
2790 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2791 * services can overload the directory system. */
2792 #define MIN_REND_POST_PERIOD (10*60)
2793 #define MIN_REND_POST_PERIOD_TESTING (5)
2795 /** Highest allowable value for CircuitsAvailableTimeout.
2796 * If this is too large, client connections will stay open for too long,
2797 * incurring extra padding overhead. */
2798 #define MAX_CIRCS_AVAILABLE_TIME (24*60*60)
2800 /** Highest allowable value for RendPostPeriod. */
2801 #define MAX_DIR_PERIOD ((7*24*60*60)/2)
2803 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2804 * will generate too many circuits and potentially overload the network. */
2805 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2807 /** Highest allowable value for MaxCircuitDirtiness: prevents time_t
2808 * overflows. */
2809 #define MAX_MAX_CIRCUIT_DIRTINESS (30*24*60*60)
2811 /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
2812 * will generate too many circuits and potentially overload the network. */
2813 #define MIN_CIRCUIT_STREAM_TIMEOUT 10
2815 /** Lowest recommended value for CircuitBuildTimeout; if it is set too low
2816 * and LearnCircuitBuildTimeout is off, the failure rate for circuit
2817 * construction may be very high. In that case, if it is set below this
2818 * threshold emit a warning.
2819 * */
2820 #define RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT (10)
2822 static int
2823 options_validate_cb(void *old_options, void *options, void *default_options,
2824 int from_setconf, char **msg)
2826 return options_validate(old_options, options, default_options,
2827 from_setconf, msg);
2830 #define REJECT(arg) \
2831 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2832 #if defined(__GNUC__) && __GNUC__ <= 3
2833 #define COMPLAIN(args...) \
2834 STMT_BEGIN log_warn(LD_CONFIG, args); STMT_END
2835 #else
2836 #define COMPLAIN(args, ...) \
2837 STMT_BEGIN log_warn(LD_CONFIG, args, ##__VA_ARGS__); STMT_END
2838 #endif
2840 /** Log a warning message iff <b>filepath</b> is not absolute.
2841 * Warning message must contain option name <b>option</b> and
2842 * an absolute path that <b>filepath</b> will resolve to.
2844 * In case <b>filepath</b> is absolute, do nothing.
2846 static void
2847 warn_if_option_path_is_relative(const char *option,
2848 char *filepath)
2850 if (filepath && path_is_relative(filepath)) {
2851 char *abs_path = make_path_absolute(filepath);
2852 COMPLAIN("Path for %s (%s) is relative and will resolve to %s."
2853 " Is this what you wanted?", option, filepath, abs_path);
2854 tor_free(abs_path);
2858 /** Scan <b>options</b> for occurances of relative file/directory
2859 * path and log a warning whenever it is found.
2861 static void
2862 warn_about_relative_paths(or_options_t *options)
2864 tor_assert(options);
2866 warn_if_option_path_is_relative("CookieAuthFile",
2867 options->CookieAuthFile);
2868 warn_if_option_path_is_relative("ExtORPortCookieAuthFile",
2869 options->ExtORPortCookieAuthFile);
2870 warn_if_option_path_is_relative("DirPortFrontPage",
2871 options->DirPortFrontPage);
2872 warn_if_option_path_is_relative("V3BandwidthsFile",
2873 options->V3BandwidthsFile);
2874 warn_if_option_path_is_relative("ControlPortWriteToFile",
2875 options->ControlPortWriteToFile);
2876 warn_if_option_path_is_relative("GeoIPFile",options->GeoIPFile);
2877 warn_if_option_path_is_relative("GeoIPv6File",options->GeoIPv6File);
2878 warn_if_option_path_is_relative("Log",options->DebugLogFile);
2879 warn_if_option_path_is_relative("AccelDir",options->AccelDir);
2880 warn_if_option_path_is_relative("DataDirectory",options->DataDirectory);
2881 warn_if_option_path_is_relative("PidFile",options->PidFile);
2883 for (config_line_t *hs_line = options->RendConfigLines; hs_line;
2884 hs_line = hs_line->next) {
2885 if (!strcasecmp(hs_line->key, "HiddenServiceDir"))
2886 warn_if_option_path_is_relative("HiddenServiceDir",hs_line->value);
2890 /* Validate options related to single onion services.
2891 * Modifies some options that are incompatible with single onion services.
2892 * On failure returns -1, and sets *msg to an error string.
2893 * Returns 0 on success. */
2894 STATIC int
2895 options_validate_single_onion(or_options_t *options, char **msg)
2897 /* The two single onion service options must have matching values. */
2898 if (options->HiddenServiceSingleHopMode &&
2899 !options->HiddenServiceNonAnonymousMode) {
2900 REJECT("HiddenServiceSingleHopMode does not provide any server anonymity. "
2901 "It must be used with HiddenServiceNonAnonymousMode set to 1.");
2903 if (options->HiddenServiceNonAnonymousMode &&
2904 !options->HiddenServiceSingleHopMode) {
2905 REJECT("HiddenServiceNonAnonymousMode does not provide any server "
2906 "anonymity. It must be used with HiddenServiceSingleHopMode set to "
2907 "1.");
2910 /* Now that we've checked that the two options are consistent, we can safely
2911 * call the rend_service_* functions that abstract these options. */
2913 /* If you run an anonymous client with an active Single Onion service, the
2914 * client loses anonymity. */
2915 const int client_port_set = (options->SocksPort_set ||
2916 options->TransPort_set ||
2917 options->NATDPort_set ||
2918 options->DNSPort_set);
2919 if (rend_service_non_anonymous_mode_enabled(options) && client_port_set &&
2920 !options->Tor2webMode) {
2921 REJECT("HiddenServiceNonAnonymousMode is incompatible with using Tor as "
2922 "an anonymous client. Please set Socks/Trans/NATD/DNSPort to 0, or "
2923 "revert HiddenServiceNonAnonymousMode to 0.");
2926 /* If you run a hidden service in non-anonymous mode, the hidden service
2927 * loses anonymity, even if SOCKSPort / Tor2web mode isn't used. */
2928 if (!rend_service_non_anonymous_mode_enabled(options) &&
2929 options->RendConfigLines && options->Tor2webMode) {
2930 REJECT("Non-anonymous (Tor2web) mode is incompatible with using Tor as a "
2931 "hidden service. Please remove all HiddenServiceDir lines, or use "
2932 "a version of tor compiled without --enable-tor2web-mode, or use "
2933 "HiddenServiceNonAnonymousMode.");
2936 if (rend_service_allow_non_anonymous_connection(options)
2937 && options->UseEntryGuards) {
2938 /* Single Onion services only use entry guards when uploading descriptors;
2939 * all other connections are one-hop. Further, Single Onions causes the
2940 * hidden service code to do things which break the path bias
2941 * detector, and it's far easier to turn off entry guards (and
2942 * thus the path bias detector with it) than to figure out how to
2943 * make path bias compatible with single onions.
2945 log_notice(LD_CONFIG,
2946 "HiddenServiceSingleHopMode is enabled; disabling "
2947 "UseEntryGuards.");
2948 options->UseEntryGuards = 0;
2951 return 0;
2954 /** Return 0 if every setting in <b>options</b> is reasonable, is a
2955 * permissible transition from <b>old_options</b>, and none of the
2956 * testing-only settings differ from <b>default_options</b> unless in
2957 * testing mode. Else return -1. Should have no side effects, except for
2958 * normalizing the contents of <b>options</b>.
2960 * On error, tor_strdup an error explanation into *<b>msg</b>.
2962 * XXX
2963 * If <b>from_setconf</b>, we were called by the controller, and our
2964 * Log line should stay empty. If it's 0, then give us a default log
2965 * if there are no logs defined.
2967 STATIC int
2968 options_validate(or_options_t *old_options, or_options_t *options,
2969 or_options_t *default_options, int from_setconf, char **msg)
2971 int i;
2972 config_line_t *cl;
2973 const char *uname = get_uname();
2974 int n_ports=0;
2975 int world_writable_control_socket=0;
2977 tor_assert(msg);
2978 *msg = NULL;
2980 if (parse_ports(options, 1, msg, &n_ports,
2981 &world_writable_control_socket) < 0)
2982 return -1;
2984 /* Set UseEntryGuards from the configured value, before we check it below.
2985 * We change UseEntryGuards when it's incompatible with other options,
2986 * but leave UseEntryGuards_option with the original value.
2987 * Always use the value of UseEntryGuards, not UseEntryGuards_option. */
2988 options->UseEntryGuards = options->UseEntryGuards_option;
2990 warn_about_relative_paths(options);
2992 if (server_mode(options) &&
2993 (!strcmpstart(uname, "Windows 95") ||
2994 !strcmpstart(uname, "Windows 98") ||
2995 !strcmpstart(uname, "Windows Me"))) {
2996 log_warn(LD_CONFIG, "Tor is running as a server, but you are "
2997 "running %s; this probably won't work. See "
2998 "https://www.torproject.org/docs/faq.html#BestOSForRelay "
2999 "for details.", uname);
3002 if (parse_outbound_addresses(options, 1, msg) < 0)
3003 return -1;
3005 if (validate_data_directory(options)<0)
3006 REJECT("Invalid DataDirectory");
3008 if (options->Nickname == NULL) {
3009 if (server_mode(options)) {
3010 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
3012 } else {
3013 if (!is_legal_nickname(options->Nickname)) {
3014 tor_asprintf(msg,
3015 "Nickname '%s', nicknames must be between 1 and 19 characters "
3016 "inclusive, and must contain only the characters [a-zA-Z0-9].",
3017 options->Nickname);
3018 return -1;
3022 if (server_mode(options) && !options->ContactInfo)
3023 log_notice(LD_CONFIG, "Your ContactInfo config option is not set. "
3024 "Please consider setting it, so we can contact you if your server is "
3025 "misconfigured or something else goes wrong.");
3027 /* Special case on first boot if no Log options are given. */
3028 if (!options->Logs && !options->RunAsDaemon && !from_setconf) {
3029 if (quiet_level == 0)
3030 config_line_append(&options->Logs, "Log", "notice stdout");
3031 else if (quiet_level == 1)
3032 config_line_append(&options->Logs, "Log", "warn stdout");
3035 /* Validate the tor_log(s) */
3036 if (options_init_logs(old_options, options, 1)<0)
3037 REJECT("Failed to validate Log options. See logs for details.");
3039 if (authdir_mode(options)) {
3040 /* confirm that our address isn't broken, so we can complain now */
3041 uint32_t tmp;
3042 if (resolve_my_address(LOG_WARN, options, &tmp, NULL, NULL) < 0)
3043 REJECT("Failed to resolve/guess local address. See logs for details.");
3046 if (server_mode(options) && options->RendConfigLines)
3047 log_warn(LD_CONFIG,
3048 "Tor is currently configured as a relay and a hidden service. "
3049 "That's not very secure: you should probably run your hidden service "
3050 "in a separate Tor process, at least -- see "
3051 "https://trac.torproject.org/8742");
3053 /* XXXX require that the only port not be DirPort? */
3054 /* XXXX require that at least one port be listened-upon. */
3055 if (n_ports == 0 && !options->RendConfigLines)
3056 log_warn(LD_CONFIG,
3057 "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
3058 "undefined, and there aren't any hidden services configured. "
3059 "Tor will still run, but probably won't do anything.");
3061 options->TransProxyType_parsed = TPT_DEFAULT;
3062 #ifdef USE_TRANSPARENT
3063 if (options->TransProxyType) {
3064 if (!strcasecmp(options->TransProxyType, "default")) {
3065 options->TransProxyType_parsed = TPT_DEFAULT;
3066 } else if (!strcasecmp(options->TransProxyType, "pf-divert")) {
3067 #if !defined(OpenBSD) && !defined( DARWIN )
3068 /* Later versions of OS X have pf */
3069 REJECT("pf-divert is a OpenBSD-specific "
3070 "and OS X/Darwin-specific feature.");
3071 #else
3072 options->TransProxyType_parsed = TPT_PF_DIVERT;
3073 #endif
3074 } else if (!strcasecmp(options->TransProxyType, "tproxy")) {
3075 #if !defined(__linux__)
3076 REJECT("TPROXY is a Linux-specific feature.");
3077 #else
3078 options->TransProxyType_parsed = TPT_TPROXY;
3079 #endif
3080 } else if (!strcasecmp(options->TransProxyType, "ipfw")) {
3081 #ifndef KERNEL_MAY_SUPPORT_IPFW
3082 /* Earlier versions of OS X have ipfw */
3083 REJECT("ipfw is a FreeBSD-specific "
3084 "and OS X/Darwin-specific feature.");
3085 #else
3086 options->TransProxyType_parsed = TPT_IPFW;
3087 #endif
3088 } else {
3089 REJECT("Unrecognized value for TransProxyType");
3092 if (strcasecmp(options->TransProxyType, "default") &&
3093 !options->TransPort_set) {
3094 REJECT("Cannot use TransProxyType without any valid TransPort.");
3097 #else
3098 if (options->TransPort_set)
3099 REJECT("TransPort is disabled in this build.");
3100 #endif
3102 if (options->TokenBucketRefillInterval <= 0
3103 || options->TokenBucketRefillInterval > 1000) {
3104 REJECT("TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
3107 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3108 options->ExcludeExitNodesUnion_ = routerset_new();
3109 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeExitNodes);
3110 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeNodes);
3113 if (options->SchedulerLowWaterMark__ == 0 ||
3114 options->SchedulerLowWaterMark__ > UINT32_MAX) {
3115 log_warn(LD_GENERAL, "Bad SchedulerLowWaterMark__ option");
3116 return -1;
3117 } else if (options->SchedulerHighWaterMark__ <=
3118 options->SchedulerLowWaterMark__ ||
3119 options->SchedulerHighWaterMark__ > UINT32_MAX) {
3120 log_warn(LD_GENERAL, "Bad SchedulerHighWaterMark option");
3121 return -1;
3124 if (options->NodeFamilies) {
3125 options->NodeFamilySets = smartlist_new();
3126 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3127 routerset_t *rs = routerset_new();
3128 if (routerset_parse(rs, cl->value, cl->key) == 0) {
3129 smartlist_add(options->NodeFamilySets, rs);
3130 } else {
3131 routerset_free(rs);
3136 if (options->ExcludeNodes && options->StrictNodes) {
3137 COMPLAIN("You have asked to exclude certain relays from all positions "
3138 "in your circuits. Expect hidden services and other Tor "
3139 "features to be broken in unpredictable ways.");
3142 for (cl = options->RecommendedPackages; cl; cl = cl->next) {
3143 if (! validate_recommended_package_line(cl->value)) {
3144 log_warn(LD_CONFIG, "Invalid RecommendedPackage line %s will be ignored",
3145 escaped(cl->value));
3149 if (options->AuthoritativeDir) {
3150 if (!options->ContactInfo && !options->TestingTorNetwork)
3151 REJECT("Authoritative directory servers must set ContactInfo");
3152 if (!options->RecommendedClientVersions)
3153 options->RecommendedClientVersions =
3154 config_lines_dup(options->RecommendedVersions);
3155 if (!options->RecommendedServerVersions)
3156 options->RecommendedServerVersions =
3157 config_lines_dup(options->RecommendedVersions);
3158 if (options->VersioningAuthoritativeDir &&
3159 (!options->RecommendedClientVersions ||
3160 !options->RecommendedServerVersions))
3161 REJECT("Versioning authoritative dir servers must set "
3162 "Recommended*Versions.");
3163 if (options->UseEntryGuards) {
3164 log_info(LD_CONFIG, "Authoritative directory servers can't set "
3165 "UseEntryGuards. Disabling.");
3166 options->UseEntryGuards = 0;
3168 if (!options->DownloadExtraInfo && authdir_mode_v3(options)) {
3169 log_info(LD_CONFIG, "Authoritative directories always try to download "
3170 "extra-info documents. Setting DownloadExtraInfo.");
3171 options->DownloadExtraInfo = 1;
3173 if (!(options->BridgeAuthoritativeDir ||
3174 options->V3AuthoritativeDir))
3175 REJECT("AuthoritativeDir is set, but none of "
3176 "(Bridge/V3)AuthoritativeDir is set.");
3177 /* If we have a v3bandwidthsfile and it's broken, complain on startup */
3178 if (options->V3BandwidthsFile && !old_options) {
3179 dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
3181 /* same for guardfraction file */
3182 if (options->GuardfractionFile && !old_options) {
3183 dirserv_read_guardfraction_file(options->GuardfractionFile, NULL);
3187 if (options->AuthoritativeDir && !options->DirPort_set)
3188 REJECT("Running as authoritative directory, but no DirPort set.");
3190 if (options->AuthoritativeDir && !options->ORPort_set)
3191 REJECT("Running as authoritative directory, but no ORPort set.");
3193 if (options->AuthoritativeDir && options->ClientOnly)
3194 REJECT("Running as authoritative directory, but ClientOnly also set.");
3196 if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
3197 REJECT("FetchDirInfoExtraEarly requires that you also set "
3198 "FetchDirInfoEarly");
3200 if (options->ConnLimit <= 0) {
3201 tor_asprintf(msg,
3202 "ConnLimit must be greater than 0, but was set to %d",
3203 options->ConnLimit);
3204 return -1;
3207 if (options->PathsNeededToBuildCircuits >= 0.0) {
3208 if (options->PathsNeededToBuildCircuits < 0.25) {
3209 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too low. Increasing "
3210 "to 0.25");
3211 options->PathsNeededToBuildCircuits = 0.25;
3212 } else if (options->PathsNeededToBuildCircuits > 0.95) {
3213 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too high. Decreasing "
3214 "to 0.95");
3215 options->PathsNeededToBuildCircuits = 0.95;
3219 if (options->MaxClientCircuitsPending <= 0 ||
3220 options->MaxClientCircuitsPending > MAX_MAX_CLIENT_CIRCUITS_PENDING) {
3221 tor_asprintf(msg,
3222 "MaxClientCircuitsPending must be between 1 and %d, but "
3223 "was set to %d", MAX_MAX_CLIENT_CIRCUITS_PENDING,
3224 options->MaxClientCircuitsPending);
3225 return -1;
3228 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3229 return -1;
3231 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3232 return -1;
3234 if (validate_ports_csv(options->RejectPlaintextPorts,
3235 "RejectPlaintextPorts", msg) < 0)
3236 return -1;
3238 if (validate_ports_csv(options->WarnPlaintextPorts,
3239 "WarnPlaintextPorts", msg) < 0)
3240 return -1;
3242 if (options->FascistFirewall && !options->ReachableAddresses) {
3243 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3244 /* We already have firewall ports set, so migrate them to
3245 * ReachableAddresses, which will set ReachableORAddresses and
3246 * ReachableDirAddresses if they aren't set explicitly. */
3247 smartlist_t *instead = smartlist_new();
3248 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3249 new_line->key = tor_strdup("ReachableAddresses");
3250 /* If we're configured with the old format, we need to prepend some
3251 * open ports. */
3252 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3254 int p = atoi(portno);
3255 if (p<0) continue;
3256 smartlist_add_asprintf(instead, "*:%d", p);
3258 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3259 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3260 log_notice(LD_CONFIG,
3261 "Converting FascistFirewall and FirewallPorts "
3262 "config options to new format: \"ReachableAddresses %s\"",
3263 new_line->value);
3264 options->ReachableAddresses = new_line;
3265 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3266 smartlist_free(instead);
3267 } else {
3268 /* We do not have FirewallPorts set, so add 80 to
3269 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3270 if (!options->ReachableDirAddresses) {
3271 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3272 new_line->key = tor_strdup("ReachableDirAddresses");
3273 new_line->value = tor_strdup("*:80");
3274 options->ReachableDirAddresses = new_line;
3275 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3276 "to new format: \"ReachableDirAddresses *:80\"");
3278 if (!options->ReachableORAddresses) {
3279 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3280 new_line->key = tor_strdup("ReachableORAddresses");
3281 new_line->value = tor_strdup("*:443");
3282 options->ReachableORAddresses = new_line;
3283 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3284 "to new format: \"ReachableORAddresses *:443\"");
3289 /* Terminate Reachable*Addresses with reject *
3291 for (i=0; i<3; i++) {
3292 config_line_t **linep =
3293 (i==0) ? &options->ReachableAddresses :
3294 (i==1) ? &options->ReachableORAddresses :
3295 &options->ReachableDirAddresses;
3296 if (!*linep)
3297 continue;
3298 /* We need to end with a reject *:*, not an implicit accept *:* */
3299 for (;;) {
3300 linep = &((*linep)->next);
3301 if (!*linep) {
3302 *linep = tor_malloc_zero(sizeof(config_line_t));
3303 (*linep)->key = tor_strdup(
3304 (i==0) ? "ReachableAddresses" :
3305 (i==1) ? "ReachableORAddresses" :
3306 "ReachableDirAddresses");
3307 (*linep)->value = tor_strdup("reject *:*");
3308 break;
3313 if ((options->ReachableAddresses ||
3314 options->ReachableORAddresses ||
3315 options->ReachableDirAddresses ||
3316 options->ClientUseIPv4 == 0) &&
3317 server_mode(options))
3318 REJECT("Servers must be able to freely connect to the rest "
3319 "of the Internet, so they must not set Reachable*Addresses "
3320 "or FascistFirewall or FirewallPorts or ClientUseIPv4 0.");
3322 if (options->UseBridges &&
3323 server_mode(options))
3324 REJECT("Servers must be able to freely connect to the rest "
3325 "of the Internet, so they must not set UseBridges.");
3327 /* If both of these are set, we'll end up with funny behavior where we
3328 * demand enough entrynodes be up and running else we won't build
3329 * circuits, yet we never actually use them. */
3330 if (options->UseBridges && options->EntryNodes)
3331 REJECT("You cannot set both UseBridges and EntryNodes.");
3333 /* If we have UseBridges as 1 and UseEntryGuards as 0, we end up bypassing
3334 * the use of bridges */
3335 if (options->UseBridges && !options->UseEntryGuards)
3336 REJECT("Setting UseBridges requires also setting UseEntryGuards.");
3338 options->MaxMemInQueues =
3339 compute_real_max_mem_in_queues(options->MaxMemInQueues_raw,
3340 server_mode(options));
3341 options->MaxMemInQueues_low_threshold = (options->MaxMemInQueues / 4) * 3;
3343 if (!options->SafeLogging ||
3344 !strcasecmp(options->SafeLogging, "0")) {
3345 options->SafeLogging_ = SAFELOG_SCRUB_NONE;
3346 } else if (!strcasecmp(options->SafeLogging, "relay")) {
3347 options->SafeLogging_ = SAFELOG_SCRUB_RELAY;
3348 } else if (!strcasecmp(options->SafeLogging, "1")) {
3349 options->SafeLogging_ = SAFELOG_SCRUB_ALL;
3350 } else {
3351 tor_asprintf(msg,
3352 "Unrecognized value '%s' in SafeLogging",
3353 escaped(options->SafeLogging));
3354 return -1;
3357 if (compute_publishserverdescriptor(options) < 0) {
3358 tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
3359 return -1;
3362 if ((options->BridgeRelay
3363 || options->PublishServerDescriptor_ & BRIDGE_DIRINFO)
3364 && (options->PublishServerDescriptor_ & V3_DIRINFO)) {
3365 REJECT("Bridges are not supposed to publish router descriptors to the "
3366 "directory authorities. Please correct your "
3367 "PublishServerDescriptor line.");
3370 if (options->BridgeRelay && options->DirPort_set) {
3371 log_warn(LD_CONFIG, "Can't set a DirPort on a bridge relay; disabling "
3372 "DirPort");
3373 config_free_lines(options->DirPort_lines);
3374 options->DirPort_lines = NULL;
3375 options->DirPort_set = 0;
3378 if (server_mode(options) && options->ConnectionPadding != -1) {
3379 REJECT("Relays must use 'auto' for the ConnectionPadding setting.");
3382 if (server_mode(options) && options->ReducedConnectionPadding != 0) {
3383 REJECT("Relays cannot set ReducedConnectionPadding. ");
3386 if (options->MinUptimeHidServDirectoryV2 < 0) {
3387 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3388 "least 0 seconds. Changing to 0.");
3389 options->MinUptimeHidServDirectoryV2 = 0;
3392 const int min_rendpostperiod =
3393 options->TestingTorNetwork ?
3394 MIN_REND_POST_PERIOD_TESTING : MIN_REND_POST_PERIOD;
3395 if (options->RendPostPeriod < min_rendpostperiod) {
3396 log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
3397 "raising to %d seconds.", min_rendpostperiod);
3398 options->RendPostPeriod = min_rendpostperiod;;
3401 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3402 log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3403 MAX_DIR_PERIOD);
3404 options->RendPostPeriod = MAX_DIR_PERIOD;
3407 /* Check the Single Onion Service options */
3408 if (options_validate_single_onion(options, msg) < 0)
3409 return -1;
3411 if (options->CircuitsAvailableTimeout > MAX_CIRCS_AVAILABLE_TIME) {
3412 // options_t is immutable for new code (the above code is older),
3413 // so just make the user fix the value themselves rather than
3414 // silently keep a shadow value lower than what they asked for.
3415 REJECT("CircuitsAvailableTimeout is too large. Max is 24 hours.");
3418 #ifdef ENABLE_TOR2WEB_MODE
3419 if (options->Tor2webMode && options->UseEntryGuards) {
3420 /* tor2web mode clients do not (and should not) use entry guards
3421 * in any meaningful way. Further, tor2web mode causes the hidden
3422 * service client code to do things which break the path bias
3423 * detector, and it's far easier to turn off entry guards (and
3424 * thus the path bias detector with it) than to figure out how to
3425 * make a piece of code which cannot possibly help tor2web mode
3426 * users compatible with tor2web mode.
3428 log_notice(LD_CONFIG,
3429 "Tor2WebMode is enabled; disabling UseEntryGuards.");
3430 options->UseEntryGuards = 0;
3432 #endif
3434 if (options->Tor2webRendezvousPoints && !options->Tor2webMode) {
3435 REJECT("Tor2webRendezvousPoints cannot be set without Tor2webMode.");
3438 if (options->EntryNodes && !options->UseEntryGuards) {
3439 REJECT("If EntryNodes is set, UseEntryGuards must be enabled.");
3442 if (!(options->UseEntryGuards) &&
3443 (options->RendConfigLines != NULL) &&
3444 !rend_service_allow_non_anonymous_connection(options)) {
3445 log_warn(LD_CONFIG,
3446 "UseEntryGuards is disabled, but you have configured one or more "
3447 "hidden services on this Tor instance. Your hidden services "
3448 "will be very easy to locate using a well-known attack -- see "
3449 "http://freehaven.net/anonbib/#hs-attack06 for details.");
3452 if (options->EntryNodes &&
3453 routerset_is_list(options->EntryNodes) &&
3454 (routerset_len(options->EntryNodes) == 1) &&
3455 (options->RendConfigLines != NULL)) {
3456 tor_asprintf(msg,
3457 "You have one single EntryNodes and at least one hidden service "
3458 "configured. This is bad because it's very easy to locate your "
3459 "entry guard which can then lead to the deanonymization of your "
3460 "hidden service -- for more details, see "
3461 "https://trac.torproject.org/projects/tor/ticket/14917. "
3462 "For this reason, the use of one EntryNodes with an hidden "
3463 "service is prohibited until a better solution is found.");
3464 return -1;
3467 /* Inform the hidden service operator that pinning EntryNodes can possibly
3468 * be harmful for the service anonymity. */
3469 if (options->EntryNodes &&
3470 routerset_is_list(options->EntryNodes) &&
3471 (options->RendConfigLines != NULL)) {
3472 log_warn(LD_CONFIG,
3473 "EntryNodes is set with multiple entries and at least one "
3474 "hidden service is configured. Pinning entry nodes can possibly "
3475 "be harmful to the service anonymity. Because of this, we "
3476 "recommend you either don't do that or make sure you know what "
3477 "you are doing. For more details, please look at "
3478 "https://trac.torproject.org/projects/tor/ticket/21155.");
3481 /* Single Onion Services: non-anonymous hidden services */
3482 if (rend_service_non_anonymous_mode_enabled(options)) {
3483 log_warn(LD_CONFIG,
3484 "HiddenServiceNonAnonymousMode is set. Every hidden service on "
3485 "this tor instance is NON-ANONYMOUS. If "
3486 "the HiddenServiceNonAnonymousMode option is changed, Tor will "
3487 "refuse to launch hidden services from the same directories, to "
3488 "protect your anonymity against config errors. This setting is "
3489 "for experimental use only.");
3492 if (!options->LearnCircuitBuildTimeout && options->CircuitBuildTimeout &&
3493 options->CircuitBuildTimeout < RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT) {
3494 log_warn(LD_CONFIG,
3495 "CircuitBuildTimeout is shorter (%d seconds) than the recommended "
3496 "minimum (%d seconds), and LearnCircuitBuildTimeout is disabled. "
3497 "If tor isn't working, raise this value or enable "
3498 "LearnCircuitBuildTimeout.",
3499 options->CircuitBuildTimeout,
3500 RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT );
3501 } else if (!options->LearnCircuitBuildTimeout &&
3502 !options->CircuitBuildTimeout) {
3503 int severity = LOG_NOTICE;
3504 /* Be a little quieter if we've deliberately disabled
3505 * LearnCircuitBuildTimeout. */
3506 if (circuit_build_times_disabled_(options, 1)) {
3507 severity = LOG_INFO;
3509 log_fn(severity, LD_CONFIG, "You disabled LearnCircuitBuildTimeout, but "
3510 "didn't specify a CircuitBuildTimeout. I'll pick a plausible "
3511 "default.");
3514 if (options->PathBiasNoticeRate > 1.0) {
3515 tor_asprintf(msg,
3516 "PathBiasNoticeRate is too high. "
3517 "It must be between 0 and 1.0");
3518 return -1;
3520 if (options->PathBiasWarnRate > 1.0) {
3521 tor_asprintf(msg,
3522 "PathBiasWarnRate is too high. "
3523 "It must be between 0 and 1.0");
3524 return -1;
3526 if (options->PathBiasExtremeRate > 1.0) {
3527 tor_asprintf(msg,
3528 "PathBiasExtremeRate is too high. "
3529 "It must be between 0 and 1.0");
3530 return -1;
3532 if (options->PathBiasNoticeUseRate > 1.0) {
3533 tor_asprintf(msg,
3534 "PathBiasNoticeUseRate is too high. "
3535 "It must be between 0 and 1.0");
3536 return -1;
3538 if (options->PathBiasExtremeUseRate > 1.0) {
3539 tor_asprintf(msg,
3540 "PathBiasExtremeUseRate is too high. "
3541 "It must be between 0 and 1.0");
3542 return -1;
3545 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3546 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3547 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3548 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3551 if (options->MaxCircuitDirtiness > MAX_MAX_CIRCUIT_DIRTINESS) {
3552 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too high; "
3553 "setting to %d days.", MAX_MAX_CIRCUIT_DIRTINESS/86400);
3554 options->MaxCircuitDirtiness = MAX_MAX_CIRCUIT_DIRTINESS;
3557 if (options->CircuitStreamTimeout &&
3558 options->CircuitStreamTimeout < MIN_CIRCUIT_STREAM_TIMEOUT) {
3559 log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
3560 "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
3561 options->CircuitStreamTimeout = MIN_CIRCUIT_STREAM_TIMEOUT;
3564 if (options->HeartbeatPeriod &&
3565 options->HeartbeatPeriod < MIN_HEARTBEAT_PERIOD) {
3566 log_warn(LD_CONFIG, "HeartbeatPeriod option is too short; "
3567 "raising to %d seconds.", MIN_HEARTBEAT_PERIOD);
3568 options->HeartbeatPeriod = MIN_HEARTBEAT_PERIOD;
3571 if (options->KeepalivePeriod < 1)
3572 REJECT("KeepalivePeriod option must be positive.");
3574 if (options->PortForwarding && options->Sandbox) {
3575 REJECT("PortForwarding is not compatible with Sandbox; at most one can "
3576 "be set");
3578 if (options->PortForwarding && options->NoExec) {
3579 COMPLAIN("Both PortForwarding and NoExec are set; PortForwarding will "
3580 "be ignored.");
3583 if (ensure_bandwidth_cap(&options->BandwidthRate,
3584 "BandwidthRate", msg) < 0)
3585 return -1;
3586 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3587 "BandwidthBurst", msg) < 0)
3588 return -1;
3589 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3590 "MaxAdvertisedBandwidth", msg) < 0)
3591 return -1;
3592 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3593 "RelayBandwidthRate", msg) < 0)
3594 return -1;
3595 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3596 "RelayBandwidthBurst", msg) < 0)
3597 return -1;
3598 if (ensure_bandwidth_cap(&options->PerConnBWRate,
3599 "PerConnBWRate", msg) < 0)
3600 return -1;
3601 if (ensure_bandwidth_cap(&options->PerConnBWBurst,
3602 "PerConnBWBurst", msg) < 0)
3603 return -1;
3604 if (ensure_bandwidth_cap(&options->AuthDirFastGuarantee,
3605 "AuthDirFastGuarantee", msg) < 0)
3606 return -1;
3607 if (ensure_bandwidth_cap(&options->AuthDirGuardBWGuarantee,
3608 "AuthDirGuardBWGuarantee", msg) < 0)
3609 return -1;
3611 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3612 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3613 if (options->RelayBandwidthBurst && !options->RelayBandwidthRate)
3614 options->RelayBandwidthRate = options->RelayBandwidthBurst;
3616 if (server_mode(options)) {
3617 const unsigned required_min_bw =
3618 public_server_mode(options) ?
3619 RELAY_REQUIRED_MIN_BANDWIDTH : BRIDGE_REQUIRED_MIN_BANDWIDTH;
3620 const char * const optbridge =
3621 public_server_mode(options) ? "" : "bridge ";
3622 if (options->BandwidthRate < required_min_bw) {
3623 tor_asprintf(msg,
3624 "BandwidthRate is set to %d bytes/second. "
3625 "For %sservers, it must be at least %u.",
3626 (int)options->BandwidthRate, optbridge,
3627 required_min_bw);
3628 return -1;
3629 } else if (options->MaxAdvertisedBandwidth <
3630 required_min_bw/2) {
3631 tor_asprintf(msg,
3632 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3633 "For %sservers, it must be at least %u.",
3634 (int)options->MaxAdvertisedBandwidth, optbridge,
3635 required_min_bw/2);
3636 return -1;
3638 if (options->RelayBandwidthRate &&
3639 options->RelayBandwidthRate < required_min_bw) {
3640 tor_asprintf(msg,
3641 "RelayBandwidthRate is set to %d bytes/second. "
3642 "For %sservers, it must be at least %u.",
3643 (int)options->RelayBandwidthRate, optbridge,
3644 required_min_bw);
3645 return -1;
3649 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3650 REJECT("RelayBandwidthBurst must be at least equal "
3651 "to RelayBandwidthRate.");
3653 if (options->BandwidthRate > options->BandwidthBurst)
3654 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3656 /* if they set relaybandwidth* really high but left bandwidth*
3657 * at the default, raise the defaults. */
3658 if (options->RelayBandwidthRate > options->BandwidthRate)
3659 options->BandwidthRate = options->RelayBandwidthRate;
3660 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3661 options->BandwidthBurst = options->RelayBandwidthBurst;
3663 if (accounting_parse_options(options, 1)<0)
3664 REJECT("Failed to parse accounting options. See logs for details.");
3666 if (options->AccountingMax) {
3667 if (options->RendConfigLines && server_mode(options)) {
3668 log_warn(LD_CONFIG, "Using accounting with a hidden service and an "
3669 "ORPort is risky: your hidden service(s) and your public "
3670 "address will all turn off at the same time, which may alert "
3671 "observers that they are being run by the same party.");
3672 } else if (config_count_key(options->RendConfigLines,
3673 "HiddenServiceDir") > 1) {
3674 log_warn(LD_CONFIG, "Using accounting with multiple hidden services is "
3675 "risky: they will all turn off at the same time, which may "
3676 "alert observers that they are being run by the same party.");
3680 options->AccountingRule = ACCT_MAX;
3681 if (options->AccountingRule_option) {
3682 if (!strcmp(options->AccountingRule_option, "sum"))
3683 options->AccountingRule = ACCT_SUM;
3684 else if (!strcmp(options->AccountingRule_option, "max"))
3685 options->AccountingRule = ACCT_MAX;
3686 else if (!strcmp(options->AccountingRule_option, "in"))
3687 options->AccountingRule = ACCT_IN;
3688 else if (!strcmp(options->AccountingRule_option, "out"))
3689 options->AccountingRule = ACCT_OUT;
3690 else
3691 REJECT("AccountingRule must be 'sum', 'max', 'in', or 'out'");
3694 if (options->DirPort_set && !options->DirCache) {
3695 REJECT("DirPort configured but DirCache disabled. DirPort requires "
3696 "DirCache.");
3699 if (options->BridgeRelay && !options->DirCache) {
3700 REJECT("We're a bridge but DirCache is disabled. BridgeRelay requires "
3701 "DirCache.");
3704 if (server_mode(options)) {
3705 char *dircache_msg = NULL;
3706 if (have_enough_mem_for_dircache(options, 0, &dircache_msg)) {
3707 log_warn(LD_CONFIG, "%s", dircache_msg);
3708 tor_free(dircache_msg);
3712 if (options->HTTPProxy) { /* parse it now */
3713 if (tor_addr_port_lookup(options->HTTPProxy,
3714 &options->HTTPProxyAddr, &options->HTTPProxyPort) < 0)
3715 REJECT("HTTPProxy failed to parse or resolve. Please fix.");
3716 if (options->HTTPProxyPort == 0) { /* give it a default */
3717 options->HTTPProxyPort = 80;
3721 if (options->HTTPProxyAuthenticator) {
3722 if (strlen(options->HTTPProxyAuthenticator) >= 512)
3723 REJECT("HTTPProxyAuthenticator is too long (>= 512 chars).");
3726 if (options->HTTPSProxy) { /* parse it now */
3727 if (tor_addr_port_lookup(options->HTTPSProxy,
3728 &options->HTTPSProxyAddr, &options->HTTPSProxyPort) <0)
3729 REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
3730 if (options->HTTPSProxyPort == 0) { /* give it a default */
3731 options->HTTPSProxyPort = 443;
3735 if (options->HTTPSProxyAuthenticator) {
3736 if (strlen(options->HTTPSProxyAuthenticator) >= 512)
3737 REJECT("HTTPSProxyAuthenticator is too long (>= 512 chars).");
3740 if (options->Socks4Proxy) { /* parse it now */
3741 if (tor_addr_port_lookup(options->Socks4Proxy,
3742 &options->Socks4ProxyAddr,
3743 &options->Socks4ProxyPort) <0)
3744 REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
3745 if (options->Socks4ProxyPort == 0) { /* give it a default */
3746 options->Socks4ProxyPort = 1080;
3750 if (options->Socks5Proxy) { /* parse it now */
3751 if (tor_addr_port_lookup(options->Socks5Proxy,
3752 &options->Socks5ProxyAddr,
3753 &options->Socks5ProxyPort) <0)
3754 REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
3755 if (options->Socks5ProxyPort == 0) { /* give it a default */
3756 options->Socks5ProxyPort = 1080;
3760 /* Check if more than one exclusive proxy type has been enabled. */
3761 if (!!options->Socks4Proxy + !!options->Socks5Proxy +
3762 !!options->HTTPSProxy > 1)
3763 REJECT("You have configured more than one proxy type. "
3764 "(Socks4Proxy|Socks5Proxy|HTTPSProxy)");
3766 /* Check if the proxies will give surprising behavior. */
3767 if (options->HTTPProxy && !(options->Socks4Proxy ||
3768 options->Socks5Proxy ||
3769 options->HTTPSProxy)) {
3770 log_warn(LD_CONFIG, "HTTPProxy configured, but no SOCKS proxy or "
3771 "HTTPS proxy configured. Watch out: this configuration will "
3772 "proxy unencrypted directory connections only.");
3775 if (options->Socks5ProxyUsername) {
3776 size_t len;
3778 len = strlen(options->Socks5ProxyUsername);
3779 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
3780 REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
3782 if (!options->Socks5ProxyPassword)
3783 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3785 len = strlen(options->Socks5ProxyPassword);
3786 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
3787 REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
3788 } else if (options->Socks5ProxyPassword)
3789 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3791 if (options->HashedControlPassword) {
3792 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3793 if (!sl) {
3794 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3795 } else {
3796 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3797 smartlist_free(sl);
3801 if (options->HashedControlSessionPassword) {
3802 smartlist_t *sl = decode_hashed_passwords(
3803 options->HashedControlSessionPassword);
3804 if (!sl) {
3805 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3806 } else {
3807 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3808 smartlist_free(sl);
3812 if (options->OwningControllerProcess) {
3813 const char *validate_pspec_msg = NULL;
3814 if (tor_validate_process_specifier(options->OwningControllerProcess,
3815 &validate_pspec_msg)) {
3816 tor_asprintf(msg, "Bad OwningControllerProcess: %s",
3817 validate_pspec_msg);
3818 return -1;
3822 if ((options->ControlPort_set || world_writable_control_socket) &&
3823 !options->HashedControlPassword &&
3824 !options->HashedControlSessionPassword &&
3825 !options->CookieAuthentication) {
3826 log_warn(LD_CONFIG, "Control%s is %s, but no authentication method "
3827 "has been configured. This means that any program on your "
3828 "computer can reconfigure your Tor. That's bad! You should "
3829 "upgrade your Tor controller as soon as possible.",
3830 options->ControlPort_set ? "Port" : "Socket",
3831 options->ControlPort_set ? "open" : "world writable");
3834 if (options->CookieAuthFileGroupReadable && !options->CookieAuthFile) {
3835 log_warn(LD_CONFIG, "CookieAuthFileGroupReadable is set, but will have "
3836 "no effect: you must specify an explicit CookieAuthFile to "
3837 "have it group-readable.");
3840 if (options->MyFamily_lines && options->BridgeRelay) {
3841 log_warn(LD_CONFIG, "Listing a family for a bridge relay is not "
3842 "supported: it can reveal bridge fingerprints to censors. "
3843 "You should also make sure you aren't listing this bridge's "
3844 "fingerprint in any other MyFamily.");
3846 if (normalize_nickname_list(&options->MyFamily,
3847 options->MyFamily_lines, "MyFamily", msg))
3848 return -1;
3849 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3850 routerset_t *rs = routerset_new();
3851 if (routerset_parse(rs, cl->value, cl->key)) {
3852 routerset_free(rs);
3853 return -1;
3855 routerset_free(rs);
3858 if (validate_addr_policies(options, msg) < 0)
3859 return -1;
3861 /* If FallbackDir is set, we don't UseDefaultFallbackDirs */
3862 if (options->UseDefaultFallbackDirs && options->FallbackDir) {
3863 log_info(LD_CONFIG, "You have set UseDefaultFallbackDirs 1 and "
3864 "FallbackDir(s). Ignoring UseDefaultFallbackDirs, and "
3865 "using the FallbackDir(s) you have set.");
3868 if (validate_dir_servers(options, old_options) < 0)
3869 REJECT("Directory authority/fallback line did not parse. See logs "
3870 "for details.");
3872 if (options->UseBridges && !options->Bridges)
3873 REJECT("If you set UseBridges, you must specify at least one bridge.");
3875 for (cl = options->Bridges; cl; cl = cl->next) {
3876 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
3877 if (!bridge_line)
3878 REJECT("Bridge line did not parse. See logs for details.");
3879 bridge_line_free(bridge_line);
3882 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
3883 if (parse_transport_line(options, cl->value, 1, 0) < 0)
3884 REJECT("Invalid client transport line. See logs for details.");
3887 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
3888 if (parse_transport_line(options, cl->value, 1, 1) < 0)
3889 REJECT("Invalid server transport line. See logs for details.");
3892 if (options->ServerTransportPlugin && !server_mode(options)) {
3893 log_notice(LD_GENERAL, "Tor is not configured as a relay but you specified"
3894 " a ServerTransportPlugin line (%s). The ServerTransportPlugin "
3895 "line will be ignored.",
3896 escaped(options->ServerTransportPlugin->value));
3899 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
3900 /** If get_bindaddr_from_transport_listen_line() fails with
3901 'transport' being NULL, it means that something went wrong
3902 while parsing the ServerTransportListenAddr line. */
3903 char *bindaddr = get_bindaddr_from_transport_listen_line(cl->value, NULL);
3904 if (!bindaddr)
3905 REJECT("ServerTransportListenAddr did not parse. See logs for details.");
3906 tor_free(bindaddr);
3909 if (options->ServerTransportListenAddr && !options->ServerTransportPlugin) {
3910 log_notice(LD_GENERAL, "You need at least a single managed-proxy to "
3911 "specify a transport listen address. The "
3912 "ServerTransportListenAddr line will be ignored.");
3915 for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
3916 /** If get_options_from_transport_options_line() fails with
3917 'transport' being NULL, it means that something went wrong
3918 while parsing the ServerTransportOptions line. */
3919 smartlist_t *options_sl =
3920 get_options_from_transport_options_line(cl->value, NULL);
3921 if (!options_sl)
3922 REJECT("ServerTransportOptions did not parse. See logs for details.");
3924 SMARTLIST_FOREACH(options_sl, char *, cp, tor_free(cp));
3925 smartlist_free(options_sl);
3928 if (options->ConstrainedSockets) {
3929 /* If the user wants to constrain socket buffer use, make sure the desired
3930 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3931 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3932 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3933 options->ConstrainedSockSize % 1024) {
3934 tor_asprintf(msg,
3935 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3936 "in 1024 byte increments.",
3937 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3938 return -1;
3940 if (options->DirPort_set) {
3941 /* Providing cached directory entries while system TCP buffers are scarce
3942 * will exacerbate the socket errors. Suggest that this be disabled. */
3943 COMPLAIN("You have requested constrained socket buffers while also "
3944 "serving directory entries via DirPort. It is strongly "
3945 "suggested that you disable serving directory requests when "
3946 "system TCP buffer resources are scarce.");
3950 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3951 options->V3AuthVotingInterval/2) {
3953 This doesn't work, but it seems like it should:
3954 what code is preventing the interval being less than twice the lead-up?
3955 if (options->TestingTorNetwork) {
3956 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3957 options->V3AuthVotingInterval) {
3958 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than "
3959 "V3AuthVotingInterval");
3960 } else {
3961 COMPLAIN("V3AuthVoteDelay plus V3AuthDistDelay is more than half "
3962 "V3AuthVotingInterval. This may lead to "
3963 "consensus instability, particularly if clocks drift.");
3965 } else {
3967 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3968 "V3AuthVotingInterval");
3974 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS) {
3975 if (options->TestingTorNetwork) {
3976 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS_TESTING) {
3977 REJECT("V3AuthVoteDelay is way too low.");
3978 } else {
3979 COMPLAIN("V3AuthVoteDelay is very low. "
3980 "This may lead to failure to vote for a consensus.");
3982 } else {
3983 REJECT("V3AuthVoteDelay is way too low.");
3987 if (options->V3AuthDistDelay < MIN_DIST_SECONDS) {
3988 if (options->TestingTorNetwork) {
3989 if (options->V3AuthDistDelay < MIN_DIST_SECONDS_TESTING) {
3990 REJECT("V3AuthDistDelay is way too low.");
3991 } else {
3992 COMPLAIN("V3AuthDistDelay is very low. "
3993 "This may lead to missing votes in a consensus.");
3995 } else {
3996 REJECT("V3AuthDistDelay is way too low.");
4000 if (options->V3AuthNIntervalsValid < 2)
4001 REJECT("V3AuthNIntervalsValid must be at least 2.");
4003 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
4004 if (options->TestingTorNetwork) {
4005 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL_TESTING) {
4006 REJECT("V3AuthVotingInterval is insanely low.");
4007 } else {
4008 COMPLAIN("V3AuthVotingInterval is very low. "
4009 "This may lead to failure to synchronise for a consensus.");
4011 } else {
4012 REJECT("V3AuthVotingInterval is insanely low.");
4014 } else if (options->V3AuthVotingInterval > 24*60*60) {
4015 REJECT("V3AuthVotingInterval is insanely high.");
4016 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
4017 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
4020 if (hs_config_service_all(options, 1) < 0)
4021 REJECT("Failed to configure rendezvous options. See logs for details.");
4023 /* Parse client-side authorization for hidden services. */
4024 if (rend_parse_service_authorization(options, 1) < 0)
4025 REJECT("Failed to configure client authorization for hidden services. "
4026 "See logs for details.");
4028 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv4,
4029 AF_INET, 1, msg)<0)
4030 return -1;
4031 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv6,
4032 AF_INET6, 1, msg)<0)
4033 return -1;
4035 if (options->TestingTorNetwork &&
4036 !(options->DirAuthorities ||
4037 (options->AlternateDirAuthority &&
4038 options->AlternateBridgeAuthority))) {
4039 REJECT("TestingTorNetwork may only be configured in combination with "
4040 "a non-default set of DirAuthority or both of "
4041 "AlternateDirAuthority and AlternateBridgeAuthority configured.");
4044 #define CHECK_DEFAULT(arg) \
4045 STMT_BEGIN \
4046 if (!options->TestingTorNetwork && \
4047 !options->UsingTestNetworkDefaults_ && \
4048 !config_is_same(&options_format,options, \
4049 default_options,#arg)) { \
4050 REJECT(#arg " may only be changed in testing Tor " \
4051 "networks!"); \
4052 } STMT_END
4053 CHECK_DEFAULT(TestingV3AuthInitialVotingInterval);
4054 CHECK_DEFAULT(TestingV3AuthInitialVoteDelay);
4055 CHECK_DEFAULT(TestingV3AuthInitialDistDelay);
4056 CHECK_DEFAULT(TestingV3AuthVotingStartOffset);
4057 CHECK_DEFAULT(TestingAuthDirTimeToLearnReachability);
4058 CHECK_DEFAULT(TestingEstimatedDescriptorPropagationTime);
4059 CHECK_DEFAULT(TestingServerDownloadSchedule);
4060 CHECK_DEFAULT(TestingClientDownloadSchedule);
4061 CHECK_DEFAULT(TestingServerConsensusDownloadSchedule);
4062 CHECK_DEFAULT(TestingClientConsensusDownloadSchedule);
4063 CHECK_DEFAULT(TestingBridgeDownloadSchedule);
4064 CHECK_DEFAULT(TestingClientMaxIntervalWithoutRequest);
4065 CHECK_DEFAULT(TestingDirConnectionMaxStall);
4066 CHECK_DEFAULT(TestingConsensusMaxDownloadTries);
4067 CHECK_DEFAULT(TestingDescriptorMaxDownloadTries);
4068 CHECK_DEFAULT(TestingMicrodescMaxDownloadTries);
4069 CHECK_DEFAULT(TestingCertMaxDownloadTries);
4070 CHECK_DEFAULT(TestingAuthKeyLifetime);
4071 CHECK_DEFAULT(TestingLinkCertLifetime);
4072 CHECK_DEFAULT(TestingSigningKeySlop);
4073 CHECK_DEFAULT(TestingAuthKeySlop);
4074 CHECK_DEFAULT(TestingLinkKeySlop);
4075 #undef CHECK_DEFAULT
4077 if (options->SigningKeyLifetime < options->TestingSigningKeySlop*2)
4078 REJECT("SigningKeyLifetime is too short.");
4079 if (options->TestingLinkCertLifetime < options->TestingAuthKeySlop*2)
4080 REJECT("LinkCertLifetime is too short.");
4081 if (options->TestingAuthKeyLifetime < options->TestingLinkKeySlop*2)
4082 REJECT("TestingAuthKeyLifetime is too short.");
4084 if (options->TestingV3AuthInitialVotingInterval
4085 < MIN_VOTE_INTERVAL_TESTING_INITIAL) {
4086 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
4087 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
4088 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
4089 "30 minutes.");
4092 if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS_TESTING) {
4093 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
4096 if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS_TESTING) {
4097 REJECT("TestingV3AuthInitialDistDelay is way too low.");
4100 if (options->TestingV3AuthInitialVoteDelay +
4101 options->TestingV3AuthInitialDistDelay >=
4102 options->TestingV3AuthInitialVotingInterval) {
4103 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
4104 "must be less than TestingV3AuthInitialVotingInterval");
4107 if (options->TestingV3AuthVotingStartOffset >
4108 MIN(options->TestingV3AuthInitialVotingInterval,
4109 options->V3AuthVotingInterval)) {
4110 REJECT("TestingV3AuthVotingStartOffset is higher than the voting "
4111 "interval.");
4112 } else if (options->TestingV3AuthVotingStartOffset < 0) {
4113 REJECT("TestingV3AuthVotingStartOffset must be non-negative.");
4116 if (options->TestingAuthDirTimeToLearnReachability < 0) {
4117 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
4118 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
4119 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
4122 if (options->TestingEstimatedDescriptorPropagationTime < 0) {
4123 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
4124 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
4125 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
4128 if (options->TestingClientMaxIntervalWithoutRequest < 1) {
4129 REJECT("TestingClientMaxIntervalWithoutRequest is way too low.");
4130 } else if (options->TestingClientMaxIntervalWithoutRequest > 3600) {
4131 COMPLAIN("TestingClientMaxIntervalWithoutRequest is insanely high.");
4134 if (options->TestingDirConnectionMaxStall < 5) {
4135 REJECT("TestingDirConnectionMaxStall is way too low.");
4136 } else if (options->TestingDirConnectionMaxStall > 3600) {
4137 COMPLAIN("TestingDirConnectionMaxStall is insanely high.");
4140 if (options->TestingConsensusMaxDownloadTries < 2) {
4141 REJECT("TestingConsensusMaxDownloadTries must be greater than 2.");
4142 } else if (options->TestingConsensusMaxDownloadTries > 800) {
4143 COMPLAIN("TestingConsensusMaxDownloadTries is insanely high.");
4146 if (options->ClientBootstrapConsensusMaxDownloadTries < 2) {
4147 REJECT("ClientBootstrapConsensusMaxDownloadTries must be greater "
4148 "than 2."
4150 } else if (options->ClientBootstrapConsensusMaxDownloadTries > 800) {
4151 COMPLAIN("ClientBootstrapConsensusMaxDownloadTries is insanely "
4152 "high.");
4155 if (options->ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries
4156 < 2) {
4157 REJECT("ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries must "
4158 "be greater than 2."
4160 } else if (
4161 options->ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries
4162 > 800) {
4163 COMPLAIN("ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries is "
4164 "insanely high.");
4167 if (options->ClientBootstrapConsensusMaxInProgressTries < 1) {
4168 REJECT("ClientBootstrapConsensusMaxInProgressTries must be greater "
4169 "than 0.");
4170 } else if (options->ClientBootstrapConsensusMaxInProgressTries
4171 > 100) {
4172 COMPLAIN("ClientBootstrapConsensusMaxInProgressTries is insanely "
4173 "high.");
4176 if (options->TestingDescriptorMaxDownloadTries < 2) {
4177 REJECT("TestingDescriptorMaxDownloadTries must be greater than 1.");
4178 } else if (options->TestingDescriptorMaxDownloadTries > 800) {
4179 COMPLAIN("TestingDescriptorMaxDownloadTries is insanely high.");
4182 if (options->TestingMicrodescMaxDownloadTries < 2) {
4183 REJECT("TestingMicrodescMaxDownloadTries must be greater than 1.");
4184 } else if (options->TestingMicrodescMaxDownloadTries > 800) {
4185 COMPLAIN("TestingMicrodescMaxDownloadTries is insanely high.");
4188 if (options->TestingCertMaxDownloadTries < 2) {
4189 REJECT("TestingCertMaxDownloadTries must be greater than 1.");
4190 } else if (options->TestingCertMaxDownloadTries > 800) {
4191 COMPLAIN("TestingCertMaxDownloadTries is insanely high.");
4194 if (options->TestingEnableConnBwEvent &&
4195 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4196 REJECT("TestingEnableConnBwEvent may only be changed in testing "
4197 "Tor networks!");
4200 if (options->TestingEnableCellStatsEvent &&
4201 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4202 REJECT("TestingEnableCellStatsEvent may only be changed in testing "
4203 "Tor networks!");
4206 if (options->TestingEnableTbEmptyEvent &&
4207 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4208 REJECT("TestingEnableTbEmptyEvent may only be changed in testing "
4209 "Tor networks!");
4212 if (options->TestingTorNetwork) {
4213 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
4214 "almost unusable in the public Tor network, and is "
4215 "therefore only advised if you are building a "
4216 "testing Tor network!");
4219 if (options->AccelName && !options->HardwareAccel)
4220 options->HardwareAccel = 1;
4221 if (options->AccelDir && !options->AccelName)
4222 REJECT("Can't use hardware crypto accelerator dir without engine name.");
4224 if (options->PublishServerDescriptor)
4225 SMARTLIST_FOREACH(options->PublishServerDescriptor, const char *, pubdes, {
4226 if (!strcmp(pubdes, "1") || !strcmp(pubdes, "0"))
4227 if (smartlist_len(options->PublishServerDescriptor) > 1) {
4228 COMPLAIN("You have passed a list of multiple arguments to the "
4229 "PublishServerDescriptor option that includes 0 or 1. "
4230 "0 or 1 should only be used as the sole argument. "
4231 "This configuration will be rejected in a future release.");
4232 break;
4236 if (options->BridgeRelay == 1 && ! options->ORPort_set)
4237 REJECT("BridgeRelay is 1, ORPort is not set. This is an invalid "
4238 "combination.");
4240 return 0;
4243 #undef REJECT
4244 #undef COMPLAIN
4246 /* Given the value that the user has set for MaxMemInQueues, compute the
4247 * actual maximum value. We clip this value if it's too low, and autodetect
4248 * it if it's set to 0. */
4249 static uint64_t
4250 compute_real_max_mem_in_queues(const uint64_t val, int log_guess)
4252 uint64_t result;
4254 if (val == 0) {
4255 #define ONE_GIGABYTE (U64_LITERAL(1) << 30)
4256 #define ONE_MEGABYTE (U64_LITERAL(1) << 20)
4257 #if SIZEOF_VOID_P >= 8
4258 #define MAX_DEFAULT_MAXMEM (8*ONE_GIGABYTE)
4259 #else
4260 #define MAX_DEFAULT_MAXMEM (2*ONE_GIGABYTE)
4261 #endif
4262 /* The user didn't pick a memory limit. Choose a very large one
4263 * that is still smaller than the system memory */
4264 static int notice_sent = 0;
4265 size_t ram = 0;
4266 if (get_total_system_memory(&ram) < 0) {
4267 /* We couldn't determine our total system memory! */
4268 #if SIZEOF_VOID_P >= 8
4269 /* 64-bit system. Let's hope for 8 GB. */
4270 result = 8 * ONE_GIGABYTE;
4271 #else
4272 /* (presumably) 32-bit system. Let's hope for 1 GB. */
4273 result = ONE_GIGABYTE;
4274 #endif
4275 } else {
4276 /* We detected it, so let's pick 3/4 of the total RAM as our limit. */
4277 const uint64_t avail = (ram / 4) * 3;
4279 /* Make sure it's in range from 0.25 GB to 8 GB. */
4280 if (avail > MAX_DEFAULT_MAXMEM) {
4281 /* If you want to use more than this much RAM, you need to configure
4282 it yourself */
4283 result = MAX_DEFAULT_MAXMEM;
4284 } else if (avail < ONE_GIGABYTE / 4) {
4285 result = ONE_GIGABYTE / 4;
4286 } else {
4287 result = avail;
4290 if (log_guess && ! notice_sent) {
4291 log_notice(LD_CONFIG, "%sMaxMemInQueues is set to "U64_FORMAT" MB. "
4292 "You can override this by setting MaxMemInQueues by hand.",
4293 ram ? "Based on detected system memory, " : "",
4294 U64_PRINTF_ARG(result / ONE_MEGABYTE));
4295 notice_sent = 1;
4297 return result;
4298 } else if (val < ONE_GIGABYTE / 4) {
4299 log_warn(LD_CONFIG, "MaxMemInQueues must be at least 256 MB for now. "
4300 "Ideally, have it as large as you can afford.");
4301 return ONE_GIGABYTE / 4;
4302 } else {
4303 /* The value was fine all along */
4304 return val;
4308 /* If we have less than 300 MB suggest disabling dircache */
4309 #define DIRCACHE_MIN_MEM_MB 300
4310 #define DIRCACHE_MIN_MEM_BYTES (DIRCACHE_MIN_MEM_MB*ONE_MEGABYTE)
4311 #define STRINGIFY(val) #val
4313 /** Create a warning message for emitting if we are a dircache but may not have
4314 * enough system memory, or if we are not a dircache but probably should be.
4315 * Return -1 when a message is returned in *msg*, else return 0. */
4316 STATIC int
4317 have_enough_mem_for_dircache(const or_options_t *options, size_t total_mem,
4318 char **msg)
4320 *msg = NULL;
4321 /* XXX We should possibly be looking at MaxMemInQueues here
4322 * unconditionally. Or we should believe total_mem unconditionally. */
4323 if (total_mem == 0) {
4324 if (get_total_system_memory(&total_mem) < 0) {
4325 total_mem = options->MaxMemInQueues >= SIZE_MAX ?
4326 SIZE_MAX : (size_t)options->MaxMemInQueues;
4329 if (options->DirCache) {
4330 if (total_mem < DIRCACHE_MIN_MEM_BYTES) {
4331 if (options->BridgeRelay) {
4332 *msg = tor_strdup("Running a Bridge with less than "
4333 STRINGIFY(DIRCACHE_MIN_MEM_MB) " MB of memory is not "
4334 "recommended.");
4335 } else {
4336 *msg = tor_strdup("Being a directory cache (default) with less than "
4337 STRINGIFY(DIRCACHE_MIN_MEM_MB) " MB of memory is not "
4338 "recommended and may consume most of the available "
4339 "resources, consider disabling this functionality by "
4340 "setting the DirCache option to 0.");
4343 } else {
4344 if (total_mem >= DIRCACHE_MIN_MEM_BYTES) {
4345 *msg = tor_strdup("DirCache is disabled and we are configured as a "
4346 "relay. This may disqualify us from becoming a guard in the "
4347 "future.");
4350 return *msg == NULL ? 0 : -1;
4352 #undef STRINGIFY
4354 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
4355 * equal strings. */
4356 static int
4357 opt_streq(const char *s1, const char *s2)
4359 return 0 == strcmp_opt(s1, s2);
4362 /** Check if any of the previous options have changed but aren't allowed to. */
4363 static int
4364 options_transition_allowed(const or_options_t *old,
4365 const or_options_t *new_val,
4366 char **msg)
4368 if (!old)
4369 return 0;
4371 if (!opt_streq(old->PidFile, new_val->PidFile)) {
4372 *msg = tor_strdup("PidFile is not allowed to change.");
4373 return -1;
4376 if (old->RunAsDaemon != new_val->RunAsDaemon) {
4377 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
4378 "is not allowed.");
4379 return -1;
4382 if (old->Sandbox != new_val->Sandbox) {
4383 *msg = tor_strdup("While Tor is running, changing Sandbox "
4384 "is not allowed.");
4385 return -1;
4388 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
4389 tor_asprintf(msg,
4390 "While Tor is running, changing DataDirectory "
4391 "(\"%s\"->\"%s\") is not allowed.",
4392 old->DataDirectory, new_val->DataDirectory);
4393 return -1;
4396 if (!opt_streq(old->User, new_val->User)) {
4397 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
4398 return -1;
4401 if (old->KeepBindCapabilities != new_val->KeepBindCapabilities) {
4402 *msg = tor_strdup("While Tor is running, changing KeepBindCapabilities is "
4403 "not allowed.");
4404 return -1;
4407 if (!opt_streq(old->SyslogIdentityTag, new_val->SyslogIdentityTag)) {
4408 *msg = tor_strdup("While Tor is running, changing "
4409 "SyslogIdentityTag is not allowed.");
4410 return -1;
4413 if ((old->HardwareAccel != new_val->HardwareAccel)
4414 || !opt_streq(old->AccelName, new_val->AccelName)
4415 || !opt_streq(old->AccelDir, new_val->AccelDir)) {
4416 *msg = tor_strdup("While Tor is running, changing OpenSSL hardware "
4417 "acceleration engine is not allowed.");
4418 return -1;
4421 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
4422 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
4423 "is not allowed.");
4424 return -1;
4427 if (old->DisableAllSwap != new_val->DisableAllSwap) {
4428 *msg = tor_strdup("While Tor is running, changing DisableAllSwap "
4429 "is not allowed.");
4430 return -1;
4433 if (old->TokenBucketRefillInterval != new_val->TokenBucketRefillInterval) {
4434 *msg = tor_strdup("While Tor is running, changing TokenBucketRefill"
4435 "Interval is not allowed");
4436 return -1;
4439 if (old->HiddenServiceSingleHopMode != new_val->HiddenServiceSingleHopMode) {
4440 *msg = tor_strdup("While Tor is running, changing "
4441 "HiddenServiceSingleHopMode is not allowed.");
4442 return -1;
4445 if (old->HiddenServiceNonAnonymousMode !=
4446 new_val->HiddenServiceNonAnonymousMode) {
4447 *msg = tor_strdup("While Tor is running, changing "
4448 "HiddenServiceNonAnonymousMode is not allowed.");
4449 return -1;
4452 if (old->DisableDebuggerAttachment &&
4453 !new_val->DisableDebuggerAttachment) {
4454 *msg = tor_strdup("While Tor is running, disabling "
4455 "DisableDebuggerAttachment is not allowed.");
4456 return -1;
4459 if (old->NoExec && !new_val->NoExec) {
4460 *msg = tor_strdup("While Tor is running, disabling "
4461 "NoExec is not allowed.");
4462 return -1;
4465 if (sandbox_is_active()) {
4466 #define SB_NOCHANGE_STR(opt) \
4467 do { \
4468 if (! opt_streq(old->opt, new_val->opt)) { \
4469 *msg = tor_strdup("Can't change " #opt " while Sandbox is active"); \
4470 return -1; \
4472 } while (0)
4474 SB_NOCHANGE_STR(Address);
4475 SB_NOCHANGE_STR(ServerDNSResolvConfFile);
4476 SB_NOCHANGE_STR(DirPortFrontPage);
4477 SB_NOCHANGE_STR(CookieAuthFile);
4478 SB_NOCHANGE_STR(ExtORPortCookieAuthFile);
4480 #undef SB_NOCHANGE_STR
4482 if (! config_lines_eq(old->Logs, new_val->Logs)) {
4483 *msg = tor_strdup("Can't change Logs while Sandbox is active");
4484 return -1;
4486 if (old->ConnLimit != new_val->ConnLimit) {
4487 *msg = tor_strdup("Can't change ConnLimit while Sandbox is active");
4488 return -1;
4490 if (server_mode(old) != server_mode(new_val)) {
4491 *msg = tor_strdup("Can't start/stop being a server while "
4492 "Sandbox is active");
4493 return -1;
4497 return 0;
4500 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
4501 * will require us to rotate the CPU and DNS workers; else return 0. */
4502 static int
4503 options_transition_affects_workers(const or_options_t *old_options,
4504 const or_options_t *new_options)
4506 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
4507 old_options->NumCPUs != new_options->NumCPUs ||
4508 !config_lines_eq(old_options->ORPort_lines, new_options->ORPort_lines) ||
4509 old_options->ServerDNSSearchDomains !=
4510 new_options->ServerDNSSearchDomains ||
4511 old_options->SafeLogging_ != new_options->SafeLogging_ ||
4512 old_options->ClientOnly != new_options->ClientOnly ||
4513 public_server_mode(old_options) != public_server_mode(new_options) ||
4514 !config_lines_eq(old_options->Logs, new_options->Logs) ||
4515 old_options->LogMessageDomains != new_options->LogMessageDomains)
4516 return 1;
4518 /* Check whether log options match. */
4520 /* Nothing that changed matters. */
4521 return 0;
4524 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
4525 * will require us to generate a new descriptor; else return 0. */
4526 static int
4527 options_transition_affects_descriptor(const or_options_t *old_options,
4528 const or_options_t *new_options)
4530 /* XXX We can be smarter here. If your DirPort isn't being
4531 * published and you just turned it off, no need to republish. Etc. */
4532 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
4533 !opt_streq(old_options->Nickname,new_options->Nickname) ||
4534 !opt_streq(old_options->Address,new_options->Address) ||
4535 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
4536 old_options->ExitRelay != new_options->ExitRelay ||
4537 old_options->ExitPolicyRejectPrivate !=
4538 new_options->ExitPolicyRejectPrivate ||
4539 old_options->ExitPolicyRejectLocalInterfaces !=
4540 new_options->ExitPolicyRejectLocalInterfaces ||
4541 old_options->IPv6Exit != new_options->IPv6Exit ||
4542 !config_lines_eq(old_options->ORPort_lines,
4543 new_options->ORPort_lines) ||
4544 !config_lines_eq(old_options->DirPort_lines,
4545 new_options->DirPort_lines) ||
4546 old_options->ClientOnly != new_options->ClientOnly ||
4547 old_options->DisableNetwork != new_options->DisableNetwork ||
4548 old_options->PublishServerDescriptor_ !=
4549 new_options->PublishServerDescriptor_ ||
4550 get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
4551 get_effective_bwburst(old_options) !=
4552 get_effective_bwburst(new_options) ||
4553 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
4554 !config_lines_eq(old_options->MyFamily, new_options->MyFamily) ||
4555 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
4556 old_options->AccountingMax != new_options->AccountingMax ||
4557 old_options->AccountingRule != new_options->AccountingRule ||
4558 public_server_mode(old_options) != public_server_mode(new_options) ||
4559 old_options->DirCache != new_options->DirCache ||
4560 old_options->AssumeReachable != new_options->AssumeReachable)
4561 return 1;
4563 return 0;
4566 #ifdef _WIN32
4567 /** Return the directory on windows where we expect to find our application
4568 * data. */
4569 static char *
4570 get_windows_conf_root(void)
4572 static int is_set = 0;
4573 static char path[MAX_PATH*2+1];
4574 TCHAR tpath[MAX_PATH] = {0};
4576 LPITEMIDLIST idl;
4577 IMalloc *m;
4578 HRESULT result;
4580 if (is_set)
4581 return path;
4583 /* Find X:\documents and settings\username\application data\ .
4584 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
4586 #ifdef ENABLE_LOCAL_APPDATA
4587 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
4588 #else
4589 #define APPDATA_PATH CSIDL_APPDATA
4590 #endif
4591 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
4592 getcwd(path,MAX_PATH);
4593 is_set = 1;
4594 log_warn(LD_CONFIG,
4595 "I couldn't find your application data folder: are you "
4596 "running an ancient version of Windows 95? Defaulting to \"%s\"",
4597 path);
4598 return path;
4600 /* Convert the path from an "ID List" (whatever that is!) to a path. */
4601 result = SHGetPathFromIDList(idl, tpath);
4602 #ifdef UNICODE
4603 wcstombs(path,tpath,sizeof(path));
4604 path[sizeof(path)-1] = '\0';
4605 #else
4606 strlcpy(path,tpath,sizeof(path));
4607 #endif
4609 /* Now we need to free the memory that the path-idl was stored in. In
4610 * typical Windows fashion, we can't just call 'free()' on it. */
4611 SHGetMalloc(&m);
4612 if (m) {
4613 m->lpVtbl->Free(m, idl);
4614 m->lpVtbl->Release(m);
4616 if (!SUCCEEDED(result)) {
4617 return NULL;
4619 strlcat(path,"\\tor",MAX_PATH);
4620 is_set = 1;
4621 return path;
4623 #endif
4625 /** Return the default location for our torrc file (if <b>defaults_file</b> is
4626 * false), or for the torrc-defaults file (if <b>defaults_file</b> is true). */
4627 static const char *
4628 get_default_conf_file(int defaults_file)
4630 #ifdef DISABLE_SYSTEM_TORRC
4631 (void) defaults_file;
4632 return NULL;
4633 #elif defined(_WIN32)
4634 if (defaults_file) {
4635 static char defaults_path[MAX_PATH+1];
4636 tor_snprintf(defaults_path, MAX_PATH, "%s\\torrc-defaults",
4637 get_windows_conf_root());
4638 return defaults_path;
4639 } else {
4640 static char path[MAX_PATH+1];
4641 tor_snprintf(path, MAX_PATH, "%s\\torrc",
4642 get_windows_conf_root());
4643 return path;
4645 #else
4646 return defaults_file ? CONFDIR "/torrc-defaults" : CONFDIR "/torrc";
4647 #endif
4650 /** Verify whether lst is a list of strings containing valid-looking
4651 * comma-separated nicknames, or NULL. Will normalise <b>lst</b> to prefix '$'
4652 * to any nickname or fingerprint that needs it. Also splits comma-separated
4653 * list elements into multiple elements. Return 0 on success.
4654 * Warn and return -1 on failure.
4656 static int
4657 normalize_nickname_list(config_line_t **normalized_out,
4658 const config_line_t *lst, const char *name,
4659 char **msg)
4661 if (!lst)
4662 return 0;
4664 config_line_t *new_nicknames = NULL;
4665 config_line_t **new_nicknames_next = &new_nicknames;
4667 const config_line_t *cl;
4668 for (cl = lst; cl; cl = cl->next) {
4669 const char *line = cl->value;
4670 if (!line)
4671 continue;
4673 int valid_line = 1;
4674 smartlist_t *sl = smartlist_new();
4675 smartlist_split_string(sl, line, ",",
4676 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
4677 SMARTLIST_FOREACH_BEGIN(sl, char *, s)
4679 char *normalized = NULL;
4680 if (!is_legal_nickname_or_hexdigest(s)) {
4681 // check if first char is dollar
4682 if (s[0] != '$') {
4683 // Try again but with a dollar symbol prepended
4684 char *prepended;
4685 tor_asprintf(&prepended, "$%s", s);
4687 if (is_legal_nickname_or_hexdigest(prepended)) {
4688 // The nickname is valid when it's prepended, set it as the
4689 // normalized version
4690 normalized = prepended;
4691 } else {
4692 // Still not valid, free and fallback to error message
4693 tor_free(prepended);
4697 if (!normalized) {
4698 tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
4699 valid_line = 0;
4700 break;
4702 } else {
4703 normalized = tor_strdup(s);
4706 config_line_t *next = tor_malloc_zero(sizeof(*next));
4707 next->key = tor_strdup(cl->key);
4708 next->value = normalized;
4709 next->next = NULL;
4711 *new_nicknames_next = next;
4712 new_nicknames_next = &next->next;
4713 } SMARTLIST_FOREACH_END(s);
4715 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
4716 smartlist_free(sl);
4718 if (!valid_line) {
4719 config_free_lines(new_nicknames);
4720 return -1;
4724 *normalized_out = new_nicknames;
4726 return 0;
4729 /** Learn config file name from command line arguments, or use the default.
4731 * If <b>defaults_file</b> is true, we're looking for torrc-defaults;
4732 * otherwise, we're looking for the regular torrc_file.
4734 * Set *<b>using_default_fname</b> to true if we're using the default
4735 * configuration file name; or false if we've set it from the command line.
4737 * Set *<b>ignore_missing_torrc</b> to true if we should ignore the resulting
4738 * filename if it doesn't exist.
4740 static char *
4741 find_torrc_filename(config_line_t *cmd_arg,
4742 int defaults_file,
4743 int *using_default_fname, int *ignore_missing_torrc)
4745 char *fname=NULL;
4746 config_line_t *p_index;
4747 const char *fname_opt = defaults_file ? "--defaults-torrc" : "-f";
4748 const char *ignore_opt = defaults_file ? NULL : "--ignore-missing-torrc";
4750 if (defaults_file)
4751 *ignore_missing_torrc = 1;
4753 for (p_index = cmd_arg; p_index; p_index = p_index->next) {
4754 if (!strcmp(p_index->key, fname_opt)) {
4755 if (fname) {
4756 log_warn(LD_CONFIG, "Duplicate %s options on command line.",
4757 fname_opt);
4758 tor_free(fname);
4760 fname = expand_filename(p_index->value);
4763 char *absfname;
4764 absfname = make_path_absolute(fname);
4765 tor_free(fname);
4766 fname = absfname;
4769 *using_default_fname = 0;
4770 } else if (ignore_opt && !strcmp(p_index->key,ignore_opt)) {
4771 *ignore_missing_torrc = 1;
4775 if (*using_default_fname) {
4776 /* didn't find one, try CONFDIR */
4777 const char *dflt = get_default_conf_file(defaults_file);
4778 file_status_t st = file_status(dflt);
4779 if (dflt && (st == FN_FILE || st == FN_EMPTY)) {
4780 fname = tor_strdup(dflt);
4781 } else {
4782 #ifndef _WIN32
4783 char *fn = NULL;
4784 if (!defaults_file) {
4785 fn = expand_filename("~/.torrc");
4787 if (fn) {
4788 file_status_t hmst = file_status(fn);
4789 if (hmst == FN_FILE || hmst == FN_EMPTY || dflt == NULL) {
4790 fname = fn;
4791 } else {
4792 tor_free(fn);
4793 fname = tor_strdup(dflt);
4795 } else {
4796 fname = dflt ? tor_strdup(dflt) : NULL;
4798 #else
4799 fname = dflt ? tor_strdup(dflt) : NULL;
4800 #endif
4803 return fname;
4806 /** Read the torrc from standard input and return it as a string.
4807 * Upon failure, return NULL.
4809 static char *
4810 load_torrc_from_stdin(void)
4812 size_t sz_out;
4814 return read_file_to_str_until_eof(STDIN_FILENO,SIZE_MAX,&sz_out);
4817 /** Load a configuration file from disk, setting torrc_fname or
4818 * torrc_defaults_fname if successful.
4820 * If <b>defaults_file</b> is true, load torrc-defaults; otherwise load torrc.
4822 * Return the contents of the file on success, and NULL on failure.
4824 static char *
4825 load_torrc_from_disk(config_line_t *cmd_arg, int defaults_file)
4827 char *fname=NULL;
4828 char *cf = NULL;
4829 int using_default_torrc = 1;
4830 int ignore_missing_torrc = 0;
4831 char **fname_var = defaults_file ? &torrc_defaults_fname : &torrc_fname;
4833 if (*fname_var == NULL) {
4834 fname = find_torrc_filename(cmd_arg, defaults_file,
4835 &using_default_torrc, &ignore_missing_torrc);
4836 tor_free(*fname_var);
4837 *fname_var = fname;
4838 } else {
4839 fname = *fname_var;
4841 log_debug(LD_CONFIG, "Opening config file \"%s\"", fname?fname:"<NULL>");
4843 /* Open config file */
4844 file_status_t st = fname ? file_status(fname) : FN_EMPTY;
4845 if (fname == NULL ||
4846 !(st == FN_FILE || st == FN_EMPTY) ||
4847 !(cf = read_file_to_str(fname,0,NULL))) {
4848 if (using_default_torrc == 1 || ignore_missing_torrc) {
4849 if (!defaults_file)
4850 log_notice(LD_CONFIG, "Configuration file \"%s\" not present, "
4851 "using reasonable defaults.", fname);
4852 tor_free(fname); /* sets fname to NULL */
4853 *fname_var = NULL;
4854 cf = tor_strdup("");
4855 } else {
4856 log_warn(LD_CONFIG,
4857 "Unable to open configuration file \"%s\".", fname);
4858 goto err;
4860 } else {
4861 log_notice(LD_CONFIG, "Read configuration file \"%s\".", fname);
4864 return cf;
4865 err:
4866 tor_free(fname);
4867 *fname_var = NULL;
4868 return NULL;
4871 /** Read a configuration file into <b>options</b>, finding the configuration
4872 * file location based on the command line. After loading the file
4873 * call options_init_from_string() to load the config.
4874 * Return 0 if success, -1 if failure. */
4876 options_init_from_torrc(int argc, char **argv)
4878 char *cf=NULL, *cf_defaults=NULL;
4879 int command;
4880 int retval = -1;
4881 char *command_arg = NULL;
4882 char *errmsg=NULL;
4883 config_line_t *p_index = NULL;
4884 config_line_t *cmdline_only_options = NULL;
4886 /* Go through command-line variables */
4887 if (! have_parsed_cmdline) {
4888 /* Or we could redo the list every time we pass this place.
4889 * It does not really matter */
4890 if (config_parse_commandline(argc, argv, 0, &global_cmdline_options,
4891 &global_cmdline_only_options) < 0) {
4892 goto err;
4894 have_parsed_cmdline = 1;
4896 cmdline_only_options = global_cmdline_only_options;
4898 if (config_line_find(cmdline_only_options, "-h") ||
4899 config_line_find(cmdline_only_options, "--help")) {
4900 print_usage();
4901 exit(0);
4903 if (config_line_find(cmdline_only_options, "--list-torrc-options")) {
4904 /* For validating whether we've documented everything. */
4905 list_torrc_options();
4906 exit(0);
4908 if (config_line_find(cmdline_only_options, "--list-deprecated-options")) {
4909 /* For validating whether what we have deprecated really exists. */
4910 list_deprecated_options();
4911 exit(0);
4914 if (config_line_find(cmdline_only_options, "--version")) {
4915 printf("Tor version %s.\n",get_version());
4916 exit(0);
4919 if (config_line_find(cmdline_only_options, "--library-versions")) {
4920 printf("Tor version %s. \n", get_version());
4921 printf("Library versions\tCompiled\t\tRuntime\n");
4922 printf("Libevent\t\t%-15s\t\t%s\n",
4923 tor_libevent_get_header_version_str(),
4924 tor_libevent_get_version_str());
4925 printf("OpenSSL \t\t%-15s\t\t%s\n",
4926 crypto_openssl_get_header_version_str(),
4927 crypto_openssl_get_version_str());
4928 if (tor_compress_supports_method(ZLIB_METHOD)) {
4929 printf("Zlib \t\t%-15s\t\t%s\n",
4930 tor_compress_version_str(ZLIB_METHOD),
4931 tor_compress_header_version_str(ZLIB_METHOD));
4933 if (tor_compress_supports_method(LZMA_METHOD)) {
4934 printf("Liblzma \t\t%-15s\t\t%s\n",
4935 tor_compress_version_str(LZMA_METHOD),
4936 tor_compress_header_version_str(LZMA_METHOD));
4938 if (tor_compress_supports_method(ZSTD_METHOD)) {
4939 printf("Libzstd \t\t%-15s\t\t%s\n",
4940 tor_compress_version_str(ZSTD_METHOD),
4941 tor_compress_header_version_str(ZSTD_METHOD));
4943 //TODO: Hex versions?
4944 exit(0);
4947 command = CMD_RUN_TOR;
4948 for (p_index = cmdline_only_options; p_index; p_index = p_index->next) {
4949 if (!strcmp(p_index->key,"--keygen")) {
4950 command = CMD_KEYGEN;
4951 } else if (!strcmp(p_index->key, "--key-expiration")) {
4952 command = CMD_KEY_EXPIRATION;
4953 command_arg = p_index->value;
4954 } else if (!strcmp(p_index->key,"--list-fingerprint")) {
4955 command = CMD_LIST_FINGERPRINT;
4956 } else if (!strcmp(p_index->key, "--hash-password")) {
4957 command = CMD_HASH_PASSWORD;
4958 command_arg = p_index->value;
4959 } else if (!strcmp(p_index->key, "--dump-config")) {
4960 command = CMD_DUMP_CONFIG;
4961 command_arg = p_index->value;
4962 } else if (!strcmp(p_index->key, "--verify-config")) {
4963 command = CMD_VERIFY_CONFIG;
4967 if (command == CMD_HASH_PASSWORD) {
4968 cf_defaults = tor_strdup("");
4969 cf = tor_strdup("");
4970 } else {
4971 cf_defaults = load_torrc_from_disk(cmdline_only_options, 1);
4973 const config_line_t *f_line = config_line_find(cmdline_only_options,
4974 "-f");
4976 const int read_torrc_from_stdin =
4977 (f_line != NULL && strcmp(f_line->value, "-") == 0);
4979 if (read_torrc_from_stdin) {
4980 cf = load_torrc_from_stdin();
4981 } else {
4982 cf = load_torrc_from_disk(cmdline_only_options, 0);
4985 if (!cf) {
4986 if (config_line_find(cmdline_only_options, "--allow-missing-torrc")) {
4987 cf = tor_strdup("");
4988 } else {
4989 goto err;
4994 retval = options_init_from_string(cf_defaults, cf, command, command_arg,
4995 &errmsg);
4997 if (retval < 0)
4998 goto err;
5000 if (config_line_find(cmdline_only_options, "--no-passphrase")) {
5001 if (command == CMD_KEYGEN) {
5002 get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_OFF;
5003 } else {
5004 log_err(LD_CONFIG, "--no-passphrase specified without --keygen!");
5005 exit(1);
5009 if (config_line_find(cmdline_only_options, "--newpass")) {
5010 if (command == CMD_KEYGEN) {
5011 get_options_mutable()->change_key_passphrase = 1;
5012 } else {
5013 log_err(LD_CONFIG, "--newpass specified without --keygen!");
5014 exit(1);
5019 const config_line_t *fd_line = config_line_find(cmdline_only_options,
5020 "--passphrase-fd");
5021 if (fd_line) {
5022 if (get_options()->keygen_force_passphrase == FORCE_PASSPHRASE_OFF) {
5023 log_err(LD_CONFIG, "--no-passphrase specified with --passphrase-fd!");
5024 exit(1);
5025 } else if (command != CMD_KEYGEN) {
5026 log_err(LD_CONFIG, "--passphrase-fd specified without --keygen!");
5027 exit(1);
5028 } else {
5029 const char *v = fd_line->value;
5030 int ok = 1;
5031 long fd = tor_parse_long(v, 10, 0, INT_MAX, &ok, NULL);
5032 if (fd < 0 || ok == 0) {
5033 log_err(LD_CONFIG, "Invalid --passphrase-fd value %s", escaped(v));
5034 exit(1);
5036 get_options_mutable()->keygen_passphrase_fd = (int)fd;
5037 get_options_mutable()->use_keygen_passphrase_fd = 1;
5038 get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_ON;
5044 const config_line_t *key_line = config_line_find(cmdline_only_options,
5045 "--master-key");
5046 if (key_line) {
5047 if (command != CMD_KEYGEN) {
5048 log_err(LD_CONFIG, "--master-key without --keygen!");
5049 exit(1);
5050 } else {
5051 get_options_mutable()->master_key_fname = tor_strdup(key_line->value);
5056 err:
5058 tor_free(cf);
5059 tor_free(cf_defaults);
5060 if (errmsg) {
5061 log_warn(LD_CONFIG,"%s", errmsg);
5062 tor_free(errmsg);
5064 return retval < 0 ? -1 : 0;
5067 /** Load the options from the configuration in <b>cf</b>, validate
5068 * them for consistency and take actions based on them.
5070 * Return 0 if success, negative on error:
5071 * * -1 for general errors.
5072 * * -2 for failure to parse/validate,
5073 * * -3 for transition not allowed
5074 * * -4 for error while setting the new options
5076 setopt_err_t
5077 options_init_from_string(const char *cf_defaults, const char *cf,
5078 int command, const char *command_arg,
5079 char **msg)
5081 or_options_t *oldoptions, *newoptions, *newdefaultoptions=NULL;
5082 config_line_t *cl;
5083 int retval;
5084 setopt_err_t err = SETOPT_ERR_MISC;
5085 int cf_has_include = 0;
5086 tor_assert(msg);
5088 oldoptions = global_options; /* get_options unfortunately asserts if
5089 this is the first time we run*/
5091 newoptions = tor_malloc_zero(sizeof(or_options_t));
5092 newoptions->magic_ = OR_OPTIONS_MAGIC;
5093 options_init(newoptions);
5094 newoptions->command = command;
5095 newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
5097 for (int i = 0; i < 2; ++i) {
5098 const char *body = i==0 ? cf_defaults : cf;
5099 if (!body)
5100 continue;
5101 /* get config lines, assign them */
5102 retval = config_get_lines_include(body, &cl, 1,
5103 body == cf ? &cf_has_include : NULL);
5104 if (retval < 0) {
5105 err = SETOPT_ERR_PARSE;
5106 goto err;
5108 retval = config_assign(&options_format, newoptions, cl,
5109 CAL_WARN_DEPRECATIONS, msg);
5110 config_free_lines(cl);
5111 if (retval < 0) {
5112 err = SETOPT_ERR_PARSE;
5113 goto err;
5115 if (i==0)
5116 newdefaultoptions = config_dup(&options_format, newoptions);
5119 if (newdefaultoptions == NULL) {
5120 newdefaultoptions = config_dup(&options_format, global_default_options);
5123 /* Go through command-line variables too */
5124 retval = config_assign(&options_format, newoptions,
5125 global_cmdline_options, CAL_WARN_DEPRECATIONS, msg);
5126 if (retval < 0) {
5127 err = SETOPT_ERR_PARSE;
5128 goto err;
5131 newoptions->IncludeUsed = cf_has_include;
5133 /* If this is a testing network configuration, change defaults
5134 * for a list of dependent config options, re-initialize newoptions
5135 * with the new defaults, and assign all options to it second time. */
5136 if (newoptions->TestingTorNetwork) {
5137 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
5138 * this? We could, for example, make the parsing algorithm do two passes
5139 * over the configuration. If it finds any "suite" options like
5140 * TestingTorNetwork, it could change the defaults before its second pass.
5141 * Not urgent so long as this seems to work, but at any sign of trouble,
5142 * let's clean it up. -NM */
5144 /* Change defaults. */
5145 for (int i = 0; testing_tor_network_defaults[i].name; ++i) {
5146 const config_var_t *new_var = &testing_tor_network_defaults[i];
5147 config_var_t *old_var =
5148 config_find_option_mutable(&options_format, new_var->name);
5149 tor_assert(new_var);
5150 tor_assert(old_var);
5151 old_var->initvalue = new_var->initvalue;
5153 if ((config_find_deprecation(&options_format, new_var->name))) {
5154 log_warn(LD_GENERAL, "Testing options override the deprecated "
5155 "option %s. Is that intentional?",
5156 new_var->name);
5160 /* Clear newoptions and re-initialize them with new defaults. */
5161 or_options_free(newoptions);
5162 or_options_free(newdefaultoptions);
5163 newdefaultoptions = NULL;
5164 newoptions = tor_malloc_zero(sizeof(or_options_t));
5165 newoptions->magic_ = OR_OPTIONS_MAGIC;
5166 options_init(newoptions);
5167 newoptions->command = command;
5168 newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
5170 /* Assign all options a second time. */
5171 for (int i = 0; i < 2; ++i) {
5172 const char *body = i==0 ? cf_defaults : cf;
5173 if (!body)
5174 continue;
5175 /* get config lines, assign them */
5176 retval = config_get_lines_include(body, &cl, 1,
5177 body == cf ? &cf_has_include : NULL);
5178 if (retval < 0) {
5179 err = SETOPT_ERR_PARSE;
5180 goto err;
5182 retval = config_assign(&options_format, newoptions, cl, 0, msg);
5183 config_free_lines(cl);
5184 if (retval < 0) {
5185 err = SETOPT_ERR_PARSE;
5186 goto err;
5188 if (i==0)
5189 newdefaultoptions = config_dup(&options_format, newoptions);
5191 /* Assign command-line variables a second time too */
5192 retval = config_assign(&options_format, newoptions,
5193 global_cmdline_options, 0, msg);
5194 if (retval < 0) {
5195 err = SETOPT_ERR_PARSE;
5196 goto err;
5200 newoptions->IncludeUsed = cf_has_include;
5202 /* Validate newoptions */
5203 if (options_validate(oldoptions, newoptions, newdefaultoptions,
5204 0, msg) < 0) {
5205 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
5206 goto err;
5209 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
5210 err = SETOPT_ERR_TRANSITION;
5211 goto err;
5214 if (set_options(newoptions, msg)) {
5215 err = SETOPT_ERR_SETTING;
5216 goto err; /* frees and replaces old options */
5218 or_options_free(global_default_options);
5219 global_default_options = newdefaultoptions;
5221 return SETOPT_OK;
5223 err:
5224 or_options_free(newoptions);
5225 or_options_free(newdefaultoptions);
5226 if (*msg) {
5227 char *old_msg = *msg;
5228 tor_asprintf(msg, "Failed to parse/validate config: %s", old_msg);
5229 tor_free(old_msg);
5231 return err;
5234 /** Return the location for our configuration file. May return NULL.
5236 const char *
5237 get_torrc_fname(int defaults_fname)
5239 const char *fname = defaults_fname ? torrc_defaults_fname : torrc_fname;
5241 if (fname)
5242 return fname;
5243 else
5244 return get_default_conf_file(defaults_fname);
5247 /** Adjust the address map based on the MapAddress elements in the
5248 * configuration <b>options</b>
5250 void
5251 config_register_addressmaps(const or_options_t *options)
5253 smartlist_t *elts;
5254 config_line_t *opt;
5255 const char *from, *to, *msg;
5257 addressmap_clear_configured();
5258 elts = smartlist_new();
5259 for (opt = options->AddressMap; opt; opt = opt->next) {
5260 smartlist_split_string(elts, opt->value, NULL,
5261 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
5262 if (smartlist_len(elts) < 2) {
5263 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
5264 opt->value);
5265 goto cleanup;
5268 from = smartlist_get(elts,0);
5269 to = smartlist_get(elts,1);
5271 if (to[0] == '.' || from[0] == '.') {
5272 log_warn(LD_CONFIG,"MapAddress '%s' is ambiguous - address starts with a"
5273 "'.'. Ignoring.",opt->value);
5274 goto cleanup;
5277 if (addressmap_register_auto(from, to, 0, ADDRMAPSRC_TORRC, &msg) < 0) {
5278 log_warn(LD_CONFIG,"MapAddress '%s' failed: %s. Ignoring.", opt->value,
5279 msg);
5280 goto cleanup;
5283 if (smartlist_len(elts) > 2)
5284 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
5286 cleanup:
5287 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
5288 smartlist_clear(elts);
5290 smartlist_free(elts);
5293 /** As addressmap_register(), but detect the wildcarded status of "from" and
5294 * "to", and do not steal a reference to <b>to</b>. */
5295 /* XXXX move to connection_edge.c */
5297 addressmap_register_auto(const char *from, const char *to,
5298 time_t expires,
5299 addressmap_entry_source_t addrmap_source,
5300 const char **msg)
5302 int from_wildcard = 0, to_wildcard = 0;
5304 *msg = "whoops, forgot the error message";
5306 if (!strcmp(to, "*") || !strcmp(from, "*")) {
5307 *msg = "can't remap from or to *";
5308 return -1;
5310 /* Detect asterisks in expressions of type: '*.example.com' */
5311 if (!strncmp(from,"*.",2)) {
5312 from += 2;
5313 from_wildcard = 1;
5315 if (!strncmp(to,"*.",2)) {
5316 to += 2;
5317 to_wildcard = 1;
5320 if (to_wildcard && !from_wildcard) {
5321 *msg = "can only use wildcard (i.e. '*.') if 'from' address "
5322 "uses wildcard also";
5323 return -1;
5326 if (address_is_invalid_destination(to, 1)) {
5327 *msg = "destination is invalid";
5328 return -1;
5331 addressmap_register(from, tor_strdup(to), expires, addrmap_source,
5332 from_wildcard, to_wildcard);
5334 return 0;
5338 * Initialize the logs based on the configuration file.
5340 static int
5341 options_init_logs(const or_options_t *old_options, or_options_t *options,
5342 int validate_only)
5344 config_line_t *opt;
5345 int ok;
5346 smartlist_t *elts;
5347 int run_as_daemon =
5348 #ifdef _WIN32
5350 #else
5351 options->RunAsDaemon;
5352 #endif
5354 if (options->LogTimeGranularity <= 0) {
5355 log_warn(LD_CONFIG, "Log time granularity '%d' has to be positive.",
5356 options->LogTimeGranularity);
5357 return -1;
5358 } else if (1000 % options->LogTimeGranularity != 0 &&
5359 options->LogTimeGranularity % 1000 != 0) {
5360 int granularity = options->LogTimeGranularity;
5361 if (granularity < 40) {
5362 do granularity++;
5363 while (1000 % granularity != 0);
5364 } else if (granularity < 1000) {
5365 granularity = 1000 / granularity;
5366 while (1000 % granularity != 0)
5367 granularity--;
5368 granularity = 1000 / granularity;
5369 } else {
5370 granularity = 1000 * ((granularity / 1000) + 1);
5372 log_warn(LD_CONFIG, "Log time granularity '%d' has to be either a "
5373 "divisor or a multiple of 1 second. Changing to "
5374 "'%d'.",
5375 options->LogTimeGranularity, granularity);
5376 if (!validate_only)
5377 set_log_time_granularity(granularity);
5378 } else {
5379 if (!validate_only)
5380 set_log_time_granularity(options->LogTimeGranularity);
5383 ok = 1;
5384 elts = smartlist_new();
5386 for (opt = options->Logs; opt; opt = opt->next) {
5387 log_severity_list_t *severity;
5388 const char *cfg = opt->value;
5389 severity = tor_malloc_zero(sizeof(log_severity_list_t));
5390 if (parse_log_severity_config(&cfg, severity) < 0) {
5391 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
5392 opt->value);
5393 ok = 0; goto cleanup;
5396 smartlist_split_string(elts, cfg, NULL,
5397 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
5399 if (smartlist_len(elts) == 0)
5400 smartlist_add_strdup(elts, "stdout");
5402 if (smartlist_len(elts) == 1 &&
5403 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
5404 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
5405 int err = smartlist_len(elts) &&
5406 !strcasecmp(smartlist_get(elts,0), "stderr");
5407 if (!validate_only) {
5408 if (run_as_daemon) {
5409 log_warn(LD_CONFIG,
5410 "Can't log to %s with RunAsDaemon set; skipping stdout",
5411 err?"stderr":"stdout");
5412 } else {
5413 add_stream_log(severity, err?"<stderr>":"<stdout>",
5414 fileno(err?stderr:stdout));
5417 goto cleanup;
5419 if (smartlist_len(elts) == 1 &&
5420 !strcasecmp(smartlist_get(elts,0), "syslog")) {
5421 #ifdef HAVE_SYSLOG_H
5422 if (!validate_only) {
5423 add_syslog_log(severity, options->SyslogIdentityTag);
5425 #else
5426 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
5427 #endif
5428 goto cleanup;
5431 if (smartlist_len(elts) == 2 &&
5432 !strcasecmp(smartlist_get(elts,0), "file")) {
5433 if (!validate_only) {
5434 char *fname = expand_filename(smartlist_get(elts, 1));
5435 /* Truncate if TruncateLogFile is set and we haven't seen this option
5436 line before. */
5437 int truncate_log = 0;
5438 if (options->TruncateLogFile) {
5439 truncate_log = 1;
5440 if (old_options) {
5441 config_line_t *opt2;
5442 for (opt2 = old_options->Logs; opt2; opt2 = opt2->next)
5443 if (!strcmp(opt->value, opt2->value)) {
5444 truncate_log = 0;
5445 break;
5449 if (add_file_log(severity, fname, truncate_log) < 0) {
5450 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
5451 opt->value, strerror(errno));
5452 ok = 0;
5454 tor_free(fname);
5456 goto cleanup;
5459 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
5460 opt->value);
5461 ok = 0; goto cleanup;
5463 cleanup:
5464 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
5465 smartlist_clear(elts);
5466 tor_free(severity);
5468 smartlist_free(elts);
5470 if (ok && !validate_only)
5471 logs_set_domain_logging(options->LogMessageDomains);
5473 return ok?0:-1;
5476 /** Given a smartlist of SOCKS arguments to be passed to a transport
5477 * proxy in <b>args</b>, validate them and return -1 if they are
5478 * corrupted. Return 0 if they seem OK. */
5479 static int
5480 validate_transport_socks_arguments(const smartlist_t *args)
5482 char *socks_string = NULL;
5483 size_t socks_string_len;
5485 tor_assert(args);
5486 tor_assert(smartlist_len(args) > 0);
5488 SMARTLIST_FOREACH_BEGIN(args, const char *, s) {
5489 if (!string_is_key_value(LOG_WARN, s)) { /* items should be k=v items */
5490 log_warn(LD_CONFIG, "'%s' is not a k=v item.", s);
5491 return -1;
5493 } SMARTLIST_FOREACH_END(s);
5495 socks_string = pt_stringify_socks_args(args);
5496 if (!socks_string)
5497 return -1;
5499 socks_string_len = strlen(socks_string);
5500 tor_free(socks_string);
5502 if (socks_string_len > MAX_SOCKS5_AUTH_SIZE_TOTAL) {
5503 log_warn(LD_CONFIG, "SOCKS arguments can't be more than %u bytes (%lu).",
5504 MAX_SOCKS5_AUTH_SIZE_TOTAL,
5505 (unsigned long) socks_string_len);
5506 return -1;
5509 return 0;
5512 /** Deallocate a bridge_line_t structure. */
5513 /* private */ void
5514 bridge_line_free(bridge_line_t *bridge_line)
5516 if (!bridge_line)
5517 return;
5519 if (bridge_line->socks_args) {
5520 SMARTLIST_FOREACH(bridge_line->socks_args, char*, s, tor_free(s));
5521 smartlist_free(bridge_line->socks_args);
5523 tor_free(bridge_line->transport_name);
5524 tor_free(bridge_line);
5527 /** Parse the contents of a string, <b>line</b>, containing a Bridge line,
5528 * into a bridge_line_t.
5530 * Validates that the IP:PORT, fingerprint, and SOCKS arguments (given to the
5531 * Pluggable Transport, if a one was specified) are well-formed.
5533 * Returns NULL If the Bridge line could not be validated, and returns a
5534 * bridge_line_t containing the parsed information otherwise.
5536 * Bridge line format:
5537 * Bridge [transport] IP:PORT [id-fingerprint] [k=v] [k=v] ...
5539 /* private */ bridge_line_t *
5540 parse_bridge_line(const char *line)
5542 smartlist_t *items = NULL;
5543 char *addrport=NULL, *fingerprint=NULL;
5544 char *field=NULL;
5545 bridge_line_t *bridge_line = tor_malloc_zero(sizeof(bridge_line_t));
5547 items = smartlist_new();
5548 smartlist_split_string(items, line, NULL,
5549 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5550 if (smartlist_len(items) < 1) {
5551 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
5552 goto err;
5555 /* first field is either a transport name or addrport */
5556 field = smartlist_get(items, 0);
5557 smartlist_del_keeporder(items, 0);
5559 if (string_is_C_identifier(field)) {
5560 /* It's a transport name. */
5561 bridge_line->transport_name = field;
5562 if (smartlist_len(items) < 1) {
5563 log_warn(LD_CONFIG, "Too few items to Bridge line.");
5564 goto err;
5566 addrport = smartlist_get(items, 0); /* Next field is addrport then. */
5567 smartlist_del_keeporder(items, 0);
5568 } else {
5569 addrport = field;
5572 if (tor_addr_port_parse(LOG_INFO, addrport,
5573 &bridge_line->addr, &bridge_line->port, 443)<0) {
5574 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
5575 goto err;
5578 /* If transports are enabled, next field could be a fingerprint or a
5579 socks argument. If transports are disabled, next field must be
5580 a fingerprint. */
5581 if (smartlist_len(items)) {
5582 if (bridge_line->transport_name) { /* transports enabled: */
5583 field = smartlist_get(items, 0);
5584 smartlist_del_keeporder(items, 0);
5586 /* If it's a key=value pair, then it's a SOCKS argument for the
5587 transport proxy... */
5588 if (string_is_key_value(LOG_DEBUG, field)) {
5589 bridge_line->socks_args = smartlist_new();
5590 smartlist_add(bridge_line->socks_args, field);
5591 } else { /* ...otherwise, it's the bridge fingerprint. */
5592 fingerprint = field;
5595 } else { /* transports disabled: */
5596 fingerprint = smartlist_join_strings(items, "", 0, NULL);
5600 /* Handle fingerprint, if it was provided. */
5601 if (fingerprint) {
5602 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
5603 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
5604 goto err;
5606 if (base16_decode(bridge_line->digest, DIGEST_LEN,
5607 fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
5608 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
5609 goto err;
5613 /* If we are using transports, any remaining items in the smartlist
5614 should be k=v values. */
5615 if (bridge_line->transport_name && smartlist_len(items)) {
5616 if (!bridge_line->socks_args)
5617 bridge_line->socks_args = smartlist_new();
5619 /* append remaining items of 'items' to 'socks_args' */
5620 smartlist_add_all(bridge_line->socks_args, items);
5621 smartlist_clear(items);
5623 tor_assert(smartlist_len(bridge_line->socks_args) > 0);
5626 if (bridge_line->socks_args) {
5627 if (validate_transport_socks_arguments(bridge_line->socks_args) < 0)
5628 goto err;
5631 goto done;
5633 err:
5634 bridge_line_free(bridge_line);
5635 bridge_line = NULL;
5637 done:
5638 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5639 smartlist_free(items);
5640 tor_free(addrport);
5641 tor_free(fingerprint);
5643 return bridge_line;
5646 /** Read the contents of a ClientTransportPlugin or ServerTransportPlugin
5647 * line from <b>line</b>, depending on the value of <b>server</b>. Return 0
5648 * if the line is well-formed, and -1 if it isn't.
5650 * If <b>validate_only</b> is 0, the line is well-formed, and the transport is
5651 * needed by some bridge:
5652 * - If it's an external proxy line, add the transport described in the line to
5653 * our internal transport list.
5654 * - If it's a managed proxy line, launch the managed proxy.
5657 STATIC int
5658 parse_transport_line(const or_options_t *options,
5659 const char *line, int validate_only,
5660 int server)
5663 smartlist_t *items = NULL;
5664 int r;
5665 const char *transports = NULL;
5666 smartlist_t *transport_list = NULL;
5667 char *type = NULL;
5668 char *addrport = NULL;
5669 tor_addr_t addr;
5670 uint16_t port = 0;
5671 int socks_ver = PROXY_NONE;
5673 /* managed proxy options */
5674 int is_managed = 0;
5675 char **proxy_argv = NULL;
5676 char **tmp = NULL;
5677 int proxy_argc, i;
5678 int is_useless_proxy = 1;
5680 int line_length;
5682 /* Split the line into space-separated tokens */
5683 items = smartlist_new();
5684 smartlist_split_string(items, line, NULL,
5685 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5686 line_length = smartlist_len(items);
5688 if (line_length < 3) {
5689 log_warn(LD_CONFIG,
5690 "Too few arguments on %sTransportPlugin line.",
5691 server ? "Server" : "Client");
5692 goto err;
5695 /* Get the first line element, split it to commas into
5696 transport_list (in case it's multiple transports) and validate
5697 the transport names. */
5698 transports = smartlist_get(items, 0);
5699 transport_list = smartlist_new();
5700 smartlist_split_string(transport_list, transports, ",",
5701 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
5702 SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
5703 /* validate transport names */
5704 if (!string_is_C_identifier(transport_name)) {
5705 log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
5706 transport_name);
5707 goto err;
5710 /* see if we actually need the transports provided by this proxy */
5711 if (!validate_only && transport_is_needed(transport_name))
5712 is_useless_proxy = 0;
5713 } SMARTLIST_FOREACH_END(transport_name);
5715 type = smartlist_get(items, 1);
5716 if (!strcmp(type, "exec")) {
5717 is_managed = 1;
5718 } else if (server && !strcmp(type, "proxy")) {
5719 /* 'proxy' syntax only with ServerTransportPlugin */
5720 is_managed = 0;
5721 } else if (!server && !strcmp(type, "socks4")) {
5722 /* 'socks4' syntax only with ClientTransportPlugin */
5723 is_managed = 0;
5724 socks_ver = PROXY_SOCKS4;
5725 } else if (!server && !strcmp(type, "socks5")) {
5726 /* 'socks5' syntax only with ClientTransportPlugin */
5727 is_managed = 0;
5728 socks_ver = PROXY_SOCKS5;
5729 } else {
5730 log_warn(LD_CONFIG,
5731 "Strange %sTransportPlugin type '%s'",
5732 server ? "Server" : "Client", type);
5733 goto err;
5736 if (is_managed && options->Sandbox) {
5737 log_warn(LD_CONFIG,
5738 "Managed proxies are not compatible with Sandbox mode."
5739 "(%sTransportPlugin line was %s)",
5740 server ? "Server" : "Client", escaped(line));
5741 goto err;
5744 if (is_managed && options->NoExec) {
5745 log_warn(LD_CONFIG,
5746 "Managed proxies are not compatible with NoExec mode; ignoring."
5747 "(%sTransportPlugin line was %s)",
5748 server ? "Server" : "Client", escaped(line));
5749 r = 0;
5750 goto done;
5753 if (is_managed) {
5754 /* managed */
5756 if (!server && !validate_only && is_useless_proxy) {
5757 log_info(LD_GENERAL,
5758 "Pluggable transport proxy (%s) does not provide "
5759 "any needed transports and will not be launched.",
5760 line);
5764 * If we are not just validating, use the rest of the line as the
5765 * argv of the proxy to be launched. Also, make sure that we are
5766 * only launching proxies that contribute useful transports.
5769 if (!validate_only && (server || !is_useless_proxy)) {
5770 proxy_argc = line_length - 2;
5771 tor_assert(proxy_argc > 0);
5772 proxy_argv = tor_calloc((proxy_argc + 1), sizeof(char *));
5773 tmp = proxy_argv;
5775 for (i = 0; i < proxy_argc; i++) {
5776 /* store arguments */
5777 *tmp++ = smartlist_get(items, 2);
5778 smartlist_del_keeporder(items, 2);
5780 *tmp = NULL; /* terminated with NULL, just like execve() likes it */
5782 /* kickstart the thing */
5783 if (server) {
5784 pt_kickstart_server_proxy(transport_list, proxy_argv);
5785 } else {
5786 pt_kickstart_client_proxy(transport_list, proxy_argv);
5789 } else {
5790 /* external */
5792 /* ClientTransportPlugins connecting through a proxy is managed only. */
5793 if (!server && (options->Socks4Proxy || options->Socks5Proxy ||
5794 options->HTTPSProxy)) {
5795 log_warn(LD_CONFIG, "You have configured an external proxy with another "
5796 "proxy type. (Socks4Proxy|Socks5Proxy|HTTPSProxy)");
5797 goto err;
5800 if (smartlist_len(transport_list) != 1) {
5801 log_warn(LD_CONFIG,
5802 "You can't have an external proxy with more than "
5803 "one transport.");
5804 goto err;
5807 addrport = smartlist_get(items, 2);
5809 if (tor_addr_port_lookup(addrport, &addr, &port) < 0) {
5810 log_warn(LD_CONFIG,
5811 "Error parsing transport address '%s'", addrport);
5812 goto err;
5815 if (!port) {
5816 log_warn(LD_CONFIG,
5817 "Transport address '%s' has no port.", addrport);
5818 goto err;
5821 if (!validate_only) {
5822 log_info(LD_DIR, "%s '%s' at %s.",
5823 server ? "Server transport" : "Transport",
5824 transports, fmt_addrport(&addr, port));
5826 if (!server) {
5827 transport_add_from_config(&addr, port,
5828 smartlist_get(transport_list, 0),
5829 socks_ver);
5834 r = 0;
5835 goto done;
5837 err:
5838 r = -1;
5840 done:
5841 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5842 smartlist_free(items);
5843 if (transport_list) {
5844 SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
5845 smartlist_free(transport_list);
5848 return r;
5851 /** Given a ServerTransportListenAddr <b>line</b>, return its
5852 * <address:port> string. Return NULL if the line was not
5853 * well-formed.
5855 * If <b>transport</b> is set, return NULL if the line is not
5856 * referring to <b>transport</b>.
5858 * The returned string is allocated on the heap and it's the
5859 * responsibility of the caller to free it. */
5860 static char *
5861 get_bindaddr_from_transport_listen_line(const char *line,const char *transport)
5863 smartlist_t *items = NULL;
5864 const char *parsed_transport = NULL;
5865 char *addrport = NULL;
5866 tor_addr_t addr;
5867 uint16_t port = 0;
5869 items = smartlist_new();
5870 smartlist_split_string(items, line, NULL,
5871 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5873 if (smartlist_len(items) < 2) {
5874 log_warn(LD_CONFIG,"Too few arguments on ServerTransportListenAddr line.");
5875 goto err;
5878 parsed_transport = smartlist_get(items, 0);
5879 addrport = tor_strdup(smartlist_get(items, 1));
5881 /* If 'transport' is given, check if it matches the one on the line */
5882 if (transport && strcmp(transport, parsed_transport))
5883 goto err;
5885 /* Validate addrport */
5886 if (tor_addr_port_parse(LOG_WARN, addrport, &addr, &port, -1)<0) {
5887 log_warn(LD_CONFIG, "Error parsing ServerTransportListenAddr "
5888 "address '%s'", addrport);
5889 goto err;
5892 goto done;
5894 err:
5895 tor_free(addrport);
5896 addrport = NULL;
5898 done:
5899 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5900 smartlist_free(items);
5902 return addrport;
5905 /** Given a ServerTransportOptions <b>line</b>, return a smartlist
5906 * with the options. Return NULL if the line was not well-formed.
5908 * If <b>transport</b> is set, return NULL if the line is not
5909 * referring to <b>transport</b>.
5911 * The returned smartlist and its strings are allocated on the heap
5912 * and it's the responsibility of the caller to free it. */
5913 smartlist_t *
5914 get_options_from_transport_options_line(const char *line,const char *transport)
5916 smartlist_t *items = smartlist_new();
5917 smartlist_t *options = smartlist_new();
5918 const char *parsed_transport = NULL;
5920 smartlist_split_string(items, line, NULL,
5921 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5923 if (smartlist_len(items) < 2) {
5924 log_warn(LD_CONFIG,"Too few arguments on ServerTransportOptions line.");
5925 goto err;
5928 parsed_transport = smartlist_get(items, 0);
5929 /* If 'transport' is given, check if it matches the one on the line */
5930 if (transport && strcmp(transport, parsed_transport))
5931 goto err;
5933 SMARTLIST_FOREACH_BEGIN(items, const char *, option) {
5934 if (option_sl_idx == 0) /* skip the transport field (first field)*/
5935 continue;
5937 /* validate that it's a k=v value */
5938 if (!string_is_key_value(LOG_WARN, option)) {
5939 log_warn(LD_CONFIG, "%s is not a k=v value.", escaped(option));
5940 goto err;
5943 /* add it to the options smartlist */
5944 smartlist_add_strdup(options, option);
5945 log_debug(LD_CONFIG, "Added %s to the list of options", escaped(option));
5946 } SMARTLIST_FOREACH_END(option);
5948 goto done;
5950 err:
5951 SMARTLIST_FOREACH(options, char*, s, tor_free(s));
5952 smartlist_free(options);
5953 options = NULL;
5955 done:
5956 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5957 smartlist_free(items);
5959 return options;
5962 /** Given the name of a pluggable transport in <b>transport</b>, check
5963 * the configuration file to see if the user has explicitly asked for
5964 * it to listen on a specific port. Return a <address:port> string if
5965 * so, otherwise NULL. */
5966 char *
5967 get_transport_bindaddr_from_config(const char *transport)
5969 config_line_t *cl;
5970 const or_options_t *options = get_options();
5972 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
5973 char *bindaddr =
5974 get_bindaddr_from_transport_listen_line(cl->value, transport);
5975 if (bindaddr)
5976 return bindaddr;
5979 return NULL;
5982 /** Given the name of a pluggable transport in <b>transport</b>, check
5983 * the configuration file to see if the user has asked us to pass any
5984 * parameters to the pluggable transport. Return a smartlist
5985 * containing the parameters, otherwise NULL. */
5986 smartlist_t *
5987 get_options_for_server_transport(const char *transport)
5989 config_line_t *cl;
5990 const or_options_t *options = get_options();
5992 for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
5993 smartlist_t *options_sl =
5994 get_options_from_transport_options_line(cl->value, transport);
5995 if (options_sl)
5996 return options_sl;
5999 return NULL;
6002 /** Read the contents of a DirAuthority line from <b>line</b>. If
6003 * <b>validate_only</b> is 0, and the line is well-formed, and it
6004 * shares any bits with <b>required_type</b> or <b>required_type</b>
6005 * is NO_DIRINFO (zero), then add the dirserver described in the line
6006 * (minus whatever bits it's missing) as a valid authority.
6007 * Return 0 on success or filtering out by type,
6008 * or -1 if the line isn't well-formed or if we can't add it. */
6009 STATIC int
6010 parse_dir_authority_line(const char *line, dirinfo_type_t required_type,
6011 int validate_only)
6013 smartlist_t *items = NULL;
6014 int r;
6015 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
6016 tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
6017 uint16_t dir_port = 0, or_port = 0;
6018 char digest[DIGEST_LEN];
6019 char v3_digest[DIGEST_LEN];
6020 dirinfo_type_t type = 0;
6021 double weight = 1.0;
6023 items = smartlist_new();
6024 smartlist_split_string(items, line, NULL,
6025 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6026 if (smartlist_len(items) < 1) {
6027 log_warn(LD_CONFIG, "No arguments on DirAuthority line.");
6028 goto err;
6031 if (is_legal_nickname(smartlist_get(items, 0))) {
6032 nickname = smartlist_get(items, 0);
6033 smartlist_del_keeporder(items, 0);
6036 while (smartlist_len(items)) {
6037 char *flag = smartlist_get(items, 0);
6038 if (TOR_ISDIGIT(flag[0]))
6039 break;
6040 if (!strcasecmp(flag, "hs") ||
6041 !strcasecmp(flag, "no-hs")) {
6042 log_warn(LD_CONFIG, "The DirAuthority options 'hs' and 'no-hs' are "
6043 "obsolete; you don't need them any more.");
6044 } else if (!strcasecmp(flag, "bridge")) {
6045 type |= BRIDGE_DIRINFO;
6046 } else if (!strcasecmp(flag, "no-v2")) {
6047 /* obsolete, but may still be contained in DirAuthority lines generated
6048 by various tools */;
6049 } else if (!strcasecmpstart(flag, "orport=")) {
6050 int ok;
6051 char *portstring = flag + strlen("orport=");
6052 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
6053 if (!ok)
6054 log_warn(LD_CONFIG, "Invalid orport '%s' on DirAuthority line.",
6055 portstring);
6056 } else if (!strcmpstart(flag, "weight=")) {
6057 int ok;
6058 const char *wstring = flag + strlen("weight=");
6059 weight = tor_parse_double(wstring, 0, (double)UINT64_MAX, &ok, NULL);
6060 if (!ok) {
6061 log_warn(LD_CONFIG, "Invalid weight '%s' on DirAuthority line.",flag);
6062 weight=1.0;
6064 } else if (!strcasecmpstart(flag, "v3ident=")) {
6065 char *idstr = flag + strlen("v3ident=");
6066 if (strlen(idstr) != HEX_DIGEST_LEN ||
6067 base16_decode(v3_digest, DIGEST_LEN,
6068 idstr, HEX_DIGEST_LEN) != DIGEST_LEN) {
6069 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirAuthority line",
6070 flag);
6071 } else {
6072 type |= V3_DIRINFO|EXTRAINFO_DIRINFO|MICRODESC_DIRINFO;
6074 } else if (!strcasecmpstart(flag, "ipv6=")) {
6075 if (ipv6_addrport_ptr) {
6076 log_warn(LD_CONFIG, "Redundant ipv6 addr/port on DirAuthority line");
6077 } else {
6078 if (tor_addr_port_parse(LOG_WARN, flag+strlen("ipv6="),
6079 &ipv6_addrport.addr, &ipv6_addrport.port,
6080 -1) < 0
6081 || tor_addr_family(&ipv6_addrport.addr) != AF_INET6) {
6082 log_warn(LD_CONFIG, "Bad ipv6 addr/port %s on DirAuthority line",
6083 escaped(flag));
6084 goto err;
6086 ipv6_addrport_ptr = &ipv6_addrport;
6088 } else {
6089 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirAuthority line",
6090 flag);
6092 tor_free(flag);
6093 smartlist_del_keeporder(items, 0);
6096 if (smartlist_len(items) < 2) {
6097 log_warn(LD_CONFIG, "Too few arguments to DirAuthority line.");
6098 goto err;
6100 addrport = smartlist_get(items, 0);
6101 smartlist_del_keeporder(items, 0);
6102 if (addr_port_lookup(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
6103 log_warn(LD_CONFIG, "Error parsing DirAuthority address '%s'", addrport);
6104 goto err;
6106 if (!dir_port) {
6107 log_warn(LD_CONFIG, "Missing port in DirAuthority address '%s'",addrport);
6108 goto err;
6111 fingerprint = smartlist_join_strings(items, "", 0, NULL);
6112 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
6113 log_warn(LD_CONFIG, "Key digest '%s' for DirAuthority is wrong length %d.",
6114 fingerprint, (int)strlen(fingerprint));
6115 goto err;
6117 if (base16_decode(digest, DIGEST_LEN,
6118 fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
6119 log_warn(LD_CONFIG, "Unable to decode DirAuthority key digest.");
6120 goto err;
6123 if (!validate_only && (!required_type || required_type & type)) {
6124 dir_server_t *ds;
6125 if (required_type)
6126 type &= required_type; /* pare down what we think of them as an
6127 * authority for. */
6128 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
6129 address, (int)dir_port, (char*)smartlist_get(items,0));
6130 if (!(ds = trusted_dir_server_new(nickname, address, dir_port, or_port,
6131 ipv6_addrport_ptr,
6132 digest, v3_digest, type, weight)))
6133 goto err;
6134 dir_server_add(ds);
6137 r = 0;
6138 goto done;
6140 err:
6141 r = -1;
6143 done:
6144 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
6145 smartlist_free(items);
6146 tor_free(addrport);
6147 tor_free(address);
6148 tor_free(nickname);
6149 tor_free(fingerprint);
6150 return r;
6153 /** Read the contents of a FallbackDir line from <b>line</b>. If
6154 * <b>validate_only</b> is 0, and the line is well-formed, then add the
6155 * dirserver described in the line as a fallback directory. Return 0 on
6156 * success, or -1 if the line isn't well-formed or if we can't add it. */
6158 parse_dir_fallback_line(const char *line,
6159 int validate_only)
6161 int r = -1;
6162 smartlist_t *items = smartlist_new(), *positional = smartlist_new();
6163 int orport = -1;
6164 uint16_t dirport;
6165 tor_addr_t addr;
6166 int ok;
6167 char id[DIGEST_LEN];
6168 char *address=NULL;
6169 tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
6170 double weight=1.0;
6172 memset(id, 0, sizeof(id));
6173 smartlist_split_string(items, line, NULL,
6174 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6175 SMARTLIST_FOREACH_BEGIN(items, const char *, cp) {
6176 const char *eq = strchr(cp, '=');
6177 ok = 1;
6178 if (! eq) {
6179 smartlist_add(positional, (char*)cp);
6180 continue;
6182 if (!strcmpstart(cp, "orport=")) {
6183 orport = (int)tor_parse_long(cp+strlen("orport="), 10,
6184 1, 65535, &ok, NULL);
6185 } else if (!strcmpstart(cp, "id=")) {
6186 ok = base16_decode(id, DIGEST_LEN, cp+strlen("id="),
6187 strlen(cp)-strlen("id=")) == DIGEST_LEN;
6188 } else if (!strcasecmpstart(cp, "ipv6=")) {
6189 if (ipv6_addrport_ptr) {
6190 log_warn(LD_CONFIG, "Redundant ipv6 addr/port on FallbackDir line");
6191 } else {
6192 if (tor_addr_port_parse(LOG_WARN, cp+strlen("ipv6="),
6193 &ipv6_addrport.addr, &ipv6_addrport.port,
6194 -1) < 0
6195 || tor_addr_family(&ipv6_addrport.addr) != AF_INET6) {
6196 log_warn(LD_CONFIG, "Bad ipv6 addr/port %s on FallbackDir line",
6197 escaped(cp));
6198 goto end;
6200 ipv6_addrport_ptr = &ipv6_addrport;
6202 } else if (!strcmpstart(cp, "weight=")) {
6203 int num_ok;
6204 const char *wstring = cp + strlen("weight=");
6205 weight = tor_parse_double(wstring, 0, (double)UINT64_MAX, &num_ok, NULL);
6206 if (!num_ok) {
6207 log_warn(LD_CONFIG, "Invalid weight '%s' on FallbackDir line.", cp);
6208 weight=1.0;
6212 if (!ok) {
6213 log_warn(LD_CONFIG, "Bad FallbackDir option %s", escaped(cp));
6214 goto end;
6216 } SMARTLIST_FOREACH_END(cp);
6218 if (smartlist_len(positional) != 1) {
6219 log_warn(LD_CONFIG, "Couldn't parse FallbackDir line %s", escaped(line));
6220 goto end;
6223 if (tor_digest_is_zero(id)) {
6224 log_warn(LD_CONFIG, "Missing identity on FallbackDir line");
6225 goto end;
6228 if (orport <= 0) {
6229 log_warn(LD_CONFIG, "Missing orport on FallbackDir line");
6230 goto end;
6233 if (tor_addr_port_split(LOG_INFO, smartlist_get(positional, 0),
6234 &address, &dirport) < 0 ||
6235 tor_addr_parse(&addr, address)<0) {
6236 log_warn(LD_CONFIG, "Couldn't parse address:port %s on FallbackDir line",
6237 (const char*)smartlist_get(positional, 0));
6238 goto end;
6241 if (!validate_only) {
6242 dir_server_t *ds;
6243 ds = fallback_dir_server_new(&addr, dirport, orport, ipv6_addrport_ptr,
6244 id, weight);
6245 if (!ds) {
6246 log_warn(LD_CONFIG, "Couldn't create FallbackDir %s", escaped(line));
6247 goto end;
6249 dir_server_add(ds);
6252 r = 0;
6254 end:
6255 SMARTLIST_FOREACH(items, char *, cp, tor_free(cp));
6256 smartlist_free(items);
6257 smartlist_free(positional);
6258 tor_free(address);
6259 return r;
6262 /** Allocate and return a new port_cfg_t with reasonable defaults. */
6263 STATIC port_cfg_t *
6264 port_cfg_new(size_t namelen)
6266 tor_assert(namelen <= SIZE_T_CEILING - sizeof(port_cfg_t) - 1);
6267 port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t) + namelen + 1);
6268 cfg->entry_cfg.ipv4_traffic = 1;
6269 cfg->entry_cfg.ipv6_traffic = 1;
6270 cfg->entry_cfg.dns_request = 1;
6271 cfg->entry_cfg.onion_traffic = 1;
6272 cfg->entry_cfg.cache_ipv4_answers = 1;
6273 cfg->entry_cfg.prefer_ipv6_virtaddr = 1;
6274 return cfg;
6277 /** Free all storage held in <b>port</b> */
6278 STATIC void
6279 port_cfg_free(port_cfg_t *port)
6281 tor_free(port);
6284 /** Warn for every port in <b>ports</b> of type <b>listener_type</b> that is
6285 * on a publicly routable address. */
6286 static void
6287 warn_nonlocal_client_ports(const smartlist_t *ports,
6288 const char *portname,
6289 const int listener_type)
6291 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
6292 if (port->type != listener_type)
6293 continue;
6294 if (port->is_unix_addr) {
6295 /* Unix sockets aren't accessible over a network. */
6296 } else if (!tor_addr_is_internal(&port->addr, 1)) {
6297 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
6298 "Other people on the Internet might find your computer and "
6299 "use it as an open proxy. Please don't allow this unless you "
6300 "have a good reason.",
6301 fmt_addrport(&port->addr, port->port), portname);
6302 } else if (!tor_addr_is_loopback(&port->addr)) {
6303 log_notice(LD_CONFIG, "You configured a non-loopback address '%s' "
6304 "for %sPort. This allows everybody on your local network to "
6305 "use your machine as a proxy. Make sure this is what you "
6306 "wanted.",
6307 fmt_addrport(&port->addr, port->port), portname);
6309 } SMARTLIST_FOREACH_END(port);
6312 /** Warn for every Extended ORPort port in <b>ports</b> that is on a
6313 * publicly routable address. */
6314 static void
6315 warn_nonlocal_ext_orports(const smartlist_t *ports, const char *portname)
6317 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
6318 if (port->type != CONN_TYPE_EXT_OR_LISTENER)
6319 continue;
6320 if (port->is_unix_addr)
6321 continue;
6322 /* XXX maybe warn even if address is RFC1918? */
6323 if (!tor_addr_is_internal(&port->addr, 1)) {
6324 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
6325 "This is not advised; this address is supposed to only be "
6326 "exposed on localhost so that your pluggable transport "
6327 "proxies can connect to it.",
6328 fmt_addrport(&port->addr, port->port), portname);
6330 } SMARTLIST_FOREACH_END(port);
6333 /** Given a list of port_cfg_t in <b>ports</b>, warn if any controller port
6334 * there is listening on any non-loopback address. If <b>forbid_nonlocal</b>
6335 * is true, then emit a stronger warning and remove the port from the list.
6337 static void
6338 warn_nonlocal_controller_ports(smartlist_t *ports, unsigned forbid_nonlocal)
6340 int warned = 0;
6341 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
6342 if (port->type != CONN_TYPE_CONTROL_LISTENER)
6343 continue;
6344 if (port->is_unix_addr)
6345 continue;
6346 if (!tor_addr_is_loopback(&port->addr)) {
6347 if (forbid_nonlocal) {
6348 if (!warned)
6349 log_warn(LD_CONFIG,
6350 "You have a ControlPort set to accept "
6351 "unauthenticated connections from a non-local address. "
6352 "This means that programs not running on your computer "
6353 "can reconfigure your Tor, without even having to guess a "
6354 "password. That's so bad that I'm closing your ControlPort "
6355 "for you. If you need to control your Tor remotely, try "
6356 "enabling authentication and using a tool like stunnel or "
6357 "ssh to encrypt remote access.");
6358 warned = 1;
6359 port_cfg_free(port);
6360 SMARTLIST_DEL_CURRENT(ports, port);
6361 } else {
6362 log_warn(LD_CONFIG, "You have a ControlPort set to accept "
6363 "connections from a non-local address. This means that "
6364 "programs not running on your computer can reconfigure your "
6365 "Tor. That's pretty bad, since the controller "
6366 "protocol isn't encrypted! Maybe you should just listen on "
6367 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
6368 "remote connections to your control port.");
6369 return; /* No point in checking the rest */
6372 } SMARTLIST_FOREACH_END(port);
6376 * Take a string (<b>line</b>) that begins with either an address:port, a
6377 * port, or an AF_UNIX address, optionally quoted, prefixed with
6378 * "unix:". Parse that line, and on success, set <b>addrport_out</b> to a new
6379 * string containing the beginning portion (without prefix). Iff there was a
6380 * unix: prefix, set <b>is_unix_out</b> to true. On success, also set
6381 * <b>rest_out</b> to point to the part of the line after the address portion.
6383 * Return 0 on success, -1 on failure.
6386 port_cfg_line_extract_addrport(const char *line,
6387 char **addrport_out,
6388 int *is_unix_out,
6389 const char **rest_out)
6391 tor_assert(line);
6392 tor_assert(addrport_out);
6393 tor_assert(is_unix_out);
6394 tor_assert(rest_out);
6396 line = eat_whitespace(line);
6398 if (!strcmpstart(line, unix_q_socket_prefix)) {
6399 // It starts with unix:"
6400 size_t sz;
6401 *is_unix_out = 1;
6402 *addrport_out = NULL;
6403 line += strlen(unix_socket_prefix); /*No q: Keep the quote */
6404 *rest_out = unescape_string(line, addrport_out, &sz);
6405 if (!*rest_out || (*addrport_out && sz != strlen(*addrport_out))) {
6406 tor_free(*addrport_out);
6407 return -1;
6409 *rest_out = eat_whitespace(*rest_out);
6410 return 0;
6411 } else {
6412 // Is there a unix: prefix?
6413 if (!strcmpstart(line, unix_socket_prefix)) {
6414 line += strlen(unix_socket_prefix);
6415 *is_unix_out = 1;
6416 } else {
6417 *is_unix_out = 0;
6420 const char *end = find_whitespace(line);
6421 if (BUG(!end)) {
6422 end = strchr(line, '\0'); // LCOV_EXCL_LINE -- this can't be NULL
6424 tor_assert(end && end >= line);
6425 *addrport_out = tor_strndup(line, end - line);
6426 *rest_out = eat_whitespace(end);
6427 return 0;
6431 static void
6432 warn_client_dns_cache(const char *option, int disabling)
6434 if (disabling)
6435 return;
6437 warn_deprecated_option(option,
6438 "Client-side DNS cacheing enables a wide variety of route-"
6439 "capture attacks. If a single bad exit node lies to you about "
6440 "an IP address, cacheing that address would make you visit "
6441 "an address of the attacker's choice every time you connected "
6442 "to your destination.");
6446 * Parse port configuration for a single port type.
6448 * Read entries of the "FooPort" type from the list <b>ports</b>. Syntax is
6449 * that FooPort can have any number of entries of the format
6450 * "[Address:][Port] IsolationOptions".
6452 * In log messages, describe the port type as <b>portname</b>.
6454 * If no address is specified, default to <b>defaultaddr</b>. If no
6455 * FooPort is given, default to defaultport (if 0, there is no default).
6457 * If CL_PORT_NO_STREAM_OPTIONS is set in <b>flags</b>, do not allow stream
6458 * isolation options in the FooPort entries.
6460 * If CL_PORT_WARN_NONLOCAL is set in <b>flags</b>, warn if any of the
6461 * ports are not on a local address. If CL_PORT_FORBID_NONLOCAL is set,
6462 * this is a control port with no password set: don't even allow it.
6464 * If CL_PORT_SERVER_OPTIONS is set in <b>flags</b>, do not allow stream
6465 * isolation options in the FooPort entries; instead allow the
6466 * server-port option set.
6468 * If CL_PORT_TAKES_HOSTNAMES is set in <b>flags</b>, allow the options
6469 * {No,}IPv{4,6}Traffic.
6471 * On success, if <b>out</b> is given, add a new port_cfg_t entry to
6472 * <b>out</b> for every port that the client should listen on. Return 0
6473 * on success, -1 on failure.
6475 STATIC int
6476 parse_port_config(smartlist_t *out,
6477 const config_line_t *ports,
6478 const char *portname,
6479 int listener_type,
6480 const char *defaultaddr,
6481 int defaultport,
6482 const unsigned flags)
6484 smartlist_t *elts;
6485 int retval = -1;
6486 const unsigned is_control = (listener_type == CONN_TYPE_CONTROL_LISTENER);
6487 const unsigned is_ext_orport = (listener_type == CONN_TYPE_EXT_OR_LISTENER);
6488 const unsigned allow_no_stream_options = flags & CL_PORT_NO_STREAM_OPTIONS;
6489 const unsigned use_server_options = flags & CL_PORT_SERVER_OPTIONS;
6490 const unsigned warn_nonlocal = flags & CL_PORT_WARN_NONLOCAL;
6491 const unsigned forbid_nonlocal = flags & CL_PORT_FORBID_NONLOCAL;
6492 const unsigned default_to_group_writable =
6493 flags & CL_PORT_DFLT_GROUP_WRITABLE;
6494 const unsigned takes_hostnames = flags & CL_PORT_TAKES_HOSTNAMES;
6495 const unsigned is_unix_socket = flags & CL_PORT_IS_UNIXSOCKET;
6496 int got_zero_port=0, got_nonzero_port=0;
6497 char *unix_socket_path = NULL;
6499 /* If there's no FooPort, then maybe make a default one. */
6500 if (! ports) {
6501 if (defaultport && defaultaddr && out) {
6502 port_cfg_t *cfg = port_cfg_new(is_unix_socket ? strlen(defaultaddr) : 0);
6503 cfg->type = listener_type;
6504 if (is_unix_socket) {
6505 tor_addr_make_unspec(&cfg->addr);
6506 memcpy(cfg->unix_addr, defaultaddr, strlen(defaultaddr) + 1);
6507 cfg->is_unix_addr = 1;
6508 } else {
6509 cfg->port = defaultport;
6510 tor_addr_parse(&cfg->addr, defaultaddr);
6512 cfg->entry_cfg.session_group = SESSION_GROUP_UNSET;
6513 cfg->entry_cfg.isolation_flags = ISO_DEFAULT;
6514 smartlist_add(out, cfg);
6516 return 0;
6519 /* At last we can actually parse the FooPort lines. The syntax is:
6520 * [Addr:](Port|auto) [Options].*/
6521 elts = smartlist_new();
6522 char *addrport = NULL;
6524 for (; ports; ports = ports->next) {
6525 tor_addr_t addr;
6526 int port;
6527 int sessiongroup = SESSION_GROUP_UNSET;
6528 unsigned isolation = ISO_DEFAULT;
6529 int prefer_no_auth = 0;
6530 int socks_iso_keep_alive = 0;
6532 uint16_t ptmp=0;
6533 int ok;
6534 /* This must be kept in sync with port_cfg_new's defaults */
6535 int no_listen = 0, no_advertise = 0, all_addrs = 0,
6536 bind_ipv4_only = 0, bind_ipv6_only = 0,
6537 ipv4_traffic = 1, ipv6_traffic = 1, prefer_ipv6 = 0, dns_request = 1,
6538 onion_traffic = 1,
6539 cache_ipv4 = 1, use_cached_ipv4 = 0,
6540 cache_ipv6 = 0, use_cached_ipv6 = 0,
6541 prefer_ipv6_automap = 1, world_writable = 0, group_writable = 0,
6542 relax_dirmode_check = 0,
6543 has_used_unix_socket_only_option = 0;
6545 int is_unix_tagged_addr = 0;
6546 const char *rest_of_line = NULL;
6547 if (port_cfg_line_extract_addrport(ports->value,
6548 &addrport, &is_unix_tagged_addr, &rest_of_line)<0) {
6549 log_warn(LD_CONFIG, "Invalid %sPort line with unparsable address",
6550 portname);
6551 goto err;
6553 if (strlen(addrport) == 0) {
6554 log_warn(LD_CONFIG, "Invalid %sPort line with no address", portname);
6555 goto err;
6558 /* Split the remainder... */
6559 smartlist_split_string(elts, rest_of_line, NULL,
6560 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
6562 /* Let's start to check if it's a Unix socket path. */
6563 if (is_unix_tagged_addr) {
6564 #ifndef HAVE_SYS_UN_H
6565 log_warn(LD_CONFIG, "Unix sockets not supported on this system.");
6566 goto err;
6567 #endif
6568 unix_socket_path = addrport;
6569 addrport = NULL;
6572 if (unix_socket_path &&
6573 ! conn_listener_type_supports_af_unix(listener_type)) {
6574 log_warn(LD_CONFIG, "%sPort does not support unix sockets", portname);
6575 goto err;
6578 if (unix_socket_path) {
6579 port = 1;
6580 } else if (is_unix_socket) {
6581 if (BUG(!addrport))
6582 goto err; // LCOV_EXCL_LINE unreachable, but coverity can't tell that
6583 unix_socket_path = tor_strdup(addrport);
6584 if (!strcmp(addrport, "0"))
6585 port = 0;
6586 else
6587 port = 1;
6588 } else if (!strcmp(addrport, "auto")) {
6589 port = CFG_AUTO_PORT;
6590 int af = tor_addr_parse(&addr, defaultaddr);
6591 tor_assert(af >= 0);
6592 } else if (!strcasecmpend(addrport, ":auto")) {
6593 char *addrtmp = tor_strndup(addrport, strlen(addrport)-5);
6594 port = CFG_AUTO_PORT;
6595 if (tor_addr_port_lookup(addrtmp, &addr, &ptmp)<0 || ptmp) {
6596 log_warn(LD_CONFIG, "Invalid address '%s' for %sPort",
6597 escaped(addrport), portname);
6598 tor_free(addrtmp);
6599 goto err;
6601 tor_free(addrtmp);
6602 } else {
6603 /* Try parsing integer port before address, because, who knows?
6604 "9050" might be a valid address. */
6605 port = (int) tor_parse_long(addrport, 10, 0, 65535, &ok, NULL);
6606 if (ok) {
6607 int af = tor_addr_parse(&addr, defaultaddr);
6608 tor_assert(af >= 0);
6609 } else if (tor_addr_port_lookup(addrport, &addr, &ptmp) == 0) {
6610 if (ptmp == 0) {
6611 log_warn(LD_CONFIG, "%sPort line has address but no port", portname);
6612 goto err;
6614 port = ptmp;
6615 } else {
6616 log_warn(LD_CONFIG, "Couldn't parse address %s for %sPort",
6617 escaped(addrport), portname);
6618 goto err;
6622 if (unix_socket_path && default_to_group_writable)
6623 group_writable = 1;
6625 /* Now parse the rest of the options, if any. */
6626 if (use_server_options) {
6627 /* This is a server port; parse advertising options */
6628 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
6629 if (!strcasecmp(elt, "NoAdvertise")) {
6630 no_advertise = 1;
6631 } else if (!strcasecmp(elt, "NoListen")) {
6632 no_listen = 1;
6633 #if 0
6634 /* not implemented yet. */
6635 } else if (!strcasecmp(elt, "AllAddrs")) {
6637 all_addrs = 1;
6638 #endif
6639 } else if (!strcasecmp(elt, "IPv4Only")) {
6640 bind_ipv4_only = 1;
6641 } else if (!strcasecmp(elt, "IPv6Only")) {
6642 bind_ipv6_only = 1;
6643 } else {
6644 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6645 portname, escaped(elt));
6647 } SMARTLIST_FOREACH_END(elt);
6649 if (no_advertise && no_listen) {
6650 log_warn(LD_CONFIG, "Tried to set both NoListen and NoAdvertise "
6651 "on %sPort line '%s'",
6652 portname, escaped(ports->value));
6653 goto err;
6655 if (bind_ipv4_only && bind_ipv6_only) {
6656 log_warn(LD_CONFIG, "Tried to set both IPv4Only and IPv6Only "
6657 "on %sPort line '%s'",
6658 portname, escaped(ports->value));
6659 goto err;
6661 if (bind_ipv4_only && tor_addr_family(&addr) == AF_INET6) {
6662 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv6",
6663 portname);
6664 goto err;
6666 if (bind_ipv6_only && tor_addr_family(&addr) == AF_INET) {
6667 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv4",
6668 portname);
6669 goto err;
6671 } else {
6672 /* This is a client port; parse isolation options */
6673 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
6674 int no = 0, isoflag = 0;
6675 const char *elt_orig = elt;
6677 if (!strcasecmpstart(elt, "SessionGroup=")) {
6678 int group = (int)tor_parse_long(elt+strlen("SessionGroup="),
6679 10, 0, INT_MAX, &ok, NULL);
6680 if (!ok || !allow_no_stream_options) {
6681 log_warn(LD_CONFIG, "Invalid %sPort option '%s'",
6682 portname, escaped(elt));
6683 goto err;
6685 if (sessiongroup >= 0) {
6686 log_warn(LD_CONFIG, "Multiple SessionGroup options on %sPort",
6687 portname);
6688 goto err;
6690 sessiongroup = group;
6691 continue;
6694 if (!strcasecmpstart(elt, "No")) {
6695 no = 1;
6696 elt += 2;
6699 if (!strcasecmp(elt, "GroupWritable")) {
6700 group_writable = !no;
6701 has_used_unix_socket_only_option = 1;
6702 continue;
6703 } else if (!strcasecmp(elt, "WorldWritable")) {
6704 world_writable = !no;
6705 has_used_unix_socket_only_option = 1;
6706 continue;
6707 } else if (!strcasecmp(elt, "RelaxDirModeCheck")) {
6708 relax_dirmode_check = !no;
6709 has_used_unix_socket_only_option = 1;
6710 continue;
6713 if (allow_no_stream_options) {
6714 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6715 portname, escaped(elt));
6716 continue;
6719 if (takes_hostnames) {
6720 if (!strcasecmp(elt, "IPv4Traffic")) {
6721 ipv4_traffic = ! no;
6722 continue;
6723 } else if (!strcasecmp(elt, "IPv6Traffic")) {
6724 ipv6_traffic = ! no;
6725 continue;
6726 } else if (!strcasecmp(elt, "PreferIPv6")) {
6727 prefer_ipv6 = ! no;
6728 continue;
6729 } else if (!strcasecmp(elt, "DNSRequest")) {
6730 dns_request = ! no;
6731 continue;
6732 } else if (!strcasecmp(elt, "OnionTraffic")) {
6733 onion_traffic = ! no;
6734 continue;
6735 } else if (!strcasecmp(elt, "OnionTrafficOnly")) {
6736 /* Only connect to .onion addresses. Equivalent to
6737 * NoDNSRequest, NoIPv4Traffic, NoIPv6Traffic. The option
6738 * NoOnionTrafficOnly is not supported, it's too confusing. */
6739 if (no) {
6740 log_warn(LD_CONFIG, "Unsupported %sPort option 'No%s'. Use "
6741 "DNSRequest, IPv4Traffic, and/or IPv6Traffic instead.",
6742 portname, escaped(elt));
6743 } else {
6744 ipv4_traffic = ipv6_traffic = dns_request = 0;
6746 continue;
6749 if (!strcasecmp(elt, "CacheIPv4DNS")) {
6750 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6751 cache_ipv4 = ! no;
6752 continue;
6753 } else if (!strcasecmp(elt, "CacheIPv6DNS")) {
6754 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6755 cache_ipv6 = ! no;
6756 continue;
6757 } else if (!strcasecmp(elt, "CacheDNS")) {
6758 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6759 cache_ipv4 = cache_ipv6 = ! no;
6760 continue;
6761 } else if (!strcasecmp(elt, "UseIPv4Cache")) {
6762 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6763 use_cached_ipv4 = ! no;
6764 continue;
6765 } else if (!strcasecmp(elt, "UseIPv6Cache")) {
6766 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6767 use_cached_ipv6 = ! no;
6768 continue;
6769 } else if (!strcasecmp(elt, "UseDNSCache")) {
6770 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6771 use_cached_ipv4 = use_cached_ipv6 = ! no;
6772 continue;
6773 } else if (!strcasecmp(elt, "PreferIPv6Automap")) {
6774 prefer_ipv6_automap = ! no;
6775 continue;
6776 } else if (!strcasecmp(elt, "PreferSOCKSNoAuth")) {
6777 prefer_no_auth = ! no;
6778 continue;
6779 } else if (!strcasecmp(elt, "KeepAliveIsolateSOCKSAuth")) {
6780 socks_iso_keep_alive = ! no;
6781 continue;
6784 if (!strcasecmpend(elt, "s"))
6785 elt[strlen(elt)-1] = '\0'; /* kill plurals. */
6787 if (!strcasecmp(elt, "IsolateDestPort")) {
6788 isoflag = ISO_DESTPORT;
6789 } else if (!strcasecmp(elt, "IsolateDestAddr")) {
6790 isoflag = ISO_DESTADDR;
6791 } else if (!strcasecmp(elt, "IsolateSOCKSAuth")) {
6792 isoflag = ISO_SOCKSAUTH;
6793 } else if (!strcasecmp(elt, "IsolateClientProtocol")) {
6794 isoflag = ISO_CLIENTPROTO;
6795 } else if (!strcasecmp(elt, "IsolateClientAddr")) {
6796 isoflag = ISO_CLIENTADDR;
6797 } else {
6798 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6799 portname, escaped(elt_orig));
6802 if (no) {
6803 isolation &= ~isoflag;
6804 } else {
6805 isolation |= isoflag;
6807 } SMARTLIST_FOREACH_END(elt);
6810 if (port)
6811 got_nonzero_port = 1;
6812 else
6813 got_zero_port = 1;
6815 if (dns_request == 0 && listener_type == CONN_TYPE_AP_DNS_LISTENER) {
6816 log_warn(LD_CONFIG, "You have a %sPort entry with DNS disabled; that "
6817 "won't work.", portname);
6818 goto err;
6821 if (ipv4_traffic == 0 && ipv6_traffic == 0 && onion_traffic == 0
6822 && listener_type != CONN_TYPE_AP_DNS_LISTENER) {
6823 log_warn(LD_CONFIG, "You have a %sPort entry with all of IPv4 and "
6824 "IPv6 and .onion disabled; that won't work.", portname);
6825 goto err;
6828 if (dns_request == 1 && ipv4_traffic == 0 && ipv6_traffic == 0
6829 && listener_type != CONN_TYPE_AP_DNS_LISTENER) {
6830 log_warn(LD_CONFIG, "You have a %sPort entry with DNSRequest enabled, "
6831 "but IPv4 and IPv6 disabled; DNS-based sites won't work.",
6832 portname);
6833 goto err;
6836 if ( has_used_unix_socket_only_option && ! unix_socket_path) {
6837 log_warn(LD_CONFIG, "You have a %sPort entry with GroupWritable, "
6838 "WorldWritable, or RelaxDirModeCheck, but it is not a "
6839 "unix socket.", portname);
6840 goto err;
6843 if (!(isolation & ISO_SOCKSAUTH) && socks_iso_keep_alive) {
6844 log_warn(LD_CONFIG, "You have a %sPort entry with both "
6845 "NoIsolateSOCKSAuth and KeepAliveIsolateSOCKSAuth set.",
6846 portname);
6847 goto err;
6850 if (unix_socket_path && (isolation & ISO_CLIENTADDR)) {
6851 /* `IsolateClientAddr` is nonsensical in the context of AF_LOCAL.
6852 * just silently remove the isolation flag.
6854 isolation &= ~ISO_CLIENTADDR;
6857 if (out && port) {
6858 size_t namelen = unix_socket_path ? strlen(unix_socket_path) : 0;
6859 port_cfg_t *cfg = port_cfg_new(namelen);
6860 if (unix_socket_path) {
6861 tor_addr_make_unspec(&cfg->addr);
6862 memcpy(cfg->unix_addr, unix_socket_path, namelen + 1);
6863 cfg->is_unix_addr = 1;
6864 tor_free(unix_socket_path);
6865 } else {
6866 tor_addr_copy(&cfg->addr, &addr);
6867 cfg->port = port;
6869 cfg->type = listener_type;
6870 cfg->is_world_writable = world_writable;
6871 cfg->is_group_writable = group_writable;
6872 cfg->relax_dirmode_check = relax_dirmode_check;
6873 cfg->entry_cfg.isolation_flags = isolation;
6874 cfg->entry_cfg.session_group = sessiongroup;
6875 cfg->server_cfg.no_advertise = no_advertise;
6876 cfg->server_cfg.no_listen = no_listen;
6877 cfg->server_cfg.all_addrs = all_addrs;
6878 cfg->server_cfg.bind_ipv4_only = bind_ipv4_only;
6879 cfg->server_cfg.bind_ipv6_only = bind_ipv6_only;
6880 cfg->entry_cfg.ipv4_traffic = ipv4_traffic;
6881 cfg->entry_cfg.ipv6_traffic = ipv6_traffic;
6882 cfg->entry_cfg.prefer_ipv6 = prefer_ipv6;
6883 cfg->entry_cfg.dns_request = dns_request;
6884 cfg->entry_cfg.onion_traffic = onion_traffic;
6885 cfg->entry_cfg.cache_ipv4_answers = cache_ipv4;
6886 cfg->entry_cfg.cache_ipv6_answers = cache_ipv6;
6887 cfg->entry_cfg.use_cached_ipv4_answers = use_cached_ipv4;
6888 cfg->entry_cfg.use_cached_ipv6_answers = use_cached_ipv6;
6889 cfg->entry_cfg.prefer_ipv6_virtaddr = prefer_ipv6_automap;
6890 cfg->entry_cfg.socks_prefer_no_auth = prefer_no_auth;
6891 if (! (isolation & ISO_SOCKSAUTH))
6892 cfg->entry_cfg.socks_prefer_no_auth = 1;
6893 cfg->entry_cfg.socks_iso_keep_alive = socks_iso_keep_alive;
6895 smartlist_add(out, cfg);
6897 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
6898 smartlist_clear(elts);
6899 tor_free(addrport);
6900 tor_free(unix_socket_path);
6903 if (warn_nonlocal && out) {
6904 if (is_control)
6905 warn_nonlocal_controller_ports(out, forbid_nonlocal);
6906 else if (is_ext_orport)
6907 warn_nonlocal_ext_orports(out, portname);
6908 else
6909 warn_nonlocal_client_ports(out, portname, listener_type);
6912 if (got_zero_port && got_nonzero_port) {
6913 log_warn(LD_CONFIG, "You specified a nonzero %sPort along with '%sPort 0' "
6914 "in the same configuration. Did you mean to disable %sPort or "
6915 "not?", portname, portname, portname);
6916 goto err;
6919 retval = 0;
6920 err:
6921 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
6922 smartlist_free(elts);
6923 tor_free(unix_socket_path);
6924 tor_free(addrport);
6925 return retval;
6928 /** Return the number of ports which are actually going to listen with type
6929 * <b>listenertype</b>. Do not count no_listen ports. Only count unix
6930 * sockets if count_sockets is true. */
6931 static int
6932 count_real_listeners(const smartlist_t *ports, int listenertype,
6933 int count_sockets)
6935 int n = 0;
6936 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
6937 if (port->server_cfg.no_listen)
6938 continue;
6939 if (!count_sockets && port->is_unix_addr)
6940 continue;
6941 if (port->type != listenertype)
6942 continue;
6943 ++n;
6944 } SMARTLIST_FOREACH_END(port);
6945 return n;
6948 /** Parse all ports from <b>options</b>. On success, set *<b>n_ports_out</b>
6949 * to the number of ports that are listed, update the *Port_set values in
6950 * <b>options</b>, and return 0. On failure, set *<b>msg</b> to a
6951 * description of the problem and return -1.
6953 * If <b>validate_only</b> is false, set configured_client_ports to the
6954 * new list of ports parsed from <b>options</b>.
6956 static int
6957 parse_ports(or_options_t *options, int validate_only,
6958 char **msg, int *n_ports_out,
6959 int *world_writable_control_socket)
6961 smartlist_t *ports;
6962 int retval = -1;
6964 ports = smartlist_new();
6966 *n_ports_out = 0;
6968 const unsigned gw_flag = options->SocksSocketsGroupWritable ?
6969 CL_PORT_DFLT_GROUP_WRITABLE : 0;
6970 if (parse_port_config(ports,
6971 options->SocksPort_lines,
6972 "Socks", CONN_TYPE_AP_LISTENER,
6973 "127.0.0.1", 9050,
6974 ((validate_only ? 0 : CL_PORT_WARN_NONLOCAL)
6975 | CL_PORT_TAKES_HOSTNAMES | gw_flag)) < 0) {
6976 *msg = tor_strdup("Invalid SocksPort configuration");
6977 goto err;
6979 if (parse_port_config(ports,
6980 options->DNSPort_lines,
6981 "DNS", CONN_TYPE_AP_DNS_LISTENER,
6982 "127.0.0.1", 0,
6983 CL_PORT_WARN_NONLOCAL|CL_PORT_TAKES_HOSTNAMES) < 0) {
6984 *msg = tor_strdup("Invalid DNSPort configuration");
6985 goto err;
6987 if (parse_port_config(ports,
6988 options->TransPort_lines,
6989 "Trans", CONN_TYPE_AP_TRANS_LISTENER,
6990 "127.0.0.1", 0,
6991 CL_PORT_WARN_NONLOCAL) < 0) {
6992 *msg = tor_strdup("Invalid TransPort configuration");
6993 goto err;
6995 if (parse_port_config(ports,
6996 options->NATDPort_lines,
6997 "NATD", CONN_TYPE_AP_NATD_LISTENER,
6998 "127.0.0.1", 0,
6999 CL_PORT_WARN_NONLOCAL) < 0) {
7000 *msg = tor_strdup("Invalid NatdPort configuration");
7001 goto err;
7004 unsigned control_port_flags = CL_PORT_NO_STREAM_OPTIONS |
7005 CL_PORT_WARN_NONLOCAL;
7006 const int any_passwords = (options->HashedControlPassword ||
7007 options->HashedControlSessionPassword ||
7008 options->CookieAuthentication);
7009 if (! any_passwords)
7010 control_port_flags |= CL_PORT_FORBID_NONLOCAL;
7011 if (options->ControlSocketsGroupWritable)
7012 control_port_flags |= CL_PORT_DFLT_GROUP_WRITABLE;
7014 if (parse_port_config(ports,
7015 options->ControlPort_lines,
7016 "Control", CONN_TYPE_CONTROL_LISTENER,
7017 "127.0.0.1", 0,
7018 control_port_flags) < 0) {
7019 *msg = tor_strdup("Invalid ControlPort configuration");
7020 goto err;
7023 if (parse_port_config(ports, options->ControlSocket,
7024 "ControlSocket",
7025 CONN_TYPE_CONTROL_LISTENER, NULL, 0,
7026 control_port_flags | CL_PORT_IS_UNIXSOCKET) < 0) {
7027 *msg = tor_strdup("Invalid ControlSocket configuration");
7028 goto err;
7031 if (! options->ClientOnly) {
7032 if (parse_port_config(ports,
7033 options->ORPort_lines,
7034 "OR", CONN_TYPE_OR_LISTENER,
7035 "0.0.0.0", 0,
7036 CL_PORT_SERVER_OPTIONS) < 0) {
7037 *msg = tor_strdup("Invalid ORPort configuration");
7038 goto err;
7040 if (parse_port_config(ports,
7041 options->ExtORPort_lines,
7042 "ExtOR", CONN_TYPE_EXT_OR_LISTENER,
7043 "127.0.0.1", 0,
7044 CL_PORT_SERVER_OPTIONS|CL_PORT_WARN_NONLOCAL) < 0) {
7045 *msg = tor_strdup("Invalid ExtORPort configuration");
7046 goto err;
7048 if (parse_port_config(ports,
7049 options->DirPort_lines,
7050 "Dir", CONN_TYPE_DIR_LISTENER,
7051 "0.0.0.0", 0,
7052 CL_PORT_SERVER_OPTIONS) < 0) {
7053 *msg = tor_strdup("Invalid DirPort configuration");
7054 goto err;
7058 int n_low_ports = 0;
7059 if (check_server_ports(ports, options, &n_low_ports) < 0) {
7060 *msg = tor_strdup("Misconfigured server ports");
7061 goto err;
7063 if (have_low_ports < 0)
7064 have_low_ports = (n_low_ports > 0);
7066 *n_ports_out = smartlist_len(ports);
7068 retval = 0;
7070 /* Update the *Port_set options. The !! here is to force a boolean out of
7071 an integer. */
7072 options->ORPort_set =
7073 !! count_real_listeners(ports, CONN_TYPE_OR_LISTENER, 0);
7074 options->SocksPort_set =
7075 !! count_real_listeners(ports, CONN_TYPE_AP_LISTENER, 1);
7076 options->TransPort_set =
7077 !! count_real_listeners(ports, CONN_TYPE_AP_TRANS_LISTENER, 1);
7078 options->NATDPort_set =
7079 !! count_real_listeners(ports, CONN_TYPE_AP_NATD_LISTENER, 1);
7080 /* Use options->ControlSocket to test if a control socket is set */
7081 options->ControlPort_set =
7082 !! count_real_listeners(ports, CONN_TYPE_CONTROL_LISTENER, 0);
7083 options->DirPort_set =
7084 !! count_real_listeners(ports, CONN_TYPE_DIR_LISTENER, 0);
7085 options->DNSPort_set =
7086 !! count_real_listeners(ports, CONN_TYPE_AP_DNS_LISTENER, 1);
7087 options->ExtORPort_set =
7088 !! count_real_listeners(ports, CONN_TYPE_EXT_OR_LISTENER, 0);
7090 if (world_writable_control_socket) {
7091 SMARTLIST_FOREACH(ports, port_cfg_t *, p,
7092 if (p->type == CONN_TYPE_CONTROL_LISTENER &&
7093 p->is_unix_addr &&
7094 p->is_world_writable) {
7095 *world_writable_control_socket = 1;
7096 break;
7100 if (!validate_only) {
7101 if (configured_ports) {
7102 SMARTLIST_FOREACH(configured_ports,
7103 port_cfg_t *, p, port_cfg_free(p));
7104 smartlist_free(configured_ports);
7106 configured_ports = ports;
7107 ports = NULL; /* prevent free below. */
7110 err:
7111 if (ports) {
7112 SMARTLIST_FOREACH(ports, port_cfg_t *, p, port_cfg_free(p));
7113 smartlist_free(ports);
7115 return retval;
7118 /* Does port bind to IPv4? */
7119 static int
7120 port_binds_ipv4(const port_cfg_t *port)
7122 return tor_addr_family(&port->addr) == AF_INET ||
7123 (tor_addr_family(&port->addr) == AF_UNSPEC
7124 && !port->server_cfg.bind_ipv6_only);
7127 /* Does port bind to IPv6? */
7128 static int
7129 port_binds_ipv6(const port_cfg_t *port)
7131 return tor_addr_family(&port->addr) == AF_INET6 ||
7132 (tor_addr_family(&port->addr) == AF_UNSPEC
7133 && !port->server_cfg.bind_ipv4_only);
7136 /** Given a list of <b>port_cfg_t</b> in <b>ports</b>, check them for internal
7137 * consistency and warn as appropriate. Set *<b>n_low_ports_out</b> to the
7138 * number of sub-1024 ports we will be binding. */
7139 static int
7140 check_server_ports(const smartlist_t *ports,
7141 const or_options_t *options,
7142 int *n_low_ports_out)
7144 int n_orport_advertised = 0;
7145 int n_orport_advertised_ipv4 = 0;
7146 int n_orport_listeners = 0;
7147 int n_dirport_advertised = 0;
7148 int n_dirport_listeners = 0;
7149 int n_low_port = 0;
7150 int r = 0;
7152 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
7153 if (port->type == CONN_TYPE_DIR_LISTENER) {
7154 if (! port->server_cfg.no_advertise)
7155 ++n_dirport_advertised;
7156 if (! port->server_cfg.no_listen)
7157 ++n_dirport_listeners;
7158 } else if (port->type == CONN_TYPE_OR_LISTENER) {
7159 if (! port->server_cfg.no_advertise) {
7160 ++n_orport_advertised;
7161 if (port_binds_ipv4(port))
7162 ++n_orport_advertised_ipv4;
7164 if (! port->server_cfg.no_listen)
7165 ++n_orport_listeners;
7166 } else {
7167 continue;
7169 #ifndef _WIN32
7170 if (!port->server_cfg.no_listen && port->port < 1024)
7171 ++n_low_port;
7172 #endif
7173 } SMARTLIST_FOREACH_END(port);
7175 if (n_orport_advertised && !n_orport_listeners) {
7176 log_warn(LD_CONFIG, "We are advertising an ORPort, but not actually "
7177 "listening on one.");
7178 r = -1;
7180 if (n_orport_listeners && !n_orport_advertised) {
7181 log_warn(LD_CONFIG, "We are listening on an ORPort, but not advertising "
7182 "any ORPorts. This will keep us from building a %s "
7183 "descriptor, and make us impossible to use.",
7184 options->BridgeRelay ? "bridge" : "router");
7185 r = -1;
7187 if (n_dirport_advertised && !n_dirport_listeners) {
7188 log_warn(LD_CONFIG, "We are advertising a DirPort, but not actually "
7189 "listening on one.");
7190 r = -1;
7192 if (n_dirport_advertised > 1) {
7193 log_warn(LD_CONFIG, "Can't advertise more than one DirPort.");
7194 r = -1;
7196 if (n_orport_advertised && !n_orport_advertised_ipv4 &&
7197 !options->BridgeRelay) {
7198 log_warn(LD_CONFIG, "Configured non-bridge only to listen on an IPv6 "
7199 "address.");
7200 r = -1;
7203 if (n_low_port && options->AccountingMax &&
7204 (!have_capability_support() || options->KeepBindCapabilities == 0)) {
7205 const char *extra = "";
7206 if (options->KeepBindCapabilities == 0 && have_capability_support())
7207 extra = ", and you have disabled KeepBindCapabilities.";
7208 log_warn(LD_CONFIG,
7209 "You have set AccountingMax to use hibernation. You have also "
7210 "chosen a low DirPort or OrPort%s."
7211 "This combination can make Tor stop "
7212 "working when it tries to re-attach the port after a period of "
7213 "hibernation. Please choose a different port or turn off "
7214 "hibernation unless you know this combination will work on your "
7215 "platform.", extra);
7218 if (n_low_ports_out)
7219 *n_low_ports_out = n_low_port;
7221 return r;
7224 /** Return a list of port_cfg_t for client ports parsed from the
7225 * options. */
7226 MOCK_IMPL(const smartlist_t *,
7227 get_configured_ports,(void))
7229 if (!configured_ports)
7230 configured_ports = smartlist_new();
7231 return configured_ports;
7234 /** Return an address:port string representation of the address
7235 * where the first <b>listener_type</b> listener waits for
7236 * connections. Return NULL if we couldn't find a listener. The
7237 * string is allocated on the heap and it's the responsibility of the
7238 * caller to free it after use.
7240 * This function is meant to be used by the pluggable transport proxy
7241 * spawning code, please make sure that it fits your purposes before
7242 * using it. */
7243 char *
7244 get_first_listener_addrport_string(int listener_type)
7246 static const char *ipv4_localhost = "127.0.0.1";
7247 static const char *ipv6_localhost = "[::1]";
7248 const char *address;
7249 uint16_t port;
7250 char *string = NULL;
7252 if (!configured_ports)
7253 return NULL;
7255 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
7256 if (cfg->server_cfg.no_listen)
7257 continue;
7259 if (cfg->type == listener_type &&
7260 tor_addr_family(&cfg->addr) != AF_UNSPEC) {
7262 /* We found the first listener of the type we are interested in! */
7264 /* If a listener is listening on INADDR_ANY, assume that it's
7265 also listening on 127.0.0.1, and point the transport proxy
7266 there: */
7267 if (tor_addr_is_null(&cfg->addr))
7268 address = tor_addr_is_v4(&cfg->addr) ? ipv4_localhost : ipv6_localhost;
7269 else
7270 address = fmt_and_decorate_addr(&cfg->addr);
7272 /* If a listener is configured with port 'auto', we are forced
7273 to iterate all listener connections and find out in which
7274 port it ended up listening: */
7275 if (cfg->port == CFG_AUTO_PORT) {
7276 port = router_get_active_listener_port_by_type_af(listener_type,
7277 tor_addr_family(&cfg->addr));
7278 if (!port)
7279 return NULL;
7280 } else {
7281 port = cfg->port;
7284 tor_asprintf(&string, "%s:%u", address, port);
7286 return string;
7289 } SMARTLIST_FOREACH_END(cfg);
7291 return NULL;
7294 /** Return the first advertised port of type <b>listener_type</b> in
7295 * <b>address_family</b>. Returns 0 when no port is found, and when passed
7296 * AF_UNSPEC. */
7298 get_first_advertised_port_by_type_af(int listener_type, int address_family)
7300 if (address_family == AF_UNSPEC)
7301 return 0;
7303 const smartlist_t *conf_ports = get_configured_ports();
7304 SMARTLIST_FOREACH_BEGIN(conf_ports, const port_cfg_t *, cfg) {
7305 if (cfg->type == listener_type &&
7306 !cfg->server_cfg.no_advertise) {
7307 if ((address_family == AF_INET && port_binds_ipv4(cfg)) ||
7308 (address_family == AF_INET6 && port_binds_ipv6(cfg))) {
7309 return cfg->port;
7312 } SMARTLIST_FOREACH_END(cfg);
7313 return 0;
7316 /** Return the first advertised address of type <b>listener_type</b> in
7317 * <b>address_family</b>. Returns NULL if there is no advertised address,
7318 * and when passed AF_UNSPEC. */
7319 const tor_addr_t *
7320 get_first_advertised_addr_by_type_af(int listener_type, int address_family)
7322 if (address_family == AF_UNSPEC)
7323 return NULL;
7324 if (!configured_ports)
7325 return NULL;
7326 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
7327 if (cfg->type == listener_type &&
7328 !cfg->server_cfg.no_advertise) {
7329 if ((address_family == AF_INET && port_binds_ipv4(cfg)) ||
7330 (address_family == AF_INET6 && port_binds_ipv6(cfg))) {
7331 return &cfg->addr;
7334 } SMARTLIST_FOREACH_END(cfg);
7335 return NULL;
7338 /** Return 1 if a port exists of type <b>listener_type</b> on <b>addr</b> and
7339 * <b>port</b>. If <b>check_wildcard</b> is true, INADDR[6]_ANY and AF_UNSPEC
7340 * addresses match any address of the appropriate family; and port -1 matches
7341 * any port.
7342 * To match auto ports, pass CFG_PORT_AUTO. (Does not match on the actual
7343 * automatically chosen listener ports.) */
7345 port_exists_by_type_addr_port(int listener_type, const tor_addr_t *addr,
7346 int port, int check_wildcard)
7348 if (!configured_ports || !addr)
7349 return 0;
7350 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
7351 if (cfg->type == listener_type) {
7352 if (cfg->port == port || (check_wildcard && port == -1)) {
7353 /* Exact match */
7354 if (tor_addr_eq(&cfg->addr, addr)) {
7355 return 1;
7357 /* Skip wildcard matches if we're not doing them */
7358 if (!check_wildcard) {
7359 continue;
7361 /* Wildcard matches IPv4 */
7362 const int cfg_v4 = port_binds_ipv4(cfg);
7363 const int cfg_any_v4 = tor_addr_is_null(&cfg->addr) && cfg_v4;
7364 const int addr_v4 = tor_addr_family(addr) == AF_INET ||
7365 tor_addr_family(addr) == AF_UNSPEC;
7366 const int addr_any_v4 = tor_addr_is_null(&cfg->addr) && addr_v4;
7367 if ((cfg_any_v4 && addr_v4) || (cfg_v4 && addr_any_v4)) {
7368 return 1;
7370 /* Wildcard matches IPv6 */
7371 const int cfg_v6 = port_binds_ipv6(cfg);
7372 const int cfg_any_v6 = tor_addr_is_null(&cfg->addr) && cfg_v6;
7373 const int addr_v6 = tor_addr_family(addr) == AF_INET6 ||
7374 tor_addr_family(addr) == AF_UNSPEC;
7375 const int addr_any_v6 = tor_addr_is_null(&cfg->addr) && addr_v6;
7376 if ((cfg_any_v6 && addr_v6) || (cfg_v6 && addr_any_v6)) {
7377 return 1;
7381 } SMARTLIST_FOREACH_END(cfg);
7382 return 0;
7385 /* Like port_exists_by_type_addr_port, but accepts a host-order IPv4 address
7386 * instead. */
7388 port_exists_by_type_addr32h_port(int listener_type, uint32_t addr_ipv4h,
7389 int port, int check_wildcard)
7391 tor_addr_t ipv4;
7392 tor_addr_from_ipv4h(&ipv4, addr_ipv4h);
7393 return port_exists_by_type_addr_port(listener_type, &ipv4, port,
7394 check_wildcard);
7397 /** Adjust the value of options->DataDirectory, or fill it in if it's
7398 * absent. Return 0 on success, -1 on failure. */
7399 static int
7400 normalize_data_directory(or_options_t *options)
7402 #ifdef _WIN32
7403 char *p;
7404 if (options->DataDirectory)
7405 return 0; /* all set */
7406 p = tor_malloc(MAX_PATH);
7407 strlcpy(p,get_windows_conf_root(),MAX_PATH);
7408 options->DataDirectory = p;
7409 return 0;
7410 #else
7411 const char *d = options->DataDirectory;
7412 if (!d)
7413 d = "~/.tor";
7415 if (strncmp(d,"~/",2) == 0) {
7416 char *fn = expand_filename(d);
7417 if (!fn) {
7418 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
7419 return -1;
7421 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
7422 /* If our homedir is /, we probably don't want to use it. */
7423 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
7424 * want. */
7425 log_warn(LD_CONFIG,
7426 "Default DataDirectory is \"~/.tor\". This expands to "
7427 "\"%s\", which is probably not what you want. Using "
7428 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
7429 tor_free(fn);
7430 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
7432 tor_free(options->DataDirectory);
7433 options->DataDirectory = fn;
7435 return 0;
7436 #endif
7439 /** Check and normalize the value of options->DataDirectory; return 0 if it
7440 * is sane, -1 otherwise. */
7441 static int
7442 validate_data_directory(or_options_t *options)
7444 if (normalize_data_directory(options) < 0)
7445 return -1;
7446 tor_assert(options->DataDirectory);
7447 if (strlen(options->DataDirectory) > (512-128)) {
7448 log_warn(LD_CONFIG, "DataDirectory is too long.");
7449 return -1;
7451 return 0;
7454 /** This string must remain the same forevermore. It is how we
7455 * recognize that the torrc file doesn't need to be backed up. */
7456 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
7457 "if you edit it, comments will not be preserved"
7458 /** This string can change; it tries to give the reader an idea
7459 * that editing this file by hand is not a good plan. */
7460 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
7461 "to torrc.orig.1 or similar, and Tor will ignore it"
7463 /** Save a configuration file for the configuration in <b>options</b>
7464 * into the file <b>fname</b>. If the file already exists, and
7465 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
7466 * replace it. Return 0 on success, -1 on failure. */
7467 static int
7468 write_configuration_file(const char *fname, const or_options_t *options)
7470 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
7471 int rename_old = 0, r;
7473 if (!fname)
7474 return -1;
7476 switch (file_status(fname)) {
7477 /* create backups of old config files, even if they're empty */
7478 case FN_FILE:
7479 case FN_EMPTY:
7480 old_val = read_file_to_str(fname, 0, NULL);
7481 if (!old_val || strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
7482 rename_old = 1;
7484 tor_free(old_val);
7485 break;
7486 case FN_NOENT:
7487 break;
7488 case FN_ERROR:
7489 case FN_DIR:
7490 default:
7491 log_warn(LD_CONFIG,
7492 "Config file \"%s\" is not a file? Failing.", fname);
7493 return -1;
7496 if (!(new_conf = options_dump(options, OPTIONS_DUMP_MINIMAL))) {
7497 log_warn(LD_BUG, "Couldn't get configuration string");
7498 goto err;
7501 tor_asprintf(&new_val, "%s\n%s\n\n%s",
7502 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
7504 if (rename_old) {
7505 int i = 1;
7506 char *fn_tmp = NULL;
7507 while (1) {
7508 tor_asprintf(&fn_tmp, "%s.orig.%d", fname, i);
7509 if (file_status(fn_tmp) == FN_NOENT)
7510 break;
7511 tor_free(fn_tmp);
7512 ++i;
7514 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
7515 if (tor_rename(fname, fn_tmp) < 0) {//XXXX sandbox doesn't allow
7516 log_warn(LD_FS,
7517 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
7518 fname, fn_tmp, strerror(errno));
7519 tor_free(fn_tmp);
7520 goto err;
7522 tor_free(fn_tmp);
7525 if (write_str_to_file(fname, new_val, 0) < 0)
7526 goto err;
7528 r = 0;
7529 goto done;
7530 err:
7531 r = -1;
7532 done:
7533 tor_free(new_val);
7534 tor_free(new_conf);
7535 return r;
7539 * Save the current configuration file value to disk. Return 0 on
7540 * success, -1 on failure.
7543 options_save_current(void)
7545 /* This fails if we can't write to our configuration file.
7547 * If we try falling back to datadirectory or something, we have a better
7548 * chance of saving the configuration, but a better chance of doing
7549 * something the user never expected. */
7550 return write_configuration_file(get_torrc_fname(0), get_options());
7553 /** Return the number of cpus configured in <b>options</b>. If we are
7554 * told to auto-detect the number of cpus, return the auto-detected number. */
7556 get_num_cpus(const or_options_t *options)
7558 if (options->NumCPUs == 0) {
7559 int n = compute_num_cpus();
7560 return (n >= 1) ? n : 1;
7561 } else {
7562 return options->NumCPUs;
7567 * Initialize the libevent library.
7569 static void
7570 init_libevent(const or_options_t *options)
7572 tor_libevent_cfg cfg;
7574 tor_assert(options);
7576 configure_libevent_logging();
7577 /* If the kernel complains that some method (say, epoll) doesn't
7578 * exist, we don't care about it, since libevent will cope.
7580 suppress_libevent_log_msg("Function not implemented");
7582 memset(&cfg, 0, sizeof(cfg));
7583 cfg.num_cpus = get_num_cpus(options);
7584 cfg.msec_per_tick = options->TokenBucketRefillInterval;
7586 tor_libevent_initialize(&cfg);
7588 suppress_libevent_log_msg(NULL);
7591 /** Return a newly allocated string holding a filename relative to the data
7592 * directory. If <b>sub1</b> is present, it is the first path component after
7593 * the data directory. If <b>sub2</b> is also present, it is the second path
7594 * component after the data directory. If <b>suffix</b> is present, it
7595 * is appended to the filename.
7597 * Examples:
7598 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
7599 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
7600 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
7601 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
7603 * Note: Consider using the get_datadir_fname* macros in or.h.
7605 MOCK_IMPL(char *,
7606 options_get_datadir_fname2_suffix,(const or_options_t *options,
7607 const char *sub1, const char *sub2,
7608 const char *suffix))
7610 char *fname = NULL;
7611 size_t len;
7612 tor_assert(options);
7613 tor_assert(options->DataDirectory);
7614 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
7615 len = strlen(options->DataDirectory);
7616 if (sub1) {
7617 len += strlen(sub1)+1;
7618 if (sub2)
7619 len += strlen(sub2)+1;
7621 if (suffix)
7622 len += strlen(suffix);
7623 len++;
7624 fname = tor_malloc(len);
7625 if (sub1) {
7626 if (sub2) {
7627 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
7628 options->DataDirectory, sub1, sub2);
7629 } else {
7630 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
7631 options->DataDirectory, sub1);
7633 } else {
7634 strlcpy(fname, options->DataDirectory, len);
7636 if (suffix)
7637 strlcat(fname, suffix, len);
7638 return fname;
7641 /** Check wether the data directory has a private subdirectory
7642 * <b>subdir</b>. If not, try to create it. Return 0 on success,
7643 * -1 otherwise. */
7645 check_or_create_data_subdir(const char *subdir)
7647 char *statsdir = get_datadir_fname(subdir);
7648 int return_val = 0;
7650 if (check_private_dir(statsdir, CPD_CREATE, get_options()->User) < 0) {
7651 log_warn(LD_HIST, "Unable to create %s/ directory!", subdir);
7652 return_val = -1;
7654 tor_free(statsdir);
7655 return return_val;
7658 /** Create a file named <b>fname</b> with contents <b>str</b> in the
7659 * subdirectory <b>subdir</b> of the data directory. <b>descr</b>
7660 * should be a short description of the file's content and will be
7661 * used for the warning message, if it's present and the write process
7662 * fails. Return 0 on success, -1 otherwise.*/
7664 write_to_data_subdir(const char* subdir, const char* fname,
7665 const char* str, const char* descr)
7667 char *filename = get_datadir_fname2(subdir, fname);
7668 int return_val = 0;
7670 if (write_str_to_file(filename, str, 0) < 0) {
7671 log_warn(LD_HIST, "Unable to write %s to disk!", descr ? descr : fname);
7672 return_val = -1;
7674 tor_free(filename);
7675 return return_val;
7678 /** Given a file name check to see whether the file exists but has not been
7679 * modified for a very long time. If so, remove it. */
7680 void
7681 remove_file_if_very_old(const char *fname, time_t now)
7683 #define VERY_OLD_FILE_AGE (28*24*60*60)
7684 struct stat st;
7686 log_debug(LD_FS, "stat()ing %s", fname);
7687 if (stat(sandbox_intern_string(fname), &st)==0 &&
7688 st.st_mtime < now-VERY_OLD_FILE_AGE) {
7689 char buf[ISO_TIME_LEN+1];
7690 format_local_iso_time(buf, st.st_mtime);
7691 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
7692 "Removing it.", fname, buf);
7693 if (unlink(fname) != 0) {
7694 log_warn(LD_FS, "Failed to unlink %s: %s",
7695 fname, strerror(errno));
7700 /** Return a smartlist of ports that must be forwarded by
7701 * tor-fw-helper. The smartlist contains the ports in a string format
7702 * that is understandable by tor-fw-helper. */
7703 smartlist_t *
7704 get_list_of_ports_to_forward(void)
7706 smartlist_t *ports_to_forward = smartlist_new();
7707 int port = 0;
7709 /** XXX TODO tor-fw-helper does not support forwarding ports to
7710 other hosts than the local one. If the user is binding to a
7711 different IP address, tor-fw-helper won't work. */
7712 port = router_get_advertised_or_port(get_options()); /* Get ORPort */
7713 if (port)
7714 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
7716 port = router_get_advertised_dir_port(get_options(), 0); /* Get DirPort */
7717 if (port)
7718 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
7720 /* Get ports of transport proxies */
7722 smartlist_t *transport_ports = get_transport_proxy_ports();
7723 if (transport_ports) {
7724 smartlist_add_all(ports_to_forward, transport_ports);
7725 smartlist_free(transport_ports);
7729 if (!smartlist_len(ports_to_forward)) {
7730 smartlist_free(ports_to_forward);
7731 ports_to_forward = NULL;
7734 return ports_to_forward;
7737 /** Helper to implement GETINFO functions about configuration variables (not
7738 * their values). Given a "config/names" question, set *<b>answer</b> to a
7739 * new string describing the supported configuration variables and their
7740 * types. */
7742 getinfo_helper_config(control_connection_t *conn,
7743 const char *question, char **answer,
7744 const char **errmsg)
7746 (void) conn;
7747 (void) errmsg;
7748 if (!strcmp(question, "config/names")) {
7749 smartlist_t *sl = smartlist_new();
7750 int i;
7751 for (i = 0; option_vars_[i].name; ++i) {
7752 const config_var_t *var = &option_vars_[i];
7753 const char *type;
7754 /* don't tell controller about triple-underscore options */
7755 if (!strncmp(option_vars_[i].name, "___", 3))
7756 continue;
7757 switch (var->type) {
7758 case CONFIG_TYPE_STRING: type = "String"; break;
7759 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
7760 case CONFIG_TYPE_UINT: type = "Integer"; break;
7761 case CONFIG_TYPE_INT: type = "SignedInteger"; break;
7762 case CONFIG_TYPE_PORT: type = "Port"; break;
7763 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
7764 case CONFIG_TYPE_MSEC_INTERVAL: type = "TimeMsecInterval"; break;
7765 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
7766 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
7767 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
7768 case CONFIG_TYPE_AUTOBOOL: type = "Boolean+Auto"; break;
7769 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
7770 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
7771 case CONFIG_TYPE_CSV: type = "CommaList"; break;
7772 case CONFIG_TYPE_CSV_INTERVAL: type = "TimeIntervalCommaList"; break;
7773 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
7774 case CONFIG_TYPE_LINELIST_S: type = "Dependent"; break;
7775 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
7776 default:
7777 case CONFIG_TYPE_OBSOLETE:
7778 type = NULL; break;
7780 if (!type)
7781 continue;
7782 smartlist_add_asprintf(sl, "%s %s\n",var->name,type);
7784 *answer = smartlist_join_strings(sl, "", 0, NULL);
7785 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
7786 smartlist_free(sl);
7787 } else if (!strcmp(question, "config/defaults")) {
7788 smartlist_t *sl = smartlist_new();
7789 int dirauth_lines_seen = 0, fallback_lines_seen = 0;
7790 for (int i = 0; option_vars_[i].name; ++i) {
7791 const config_var_t *var = &option_vars_[i];
7792 if (var->initvalue != NULL) {
7793 if (strcmp(option_vars_[i].name, "DirAuthority") == 0) {
7795 * Count dirauth lines we have a default for; we'll use the
7796 * count later to decide whether to add the defaults manually
7798 ++dirauth_lines_seen;
7800 if (strcmp(option_vars_[i].name, "FallbackDir") == 0) {
7802 * Similarly count fallback lines, so that we can decided later
7803 * to add the defaults manually.
7805 ++fallback_lines_seen;
7807 char *val = esc_for_log(var->initvalue);
7808 smartlist_add_asprintf(sl, "%s %s\n",var->name,val);
7809 tor_free(val);
7813 if (dirauth_lines_seen == 0) {
7815 * We didn't see any directory authorities with default values,
7816 * so add the list of default authorities manually.
7820 * default_authorities is defined earlier in this file and
7821 * is a const char ** NULL-terminated array of dirauth config
7822 * lines.
7824 for (const char **i = default_authorities; *i != NULL; ++i) {
7825 char *val = esc_for_log(*i);
7826 smartlist_add_asprintf(sl, "DirAuthority %s\n", val);
7827 tor_free(val);
7831 if (fallback_lines_seen == 0 &&
7832 get_options()->UseDefaultFallbackDirs == 1) {
7834 * We didn't see any explicitly configured fallback mirrors,
7835 * so add the defaults to the list manually.
7837 * default_fallbacks is included earlier in this file and
7838 * is a const char ** NULL-terminated array of fallback config lines.
7840 const char **i;
7842 for (i = default_fallbacks; *i != NULL; ++i) {
7843 char *val = esc_for_log(*i);
7844 smartlist_add_asprintf(sl, "FallbackDir %s\n", val);
7845 tor_free(val);
7849 *answer = smartlist_join_strings(sl, "", 0, NULL);
7850 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
7851 smartlist_free(sl);
7853 return 0;
7856 /* Check whether an address has already been set against the options
7857 * depending on address family and destination type. Any exsting
7858 * value will lead to a fail, even if it is the same value. If not
7859 * set and not only validating, copy it into this location too.
7860 * Returns 0 on success or -1 if this address is already set.
7862 static int
7863 verify_and_store_outbound_address(sa_family_t family, tor_addr_t *addr,
7864 outbound_addr_t type, or_options_t *options, int validate_only)
7866 if (type>=OUTBOUND_ADDR_MAX || (family!=AF_INET && family!=AF_INET6)) {
7867 return -1;
7869 int fam_index=0;
7870 if (family==AF_INET6) {
7871 fam_index=1;
7873 tor_addr_t *dest=&options->OutboundBindAddresses[type][fam_index];
7874 if (!tor_addr_is_null(dest)) {
7875 return -1;
7877 if (!validate_only) {
7878 tor_addr_copy(dest, addr);
7880 return 0;
7883 /* Parse a list of address lines for a specific destination type.
7884 * Will store them into the options if not validate_only. If a
7885 * problem occurs, a suitable error message is store in msg.
7886 * Returns 0 on success or -1 if any address is already set.
7888 static int
7889 parse_outbound_address_lines(const config_line_t *lines, outbound_addr_t type,
7890 or_options_t *options, int validate_only, char **msg)
7892 tor_addr_t addr;
7893 sa_family_t family;
7894 while (lines) {
7895 family = tor_addr_parse(&addr, lines->value);
7896 if (verify_and_store_outbound_address(family, &addr, type,
7897 options, validate_only)) {
7898 if (msg)
7899 tor_asprintf(msg, "Multiple%s%s outbound bind addresses "
7900 "configured: %s",
7901 family==AF_INET?" IPv4":(family==AF_INET6?" IPv6":""),
7902 type==OUTBOUND_ADDR_OR?" OR":
7903 (type==OUTBOUND_ADDR_EXIT?" exit":""), lines->value);
7904 return -1;
7906 lines = lines->next;
7908 return 0;
7911 /** Parse outbound bind address option lines. If <b>validate_only</b>
7912 * is not 0 update OutboundBindAddresses in <b>options</b>.
7913 * Only one address can be set for any of these values.
7914 * On failure, set <b>msg</b> (if provided) to a newly allocated string
7915 * containing a description of the problem and return -1.
7917 static int
7918 parse_outbound_addresses(or_options_t *options, int validate_only, char **msg)
7920 if (!validate_only) {
7921 memset(&options->OutboundBindAddresses, 0,
7922 sizeof(options->OutboundBindAddresses));
7924 parse_outbound_address_lines(options->OutboundBindAddress,
7925 OUTBOUND_ADDR_EXIT_AND_OR, options, validate_only, msg);
7926 parse_outbound_address_lines(options->OutboundBindAddressOR,
7927 OUTBOUND_ADDR_OR, options, validate_only, msg);
7928 parse_outbound_address_lines(options->OutboundBindAddressExit,
7929 OUTBOUND_ADDR_EXIT, options, validate_only, msg);
7930 return 0;
7933 /** Load one of the geoip files, <a>family</a> determining which
7934 * one. <a>default_fname</a> is used if on Windows and
7935 * <a>fname</a> equals "<default>". */
7936 static void
7937 config_load_geoip_file_(sa_family_t family,
7938 const char *fname,
7939 const char *default_fname)
7941 #ifdef _WIN32
7942 char *free_fname = NULL; /* Used to hold any temporary-allocated value */
7943 /* XXXX Don't use this "<default>" junk; make our filename options
7944 * understand prefixes somehow. -NM */
7945 if (!strcmp(fname, "<default>")) {
7946 const char *conf_root = get_windows_conf_root();
7947 tor_asprintf(&free_fname, "%s\\%s", conf_root, default_fname);
7948 fname = free_fname;
7950 geoip_load_file(family, fname);
7951 tor_free(free_fname);
7952 #else
7953 (void)default_fname;
7954 geoip_load_file(family, fname);
7955 #endif
7958 /** Load geoip files for IPv4 and IPv6 if <a>options</a> and
7959 * <a>old_options</a> indicate we should. */
7960 static void
7961 config_maybe_load_geoip_files_(const or_options_t *options,
7962 const or_options_t *old_options)
7964 /* XXXX Reload GeoIPFile on SIGHUP. -NM */
7966 if (options->GeoIPFile &&
7967 ((!old_options || !opt_streq(old_options->GeoIPFile,
7968 options->GeoIPFile))
7969 || !geoip_is_loaded(AF_INET)))
7970 config_load_geoip_file_(AF_INET, options->GeoIPFile, "geoip");
7971 if (options->GeoIPv6File &&
7972 ((!old_options || !opt_streq(old_options->GeoIPv6File,
7973 options->GeoIPv6File))
7974 || !geoip_is_loaded(AF_INET6)))
7975 config_load_geoip_file_(AF_INET6, options->GeoIPv6File, "geoip6");
7978 /** Initialize cookie authentication (used so far by the ControlPort
7979 * and Extended ORPort).
7981 * Allocate memory and create a cookie (of length <b>cookie_len</b>)
7982 * in <b>cookie_out</b>.
7983 * Then write it down to <b>fname</b> and prepend it with <b>header</b>.
7985 * If <b>group_readable</b> is set, set <b>fname</b> to be readable
7986 * by the default GID.
7988 * If the whole procedure was successful, set
7989 * <b>cookie_is_set_out</b> to True. */
7991 init_cookie_authentication(const char *fname, const char *header,
7992 int cookie_len, int group_readable,
7993 uint8_t **cookie_out, int *cookie_is_set_out)
7995 char cookie_file_str_len = strlen(header) + cookie_len;
7996 char *cookie_file_str = tor_malloc(cookie_file_str_len);
7997 int retval = -1;
7999 /* We don't want to generate a new cookie every time we call
8000 * options_act(). One should be enough. */
8001 if (*cookie_is_set_out) {
8002 retval = 0; /* we are all set */
8003 goto done;
8006 /* If we've already set the cookie, free it before re-setting
8007 it. This can happen if we previously generated a cookie, but
8008 couldn't write it to a disk. */
8009 if (*cookie_out)
8010 tor_free(*cookie_out);
8012 /* Generate the cookie */
8013 *cookie_out = tor_malloc(cookie_len);
8014 crypto_rand((char *)*cookie_out, cookie_len);
8016 /* Create the string that should be written on the file. */
8017 memcpy(cookie_file_str, header, strlen(header));
8018 memcpy(cookie_file_str+strlen(header), *cookie_out, cookie_len);
8019 if (write_bytes_to_file(fname, cookie_file_str, cookie_file_str_len, 1)) {
8020 log_warn(LD_FS,"Error writing auth cookie to %s.", escaped(fname));
8021 goto done;
8024 #ifndef _WIN32
8025 if (group_readable) {
8026 if (chmod(fname, 0640)) {
8027 log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
8030 #else
8031 (void) group_readable;
8032 #endif
8034 /* Success! */
8035 log_info(LD_GENERAL, "Generated auth cookie file in '%s'.", escaped(fname));
8036 *cookie_is_set_out = 1;
8037 retval = 0;
8039 done:
8040 memwipe(cookie_file_str, 0, cookie_file_str_len);
8041 tor_free(cookie_file_str);
8042 return retval;