Partial revert of 2b48b5363f9aa5bd1 -- didn't mean to commit this
[tor/appveyor.git] / src / or / config.c
blobd8f71a0193527c9705b47132905e964766729c99
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 /* defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__) */
118 #include <systemd/sd-daemon.h>
119 #endif /* defined(HAVE_SYSTEMD) */
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 /** dummy instance of or_options_t, used for type-checking its
176 * members with CONF_CHECK_VAR_TYPE. */
177 DUMMY_TYPECHECK_INSTANCE(or_options_t);
179 /** An entry for config_vars: "The option <b>name</b> has type
180 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
181 * or_options_t.<b>member</b>"
183 #define VAR(name,conftype,member,initvalue) \
184 { name, CONFIG_TYPE_ ## conftype, offsetof(or_options_t, member), \
185 initvalue CONF_TEST_MEMBERS(or_options_t, conftype, member) }
186 /** As VAR, but the option name and member name are the same. */
187 #define V(member,conftype,initvalue) \
188 VAR(#member, conftype, member, initvalue)
189 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
190 #ifdef TOR_UNIT_TESTS
191 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL, {.INT=NULL} }
192 #else
193 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
194 #endif
197 * Macro to declare *Port options. Each one comes in three entries.
198 * For example, most users should use "SocksPort" to configure the
199 * socks port, but TorBrowser wants to use __SocksPort so that it
200 * isn't stored by SAVECONF. The SocksPortLines virtual option is
201 * used to query both options from the controller.
203 #define VPORT(member) \
204 VAR(#member "Lines", LINELIST_V, member ## _lines, NULL), \
205 VAR(#member, LINELIST_S, member ## _lines, NULL), \
206 VAR("__" #member, LINELIST_S, member ## _lines, NULL)
208 /** Array of configuration options. Until we disallow nonstandard
209 * abbreviations, order is significant, since the first matching option will
210 * be chosen first.
212 static config_var_t option_vars_[] = {
213 V(AccountingMax, MEMUNIT, "0 bytes"),
214 VAR("AccountingRule", STRING, AccountingRule_option, "max"),
215 V(AccountingStart, STRING, NULL),
216 V(Address, STRING, NULL),
217 OBSOLETE("AllowDotExit"),
218 OBSOLETE("AllowInvalidNodes"),
219 V(AllowNonRFC953Hostnames, BOOL, "0"),
220 OBSOLETE("AllowSingleHopCircuits"),
221 OBSOLETE("AllowSingleHopExits"),
222 V(AlternateBridgeAuthority, LINELIST, NULL),
223 V(AlternateDirAuthority, LINELIST, NULL),
224 OBSOLETE("AlternateHSAuthority"),
225 V(AssumeReachable, BOOL, "0"),
226 OBSOLETE("AuthDirBadDir"),
227 OBSOLETE("AuthDirBadDirCCs"),
228 V(AuthDirBadExit, LINELIST, NULL),
229 V(AuthDirBadExitCCs, CSV, ""),
230 V(AuthDirInvalid, LINELIST, NULL),
231 V(AuthDirInvalidCCs, CSV, ""),
232 V(AuthDirFastGuarantee, MEMUNIT, "100 KB"),
233 V(AuthDirGuardBWGuarantee, MEMUNIT, "2 MB"),
234 V(AuthDirPinKeys, BOOL, "1"),
235 V(AuthDirReject, LINELIST, NULL),
236 V(AuthDirRejectCCs, CSV, ""),
237 OBSOLETE("AuthDirRejectUnlisted"),
238 OBSOLETE("AuthDirListBadDirs"),
239 V(AuthDirListBadExits, BOOL, "0"),
240 V(AuthDirMaxServersPerAddr, UINT, "2"),
241 OBSOLETE("AuthDirMaxServersPerAuthAddr"),
242 V(AuthDirHasIPv6Connectivity, BOOL, "0"),
243 VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
244 V(AutomapHostsOnResolve, BOOL, "0"),
245 V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
246 V(AvoidDiskWrites, BOOL, "0"),
247 V(BandwidthBurst, MEMUNIT, "1 GB"),
248 V(BandwidthRate, MEMUNIT, "1 GB"),
249 V(BridgeAuthoritativeDir, BOOL, "0"),
250 VAR("Bridge", LINELIST, Bridges, NULL),
251 V(BridgePassword, STRING, NULL),
252 V(BridgeRecordUsageByCountry, BOOL, "1"),
253 V(BridgeRelay, BOOL, "0"),
254 V(BridgeDistribution, STRING, NULL),
255 V(CellStatistics, BOOL, "0"),
256 V(PaddingStatistics, BOOL, "1"),
257 V(LearnCircuitBuildTimeout, BOOL, "1"),
258 V(CircuitBuildTimeout, INTERVAL, "0"),
259 OBSOLETE("CircuitIdleTimeout"),
260 V(CircuitsAvailableTimeout, INTERVAL, "0"),
261 V(CircuitStreamTimeout, INTERVAL, "0"),
262 V(CircuitPriorityHalflife, DOUBLE, "-100.0"), /*negative:'Use default'*/
263 V(ClientDNSRejectInternalAddresses, BOOL,"1"),
264 V(ClientOnly, BOOL, "0"),
265 V(ClientPreferIPv6ORPort, AUTOBOOL, "auto"),
266 V(ClientPreferIPv6DirPort, AUTOBOOL, "auto"),
267 V(ClientRejectInternalAddresses, BOOL, "1"),
268 V(ClientTransportPlugin, LINELIST, NULL),
269 V(ClientUseIPv6, BOOL, "0"),
270 V(ClientUseIPv4, BOOL, "1"),
271 V(ConsensusParams, STRING, NULL),
272 V(ConnLimit, UINT, "1000"),
273 V(ConnDirectionStatistics, BOOL, "0"),
274 V(ConstrainedSockets, BOOL, "0"),
275 V(ConstrainedSockSize, MEMUNIT, "8192"),
276 V(ContactInfo, STRING, NULL),
277 OBSOLETE("ControlListenAddress"),
278 VPORT(ControlPort),
279 V(ControlPortFileGroupReadable,BOOL, "0"),
280 V(ControlPortWriteToFile, FILENAME, NULL),
281 V(ControlSocket, LINELIST, NULL),
282 V(ControlSocketsGroupWritable, BOOL, "0"),
283 V(SocksSocketsGroupWritable, BOOL, "0"),
284 V(CookieAuthentication, BOOL, "0"),
285 V(CookieAuthFileGroupReadable, BOOL, "0"),
286 V(CookieAuthFile, STRING, NULL),
287 V(CountPrivateBandwidth, BOOL, "0"),
288 V(DataDirectory, FILENAME, NULL),
289 V(DataDirectoryGroupReadable, BOOL, "0"),
290 V(DisableOOSCheck, BOOL, "1"),
291 V(DisableNetwork, BOOL, "0"),
292 V(DirAllowPrivateAddresses, BOOL, "0"),
293 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
294 OBSOLETE("DirListenAddress"),
295 V(DirPolicy, LINELIST, NULL),
296 VPORT(DirPort),
297 V(DirPortFrontPage, FILENAME, NULL),
298 VAR("DirReqStatistics", BOOL, DirReqStatistics_option, "1"),
299 VAR("DirAuthority", LINELIST, DirAuthorities, NULL),
300 V(DirCache, BOOL, "1"),
301 V(DirAuthorityFallbackRate, DOUBLE, "1.0"),
302 V(DisableAllSwap, BOOL, "0"),
303 V(DisableDebuggerAttachment, BOOL, "1"),
304 OBSOLETE("DisableIOCP"),
305 OBSOLETE("DisableV2DirectoryInfo_"),
306 OBSOLETE("DynamicDHGroups"),
307 VPORT(DNSPort),
308 OBSOLETE("DNSListenAddress"),
309 V(DownloadExtraInfo, BOOL, "0"),
310 V(TestingEnableConnBwEvent, BOOL, "0"),
311 V(TestingEnableCellStatsEvent, BOOL, "0"),
312 V(TestingEnableTbEmptyEvent, BOOL, "0"),
313 V(EnforceDistinctSubnets, BOOL, "1"),
314 V(EntryNodes, ROUTERSET, NULL),
315 V(EntryStatistics, BOOL, "0"),
316 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
317 V(ExcludeNodes, ROUTERSET, NULL),
318 V(ExcludeExitNodes, ROUTERSET, NULL),
319 OBSOLETE("ExcludeSingleHopRelays"),
320 V(ExitNodes, ROUTERSET, NULL),
321 V(ExitPolicy, LINELIST, NULL),
322 V(ExitPolicyRejectPrivate, BOOL, "1"),
323 V(ExitPolicyRejectLocalInterfaces, BOOL, "0"),
324 V(ExitPortStatistics, BOOL, "0"),
325 V(ExtendAllowPrivateAddresses, BOOL, "0"),
326 V(ExitRelay, AUTOBOOL, "auto"),
327 VPORT(ExtORPort),
328 V(ExtORPortCookieAuthFile, STRING, NULL),
329 V(ExtORPortCookieAuthFileGroupReadable, BOOL, "0"),
330 V(ExtraInfoStatistics, BOOL, "1"),
331 V(ExtendByEd25519ID, AUTOBOOL, "auto"),
332 V(FallbackDir, LINELIST, NULL),
334 V(UseDefaultFallbackDirs, BOOL, "1"),
336 OBSOLETE("FallbackNetworkstatusFile"),
337 V(FascistFirewall, BOOL, "0"),
338 V(FirewallPorts, CSV, ""),
339 OBSOLETE("FastFirstHopPK"),
340 V(FetchDirInfoEarly, BOOL, "0"),
341 V(FetchDirInfoExtraEarly, BOOL, "0"),
342 V(FetchServerDescriptors, BOOL, "1"),
343 V(FetchHidServDescriptors, BOOL, "1"),
344 V(FetchUselessDescriptors, BOOL, "0"),
345 OBSOLETE("FetchV2Networkstatus"),
346 V(GeoIPExcludeUnknown, AUTOBOOL, "auto"),
347 #ifdef _WIN32
348 V(GeoIPFile, FILENAME, "<default>"),
349 V(GeoIPv6File, FILENAME, "<default>"),
350 #else
351 V(GeoIPFile, FILENAME,
352 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
353 V(GeoIPv6File, FILENAME,
354 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip6"),
355 #endif /* defined(_WIN32) */
356 OBSOLETE("Group"),
357 V(GuardLifetime, INTERVAL, "0 minutes"),
358 V(HardwareAccel, BOOL, "0"),
359 V(HeartbeatPeriod, INTERVAL, "6 hours"),
360 V(AccelName, STRING, NULL),
361 V(AccelDir, FILENAME, NULL),
362 V(HashedControlPassword, LINELIST, NULL),
363 OBSOLETE("HidServDirectoryV2"),
364 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
365 VAR("HiddenServiceDirGroupReadable", LINELIST_S, RendConfigLines, NULL),
366 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
367 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
368 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
369 VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
370 VAR("HiddenServiceAllowUnknownPorts",LINELIST_S, RendConfigLines, NULL),
371 VAR("HiddenServiceMaxStreams",LINELIST_S, RendConfigLines, NULL),
372 VAR("HiddenServiceMaxStreamsCloseCircuit",LINELIST_S, RendConfigLines, NULL),
373 VAR("HiddenServiceNumIntroductionPoints", LINELIST_S, RendConfigLines, NULL),
374 VAR("HiddenServiceStatistics", BOOL, HiddenServiceStatistics_option, "1"),
375 V(HidServAuth, LINELIST, NULL),
376 OBSOLETE("CloseHSClientCircuitsImmediatelyOnTimeout"),
377 OBSOLETE("CloseHSServiceRendCircuitsImmediatelyOnTimeout"),
378 V(HiddenServiceSingleHopMode, BOOL, "0"),
379 V(HiddenServiceNonAnonymousMode,BOOL, "0"),
380 V(HTTPProxy, STRING, NULL),
381 V(HTTPProxyAuthenticator, STRING, NULL),
382 V(HTTPSProxy, STRING, NULL),
383 V(HTTPSProxyAuthenticator, STRING, NULL),
384 VPORT(HTTPTunnelPort),
385 V(IPv6Exit, BOOL, "0"),
386 VAR("ServerTransportPlugin", LINELIST, ServerTransportPlugin, NULL),
387 V(ServerTransportListenAddr, LINELIST, NULL),
388 V(ServerTransportOptions, LINELIST, NULL),
389 V(SigningKeyLifetime, INTERVAL, "30 days"),
390 V(Socks4Proxy, STRING, NULL),
391 V(Socks5Proxy, STRING, NULL),
392 V(Socks5ProxyUsername, STRING, NULL),
393 V(Socks5ProxyPassword, STRING, NULL),
394 V(KeepalivePeriod, INTERVAL, "5 minutes"),
395 V(KeepBindCapabilities, AUTOBOOL, "auto"),
396 VAR("Log", LINELIST, Logs, NULL),
397 V(LogMessageDomains, BOOL, "0"),
398 V(LogTimeGranularity, MSEC_INTERVAL, "1 second"),
399 V(TruncateLogFile, BOOL, "0"),
400 V(SyslogIdentityTag, STRING, NULL),
401 V(LongLivedPorts, CSV,
402 "21,22,706,1863,5050,5190,5222,5223,6523,6667,6697,8300"),
403 VAR("MapAddress", LINELIST, AddressMap, NULL),
404 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
405 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
406 V(MaxClientCircuitsPending, UINT, "32"),
407 V(MaxConsensusAgeForDiffs, INTERVAL, "0 seconds"),
408 VAR("MaxMemInQueues", MEMUNIT, MaxMemInQueues_raw, "0"),
409 OBSOLETE("MaxOnionsPending"),
410 V(MaxOnionQueueDelay, MSEC_INTERVAL, "1750 msec"),
411 V(MaxUnparseableDescSizeToLog, MEMUNIT, "10 MB"),
412 V(MinMeasuredBWsForAuthToIgnoreAdvertised, INT, "500"),
413 VAR("MyFamily", LINELIST, MyFamily_lines, NULL),
414 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
415 OBSOLETE("NamingAuthoritativeDirectory"),
416 OBSOLETE("NATDListenAddress"),
417 VPORT(NATDPort),
418 V(Nickname, STRING, NULL),
419 OBSOLETE("PredictedPortsRelevanceTime"),
420 OBSOLETE("WarnUnsafeSocks"),
421 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
422 V(NoExec, BOOL, "0"),
423 V(NumCPUs, UINT, "0"),
424 V(NumDirectoryGuards, UINT, "0"),
425 V(NumEntryGuards, UINT, "0"),
426 V(OfflineMasterKey, BOOL, "0"),
427 OBSOLETE("ORListenAddress"),
428 VPORT(ORPort),
429 V(OutboundBindAddress, LINELIST, NULL),
430 V(OutboundBindAddressOR, LINELIST, NULL),
431 V(OutboundBindAddressExit, LINELIST, NULL),
433 OBSOLETE("PathBiasDisableRate"),
434 V(PathBiasCircThreshold, INT, "-1"),
435 V(PathBiasNoticeRate, DOUBLE, "-1"),
436 V(PathBiasWarnRate, DOUBLE, "-1"),
437 V(PathBiasExtremeRate, DOUBLE, "-1"),
438 V(PathBiasScaleThreshold, INT, "-1"),
439 OBSOLETE("PathBiasScaleFactor"),
440 OBSOLETE("PathBiasMultFactor"),
441 V(PathBiasDropGuards, AUTOBOOL, "0"),
442 OBSOLETE("PathBiasUseCloseCounts"),
444 V(PathBiasUseThreshold, INT, "-1"),
445 V(PathBiasNoticeUseRate, DOUBLE, "-1"),
446 V(PathBiasExtremeUseRate, DOUBLE, "-1"),
447 V(PathBiasScaleUseThreshold, INT, "-1"),
449 V(PathsNeededToBuildCircuits, DOUBLE, "-1"),
450 V(PerConnBWBurst, MEMUNIT, "0"),
451 V(PerConnBWRate, MEMUNIT, "0"),
452 V(PidFile, STRING, NULL),
453 V(TestingTorNetwork, BOOL, "0"),
454 V(TestingMinExitFlagThreshold, MEMUNIT, "0"),
455 V(TestingMinFastFlagThreshold, MEMUNIT, "0"),
457 V(TestingLinkCertLifetime, INTERVAL, "2 days"),
458 V(TestingAuthKeyLifetime, INTERVAL, "2 days"),
459 V(TestingLinkKeySlop, INTERVAL, "3 hours"),
460 V(TestingAuthKeySlop, INTERVAL, "3 hours"),
461 V(TestingSigningKeySlop, INTERVAL, "1 day"),
463 V(OptimisticData, AUTOBOOL, "auto"),
464 V(PortForwarding, BOOL, "0"),
465 V(PortForwardingHelper, FILENAME, "tor-fw-helper"),
466 OBSOLETE("PreferTunneledDirConns"),
467 V(ProtocolWarnings, BOOL, "0"),
468 V(PublishServerDescriptor, CSV, "1"),
469 V(PublishHidServDescriptors, BOOL, "1"),
470 V(ReachableAddresses, LINELIST, NULL),
471 V(ReachableDirAddresses, LINELIST, NULL),
472 V(ReachableORAddresses, LINELIST, NULL),
473 V(RecommendedVersions, LINELIST, NULL),
474 V(RecommendedClientVersions, LINELIST, NULL),
475 V(RecommendedServerVersions, LINELIST, NULL),
476 V(RecommendedPackages, LINELIST, NULL),
477 V(ReducedConnectionPadding, BOOL, "0"),
478 V(ConnectionPadding, AUTOBOOL, "auto"),
479 V(RefuseUnknownExits, AUTOBOOL, "auto"),
480 V(RejectPlaintextPorts, CSV, ""),
481 V(RelayBandwidthBurst, MEMUNIT, "0"),
482 V(RelayBandwidthRate, MEMUNIT, "0"),
483 V(RendPostPeriod, INTERVAL, "1 hour"),
484 V(RephistTrackTime, INTERVAL, "24 hours"),
485 V(RunAsDaemon, BOOL, "0"),
486 OBSOLETE("RunTesting"), // currently unused
487 V(Sandbox, BOOL, "0"),
488 V(SafeLogging, STRING, "1"),
489 V(SafeSocks, BOOL, "0"),
490 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
491 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
492 V(ServerDNSDetectHijacking, BOOL, "1"),
493 V(ServerDNSRandomizeCase, BOOL, "1"),
494 V(ServerDNSResolvConfFile, STRING, NULL),
495 V(ServerDNSSearchDomains, BOOL, "0"),
496 V(ServerDNSTestAddresses, CSV,
497 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
498 OBSOLETE("SchedulerLowWaterMark__"),
499 OBSOLETE("SchedulerHighWaterMark__"),
500 OBSOLETE("SchedulerMaxFlushCells__"),
501 V(KISTSchedRunInterval, MSEC_INTERVAL, "0 msec"),
502 V(KISTSockBufSizeFactor, DOUBLE, "1.0"),
503 V(Schedulers, CSV, "KIST,KISTLite,Vanilla"),
504 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
505 OBSOLETE("SocksListenAddress"),
506 V(SocksPolicy, LINELIST, NULL),
507 VPORT(SocksPort),
508 V(SocksTimeout, INTERVAL, "2 minutes"),
509 V(SSLKeyLifetime, INTERVAL, "0"),
510 OBSOLETE("StrictEntryNodes"),
511 OBSOLETE("StrictExitNodes"),
512 V(StrictNodes, BOOL, "0"),
513 OBSOLETE("Support022HiddenServices"),
514 V(TestSocks, BOOL, "0"),
515 V(TokenBucketRefillInterval, MSEC_INTERVAL, "100 msec"),
516 V(Tor2webMode, BOOL, "0"),
517 V(Tor2webRendezvousPoints, ROUTERSET, NULL),
518 OBSOLETE("TLSECGroup"),
519 V(TrackHostExits, CSV, NULL),
520 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
521 OBSOLETE("TransListenAddress"),
522 VPORT(TransPort),
523 V(TransProxyType, STRING, "default"),
524 OBSOLETE("TunnelDirConns"),
525 V(UpdateBridgesFromAuthority, BOOL, "0"),
526 V(UseBridges, BOOL, "0"),
527 VAR("UseEntryGuards", BOOL, UseEntryGuards_option, "1"),
528 OBSOLETE("UseEntryGuardsAsDirGuards"),
529 V(UseGuardFraction, AUTOBOOL, "auto"),
530 V(UseMicrodescriptors, AUTOBOOL, "auto"),
531 OBSOLETE("UseNTorHandshake"),
532 V(User, STRING, NULL),
533 OBSOLETE("UserspaceIOCPBuffers"),
534 V(AuthDirSharedRandomness, BOOL, "1"),
535 V(AuthDirTestEd25519LinkKeys, BOOL, "1"),
536 OBSOLETE("V1AuthoritativeDirectory"),
537 OBSOLETE("V2AuthoritativeDirectory"),
538 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
539 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
540 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
541 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
542 V(TestingV3AuthVotingStartOffset, INTERVAL, "0"),
543 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
544 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
545 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
546 V(V3AuthNIntervalsValid, UINT, "3"),
547 V(V3AuthUseLegacyKey, BOOL, "0"),
548 V(V3BandwidthsFile, FILENAME, NULL),
549 V(GuardfractionFile, FILENAME, NULL),
550 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
551 OBSOLETE("VoteOnHidServDirectoriesV2"),
552 V(VirtualAddrNetworkIPv4, STRING, "127.192.0.0/10"),
553 V(VirtualAddrNetworkIPv6, STRING, "[FE80::]/10"),
554 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
555 OBSOLETE("UseFilteringSSLBufferevents"),
556 OBSOLETE("__UseFilteringSSLBufferevents"),
557 VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
558 VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
559 VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
560 VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
561 VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
562 NULL),
563 VAR("__OwningControllerProcess",STRING,OwningControllerProcess, NULL),
564 V(MinUptimeHidServDirectoryV2, INTERVAL, "96 hours"),
565 V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 60, 60, 120, "
566 "300, 900, 2147483647"),
567 V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 60, 300, 600, "
568 "2147483647"),
569 V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
570 "300, 600, 1800, 1800, 1800, 1800, "
571 "1800, 3600, 7200"),
572 V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
573 "300, 600, 1800, 3600, 3600, 3600, "
574 "10800, 21600, 43200"),
575 /* With the ClientBootstrapConsensus*Download* below:
576 * Clients with only authorities will try:
577 * - at least 3 authorities over 10 seconds, then exponentially backoff,
578 * with the next attempt 3-21 seconds later,
579 * Clients with authorities and fallbacks will try:
580 * - at least 2 authorities and 4 fallbacks over 21 seconds, then
581 * exponentially backoff, with the next attempts 4-33 seconds later,
582 * Clients will also retry when an application request arrives.
583 * After a number of failed requests, clients retry every 3 days + 1 hour.
585 * Clients used to try 2 authorities over 10 seconds, then wait for
586 * 60 minutes or an application request.
588 * When clients have authorities and fallbacks available, they use these
589 * schedules: (we stagger the times to avoid thundering herds) */
590 V(ClientBootstrapConsensusAuthorityDownloadSchedule, CSV_INTERVAL,
591 "6, 11, 3600, 10800, 25200, 54000, 111600, 262800" /* 3 days + 1 hour */),
592 V(ClientBootstrapConsensusFallbackDownloadSchedule, CSV_INTERVAL,
593 "0, 1, 4, 11, 3600, 10800, 25200, 54000, 111600, 262800"),
594 /* When clients only have authorities available, they use this schedule: */
595 V(ClientBootstrapConsensusAuthorityOnlyDownloadSchedule, CSV_INTERVAL,
596 "0, 3, 7, 3600, 10800, 25200, 54000, 111600, 262800"),
597 /* We don't want to overwhelm slow networks (or mirrors whose replies are
598 * blocked), but we also don't want to fail if only some mirrors are
599 * blackholed. Clients will try 3 directories simultaneously.
600 * (Relays never use simultaneous connections.) */
601 V(ClientBootstrapConsensusMaxInProgressTries, UINT, "3"),
602 /* When a client has any running bridges, check each bridge occasionally,
603 * whether or not that bridge is actually up. */
604 V(TestingBridgeDownloadSchedule, CSV_INTERVAL,
605 "10800, 25200, 54000, 111600, 262800"),
606 /* When a client is just starting, or has no running bridges, check each
607 * bridge a few times quickly, and then try again later. These schedules
608 * are much longer than the other schedules, because we try each and every
609 * configured bridge with this schedule. */
610 V(TestingBridgeBootstrapDownloadSchedule, CSV_INTERVAL,
611 "0, 30, 90, 600, 3600, 10800, 25200, 54000, 111600, 262800"),
612 V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "10 minutes"),
613 V(TestingDirConnectionMaxStall, INTERVAL, "5 minutes"),
614 V(TestingConsensusMaxDownloadTries, UINT, "8"),
615 /* Since we try connections rapidly and simultaneously, we can afford
616 * to give up earlier. (This protects against overloading directories.) */
617 V(ClientBootstrapConsensusMaxDownloadTries, UINT, "7"),
618 /* We want to give up much earlier if we're only using authorities. */
619 V(ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries, UINT, "4"),
620 V(TestingDescriptorMaxDownloadTries, UINT, "8"),
621 V(TestingMicrodescMaxDownloadTries, UINT, "8"),
622 V(TestingCertMaxDownloadTries, UINT, "8"),
623 V(TestingDirAuthVoteExit, ROUTERSET, NULL),
624 V(TestingDirAuthVoteExitIsStrict, BOOL, "0"),
625 V(TestingDirAuthVoteGuard, ROUTERSET, NULL),
626 V(TestingDirAuthVoteGuardIsStrict, BOOL, "0"),
627 V(TestingDirAuthVoteHSDir, ROUTERSET, NULL),
628 V(TestingDirAuthVoteHSDirIsStrict, BOOL, "0"),
629 VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "0"),
631 END_OF_CONFIG_VARS
634 /** Override default values with these if the user sets the TestingTorNetwork
635 * option. */
636 static const config_var_t testing_tor_network_defaults[] = {
637 V(DirAllowPrivateAddresses, BOOL, "1"),
638 V(EnforceDistinctSubnets, BOOL, "0"),
639 V(AssumeReachable, BOOL, "1"),
640 V(AuthDirMaxServersPerAddr, UINT, "0"),
641 V(ClientBootstrapConsensusAuthorityDownloadSchedule, CSV_INTERVAL,
642 "0, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
643 V(ClientBootstrapConsensusFallbackDownloadSchedule, CSV_INTERVAL,
644 "0, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
645 V(ClientBootstrapConsensusAuthorityOnlyDownloadSchedule, CSV_INTERVAL,
646 "0, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
647 V(ClientBootstrapConsensusMaxDownloadTries, UINT, "80"),
648 V(ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries, UINT, "80"),
649 V(ClientDNSRejectInternalAddresses, BOOL,"0"),
650 V(ClientRejectInternalAddresses, BOOL, "0"),
651 V(CountPrivateBandwidth, BOOL, "1"),
652 V(ExitPolicyRejectPrivate, BOOL, "0"),
653 V(ExtendAllowPrivateAddresses, BOOL, "1"),
654 V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
655 V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
656 V(V3AuthDistDelay, INTERVAL, "20 seconds"),
657 V(TestingV3AuthInitialVotingInterval, INTERVAL, "150 seconds"),
658 V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
659 V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
660 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
661 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
662 V(MinUptimeHidServDirectoryV2, INTERVAL, "0 minutes"),
663 V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 5, 10, 15, "
664 "20, 30, 60"),
665 V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, 15, 20, "
666 "30, 60"),
667 V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
668 "15, 20, 30, 60"),
669 V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
670 "15, 20, 30, 60"),
671 V(TestingBridgeDownloadSchedule, CSV_INTERVAL, "10, 30, 60"),
672 V(TestingBridgeBootstrapDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
673 "15, 20, 30, 60"),
674 V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "5 seconds"),
675 V(TestingDirConnectionMaxStall, INTERVAL, "30 seconds"),
676 V(TestingConsensusMaxDownloadTries, UINT, "80"),
677 V(TestingDescriptorMaxDownloadTries, UINT, "80"),
678 V(TestingMicrodescMaxDownloadTries, UINT, "80"),
679 V(TestingCertMaxDownloadTries, UINT, "80"),
680 V(TestingEnableConnBwEvent, BOOL, "1"),
681 V(TestingEnableCellStatsEvent, BOOL, "1"),
682 V(TestingEnableTbEmptyEvent, BOOL, "1"),
683 VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "1"),
684 V(RendPostPeriod, INTERVAL, "2 minutes"),
686 END_OF_CONFIG_VARS
689 #undef VAR
690 #undef V
691 #undef OBSOLETE
693 static const config_deprecation_t option_deprecation_notes_[] = {
694 /* Deprecated since 0.3.2.0-alpha. */
695 { "HTTPProxy", "It only applies to direct unencrypted HTTP connections "
696 "to your directory server, which your Tor probably wasn't using." },
697 { "HTTPProxyAuthenticator", "HTTPProxy is deprecated in favor of HTTPSProxy "
698 "which should be used with HTTPSProxyAuthenticator." },
699 /* End of options deprecated since 0.3.2.1-alpha */
701 /* Options deprecated since 0.3.2.2-alpha */
702 { "ReachableDirAddresses", "It has no effect on relays, and has had no "
703 "effect on clients since 0.2.8." },
704 { "ClientPreferIPv6DirPort", "It has no effect on relays, and has had no "
705 "effect on clients since 0.2.8." },
706 /* End of options deprecated since 0.3.2.2-alpha. */
708 { NULL, NULL }
711 #ifdef _WIN32
712 static char *get_windows_conf_root(void);
713 #endif
714 static int options_act_reversible(const or_options_t *old_options, char **msg);
715 static int options_transition_allowed(const or_options_t *old,
716 const or_options_t *new,
717 char **msg);
718 static int options_transition_affects_workers(
719 const or_options_t *old_options, const or_options_t *new_options);
720 static int options_transition_affects_descriptor(
721 const or_options_t *old_options, const or_options_t *new_options);
722 static int normalize_nickname_list(config_line_t **normalized_out,
723 const config_line_t *lst, const char *name,
724 char **msg);
725 static char *get_bindaddr_from_transport_listen_line(const char *line,
726 const char *transport);
727 static int parse_ports(or_options_t *options, int validate_only,
728 char **msg_out, int *n_ports_out,
729 int *world_writable_control_socket);
730 static int check_server_ports(const smartlist_t *ports,
731 const or_options_t *options,
732 int *num_low_ports_out);
733 static int validate_data_directory(or_options_t *options);
734 static int write_configuration_file(const char *fname,
735 const or_options_t *options);
736 static int options_init_logs(const or_options_t *old_options,
737 or_options_t *options, int validate_only);
739 static void init_libevent(const or_options_t *options);
740 static int opt_streq(const char *s1, const char *s2);
741 static int parse_outbound_addresses(or_options_t *options, int validate_only,
742 char **msg);
743 static void config_maybe_load_geoip_files_(const or_options_t *options,
744 const or_options_t *old_options);
745 static int options_validate_cb(void *old_options, void *options,
746 void *default_options,
747 int from_setconf, char **msg);
748 static uint64_t compute_real_max_mem_in_queues(const uint64_t val,
749 int log_guess);
751 /** Magic value for or_options_t. */
752 #define OR_OPTIONS_MAGIC 9090909
754 /** Configuration format for or_options_t. */
755 STATIC config_format_t options_format = {
756 sizeof(or_options_t),
757 OR_OPTIONS_MAGIC,
758 offsetof(or_options_t, magic_),
759 option_abbrevs_,
760 option_deprecation_notes_,
761 option_vars_,
762 options_validate_cb,
763 NULL
767 * Functions to read and write the global options pointer.
770 /** Command-line and config-file options. */
771 static or_options_t *global_options = NULL;
772 /** The fallback options_t object; this is where we look for options not
773 * in torrc before we fall back to Tor's defaults. */
774 static or_options_t *global_default_options = NULL;
775 /** Name of most recently read torrc file. */
776 static char *torrc_fname = NULL;
777 /** Name of the most recently read torrc-defaults file.*/
778 static char *torrc_defaults_fname;
779 /** Configuration options set by command line. */
780 static config_line_t *global_cmdline_options = NULL;
781 /** Non-configuration options set by the command line */
782 static config_line_t *global_cmdline_only_options = NULL;
783 /** Boolean: Have we parsed the command line? */
784 static int have_parsed_cmdline = 0;
785 /** Contents of most recently read DirPortFrontPage file. */
786 static char *global_dirfrontpagecontents = NULL;
787 /** List of port_cfg_t for all configured ports. */
788 static smartlist_t *configured_ports = NULL;
789 /** True iff we're currently validating options, and any calls to
790 * get_options() are likely to be bugs. */
791 static int in_option_validation = 0;
793 /** Return the contents of our frontpage string, or NULL if not configured. */
794 MOCK_IMPL(const char*,
795 get_dirportfrontpage, (void))
797 return global_dirfrontpagecontents;
800 /** Returns the currently configured options. */
801 MOCK_IMPL(or_options_t *,
802 get_options_mutable, (void))
804 tor_assert(global_options);
805 tor_assert_nonfatal(! in_option_validation);
806 return global_options;
809 /** Returns the currently configured options */
810 MOCK_IMPL(const or_options_t *,
811 get_options,(void))
813 return get_options_mutable();
816 /** Change the current global options to contain <b>new_val</b> instead of
817 * their current value; take action based on the new value; free the old value
818 * as necessary. Returns 0 on success, -1 on failure.
821 set_options(or_options_t *new_val, char **msg)
823 int i;
824 smartlist_t *elements;
825 config_line_t *line;
826 or_options_t *old_options = global_options;
827 global_options = new_val;
828 /* Note that we pass the *old* options below, for comparison. It
829 * pulls the new options directly out of global_options. */
830 if (options_act_reversible(old_options, msg)<0) {
831 tor_assert(*msg);
832 global_options = old_options;
833 return -1;
835 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
836 log_err(LD_BUG,
837 "Acting on config options left us in a broken state. Dying.");
838 exit(1);
840 /* Issues a CONF_CHANGED event to notify controller of the change. If Tor is
841 * just starting up then the old_options will be undefined. */
842 if (old_options && old_options != global_options) {
843 elements = smartlist_new();
844 for (i=0; options_format.vars[i].name; ++i) {
845 const config_var_t *var = &options_format.vars[i];
846 const char *var_name = var->name;
847 if (var->type == CONFIG_TYPE_LINELIST_S ||
848 var->type == CONFIG_TYPE_OBSOLETE) {
849 continue;
851 if (!config_is_same(&options_format, new_val, old_options, var_name)) {
852 line = config_get_assigned_option(&options_format, new_val,
853 var_name, 1);
855 if (line) {
856 config_line_t *next;
857 for (; line; line = next) {
858 next = line->next;
859 smartlist_add(elements, line->key);
860 smartlist_add(elements, line->value);
861 tor_free(line);
863 } else {
864 smartlist_add_strdup(elements, options_format.vars[i].name);
865 smartlist_add(elements, NULL);
869 control_event_conf_changed(elements);
870 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
871 smartlist_free(elements);
874 if (old_options != global_options)
875 or_options_free(old_options);
877 return 0;
880 extern const char tor_git_revision[]; /* from tor_main.c */
882 /** The version of this Tor process, as parsed. */
883 static char *the_tor_version = NULL;
884 /** A shorter version of this Tor process's version, for export in our router
885 * descriptor. (Does not include the git version, if any.) */
886 static char *the_short_tor_version = NULL;
888 /** Return the current Tor version. */
889 const char *
890 get_version(void)
892 if (the_tor_version == NULL) {
893 if (strlen(tor_git_revision)) {
894 tor_asprintf(&the_tor_version, "%s (git-%s)", get_short_version(),
895 tor_git_revision);
896 } else {
897 the_tor_version = tor_strdup(get_short_version());
900 return the_tor_version;
903 /** Return the current Tor version, without any git tag. */
904 const char *
905 get_short_version(void)
908 if (the_short_tor_version == NULL) {
909 #ifdef TOR_BUILD_TAG
910 tor_asprintf(&the_short_tor_version, "%s (%s)", VERSION, TOR_BUILD_TAG);
911 #else
912 the_short_tor_version = tor_strdup(VERSION);
913 #endif
915 return the_short_tor_version;
918 /** Release additional memory allocated in options
920 STATIC void
921 or_options_free(or_options_t *options)
923 if (!options)
924 return;
926 routerset_free(options->ExcludeExitNodesUnion_);
927 if (options->NodeFamilySets) {
928 SMARTLIST_FOREACH(options->NodeFamilySets, routerset_t *,
929 rs, routerset_free(rs));
930 smartlist_free(options->NodeFamilySets);
932 if (options->SchedulerTypes_) {
933 SMARTLIST_FOREACH(options->SchedulerTypes_, int *, i, tor_free(i));
934 smartlist_free(options->SchedulerTypes_);
936 tor_free(options->BridgePassword_AuthDigest_);
937 tor_free(options->command_arg);
938 tor_free(options->master_key_fname);
939 config_free_lines(options->MyFamily);
940 config_free(&options_format, options);
943 /** Release all memory and resources held by global configuration structures.
945 void
946 config_free_all(void)
948 or_options_free(global_options);
949 global_options = NULL;
950 or_options_free(global_default_options);
951 global_default_options = NULL;
953 config_free_lines(global_cmdline_options);
954 global_cmdline_options = NULL;
956 config_free_lines(global_cmdline_only_options);
957 global_cmdline_only_options = NULL;
959 if (configured_ports) {
960 SMARTLIST_FOREACH(configured_ports,
961 port_cfg_t *, p, port_cfg_free(p));
962 smartlist_free(configured_ports);
963 configured_ports = NULL;
966 tor_free(torrc_fname);
967 tor_free(torrc_defaults_fname);
968 tor_free(global_dirfrontpagecontents);
970 tor_free(the_short_tor_version);
971 tor_free(the_tor_version);
974 /** Make <b>address</b> -- a piece of information related to our operation as
975 * a client -- safe to log according to the settings in options->SafeLogging,
976 * and return it.
978 * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
980 const char *
981 safe_str_client(const char *address)
983 tor_assert(address);
984 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
985 return "[scrubbed]";
986 else
987 return address;
990 /** Make <b>address</b> -- a piece of information of unspecified sensitivity
991 * -- safe to log according to the settings in options->SafeLogging, and
992 * return it.
994 * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
995 * otherwise.)
997 const char *
998 safe_str(const char *address)
1000 tor_assert(address);
1001 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
1002 return "[scrubbed]";
1003 else
1004 return address;
1007 /** Equivalent to escaped(safe_str_client(address)). See reentrancy note on
1008 * escaped(): don't use this outside the main thread, or twice in the same
1009 * log statement. */
1010 const char *
1011 escaped_safe_str_client(const char *address)
1013 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
1014 return "[scrubbed]";
1015 else
1016 return escaped(address);
1019 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
1020 * escaped(): don't use this outside the main thread, or twice in the same
1021 * log statement. */
1022 const char *
1023 escaped_safe_str(const char *address)
1025 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
1026 return "[scrubbed]";
1027 else
1028 return escaped(address);
1032 * The severity level that should be used for warnings of severity
1033 * LOG_PROTOCOL_WARN.
1035 * We keep this outside the options, in case somebody needs to use
1036 * LOG_PROTOCOL_WARN while an option transition is happening.
1038 static int protocol_warning_severity_level = LOG_WARN;
1040 /** Return the severity level that should be used for warnings of severity
1041 * LOG_PROTOCOL_WARN. */
1043 get_protocol_warning_severity_level(void)
1045 return protocol_warning_severity_level;
1048 /** List of default directory authorities */
1050 static const char *default_authorities[] = {
1051 "moria1 orport=9101 "
1052 "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
1053 "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
1054 "tor26 orport=443 "
1055 "v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
1056 "ipv6=[2001:858:2:2:aabb:0:563b:1526]:443 "
1057 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
1058 "dizum orport=443 "
1059 "v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
1060 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
1061 "Bifroest orport=443 bridge "
1062 "37.218.247.217:80 1D8F 3A91 C37C 5D1C 4C19 B1AD 1D0C FBE8 BF72 D8E1",
1063 "gabelmoo orport=443 "
1064 "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
1065 "ipv6=[2001:638:a000:4140::ffff:189]:443 "
1066 "131.188.40.189:80 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
1067 "dannenberg orport=443 "
1068 "v3ident=0232AF901C31A04EE9848595AF9BB7620D4C5B2E "
1069 "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
1070 "maatuska orport=80 "
1071 "v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
1072 "ipv6=[2001:67c:289c::9]:80 "
1073 "171.25.193.9:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
1074 "Faravahar orport=443 "
1075 "v3ident=EFCBE720AB3A82B99F9E953CD5BF50F7EEFC7B97 "
1076 "154.35.175.225:80 CF6D 0AAF B385 BE71 B8E1 11FC 5CFF 4B47 9237 33BC",
1077 "longclaw orport=443 "
1078 "v3ident=23D15D965BC35114467363C165C4F724B64B4F66 "
1079 "199.58.81.140:80 74A9 1064 6BCE EFBC D2E8 74FC 1DC9 9743 0F96 8145",
1080 "bastet orport=443 "
1081 "v3ident=27102BC123E7AF1D4741AE047E160C91ADC76B21 "
1082 "ipv6=[2620:13:4000:6000::1000:118]:443 "
1083 "204.13.164.118:80 24E2 F139 121D 4394 C54B 5BCC 368B 3B41 1857 C413",
1084 NULL
1087 /** List of fallback directory authorities. The list is generated by opt-in of
1088 * relays that meet certain stability criteria.
1090 static const char *default_fallbacks[] = {
1091 #include "fallback_dirs.inc"
1092 NULL
1095 /** Add the default directory authorities directly into the trusted dir list,
1096 * but only add them insofar as they share bits with <b>type</b>.
1097 * Each authority's bits are restricted to the bits shared with <b>type</b>.
1098 * If <b>type</b> is ALL_DIRINFO or NO_DIRINFO (zero), add all authorities. */
1099 STATIC void
1100 add_default_trusted_dir_authorities(dirinfo_type_t type)
1102 int i;
1103 for (i=0; default_authorities[i]; i++) {
1104 if (parse_dir_authority_line(default_authorities[i], type, 0)<0) {
1105 log_err(LD_BUG, "Couldn't parse internal DirAuthority line %s",
1106 default_authorities[i]);
1111 /** Add the default fallback directory servers into the fallback directory
1112 * server list. */
1113 MOCK_IMPL(void,
1114 add_default_fallback_dir_servers,(void))
1116 int i;
1117 for (i=0; default_fallbacks[i]; i++) {
1118 if (parse_dir_fallback_line(default_fallbacks[i], 0)<0) {
1119 log_err(LD_BUG, "Couldn't parse internal FallbackDir line %s",
1120 default_fallbacks[i]);
1125 /** Look at all the config options for using alternate directory
1126 * authorities, and make sure none of them are broken. Also, warn the
1127 * user if we changed any dangerous ones.
1129 static int
1130 validate_dir_servers(or_options_t *options, or_options_t *old_options)
1132 config_line_t *cl;
1134 if (options->DirAuthorities &&
1135 (options->AlternateDirAuthority || options->AlternateBridgeAuthority)) {
1136 log_warn(LD_CONFIG,
1137 "You cannot set both DirAuthority and Alternate*Authority.");
1138 return -1;
1141 /* do we want to complain to the user about being partitionable? */
1142 if ((options->DirAuthorities &&
1143 (!old_options ||
1144 !config_lines_eq(options->DirAuthorities,
1145 old_options->DirAuthorities))) ||
1146 (options->AlternateDirAuthority &&
1147 (!old_options ||
1148 !config_lines_eq(options->AlternateDirAuthority,
1149 old_options->AlternateDirAuthority)))) {
1150 log_warn(LD_CONFIG,
1151 "You have used DirAuthority or AlternateDirAuthority to "
1152 "specify alternate directory authorities in "
1153 "your configuration. This is potentially dangerous: it can "
1154 "make you look different from all other Tor users, and hurt "
1155 "your anonymity. Even if you've specified the same "
1156 "authorities as Tor uses by default, the defaults could "
1157 "change in the future. Be sure you know what you're doing.");
1160 /* Now go through the four ways you can configure an alternate
1161 * set of directory authorities, and make sure none are broken. */
1162 for (cl = options->DirAuthorities; cl; cl = cl->next)
1163 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1164 return -1;
1165 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1166 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1167 return -1;
1168 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1169 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1170 return -1;
1171 for (cl = options->FallbackDir; cl; cl = cl->next)
1172 if (parse_dir_fallback_line(cl->value, 1)<0)
1173 return -1;
1174 return 0;
1177 /** Look at all the config options and assign new dir authorities
1178 * as appropriate.
1181 consider_adding_dir_servers(const or_options_t *options,
1182 const or_options_t *old_options)
1184 config_line_t *cl;
1185 int need_to_update =
1186 !smartlist_len(router_get_trusted_dir_servers()) ||
1187 !smartlist_len(router_get_fallback_dir_servers()) || !old_options ||
1188 !config_lines_eq(options->DirAuthorities, old_options->DirAuthorities) ||
1189 !config_lines_eq(options->FallbackDir, old_options->FallbackDir) ||
1190 (options->UseDefaultFallbackDirs != old_options->UseDefaultFallbackDirs) ||
1191 !config_lines_eq(options->AlternateBridgeAuthority,
1192 old_options->AlternateBridgeAuthority) ||
1193 !config_lines_eq(options->AlternateDirAuthority,
1194 old_options->AlternateDirAuthority);
1196 if (!need_to_update)
1197 return 0; /* all done */
1199 /* "You cannot set both DirAuthority and Alternate*Authority."
1200 * Checking that this restriction holds allows us to simplify
1201 * the unit tests. */
1202 tor_assert(!(options->DirAuthorities &&
1203 (options->AlternateDirAuthority
1204 || options->AlternateBridgeAuthority)));
1206 /* Start from a clean slate. */
1207 clear_dir_servers();
1209 if (!options->DirAuthorities) {
1210 /* then we may want some of the defaults */
1211 dirinfo_type_t type = NO_DIRINFO;
1212 if (!options->AlternateBridgeAuthority) {
1213 type |= BRIDGE_DIRINFO;
1215 if (!options->AlternateDirAuthority) {
1216 type |= V3_DIRINFO | EXTRAINFO_DIRINFO | MICRODESC_DIRINFO;
1217 /* Only add the default fallback directories when the DirAuthorities,
1218 * AlternateDirAuthority, and FallbackDir directory config options
1219 * are set to their defaults, and when UseDefaultFallbackDirs is 1. */
1220 if (!options->FallbackDir && options->UseDefaultFallbackDirs) {
1221 add_default_fallback_dir_servers();
1224 /* if type == NO_DIRINFO, we don't want to add any of the
1225 * default authorities, because we've replaced them all */
1226 if (type != NO_DIRINFO)
1227 add_default_trusted_dir_authorities(type);
1230 for (cl = options->DirAuthorities; cl; cl = cl->next)
1231 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1232 return -1;
1233 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1234 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1235 return -1;
1236 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1237 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1238 return -1;
1239 for (cl = options->FallbackDir; cl; cl = cl->next)
1240 if (parse_dir_fallback_line(cl->value, 0)<0)
1241 return -1;
1242 return 0;
1245 /* Helps determine flags to pass to switch_id. */
1246 static int have_low_ports = -1;
1248 /** Fetch the active option list, and take actions based on it. All of the
1249 * things we do should survive being done repeatedly. If present,
1250 * <b>old_options</b> contains the previous value of the options.
1252 * Return 0 if all goes well, return -1 if things went badly.
1254 static int
1255 options_act_reversible(const or_options_t *old_options, char **msg)
1257 smartlist_t *new_listeners = smartlist_new();
1258 smartlist_t *replaced_listeners = smartlist_new();
1259 static int libevent_initialized = 0;
1260 or_options_t *options = get_options_mutable();
1261 int running_tor = options->command == CMD_RUN_TOR;
1262 int set_conn_limit = 0;
1263 int r = -1;
1264 int logs_marked = 0, logs_initialized = 0;
1265 int old_min_log_level = get_min_log_level();
1267 /* Daemonize _first_, since we only want to open most of this stuff in
1268 * the subprocess. Libevent bases can't be reliably inherited across
1269 * processes. */
1270 if (running_tor && options->RunAsDaemon) {
1271 /* No need to roll back, since you can't change the value. */
1272 start_daemon();
1275 #ifdef HAVE_SYSTEMD
1276 /* Our PID may have changed, inform supervisor */
1277 sd_notifyf(0, "MAINPID=%ld\n", (long int)getpid());
1278 #endif
1280 #ifndef HAVE_SYS_UN_H
1281 if (options->ControlSocket || options->ControlSocketsGroupWritable) {
1282 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported "
1283 "on this OS/with this build.");
1284 goto rollback;
1286 #else /* !(!defined(HAVE_SYS_UN_H)) */
1287 if (options->ControlSocketsGroupWritable && !options->ControlSocket) {
1288 *msg = tor_strdup("Setting ControlSocketGroupWritable without setting"
1289 "a ControlSocket makes no sense.");
1290 goto rollback;
1292 #endif /* !defined(HAVE_SYS_UN_H) */
1294 if (running_tor) {
1295 int n_ports=0;
1296 /* We need to set the connection limit before we can open the listeners. */
1297 if (! sandbox_is_active()) {
1298 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1299 &options->ConnLimit_) < 0) {
1300 *msg = tor_strdup("Problem with ConnLimit value. "
1301 "See logs for details.");
1302 goto rollback;
1304 set_conn_limit = 1;
1305 } else {
1306 tor_assert(old_options);
1307 options->ConnLimit_ = old_options->ConnLimit_;
1310 /* Set up libevent. (We need to do this before we can register the
1311 * listeners as listeners.) */
1312 if (running_tor && !libevent_initialized) {
1313 init_libevent(options);
1314 libevent_initialized = 1;
1316 /* This has to come up after libevent is initialized. */
1317 control_initialize_event_queue();
1320 * Initialize the scheduler - this has to come after
1321 * options_init_from_torrc() sets up libevent - why yes, that seems
1322 * completely sensible to hide the libevent setup in the option parsing
1323 * code! It also needs to happen before init_keys(), so it needs to
1324 * happen here too. How yucky. */
1325 scheduler_init();
1328 /* Adjust the port configuration so we can launch listeners. */
1329 if (parse_ports(options, 0, msg, &n_ports, NULL)) {
1330 if (!*msg)
1331 *msg = tor_strdup("Unexpected problem parsing port config");
1332 goto rollback;
1335 /* Set the hibernation state appropriately.*/
1336 consider_hibernation(time(NULL));
1338 /* Launch the listeners. (We do this before we setuid, so we can bind to
1339 * ports under 1024.) We don't want to rebind if we're hibernating. If
1340 * networking is disabled, this will close all but the control listeners,
1341 * but disable those. */
1342 if (!we_are_hibernating()) {
1343 if (retry_all_listeners(replaced_listeners, new_listeners,
1344 options->DisableNetwork) < 0) {
1345 *msg = tor_strdup("Failed to bind one of the listener ports.");
1346 goto rollback;
1349 if (options->DisableNetwork) {
1350 /* Aggressively close non-controller stuff, NOW */
1351 log_notice(LD_NET, "DisableNetwork is set. Tor will not make or accept "
1352 "non-control network connections. Shutting down all existing "
1353 "connections.");
1354 connection_mark_all_noncontrol_connections();
1355 /* We can't complete circuits until the network is re-enabled. */
1356 note_that_we_maybe_cant_complete_circuits();
1360 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1361 /* Open /dev/pf before dropping privileges. */
1362 if (options->TransPort_set &&
1363 options->TransProxyType_parsed == TPT_DEFAULT) {
1364 if (get_pf_socket() < 0) {
1365 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1366 goto rollback;
1369 #endif /* defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H) */
1371 /* Attempt to lock all current and future memory with mlockall() only once */
1372 if (options->DisableAllSwap) {
1373 if (tor_mlockall() == -1) {
1374 *msg = tor_strdup("DisableAllSwap failure. Do you have proper "
1375 "permissions?");
1376 goto done;
1380 /* Setuid/setgid as appropriate */
1381 if (options->User) {
1382 tor_assert(have_low_ports != -1);
1383 unsigned switch_id_flags = 0;
1384 if (options->KeepBindCapabilities == 1) {
1385 switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
1386 switch_id_flags |= SWITCH_ID_WARN_IF_NO_CAPS;
1388 if (options->KeepBindCapabilities == -1 && have_low_ports) {
1389 switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
1391 if (switch_id(options->User, switch_id_flags) != 0) {
1392 /* No need to roll back, since you can't change the value. */
1393 *msg = tor_strdup("Problem with User value. See logs for details.");
1394 goto done;
1398 /* Ensure data directory is private; create if possible. */
1399 cpd_check_t cpd_opts = running_tor ? CPD_CREATE : CPD_CHECK;
1400 if (options->DataDirectoryGroupReadable)
1401 cpd_opts |= CPD_GROUP_READ;
1402 if (check_private_dir(options->DataDirectory,
1403 cpd_opts,
1404 options->User)<0) {
1405 tor_asprintf(msg,
1406 "Couldn't access/create private data directory \"%s\"",
1407 options->DataDirectory);
1409 goto done;
1410 /* No need to roll back, since you can't change the value. */
1413 #ifndef _WIN32
1414 if (options->DataDirectoryGroupReadable) {
1415 /* Only new dirs created get new opts, also enforce group read. */
1416 if (chmod(options->DataDirectory, 0750)) {
1417 log_warn(LD_FS,"Unable to make %s group-readable: %s",
1418 options->DataDirectory, strerror(errno));
1421 #endif /* !defined(_WIN32) */
1423 /* Bail out at this point if we're not going to be a client or server:
1424 * we don't run Tor itself. */
1425 if (!running_tor)
1426 goto commit;
1428 mark_logs_temp(); /* Close current logs once new logs are open. */
1429 logs_marked = 1;
1430 /* Configure the tor_log(s) */
1431 if (options_init_logs(old_options, options, 0)<0) {
1432 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1433 goto rollback;
1435 logs_initialized = 1;
1437 commit:
1438 r = 0;
1439 if (logs_marked) {
1440 log_severity_list_t *severity =
1441 tor_malloc_zero(sizeof(log_severity_list_t));
1442 close_temp_logs();
1443 add_callback_log(severity, control_event_logmsg);
1444 control_adjust_event_log_severity();
1445 tor_free(severity);
1446 tor_log_update_sigsafe_err_fds();
1448 if (logs_initialized) {
1449 flush_log_messages_from_startup();
1453 const char *badness = NULL;
1454 int bad_safelog = 0, bad_severity = 0, new_badness = 0;
1455 if (options->SafeLogging_ != SAFELOG_SCRUB_ALL) {
1456 bad_safelog = 1;
1457 if (!old_options || old_options->SafeLogging_ != options->SafeLogging_)
1458 new_badness = 1;
1460 if (get_min_log_level() >= LOG_INFO) {
1461 bad_severity = 1;
1462 if (get_min_log_level() != old_min_log_level)
1463 new_badness = 1;
1465 if (bad_safelog && bad_severity)
1466 badness = "you disabled SafeLogging, and "
1467 "you're logging more than \"notice\"";
1468 else if (bad_safelog)
1469 badness = "you disabled SafeLogging";
1470 else
1471 badness = "you're logging more than \"notice\"";
1472 if (new_badness)
1473 log_warn(LD_GENERAL, "Your log may contain sensitive information - %s. "
1474 "Don't log unless it serves an important reason. "
1475 "Overwrite the log afterwards.", badness);
1478 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1480 int marked = conn->marked_for_close;
1481 log_notice(LD_NET, "Closing old %s on %s:%d",
1482 conn_type_to_string(conn->type), conn->address, conn->port);
1483 connection_close_immediate(conn);
1484 if (!marked) {
1485 connection_mark_for_close(conn);
1489 if (set_conn_limit) {
1491 * If we adjusted the conn limit, recompute the OOS threshold too
1493 * How many possible sockets to keep in reserve? If we have lots of
1494 * possible sockets, keep this below a limit and set ConnLimit_high_thresh
1495 * very close to ConnLimit_, but if ConnLimit_ is low, shrink it in
1496 * proportion.
1498 * Somewhat arbitrarily, set socks_in_reserve to 5% of ConnLimit_, but
1499 * cap it at 64.
1501 int socks_in_reserve = options->ConnLimit_ / 20;
1502 if (socks_in_reserve > 64) socks_in_reserve = 64;
1504 options->ConnLimit_high_thresh = options->ConnLimit_ - socks_in_reserve;
1505 options->ConnLimit_low_thresh = (options->ConnLimit_ / 4) * 3;
1506 log_info(LD_GENERAL,
1507 "Recomputed OOS thresholds: ConnLimit %d, ConnLimit_ %d, "
1508 "ConnLimit_high_thresh %d, ConnLimit_low_thresh %d",
1509 options->ConnLimit, options->ConnLimit_,
1510 options->ConnLimit_high_thresh,
1511 options->ConnLimit_low_thresh);
1513 /* Give the OOS handler a chance with the new thresholds */
1514 connection_check_oos(get_n_open_sockets(), 0);
1517 goto done;
1519 rollback:
1520 r = -1;
1521 tor_assert(*msg);
1523 if (logs_marked) {
1524 rollback_log_changes();
1525 control_adjust_event_log_severity();
1528 if (set_conn_limit && old_options)
1529 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1530 &options->ConnLimit_);
1532 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1534 log_notice(LD_NET, "Closing partially-constructed %s on %s:%d",
1535 conn_type_to_string(conn->type), conn->address, conn->port);
1536 connection_close_immediate(conn);
1537 connection_mark_for_close(conn);
1540 done:
1541 smartlist_free(new_listeners);
1542 smartlist_free(replaced_listeners);
1543 return r;
1546 /** If we need to have a GEOIP ip-to-country map to run with our configured
1547 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1549 options_need_geoip_info(const or_options_t *options, const char **reason_out)
1551 int bridge_usage =
1552 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1553 int routerset_usage =
1554 routerset_needs_geoip(options->EntryNodes) ||
1555 routerset_needs_geoip(options->ExitNodes) ||
1556 routerset_needs_geoip(options->ExcludeExitNodes) ||
1557 routerset_needs_geoip(options->ExcludeNodes) ||
1558 routerset_needs_geoip(options->Tor2webRendezvousPoints);
1560 if (routerset_usage && reason_out) {
1561 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1562 "countries, and we need GEOIP information to figure out which ones they "
1563 "are.";
1564 } else if (bridge_usage && reason_out) {
1565 *reason_out = "We've been configured to see which countries can access "
1566 "us as a bridge, and we need GEOIP information to tell which countries "
1567 "clients are in.";
1569 return bridge_usage || routerset_usage;
1572 /** Return the bandwidthrate that we are going to report to the authorities
1573 * based on the config options. */
1574 uint32_t
1575 get_effective_bwrate(const or_options_t *options)
1577 uint64_t bw = options->BandwidthRate;
1578 if (bw > options->MaxAdvertisedBandwidth)
1579 bw = options->MaxAdvertisedBandwidth;
1580 if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1581 bw = options->RelayBandwidthRate;
1582 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1583 return (uint32_t)bw;
1586 /** Return the bandwidthburst that we are going to report to the authorities
1587 * based on the config options. */
1588 uint32_t
1589 get_effective_bwburst(const or_options_t *options)
1591 uint64_t bw = options->BandwidthBurst;
1592 if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1593 bw = options->RelayBandwidthBurst;
1594 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1595 return (uint32_t)bw;
1599 * Return true if changing the configuration from <b>old</b> to <b>new</b>
1600 * affects the guard susbsystem.
1602 static int
1603 options_transition_affects_guards(const or_options_t *old,
1604 const or_options_t *new)
1606 /* NOTE: Make sure this function stays in sync with
1607 * entry_guards_set_filtered_flags */
1609 tor_assert(old);
1610 tor_assert(new);
1612 return
1613 (old->UseEntryGuards != new->UseEntryGuards ||
1614 old->UseBridges != new->UseBridges ||
1615 old->ClientUseIPv4 != new->ClientUseIPv4 ||
1616 old->ClientUseIPv6 != new->ClientUseIPv6 ||
1617 old->FascistFirewall != new->FascistFirewall ||
1618 !routerset_equal(old->ExcludeNodes, new->ExcludeNodes) ||
1619 !routerset_equal(old->EntryNodes, new->EntryNodes) ||
1620 !smartlist_strings_eq(old->FirewallPorts, new->FirewallPorts) ||
1621 !config_lines_eq(old->Bridges, new->Bridges) ||
1622 !config_lines_eq(old->ReachableORAddresses, new->ReachableORAddresses) ||
1623 !config_lines_eq(old->ReachableDirAddresses, new->ReachableDirAddresses));
1626 /** Fetch the active option list, and take actions based on it. All of the
1627 * things we do should survive being done repeatedly. If present,
1628 * <b>old_options</b> contains the previous value of the options.
1630 * Return 0 if all goes well, return -1 if it's time to die.
1632 * Note: We haven't moved all the "act on new configuration" logic
1633 * here yet. Some is still in do_hup() and other places.
1635 STATIC int
1636 options_act(const or_options_t *old_options)
1638 config_line_t *cl;
1639 or_options_t *options = get_options_mutable();
1640 int running_tor = options->command == CMD_RUN_TOR;
1641 char *msg=NULL;
1642 const int transition_affects_workers =
1643 old_options && options_transition_affects_workers(old_options, options);
1644 int old_ewma_enabled;
1645 const int transition_affects_guards =
1646 old_options && options_transition_affects_guards(old_options, options);
1648 if (options->NoExec || options->Sandbox) {
1649 tor_disable_spawning_background_processes();
1652 /* disable ptrace and later, other basic debugging techniques */
1654 /* Remember if we already disabled debugger attachment */
1655 static int disabled_debugger_attach = 0;
1656 /* Remember if we already warned about being configured not to disable
1657 * debugger attachment */
1658 static int warned_debugger_attach = 0;
1659 /* Don't disable debugger attachment when we're running the unit tests. */
1660 if (options->DisableDebuggerAttachment && !disabled_debugger_attach &&
1661 running_tor) {
1662 int ok = tor_disable_debugger_attach();
1663 /* LCOV_EXCL_START the warned_debugger_attach is 0 can't reach inside. */
1664 if (warned_debugger_attach && ok == 1) {
1665 log_notice(LD_CONFIG, "Disabled attaching debuggers for unprivileged "
1666 "users.");
1668 /* LCOV_EXCL_STOP */
1669 disabled_debugger_attach = (ok == 1);
1670 } else if (!options->DisableDebuggerAttachment &&
1671 !warned_debugger_attach) {
1672 log_notice(LD_CONFIG, "Not disabling debugger attaching for "
1673 "unprivileged users.");
1674 warned_debugger_attach = 1;
1678 /* Write control ports to disk as appropriate */
1679 control_ports_write_to_file();
1681 if (running_tor && !have_lockfile()) {
1682 if (try_locking(options, 1) < 0)
1683 return -1;
1686 if (options->ProtocolWarnings)
1687 protocol_warning_severity_level = LOG_WARN;
1688 else
1689 protocol_warning_severity_level = LOG_INFO;
1691 if (consider_adding_dir_servers(options, old_options) < 0)
1692 return -1;
1694 if (rend_non_anonymous_mode_enabled(options)) {
1695 log_warn(LD_GENERAL, "This copy of Tor was compiled or configured to run "
1696 "in a non-anonymous mode. It will provide NO ANONYMITY.");
1699 #ifdef ENABLE_TOR2WEB_MODE
1700 /* LCOV_EXCL_START */
1701 if (!options->Tor2webMode) {
1702 log_err(LD_CONFIG, "This copy of Tor was compiled to run in "
1703 "'tor2web mode'. It can only be run with the Tor2webMode torrc "
1704 "option enabled.");
1705 return -1;
1707 /* LCOV_EXCL_STOP */
1708 #else /* !(defined(ENABLE_TOR2WEB_MODE)) */
1709 if (options->Tor2webMode) {
1710 log_err(LD_CONFIG, "This copy of Tor was not compiled to run in "
1711 "'tor2web mode'. It cannot be run with the Tor2webMode torrc "
1712 "option enabled. To enable Tor2webMode recompile with the "
1713 "--enable-tor2web-mode option.");
1714 return -1;
1716 #endif /* defined(ENABLE_TOR2WEB_MODE) */
1718 /* If we are a bridge with a pluggable transport proxy but no
1719 Extended ORPort, inform the user that they are missing out. */
1720 if (server_mode(options) && options->ServerTransportPlugin &&
1721 !options->ExtORPort_lines) {
1722 log_notice(LD_CONFIG, "We use pluggable transports but the Extended "
1723 "ORPort is disabled. Tor and your pluggable transports proxy "
1724 "communicate with each other via the Extended ORPort so it "
1725 "is suggested you enable it: it will also allow your Bridge "
1726 "to collect statistics about its clients that use pluggable "
1727 "transports. Please enable it using the ExtORPort torrc option "
1728 "(e.g. set 'ExtORPort auto').");
1731 if (options->Bridges) {
1732 mark_bridge_list();
1733 for (cl = options->Bridges; cl; cl = cl->next) {
1734 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
1735 if (!bridge_line) {
1736 log_warn(LD_BUG,
1737 "Previously validated Bridge line could not be added!");
1738 return -1;
1740 bridge_add_from_config(bridge_line);
1742 sweep_bridge_list();
1745 if (running_tor && hs_config_service_all(options, 0)<0) {
1746 log_warn(LD_BUG,
1747 "Previously validated hidden services line could not be added!");
1748 return -1;
1751 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1752 log_warn(LD_BUG, "Previously validated client authorization for "
1753 "hidden services could not be added!");
1754 return -1;
1757 /* Load state */
1758 if (! or_state_loaded() && running_tor) {
1759 if (or_state_load())
1760 return -1;
1761 rep_hist_load_mtbf_data(time(NULL));
1764 /* If we have an ExtORPort, initialize its auth cookie. */
1765 if (running_tor &&
1766 init_ext_or_cookie_authentication(!!options->ExtORPort_lines) < 0) {
1767 log_warn(LD_CONFIG,"Error creating Extended ORPort cookie file.");
1768 return -1;
1771 mark_transport_list();
1772 pt_prepare_proxy_list_for_config_read();
1773 if (!options->DisableNetwork) {
1774 if (options->ClientTransportPlugin) {
1775 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
1776 if (parse_transport_line(options, cl->value, 0, 0) < 0) {
1777 log_warn(LD_BUG,
1778 "Previously validated ClientTransportPlugin line "
1779 "could not be added!");
1780 return -1;
1785 if (options->ServerTransportPlugin && server_mode(options)) {
1786 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
1787 if (parse_transport_line(options, cl->value, 0, 1) < 0) {
1788 log_warn(LD_BUG,
1789 "Previously validated ServerTransportPlugin line "
1790 "could not be added!");
1791 return -1;
1796 sweep_transport_list();
1797 sweep_proxy_list();
1799 /* Start the PT proxy configuration. By doing this configuration
1800 here, we also figure out which proxies need to be restarted and
1801 which not. */
1802 if (pt_proxies_configuration_pending() && !net_is_disabled())
1803 pt_configure_remaining_proxies();
1805 /* Bail out at this point if we're not going to be a client or server:
1806 * we want to not fork, and to log stuff to stderr. */
1807 if (!running_tor)
1808 return 0;
1810 /* Finish backgrounding the process */
1811 if (options->RunAsDaemon) {
1812 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1813 finish_daemon(options->DataDirectory);
1816 /* We want to reinit keys as needed before we do much of anything else:
1817 keys are important, and other things can depend on them. */
1818 if (transition_affects_workers ||
1819 (options->V3AuthoritativeDir && (!old_options ||
1820 !old_options->V3AuthoritativeDir))) {
1821 if (init_keys() < 0) {
1822 log_warn(LD_BUG,"Error initializing keys; exiting");
1823 return -1;
1827 /* Write our PID to the PID file. If we do not have write permissions we
1828 * will log a warning and exit. */
1829 if (options->PidFile && !sandbox_is_active()) {
1830 if (write_pidfile(options->PidFile) < 0) {
1831 log_err(LD_CONFIG, "Unable to write PIDFile %s",
1832 escaped(options->PidFile));
1833 return -1;
1837 /* Register addressmap directives */
1838 config_register_addressmaps(options);
1839 parse_virtual_addr_network(options->VirtualAddrNetworkIPv4, AF_INET,0,NULL);
1840 parse_virtual_addr_network(options->VirtualAddrNetworkIPv6, AF_INET6,0,NULL);
1842 /* Update address policies. */
1843 if (policies_parse_from_options(options) < 0) {
1844 /* This should be impossible, but let's be sure. */
1845 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1846 return -1;
1849 if (server_mode(options)) {
1850 static int cdm_initialized = 0;
1851 if (cdm_initialized == 0) {
1852 cdm_initialized = 1;
1853 consdiffmgr_configure(NULL);
1854 consdiffmgr_validate();
1858 if (init_control_cookie_authentication(options->CookieAuthentication) < 0) {
1859 log_warn(LD_CONFIG,"Error creating control cookie authentication file.");
1860 return -1;
1863 monitor_owning_controller_process(options->OwningControllerProcess);
1865 /* reload keys as needed for rendezvous services. */
1866 if (hs_service_load_all_keys() < 0) {
1867 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1868 return -1;
1871 /* Inform the scheduler subsystem that a configuration changed happened. It
1872 * might be a change of scheduler or parameter. */
1873 scheduler_conf_changed();
1875 /* Set up accounting */
1876 if (accounting_parse_options(options, 0)<0) {
1877 log_warn(LD_CONFIG,"Error in accounting options");
1878 return -1;
1880 if (accounting_is_enabled(options))
1881 configure_accounting(time(NULL));
1883 old_ewma_enabled = cell_ewma_enabled();
1884 /* Change the cell EWMA settings */
1885 cell_ewma_set_scale_factor(options, networkstatus_get_latest_consensus());
1886 /* If we just enabled ewma, set the cmux policy on all active channels */
1887 if (cell_ewma_enabled() && !old_ewma_enabled) {
1888 channel_set_cmux_policy_everywhere(&ewma_policy);
1889 } else if (!cell_ewma_enabled() && old_ewma_enabled) {
1890 /* Turn it off everywhere */
1891 channel_set_cmux_policy_everywhere(NULL);
1894 /* Update the BridgePassword's hashed version as needed. We store this as a
1895 * digest so that we can do side-channel-proof comparisons on it.
1897 if (options->BridgePassword) {
1898 char *http_authenticator;
1899 http_authenticator = alloc_http_authenticator(options->BridgePassword);
1900 if (!http_authenticator) {
1901 log_warn(LD_BUG, "Unable to allocate HTTP authenticator. Not setting "
1902 "BridgePassword.");
1903 return -1;
1905 options->BridgePassword_AuthDigest_ = tor_malloc(DIGEST256_LEN);
1906 crypto_digest256(options->BridgePassword_AuthDigest_,
1907 http_authenticator, strlen(http_authenticator),
1908 DIGEST_SHA256);
1909 tor_free(http_authenticator);
1912 if (parse_outbound_addresses(options, 0, &msg) < 0) {
1913 log_warn(LD_BUG, "Failed parsing outbound bind addresses: %s", msg);
1914 tor_free(msg);
1915 return -1;
1918 config_maybe_load_geoip_files_(options, old_options);
1920 if (geoip_is_loaded(AF_INET) && options->GeoIPExcludeUnknown) {
1921 /* ExcludeUnknown is true or "auto" */
1922 const int is_auto = options->GeoIPExcludeUnknown == -1;
1923 int changed;
1925 changed = routerset_add_unknown_ccs(&options->ExcludeNodes, is_auto);
1926 changed += routerset_add_unknown_ccs(&options->ExcludeExitNodes, is_auto);
1928 if (changed)
1929 routerset_add_unknown_ccs(&options->ExcludeExitNodesUnion_, is_auto);
1932 /* Check for transitions that need action. */
1933 if (old_options) {
1934 int revise_trackexithosts = 0;
1935 int revise_automap_entries = 0;
1936 int abandon_circuits = 0;
1937 if ((options->UseEntryGuards && !old_options->UseEntryGuards) ||
1938 options->UseBridges != old_options->UseBridges ||
1939 (options->UseBridges &&
1940 !config_lines_eq(options->Bridges, old_options->Bridges)) ||
1941 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes) ||
1942 !routerset_equal(old_options->ExcludeExitNodes,
1943 options->ExcludeExitNodes) ||
1944 !routerset_equal(old_options->EntryNodes, options->EntryNodes) ||
1945 !routerset_equal(old_options->ExitNodes, options->ExitNodes) ||
1946 !routerset_equal(old_options->Tor2webRendezvousPoints,
1947 options->Tor2webRendezvousPoints) ||
1948 options->StrictNodes != old_options->StrictNodes) {
1949 log_info(LD_CIRC,
1950 "Changed to using entry guards or bridges, or changed "
1951 "preferred or excluded node lists. "
1952 "Abandoning previous circuits.");
1953 abandon_circuits = 1;
1956 if (transition_affects_guards) {
1957 if (guards_update_all()) {
1958 abandon_circuits = 1;
1962 if (abandon_circuits) {
1963 circuit_mark_all_unused_circs();
1964 circuit_mark_all_dirty_circs_as_unusable();
1965 revise_trackexithosts = 1;
1968 if (!smartlist_strings_eq(old_options->TrackHostExits,
1969 options->TrackHostExits))
1970 revise_trackexithosts = 1;
1972 if (revise_trackexithosts)
1973 addressmap_clear_excluded_trackexithosts(options);
1975 if (!options->AutomapHostsOnResolve &&
1976 old_options->AutomapHostsOnResolve) {
1977 revise_automap_entries = 1;
1978 } else {
1979 if (!smartlist_strings_eq(old_options->AutomapHostsSuffixes,
1980 options->AutomapHostsSuffixes))
1981 revise_automap_entries = 1;
1982 else if (!opt_streq(old_options->VirtualAddrNetworkIPv4,
1983 options->VirtualAddrNetworkIPv4) ||
1984 !opt_streq(old_options->VirtualAddrNetworkIPv6,
1985 options->VirtualAddrNetworkIPv6))
1986 revise_automap_entries = 1;
1989 if (revise_automap_entries)
1990 addressmap_clear_invalid_automaps(options);
1992 /* How long should we delay counting bridge stats after becoming a bridge?
1993 * We use this so we don't count clients who used our bridge thinking it is
1994 * a relay. If you change this, don't forget to change the log message
1995 * below. It's 4 hours (the time it takes to stop being used by clients)
1996 * plus some extra time for clock skew. */
1997 #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
1999 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
2000 int was_relay = 0;
2001 if (options->BridgeRelay) {
2002 time_t int_start = time(NULL);
2003 if (config_lines_eq(old_options->ORPort_lines,options->ORPort_lines)) {
2004 int_start += RELAY_BRIDGE_STATS_DELAY;
2005 was_relay = 1;
2007 geoip_bridge_stats_init(int_start);
2008 log_info(LD_CONFIG, "We are acting as a bridge now. Starting new "
2009 "GeoIP stats interval%s.", was_relay ? " in 6 "
2010 "hours from now" : "");
2011 } else {
2012 geoip_bridge_stats_term();
2013 log_info(LD_GENERAL, "We are no longer acting as a bridge. "
2014 "Forgetting GeoIP stats.");
2018 if (transition_affects_workers) {
2019 log_info(LD_GENERAL,
2020 "Worker-related options changed. Rotating workers.");
2022 if (server_mode(options) && !server_mode(old_options)) {
2023 cpu_init();
2024 ip_address_changed(0);
2025 if (have_completed_a_circuit() || !any_predicted_circuits(time(NULL)))
2026 inform_testing_reachability();
2028 cpuworkers_rotate_keyinfo();
2029 if (dns_reset())
2030 return -1;
2031 } else {
2032 if (dns_reset())
2033 return -1;
2036 if (options->PerConnBWRate != old_options->PerConnBWRate ||
2037 options->PerConnBWBurst != old_options->PerConnBWBurst)
2038 connection_or_update_token_buckets(get_connection_array(), options);
2041 /* Only collect directory-request statistics on relays and bridges. */
2042 options->DirReqStatistics = options->DirReqStatistics_option &&
2043 server_mode(options);
2044 options->HiddenServiceStatistics =
2045 options->HiddenServiceStatistics_option && server_mode(options);
2047 if (options->CellStatistics || options->DirReqStatistics ||
2048 options->EntryStatistics || options->ExitPortStatistics ||
2049 options->ConnDirectionStatistics ||
2050 options->HiddenServiceStatistics ||
2051 options->BridgeAuthoritativeDir) {
2052 time_t now = time(NULL);
2053 int print_notice = 0;
2055 /* Only collect other relay-only statistics on relays. */
2056 if (!public_server_mode(options)) {
2057 options->CellStatistics = 0;
2058 options->EntryStatistics = 0;
2059 options->ConnDirectionStatistics = 0;
2060 options->ExitPortStatistics = 0;
2063 if ((!old_options || !old_options->CellStatistics) &&
2064 options->CellStatistics) {
2065 rep_hist_buffer_stats_init(now);
2066 print_notice = 1;
2068 if ((!old_options || !old_options->DirReqStatistics) &&
2069 options->DirReqStatistics) {
2070 if (geoip_is_loaded(AF_INET)) {
2071 geoip_dirreq_stats_init(now);
2072 print_notice = 1;
2073 } else {
2074 /* disable statistics collection since we have no geoip file */
2075 options->DirReqStatistics = 0;
2076 if (options->ORPort_set)
2077 log_notice(LD_CONFIG, "Configured to measure directory request "
2078 "statistics, but no GeoIP database found. "
2079 "Please specify a GeoIP database using the "
2080 "GeoIPFile option.");
2083 if ((!old_options || !old_options->EntryStatistics) &&
2084 options->EntryStatistics && !should_record_bridge_info(options)) {
2085 if (geoip_is_loaded(AF_INET) || geoip_is_loaded(AF_INET6)) {
2086 geoip_entry_stats_init(now);
2087 print_notice = 1;
2088 } else {
2089 options->EntryStatistics = 0;
2090 log_notice(LD_CONFIG, "Configured to measure entry node "
2091 "statistics, but no GeoIP database found. "
2092 "Please specify a GeoIP database using the "
2093 "GeoIPFile option.");
2096 if ((!old_options || !old_options->ExitPortStatistics) &&
2097 options->ExitPortStatistics) {
2098 rep_hist_exit_stats_init(now);
2099 print_notice = 1;
2101 if ((!old_options || !old_options->ConnDirectionStatistics) &&
2102 options->ConnDirectionStatistics) {
2103 rep_hist_conn_stats_init(now);
2105 if ((!old_options || !old_options->HiddenServiceStatistics) &&
2106 options->HiddenServiceStatistics) {
2107 log_info(LD_CONFIG, "Configured to measure hidden service statistics.");
2108 rep_hist_hs_stats_init(now);
2110 if ((!old_options || !old_options->BridgeAuthoritativeDir) &&
2111 options->BridgeAuthoritativeDir) {
2112 rep_hist_desc_stats_init(now);
2113 print_notice = 1;
2115 if (print_notice)
2116 log_notice(LD_CONFIG, "Configured to measure statistics. Look for "
2117 "the *-stats files that will first be written to the "
2118 "data directory in 24 hours from now.");
2121 /* If we used to have statistics enabled but we just disabled them,
2122 stop gathering them. */
2123 if (old_options && old_options->CellStatistics &&
2124 !options->CellStatistics)
2125 rep_hist_buffer_stats_term();
2126 if (old_options && old_options->DirReqStatistics &&
2127 !options->DirReqStatistics)
2128 geoip_dirreq_stats_term();
2129 if (old_options && old_options->EntryStatistics &&
2130 !options->EntryStatistics)
2131 geoip_entry_stats_term();
2132 if (old_options && old_options->HiddenServiceStatistics &&
2133 !options->HiddenServiceStatistics)
2134 rep_hist_hs_stats_term();
2135 if (old_options && old_options->ExitPortStatistics &&
2136 !options->ExitPortStatistics)
2137 rep_hist_exit_stats_term();
2138 if (old_options && old_options->ConnDirectionStatistics &&
2139 !options->ConnDirectionStatistics)
2140 rep_hist_conn_stats_term();
2141 if (old_options && old_options->BridgeAuthoritativeDir &&
2142 !options->BridgeAuthoritativeDir)
2143 rep_hist_desc_stats_term();
2145 /* Since our options changed, we might need to regenerate and upload our
2146 * server descriptor.
2148 if (!old_options ||
2149 options_transition_affects_descriptor(old_options, options))
2150 mark_my_descriptor_dirty("config change");
2152 /* We may need to reschedule some directory stuff if our status changed. */
2153 if (old_options) {
2154 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
2155 dirvote_recalculate_timing(options, time(NULL));
2156 if (!bool_eq(directory_fetches_dir_info_early(options),
2157 directory_fetches_dir_info_early(old_options)) ||
2158 !bool_eq(directory_fetches_dir_info_later(options),
2159 directory_fetches_dir_info_later(old_options))) {
2160 /* Make sure update_router_have_minimum_dir_info() gets called. */
2161 router_dir_info_changed();
2162 /* We might need to download a new consensus status later or sooner than
2163 * we had expected. */
2164 update_consensus_networkstatus_fetch_time(time(NULL));
2168 /* Load the webpage we're going to serve every time someone asks for '/' on
2169 our DirPort. */
2170 tor_free(global_dirfrontpagecontents);
2171 if (options->DirPortFrontPage) {
2172 global_dirfrontpagecontents =
2173 read_file_to_str(options->DirPortFrontPage, 0, NULL);
2174 if (!global_dirfrontpagecontents) {
2175 log_warn(LD_CONFIG,
2176 "DirPortFrontPage file '%s' not found. Continuing anyway.",
2177 options->DirPortFrontPage);
2181 return 0;
2184 typedef enum {
2185 TAKES_NO_ARGUMENT = 0,
2186 ARGUMENT_NECESSARY = 1,
2187 ARGUMENT_OPTIONAL = 2
2188 } takes_argument_t;
2190 static const struct {
2191 const char *name;
2192 takes_argument_t takes_argument;
2193 } CMDLINE_ONLY_OPTIONS[] = {
2194 { "-f", ARGUMENT_NECESSARY },
2195 { "--allow-missing-torrc", TAKES_NO_ARGUMENT },
2196 { "--defaults-torrc", ARGUMENT_NECESSARY },
2197 { "--hash-password", ARGUMENT_NECESSARY },
2198 { "--dump-config", ARGUMENT_OPTIONAL },
2199 { "--list-fingerprint", TAKES_NO_ARGUMENT },
2200 { "--keygen", TAKES_NO_ARGUMENT },
2201 { "--key-expiration", ARGUMENT_OPTIONAL },
2202 { "--newpass", TAKES_NO_ARGUMENT },
2203 { "--no-passphrase", TAKES_NO_ARGUMENT },
2204 { "--passphrase-fd", ARGUMENT_NECESSARY },
2205 { "--verify-config", TAKES_NO_ARGUMENT },
2206 { "--ignore-missing-torrc", TAKES_NO_ARGUMENT },
2207 { "--quiet", TAKES_NO_ARGUMENT },
2208 { "--hush", TAKES_NO_ARGUMENT },
2209 { "--version", TAKES_NO_ARGUMENT },
2210 { "--library-versions", TAKES_NO_ARGUMENT },
2211 { "-h", TAKES_NO_ARGUMENT },
2212 { "--help", TAKES_NO_ARGUMENT },
2213 { "--list-torrc-options", TAKES_NO_ARGUMENT },
2214 { "--list-deprecated-options",TAKES_NO_ARGUMENT },
2215 { "--nt-service", TAKES_NO_ARGUMENT },
2216 { "-nt-service", TAKES_NO_ARGUMENT },
2217 { NULL, 0 },
2220 /** Helper: Read a list of configuration options from the command line. If
2221 * successful, or if ignore_errors is set, put them in *<b>result</b>, put the
2222 * commandline-only options in *<b>cmdline_result</b>, and return 0;
2223 * otherwise, return -1 and leave *<b>result</b> and <b>cmdline_result</b>
2224 * alone. */
2226 config_parse_commandline(int argc, char **argv, int ignore_errors,
2227 config_line_t **result,
2228 config_line_t **cmdline_result)
2230 config_line_t *param = NULL;
2232 config_line_t *front = NULL;
2233 config_line_t **new = &front;
2235 config_line_t *front_cmdline = NULL;
2236 config_line_t **new_cmdline = &front_cmdline;
2238 char *s, *arg;
2239 int i = 1;
2241 while (i < argc) {
2242 unsigned command = CONFIG_LINE_NORMAL;
2243 takes_argument_t want_arg = ARGUMENT_NECESSARY;
2244 int is_cmdline = 0;
2245 int j;
2247 for (j = 0; CMDLINE_ONLY_OPTIONS[j].name != NULL; ++j) {
2248 if (!strcmp(argv[i], CMDLINE_ONLY_OPTIONS[j].name)) {
2249 is_cmdline = 1;
2250 want_arg = CMDLINE_ONLY_OPTIONS[j].takes_argument;
2251 break;
2255 s = argv[i];
2257 /* Each keyword may be prefixed with one or two dashes. */
2258 if (*s == '-')
2259 s++;
2260 if (*s == '-')
2261 s++;
2262 /* Figure out the command, if any. */
2263 if (*s == '+') {
2264 s++;
2265 command = CONFIG_LINE_APPEND;
2266 } else if (*s == '/') {
2267 s++;
2268 command = CONFIG_LINE_CLEAR;
2269 /* A 'clear' command has no argument. */
2270 want_arg = 0;
2273 const int is_last = (i == argc-1);
2275 if (want_arg == ARGUMENT_NECESSARY && is_last) {
2276 if (ignore_errors) {
2277 arg = tor_strdup("");
2278 } else {
2279 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
2280 argv[i]);
2281 config_free_lines(front);
2282 config_free_lines(front_cmdline);
2283 return -1;
2285 } else if (want_arg == ARGUMENT_OPTIONAL && is_last) {
2286 arg = tor_strdup("");
2287 } else {
2288 arg = (want_arg != TAKES_NO_ARGUMENT) ? tor_strdup(argv[i+1]) :
2289 tor_strdup("");
2292 param = tor_malloc_zero(sizeof(config_line_t));
2293 param->key = is_cmdline ? tor_strdup(argv[i]) :
2294 tor_strdup(config_expand_abbrev(&options_format, s, 1, 1));
2295 param->value = arg;
2296 param->command = command;
2297 param->next = NULL;
2298 log_debug(LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
2299 param->key, param->value);
2301 if (is_cmdline) {
2302 *new_cmdline = param;
2303 new_cmdline = &((*new_cmdline)->next);
2304 } else {
2305 *new = param;
2306 new = &((*new)->next);
2309 i += want_arg ? 2 : 1;
2311 *cmdline_result = front_cmdline;
2312 *result = front;
2313 return 0;
2316 /** Return true iff key is a valid configuration option. */
2318 option_is_recognized(const char *key)
2320 const config_var_t *var = config_find_option(&options_format, key);
2321 return (var != NULL);
2324 /** Return the canonical name of a configuration option, or NULL
2325 * if no such option exists. */
2326 const char *
2327 option_get_canonical_name(const char *key)
2329 const config_var_t *var = config_find_option(&options_format, key);
2330 return var ? var->name : NULL;
2333 /** Return a canonical list of the options assigned for key.
2335 config_line_t *
2336 option_get_assignment(const or_options_t *options, const char *key)
2338 return config_get_assigned_option(&options_format, options, key, 1);
2341 /** Try assigning <b>list</b> to the global options. You do this by duping
2342 * options, assigning list to the new one, then validating it. If it's
2343 * ok, then throw out the old one and stick with the new one. Else,
2344 * revert to old and return failure. Return SETOPT_OK on success, or
2345 * a setopt_err_t on failure.
2347 * If not success, point *<b>msg</b> to a newly allocated string describing
2348 * what went wrong.
2350 setopt_err_t
2351 options_trial_assign(config_line_t *list, unsigned flags, char **msg)
2353 int r;
2354 or_options_t *trial_options = config_dup(&options_format, get_options());
2356 if ((r=config_assign(&options_format, trial_options,
2357 list, flags, msg)) < 0) {
2358 or_options_free(trial_options);
2359 return r;
2362 setopt_err_t rv;
2363 or_options_t *cur_options = get_options_mutable();
2365 in_option_validation = 1;
2367 if (options_validate(cur_options, trial_options,
2368 global_default_options, 1, msg) < 0) {
2369 or_options_free(trial_options);
2370 rv = SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2371 goto done;
2374 if (options_transition_allowed(cur_options, trial_options, msg) < 0) {
2375 or_options_free(trial_options);
2376 rv = SETOPT_ERR_TRANSITION;
2377 goto done;
2379 in_option_validation = 0;
2381 if (set_options(trial_options, msg)<0) {
2382 or_options_free(trial_options);
2383 rv = SETOPT_ERR_SETTING;
2384 goto done;
2387 /* we liked it. put it in place. */
2388 rv = SETOPT_OK;
2389 done:
2390 in_option_validation = 0;
2391 return rv;
2394 /** Print a usage message for tor. */
2395 static void
2396 print_usage(void)
2398 printf(
2399 "Copyright (c) 2001-2004, Roger Dingledine\n"
2400 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2401 "Copyright (c) 2007-2017, The Tor Project, Inc.\n\n"
2402 "tor -f <torrc> [args]\n"
2403 "See man page for options, or https://www.torproject.org/ for "
2404 "documentation.\n");
2407 /** Print all non-obsolete torrc options. */
2408 static void
2409 list_torrc_options(void)
2411 int i;
2412 for (i = 0; option_vars_[i].name; ++i) {
2413 const config_var_t *var = &option_vars_[i];
2414 if (var->type == CONFIG_TYPE_OBSOLETE ||
2415 var->type == CONFIG_TYPE_LINELIST_V)
2416 continue;
2417 printf("%s\n", var->name);
2421 /** Print all deprecated but non-obsolete torrc options. */
2422 static void
2423 list_deprecated_options(void)
2425 const config_deprecation_t *d;
2426 for (d = option_deprecation_notes_; d->name; ++d) {
2427 printf("%s\n", d->name);
2431 /** Last value actually set by resolve_my_address. */
2432 static uint32_t last_resolved_addr = 0;
2434 /** Accessor for last_resolved_addr from outside this file. */
2435 uint32_t
2436 get_last_resolved_addr(void)
2438 return last_resolved_addr;
2441 /** Reset last_resolved_addr from outside this file. */
2442 void
2443 reset_last_resolved_addr(void)
2445 last_resolved_addr = 0;
2448 /* Return true if <b>options</b> is using the default authorities, and false
2449 * if any authority-related option has been overridden. */
2451 using_default_dir_authorities(const or_options_t *options)
2453 return (!options->DirAuthorities && !options->AlternateDirAuthority);
2457 * Attempt getting our non-local (as judged by tor_addr_is_internal()
2458 * function) IP address using following techniques, listed in
2459 * order from best (most desirable, try first) to worst (least
2460 * desirable, try if everything else fails).
2462 * First, attempt using <b>options-\>Address</b> to get our
2463 * non-local IP address.
2465 * If <b>options-\>Address</b> represents a non-local IP address,
2466 * consider it ours.
2468 * If <b>options-\>Address</b> is a DNS name that resolves to
2469 * a non-local IP address, consider this IP address ours.
2471 * If <b>options-\>Address</b> is NULL, fall back to getting local
2472 * hostname and using it in above-described ways to try and
2473 * get our IP address.
2475 * In case local hostname cannot be resolved to a non-local IP
2476 * address, try getting an IP address of network interface
2477 * in hopes it will be non-local one.
2479 * Fail if one or more of the following is true:
2480 * - DNS name in <b>options-\>Address</b> cannot be resolved.
2481 * - <b>options-\>Address</b> is a local host address.
2482 * - Attempt at getting local hostname fails.
2483 * - Attempt at getting network interface address fails.
2485 * Return 0 if all is well, or -1 if we can't find a suitable
2486 * public IP address.
2488 * If we are returning 0:
2489 * - Put our public IP address (in host order) into *<b>addr_out</b>.
2490 * - If <b>method_out</b> is non-NULL, set *<b>method_out</b> to a static
2491 * string describing how we arrived at our answer.
2492 * - "CONFIGURED" - parsed from IP address string in
2493 * <b>options-\>Address</b>
2494 * - "RESOLVED" - resolved from DNS name in <b>options-\>Address</b>
2495 * - "GETHOSTNAME" - resolved from a local hostname.
2496 * - "INTERFACE" - retrieved from a network interface.
2497 * - If <b>hostname_out</b> is non-NULL, and we resolved a hostname to
2498 * get our address, set *<b>hostname_out</b> to a newly allocated string
2499 * holding that hostname. (If we didn't get our address by resolving a
2500 * hostname, set *<b>hostname_out</b> to NULL.)
2502 * XXXX ipv6
2505 resolve_my_address(int warn_severity, const or_options_t *options,
2506 uint32_t *addr_out,
2507 const char **method_out, char **hostname_out)
2509 struct in_addr in;
2510 uint32_t addr; /* host order */
2511 char hostname[256];
2512 const char *method_used;
2513 const char *hostname_used;
2514 int explicit_ip=1;
2515 int explicit_hostname=1;
2516 int from_interface=0;
2517 char *addr_string = NULL;
2518 const char *address = options->Address;
2519 int notice_severity = warn_severity <= LOG_NOTICE ?
2520 LOG_NOTICE : warn_severity;
2522 tor_addr_t myaddr;
2523 tor_assert(addr_out);
2526 * Step one: Fill in 'hostname' to be our best guess.
2529 if (address && *address) {
2530 strlcpy(hostname, address, sizeof(hostname));
2531 } else { /* then we need to guess our address */
2532 explicit_ip = 0; /* it's implicit */
2533 explicit_hostname = 0; /* it's implicit */
2535 if (tor_gethostname(hostname, sizeof(hostname)) < 0) {
2536 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2537 return -1;
2539 log_debug(LD_CONFIG, "Guessed local host name as '%s'", hostname);
2543 * Step two: Now that we know 'hostname', parse it or resolve it. If
2544 * it doesn't parse or resolve, look at the interface address. Set 'addr'
2545 * to be our (host-order) 32-bit answer.
2548 if (tor_inet_aton(hostname, &in) == 0) {
2549 /* then we have to resolve it */
2550 explicit_ip = 0;
2551 if (tor_lookup_hostname(hostname, &addr)) { /* failed to resolve */
2552 uint32_t interface_ip; /* host order */
2554 if (explicit_hostname) {
2555 log_fn(warn_severity, LD_CONFIG,
2556 "Could not resolve local Address '%s'. Failing.", hostname);
2557 return -1;
2559 log_fn(notice_severity, LD_CONFIG,
2560 "Could not resolve guessed local hostname '%s'. "
2561 "Trying something else.", hostname);
2562 if (get_interface_address(warn_severity, &interface_ip)) {
2563 log_fn(warn_severity, LD_CONFIG,
2564 "Could not get local interface IP address. Failing.");
2565 return -1;
2567 from_interface = 1;
2568 addr = interface_ip;
2569 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2570 "local interface. Using that.", fmt_addr32(addr));
2571 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2572 } else { /* resolved hostname into addr */
2573 tor_addr_from_ipv4h(&myaddr, addr);
2575 if (!explicit_hostname &&
2576 tor_addr_is_internal(&myaddr, 0)) {
2577 tor_addr_t interface_ip;
2579 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2580 "resolves to a private IP address (%s). Trying something "
2581 "else.", hostname, fmt_addr32(addr));
2583 if (get_interface_address6(warn_severity, AF_INET, &interface_ip)<0) {
2584 log_fn(warn_severity, LD_CONFIG,
2585 "Could not get local interface IP address. Too bad.");
2586 } else if (tor_addr_is_internal(&interface_ip, 0)) {
2587 log_fn(notice_severity, LD_CONFIG,
2588 "Interface IP address '%s' is a private address too. "
2589 "Ignoring.", fmt_addr(&interface_ip));
2590 } else {
2591 from_interface = 1;
2592 addr = tor_addr_to_ipv4h(&interface_ip);
2593 log_fn(notice_severity, LD_CONFIG,
2594 "Learned IP address '%s' for local interface."
2595 " Using that.", fmt_addr32(addr));
2596 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2600 } else {
2601 addr = ntohl(in.s_addr); /* set addr so that addr_string is not
2602 * illformed */
2606 * Step three: Check whether 'addr' is an internal IP address, and error
2607 * out if it is and we don't want that.
2610 tor_addr_from_ipv4h(&myaddr,addr);
2612 addr_string = tor_dup_ip(addr);
2613 if (tor_addr_is_internal(&myaddr, 0)) {
2614 /* make sure we're ok with publishing an internal IP */
2615 if (using_default_dir_authorities(options)) {
2616 /* if they are using the default authorities, disallow internal IPs
2617 * always. */
2618 log_fn(warn_severity, LD_CONFIG,
2619 "Address '%s' resolves to private IP address '%s'. "
2620 "Tor servers that use the default DirAuthorities must have "
2621 "public IP addresses.", hostname, addr_string);
2622 tor_free(addr_string);
2623 return -1;
2625 if (!explicit_ip) {
2626 /* even if they've set their own authorities, require an explicit IP if
2627 * they're using an internal address. */
2628 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2629 "IP address '%s'. Please set the Address config option to be "
2630 "the IP address you want to use.", hostname, addr_string);
2631 tor_free(addr_string);
2632 return -1;
2637 * Step four: We have a winner! 'addr' is our answer for sure, and
2638 * 'addr_string' is its string form. Fill out the various fields to
2639 * say how we decided it.
2642 log_debug(LD_CONFIG, "Resolved Address to '%s'.", addr_string);
2644 if (explicit_ip) {
2645 method_used = "CONFIGURED";
2646 hostname_used = NULL;
2647 } else if (explicit_hostname) {
2648 method_used = "RESOLVED";
2649 hostname_used = hostname;
2650 } else if (from_interface) {
2651 method_used = "INTERFACE";
2652 hostname_used = NULL;
2653 } else {
2654 method_used = "GETHOSTNAME";
2655 hostname_used = hostname;
2658 *addr_out = addr;
2659 if (method_out)
2660 *method_out = method_used;
2661 if (hostname_out)
2662 *hostname_out = hostname_used ? tor_strdup(hostname_used) : NULL;
2665 * Step five: Check if the answer has changed since last time (or if
2666 * there was no last time), and if so call various functions to keep
2667 * us up-to-date.
2670 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2671 /* Leave this as a notice, regardless of the requested severity,
2672 * at least until dynamic IP address support becomes bulletproof. */
2673 log_notice(LD_NET,
2674 "Your IP address seems to have changed to %s "
2675 "(METHOD=%s%s%s). Updating.",
2676 addr_string, method_used,
2677 hostname_used ? " HOSTNAME=" : "",
2678 hostname_used ? hostname_used : "");
2679 ip_address_changed(0);
2682 if (last_resolved_addr != *addr_out) {
2683 control_event_server_status(LOG_NOTICE,
2684 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s%s%s",
2685 addr_string, method_used,
2686 hostname_used ? " HOSTNAME=" : "",
2687 hostname_used ? hostname_used : "");
2689 last_resolved_addr = *addr_out;
2692 * And finally, clean up and return success.
2695 tor_free(addr_string);
2696 return 0;
2699 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2700 * on a private network.
2702 MOCK_IMPL(int,
2703 is_local_addr, (const tor_addr_t *addr))
2705 if (tor_addr_is_internal(addr, 0))
2706 return 1;
2707 /* Check whether ip is on the same /24 as we are. */
2708 if (get_options()->EnforceDistinctSubnets == 0)
2709 return 0;
2710 if (tor_addr_family(addr) == AF_INET) {
2711 uint32_t ip = tor_addr_to_ipv4h(addr);
2713 /* It's possible that this next check will hit before the first time
2714 * resolve_my_address actually succeeds. (For clients, it is likely that
2715 * resolve_my_address will never be called at all). In those cases,
2716 * last_resolved_addr will be 0, and so checking to see whether ip is on
2717 * the same /24 as last_resolved_addr will be the same as checking whether
2718 * it was on net 0, which is already done by tor_addr_is_internal.
2720 if ((last_resolved_addr & (uint32_t)0xffffff00ul)
2721 == (ip & (uint32_t)0xffffff00ul))
2722 return 1;
2724 return 0;
2727 /** Return a new empty or_options_t. Used for testing. */
2728 or_options_t *
2729 options_new(void)
2731 return config_new(&options_format);
2734 /** Set <b>options</b> to hold reasonable defaults for most options.
2735 * Each option defaults to zero. */
2736 void
2737 options_init(or_options_t *options)
2739 config_init(&options_format, options);
2742 /** Return a string containing a possible configuration file that would give
2743 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2744 * include options that are the same as Tor's defaults.
2746 char *
2747 options_dump(const or_options_t *options, int how_to_dump)
2749 const or_options_t *use_defaults;
2750 int minimal;
2751 switch (how_to_dump) {
2752 case OPTIONS_DUMP_MINIMAL:
2753 use_defaults = global_default_options;
2754 minimal = 1;
2755 break;
2756 case OPTIONS_DUMP_DEFAULTS:
2757 use_defaults = NULL;
2758 minimal = 1;
2759 break;
2760 case OPTIONS_DUMP_ALL:
2761 use_defaults = NULL;
2762 minimal = 0;
2763 break;
2764 default:
2765 log_warn(LD_BUG, "Bogus value for how_to_dump==%d", how_to_dump);
2766 return NULL;
2769 return config_dump(&options_format, use_defaults, options, minimal, 0);
2772 /** Return 0 if every element of sl is a string holding a decimal
2773 * representation of a port number, or if sl is NULL.
2774 * Otherwise set *msg and return -1. */
2775 static int
2776 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2778 int i;
2779 tor_assert(name);
2781 if (!sl)
2782 return 0;
2784 SMARTLIST_FOREACH(sl, const char *, cp,
2786 i = atoi(cp);
2787 if (i < 1 || i > 65535) {
2788 tor_asprintf(msg, "Port '%s' out of range in %s", cp, name);
2789 return -1;
2792 return 0;
2795 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2796 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2797 * Else return 0.
2799 static int
2800 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2802 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2803 /* This handles an understandable special case where somebody says "2gb"
2804 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2805 --*value;
2807 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2808 tor_asprintf(msg, "%s ("U64_FORMAT") must be at most %d",
2809 desc, U64_PRINTF_ARG(*value),
2810 ROUTER_MAX_DECLARED_BANDWIDTH);
2811 return -1;
2813 return 0;
2816 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2817 * and write it to <b>options</b>-\>PublishServerDescriptor_. Treat "1"
2818 * as "v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2819 * Treat "0" as "".
2820 * Return 0 on success or -1 if not a recognized authority type (in which
2821 * case the value of PublishServerDescriptor_ is undefined). */
2822 static int
2823 compute_publishserverdescriptor(or_options_t *options)
2825 smartlist_t *list = options->PublishServerDescriptor;
2826 dirinfo_type_t *auth = &options->PublishServerDescriptor_;
2827 *auth = NO_DIRINFO;
2828 if (!list) /* empty list, answer is none */
2829 return 0;
2830 SMARTLIST_FOREACH_BEGIN(list, const char *, string) {
2831 if (!strcasecmp(string, "v1"))
2832 log_warn(LD_CONFIG, "PublishServerDescriptor v1 has no effect, because "
2833 "there are no v1 directory authorities anymore.");
2834 else if (!strcmp(string, "1"))
2835 if (options->BridgeRelay)
2836 *auth |= BRIDGE_DIRINFO;
2837 else
2838 *auth |= V3_DIRINFO;
2839 else if (!strcasecmp(string, "v2"))
2840 log_warn(LD_CONFIG, "PublishServerDescriptor v2 has no effect, because "
2841 "there are no v2 directory authorities anymore.");
2842 else if (!strcasecmp(string, "v3"))
2843 *auth |= V3_DIRINFO;
2844 else if (!strcasecmp(string, "bridge"))
2845 *auth |= BRIDGE_DIRINFO;
2846 else if (!strcasecmp(string, "hidserv"))
2847 log_warn(LD_CONFIG,
2848 "PublishServerDescriptor hidserv is invalid. See "
2849 "PublishHidServDescriptors.");
2850 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2851 /* no authority */;
2852 else
2853 return -1;
2854 } SMARTLIST_FOREACH_END(string);
2855 return 0;
2858 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2859 * services can overload the directory system. */
2860 #define MIN_REND_POST_PERIOD (10*60)
2861 #define MIN_REND_POST_PERIOD_TESTING (5)
2863 /** Highest allowable value for CircuitsAvailableTimeout.
2864 * If this is too large, client connections will stay open for too long,
2865 * incurring extra padding overhead. */
2866 #define MAX_CIRCS_AVAILABLE_TIME (24*60*60)
2868 /** Highest allowable value for RendPostPeriod. */
2869 #define MAX_DIR_PERIOD ((7*24*60*60)/2)
2871 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2872 * will generate too many circuits and potentially overload the network. */
2873 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2875 /** Highest allowable value for MaxCircuitDirtiness: prevents time_t
2876 * overflows. */
2877 #define MAX_MAX_CIRCUIT_DIRTINESS (30*24*60*60)
2879 /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
2880 * will generate too many circuits and potentially overload the network. */
2881 #define MIN_CIRCUIT_STREAM_TIMEOUT 10
2883 /** Lowest recommended value for CircuitBuildTimeout; if it is set too low
2884 * and LearnCircuitBuildTimeout is off, the failure rate for circuit
2885 * construction may be very high. In that case, if it is set below this
2886 * threshold emit a warning.
2887 * */
2888 #define RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT (10)
2890 static int
2891 options_validate_cb(void *old_options, void *options, void *default_options,
2892 int from_setconf, char **msg)
2894 in_option_validation = 1;
2895 int rv = options_validate(old_options, options, default_options,
2896 from_setconf, msg);
2897 in_option_validation = 0;
2898 return rv;
2901 #define REJECT(arg) \
2902 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2903 #if defined(__GNUC__) && __GNUC__ <= 3
2904 #define COMPLAIN(args...) \
2905 STMT_BEGIN log_warn(LD_CONFIG, args); STMT_END
2906 #else
2907 #define COMPLAIN(args, ...) \
2908 STMT_BEGIN log_warn(LD_CONFIG, args, ##__VA_ARGS__); STMT_END
2909 #endif /* defined(__GNUC__) && __GNUC__ <= 3 */
2911 /** Log a warning message iff <b>filepath</b> is not absolute.
2912 * Warning message must contain option name <b>option</b> and
2913 * an absolute path that <b>filepath</b> will resolve to.
2915 * In case <b>filepath</b> is absolute, do nothing.
2917 * Return 1 if there were relative paths; 0 otherwise.
2919 static int
2920 warn_if_option_path_is_relative(const char *option,
2921 char *filepath)
2923 if (filepath && path_is_relative(filepath)) {
2924 char *abs_path = make_path_absolute(filepath);
2925 COMPLAIN("Path for %s (%s) is relative and will resolve to %s."
2926 " Is this what you wanted?", option, filepath, abs_path);
2927 tor_free(abs_path);
2928 return 1;
2930 return 0;
2933 /** Scan <b>options</b> for occurances of relative file/directory
2934 * path and log a warning whenever it is found.
2936 * Return 1 if there were relative paths; 0 otherwise.
2938 static int
2939 warn_about_relative_paths(or_options_t *options)
2941 tor_assert(options);
2942 int n = 0;
2944 n += warn_if_option_path_is_relative("CookieAuthFile",
2945 options->CookieAuthFile);
2946 n += warn_if_option_path_is_relative("ExtORPortCookieAuthFile",
2947 options->ExtORPortCookieAuthFile);
2948 n += warn_if_option_path_is_relative("DirPortFrontPage",
2949 options->DirPortFrontPage);
2950 n += warn_if_option_path_is_relative("V3BandwidthsFile",
2951 options->V3BandwidthsFile);
2952 n += warn_if_option_path_is_relative("ControlPortWriteToFile",
2953 options->ControlPortWriteToFile);
2954 n += warn_if_option_path_is_relative("GeoIPFile",options->GeoIPFile);
2955 n += warn_if_option_path_is_relative("GeoIPv6File",options->GeoIPv6File);
2956 n += warn_if_option_path_is_relative("Log",options->DebugLogFile);
2957 n += warn_if_option_path_is_relative("AccelDir",options->AccelDir);
2958 n += warn_if_option_path_is_relative("DataDirectory",options->DataDirectory);
2959 n += warn_if_option_path_is_relative("PidFile",options->PidFile);
2961 for (config_line_t *hs_line = options->RendConfigLines; hs_line;
2962 hs_line = hs_line->next) {
2963 if (!strcasecmp(hs_line->key, "HiddenServiceDir"))
2964 n += warn_if_option_path_is_relative("HiddenServiceDir",hs_line->value);
2966 return n != 0;
2969 /* Validate options related to the scheduler. From the Schedulers list, the
2970 * SchedulerTypes_ list is created with int values so once we select the
2971 * scheduler, which can happen anytime at runtime, we don't have to parse
2972 * strings and thus be quick.
2974 * Return 0 on success else -1 and msg is set with an error message. */
2975 static int
2976 options_validate_scheduler(or_options_t *options, char **msg)
2978 tor_assert(options);
2979 tor_assert(msg);
2981 if (!options->Schedulers || smartlist_len(options->Schedulers) == 0) {
2982 REJECT("Empty Schedulers list. Either remove the option so the defaults "
2983 "can be used or set at least one value.");
2985 /* Ok, we do have scheduler types, validate them. */
2986 options->SchedulerTypes_ = smartlist_new();
2987 SMARTLIST_FOREACH_BEGIN(options->Schedulers, const char *, type) {
2988 int *sched_type;
2989 if (!strcasecmp("KISTLite", type)) {
2990 sched_type = tor_malloc_zero(sizeof(int));
2991 *sched_type = SCHEDULER_KIST_LITE;
2992 smartlist_add(options->SchedulerTypes_, sched_type);
2993 } else if (!strcasecmp("KIST", type)) {
2994 sched_type = tor_malloc_zero(sizeof(int));
2995 *sched_type = SCHEDULER_KIST;
2996 smartlist_add(options->SchedulerTypes_, sched_type);
2997 } else if (!strcasecmp("Vanilla", type)) {
2998 sched_type = tor_malloc_zero(sizeof(int));
2999 *sched_type = SCHEDULER_VANILLA;
3000 smartlist_add(options->SchedulerTypes_, sched_type);
3001 } else {
3002 tor_asprintf(msg, "Unknown type %s in option Schedulers. "
3003 "Possible values are KIST, KISTLite and Vanilla.",
3004 escaped(type));
3005 return -1;
3007 } SMARTLIST_FOREACH_END(type);
3009 if (options->KISTSockBufSizeFactor < 0) {
3010 REJECT("KISTSockBufSizeFactor must be at least 0");
3013 /* Don't need to validate that the Interval is less than anything because
3014 * zero is valid and all negative values are valid. */
3015 if (options->KISTSchedRunInterval > KIST_SCHED_RUN_INTERVAL_MAX) {
3016 tor_asprintf(msg, "KISTSchedRunInterval must not be more than %d (ms)",
3017 KIST_SCHED_RUN_INTERVAL_MAX);
3018 return -1;
3021 return 0;
3024 /* Validate options related to single onion services.
3025 * Modifies some options that are incompatible with single onion services.
3026 * On failure returns -1, and sets *msg to an error string.
3027 * Returns 0 on success. */
3028 STATIC int
3029 options_validate_single_onion(or_options_t *options, char **msg)
3031 /* The two single onion service options must have matching values. */
3032 if (options->HiddenServiceSingleHopMode &&
3033 !options->HiddenServiceNonAnonymousMode) {
3034 REJECT("HiddenServiceSingleHopMode does not provide any server anonymity. "
3035 "It must be used with HiddenServiceNonAnonymousMode set to 1.");
3037 if (options->HiddenServiceNonAnonymousMode &&
3038 !options->HiddenServiceSingleHopMode) {
3039 REJECT("HiddenServiceNonAnonymousMode does not provide any server "
3040 "anonymity. It must be used with HiddenServiceSingleHopMode set to "
3041 "1.");
3044 /* Now that we've checked that the two options are consistent, we can safely
3045 * call the rend_service_* functions that abstract these options. */
3047 /* If you run an anonymous client with an active Single Onion service, the
3048 * client loses anonymity. */
3049 const int client_port_set = (options->SocksPort_set ||
3050 options->TransPort_set ||
3051 options->NATDPort_set ||
3052 options->DNSPort_set ||
3053 options->HTTPTunnelPort_set);
3054 if (rend_service_non_anonymous_mode_enabled(options) && client_port_set &&
3055 !options->Tor2webMode) {
3056 REJECT("HiddenServiceNonAnonymousMode is incompatible with using Tor as "
3057 "an anonymous client. Please set Socks/Trans/NATD/DNSPort to 0, or "
3058 "revert HiddenServiceNonAnonymousMode to 0.");
3061 /* If you run a hidden service in non-anonymous mode, the hidden service
3062 * loses anonymity, even if SOCKSPort / Tor2web mode isn't used. */
3063 if (!rend_service_non_anonymous_mode_enabled(options) &&
3064 options->RendConfigLines && options->Tor2webMode) {
3065 REJECT("Non-anonymous (Tor2web) mode is incompatible with using Tor as a "
3066 "hidden service. Please remove all HiddenServiceDir lines, or use "
3067 "a version of tor compiled without --enable-tor2web-mode, or use "
3068 "HiddenServiceNonAnonymousMode.");
3071 if (rend_service_allow_non_anonymous_connection(options)
3072 && options->UseEntryGuards) {
3073 /* Single Onion services only use entry guards when uploading descriptors;
3074 * all other connections are one-hop. Further, Single Onions causes the
3075 * hidden service code to do things which break the path bias
3076 * detector, and it's far easier to turn off entry guards (and
3077 * thus the path bias detector with it) than to figure out how to
3078 * make path bias compatible with single onions.
3080 log_notice(LD_CONFIG,
3081 "HiddenServiceSingleHopMode is enabled; disabling "
3082 "UseEntryGuards.");
3083 options->UseEntryGuards = 0;
3086 return 0;
3089 /** Return 0 if every setting in <b>options</b> is reasonable, is a
3090 * permissible transition from <b>old_options</b>, and none of the
3091 * testing-only settings differ from <b>default_options</b> unless in
3092 * testing mode. Else return -1. Should have no side effects, except for
3093 * normalizing the contents of <b>options</b>.
3095 * On error, tor_strdup an error explanation into *<b>msg</b>.
3097 * XXX
3098 * If <b>from_setconf</b>, we were called by the controller, and our
3099 * Log line should stay empty. If it's 0, then give us a default log
3100 * if there are no logs defined.
3102 STATIC int
3103 options_validate(or_options_t *old_options, or_options_t *options,
3104 or_options_t *default_options, int from_setconf, char **msg)
3106 int i;
3107 config_line_t *cl;
3108 const char *uname = get_uname();
3109 int n_ports=0;
3110 int world_writable_control_socket=0;
3112 tor_assert(msg);
3113 *msg = NULL;
3115 if (parse_ports(options, 1, msg, &n_ports,
3116 &world_writable_control_socket) < 0)
3117 return -1;
3119 /* Set UseEntryGuards from the configured value, before we check it below.
3120 * We change UseEntryGuards when it's incompatible with other options,
3121 * but leave UseEntryGuards_option with the original value.
3122 * Always use the value of UseEntryGuards, not UseEntryGuards_option. */
3123 options->UseEntryGuards = options->UseEntryGuards_option;
3125 if (warn_about_relative_paths(options) && options->RunAsDaemon) {
3126 REJECT("You have specified at least one relative path (see above) "
3127 "with the RunAsDaemon option. RunAsDaemon is not compatible "
3128 "with relative paths.");
3131 if (server_mode(options) &&
3132 (!strcmpstart(uname, "Windows 95") ||
3133 !strcmpstart(uname, "Windows 98") ||
3134 !strcmpstart(uname, "Windows Me"))) {
3135 log_warn(LD_CONFIG, "Tor is running as a server, but you are "
3136 "running %s; this probably won't work. See "
3137 "https://www.torproject.org/docs/faq.html#BestOSForRelay "
3138 "for details.", uname);
3141 if (parse_outbound_addresses(options, 1, msg) < 0)
3142 return -1;
3144 if (validate_data_directory(options)<0)
3145 REJECT("Invalid DataDirectory");
3147 if (options->Nickname == NULL) {
3148 if (server_mode(options)) {
3149 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
3151 } else {
3152 if (!is_legal_nickname(options->Nickname)) {
3153 tor_asprintf(msg,
3154 "Nickname '%s', nicknames must be between 1 and 19 characters "
3155 "inclusive, and must contain only the characters [a-zA-Z0-9].",
3156 options->Nickname);
3157 return -1;
3161 if (server_mode(options) && !options->ContactInfo)
3162 log_notice(LD_CONFIG, "Your ContactInfo config option is not set. "
3163 "Please consider setting it, so we can contact you if your server is "
3164 "misconfigured or something else goes wrong.");
3166 /* Special case on first boot if no Log options are given. */
3167 if (!options->Logs && !options->RunAsDaemon && !from_setconf) {
3168 if (quiet_level == 0)
3169 config_line_append(&options->Logs, "Log", "notice stdout");
3170 else if (quiet_level == 1)
3171 config_line_append(&options->Logs, "Log", "warn stdout");
3174 /* Validate the tor_log(s) */
3175 if (options_init_logs(old_options, options, 1)<0)
3176 REJECT("Failed to validate Log options. See logs for details.");
3178 if (authdir_mode(options)) {
3179 /* confirm that our address isn't broken, so we can complain now */
3180 uint32_t tmp;
3181 if (resolve_my_address(LOG_WARN, options, &tmp, NULL, NULL) < 0)
3182 REJECT("Failed to resolve/guess local address. See logs for details.");
3185 if (server_mode(options) && options->RendConfigLines)
3186 log_warn(LD_CONFIG,
3187 "Tor is currently configured as a relay and a hidden service. "
3188 "That's not very secure: you should probably run your hidden service "
3189 "in a separate Tor process, at least -- see "
3190 "https://trac.torproject.org/8742");
3192 /* XXXX require that the only port not be DirPort? */
3193 /* XXXX require that at least one port be listened-upon. */
3194 if (n_ports == 0 && !options->RendConfigLines)
3195 log_warn(LD_CONFIG,
3196 "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
3197 "undefined, and there aren't any hidden services configured. "
3198 "Tor will still run, but probably won't do anything.");
3200 options->TransProxyType_parsed = TPT_DEFAULT;
3201 #ifdef USE_TRANSPARENT
3202 if (options->TransProxyType) {
3203 if (!strcasecmp(options->TransProxyType, "default")) {
3204 options->TransProxyType_parsed = TPT_DEFAULT;
3205 } else if (!strcasecmp(options->TransProxyType, "pf-divert")) {
3206 #if !defined(OpenBSD) && !defined( DARWIN )
3207 /* Later versions of OS X have pf */
3208 REJECT("pf-divert is a OpenBSD-specific "
3209 "and OS X/Darwin-specific feature.");
3210 #else
3211 options->TransProxyType_parsed = TPT_PF_DIVERT;
3212 #endif /* !defined(OpenBSD) && !defined( DARWIN ) */
3213 } else if (!strcasecmp(options->TransProxyType, "tproxy")) {
3214 #if !defined(__linux__)
3215 REJECT("TPROXY is a Linux-specific feature.");
3216 #else
3217 options->TransProxyType_parsed = TPT_TPROXY;
3218 #endif
3219 } else if (!strcasecmp(options->TransProxyType, "ipfw")) {
3220 #ifndef KERNEL_MAY_SUPPORT_IPFW
3221 /* Earlier versions of OS X have ipfw */
3222 REJECT("ipfw is a FreeBSD-specific "
3223 "and OS X/Darwin-specific feature.");
3224 #else
3225 options->TransProxyType_parsed = TPT_IPFW;
3226 #endif /* !defined(KERNEL_MAY_SUPPORT_IPFW) */
3227 } else {
3228 REJECT("Unrecognized value for TransProxyType");
3231 if (strcasecmp(options->TransProxyType, "default") &&
3232 !options->TransPort_set) {
3233 REJECT("Cannot use TransProxyType without any valid TransPort.");
3236 #else /* !(defined(USE_TRANSPARENT)) */
3237 if (options->TransPort_set)
3238 REJECT("TransPort is disabled in this build.");
3239 #endif /* defined(USE_TRANSPARENT) */
3241 if (options->TokenBucketRefillInterval <= 0
3242 || options->TokenBucketRefillInterval > 1000) {
3243 REJECT("TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
3246 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3247 options->ExcludeExitNodesUnion_ = routerset_new();
3248 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeExitNodes);
3249 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeNodes);
3252 if (options->NodeFamilies) {
3253 options->NodeFamilySets = smartlist_new();
3254 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3255 routerset_t *rs = routerset_new();
3256 if (routerset_parse(rs, cl->value, cl->key) == 0) {
3257 smartlist_add(options->NodeFamilySets, rs);
3258 } else {
3259 routerset_free(rs);
3264 if (options->ExcludeNodes && options->StrictNodes) {
3265 COMPLAIN("You have asked to exclude certain relays from all positions "
3266 "in your circuits. Expect hidden services and other Tor "
3267 "features to be broken in unpredictable ways.");
3270 for (cl = options->RecommendedPackages; cl; cl = cl->next) {
3271 if (! validate_recommended_package_line(cl->value)) {
3272 log_warn(LD_CONFIG, "Invalid RecommendedPackage line %s will be ignored",
3273 escaped(cl->value));
3277 if (options->AuthoritativeDir) {
3278 if (!options->ContactInfo && !options->TestingTorNetwork)
3279 REJECT("Authoritative directory servers must set ContactInfo");
3280 if (!options->RecommendedClientVersions)
3281 options->RecommendedClientVersions =
3282 config_lines_dup(options->RecommendedVersions);
3283 if (!options->RecommendedServerVersions)
3284 options->RecommendedServerVersions =
3285 config_lines_dup(options->RecommendedVersions);
3286 if (options->VersioningAuthoritativeDir &&
3287 (!options->RecommendedClientVersions ||
3288 !options->RecommendedServerVersions))
3289 REJECT("Versioning authoritative dir servers must set "
3290 "Recommended*Versions.");
3291 if (options->UseEntryGuards) {
3292 log_info(LD_CONFIG, "Authoritative directory servers can't set "
3293 "UseEntryGuards. Disabling.");
3294 options->UseEntryGuards = 0;
3296 if (!options->DownloadExtraInfo && authdir_mode_v3(options)) {
3297 log_info(LD_CONFIG, "Authoritative directories always try to download "
3298 "extra-info documents. Setting DownloadExtraInfo.");
3299 options->DownloadExtraInfo = 1;
3301 if (!(options->BridgeAuthoritativeDir ||
3302 options->V3AuthoritativeDir))
3303 REJECT("AuthoritativeDir is set, but none of "
3304 "(Bridge/V3)AuthoritativeDir is set.");
3305 /* If we have a v3bandwidthsfile and it's broken, complain on startup */
3306 if (options->V3BandwidthsFile && !old_options) {
3307 dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
3309 /* same for guardfraction file */
3310 if (options->GuardfractionFile && !old_options) {
3311 dirserv_read_guardfraction_file(options->GuardfractionFile, NULL);
3315 if (options->AuthoritativeDir && !options->DirPort_set)
3316 REJECT("Running as authoritative directory, but no DirPort set.");
3318 if (options->AuthoritativeDir && !options->ORPort_set)
3319 REJECT("Running as authoritative directory, but no ORPort set.");
3321 if (options->AuthoritativeDir && options->ClientOnly)
3322 REJECT("Running as authoritative directory, but ClientOnly also set.");
3324 if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
3325 REJECT("FetchDirInfoExtraEarly requires that you also set "
3326 "FetchDirInfoEarly");
3328 if (options->ConnLimit <= 0) {
3329 tor_asprintf(msg,
3330 "ConnLimit must be greater than 0, but was set to %d",
3331 options->ConnLimit);
3332 return -1;
3335 if (options->PathsNeededToBuildCircuits >= 0.0) {
3336 if (options->PathsNeededToBuildCircuits < 0.25) {
3337 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too low. Increasing "
3338 "to 0.25");
3339 options->PathsNeededToBuildCircuits = 0.25;
3340 } else if (options->PathsNeededToBuildCircuits > 0.95) {
3341 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too high. Decreasing "
3342 "to 0.95");
3343 options->PathsNeededToBuildCircuits = 0.95;
3347 if (options->MaxClientCircuitsPending <= 0 ||
3348 options->MaxClientCircuitsPending > MAX_MAX_CLIENT_CIRCUITS_PENDING) {
3349 tor_asprintf(msg,
3350 "MaxClientCircuitsPending must be between 1 and %d, but "
3351 "was set to %d", MAX_MAX_CLIENT_CIRCUITS_PENDING,
3352 options->MaxClientCircuitsPending);
3353 return -1;
3356 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3357 return -1;
3359 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3360 return -1;
3362 if (validate_ports_csv(options->RejectPlaintextPorts,
3363 "RejectPlaintextPorts", msg) < 0)
3364 return -1;
3366 if (validate_ports_csv(options->WarnPlaintextPorts,
3367 "WarnPlaintextPorts", msg) < 0)
3368 return -1;
3370 if (options->FascistFirewall && !options->ReachableAddresses) {
3371 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3372 /* We already have firewall ports set, so migrate them to
3373 * ReachableAddresses, which will set ReachableORAddresses and
3374 * ReachableDirAddresses if they aren't set explicitly. */
3375 smartlist_t *instead = smartlist_new();
3376 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3377 new_line->key = tor_strdup("ReachableAddresses");
3378 /* If we're configured with the old format, we need to prepend some
3379 * open ports. */
3380 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3382 int p = atoi(portno);
3383 if (p<0) continue;
3384 smartlist_add_asprintf(instead, "*:%d", p);
3386 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3387 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3388 log_notice(LD_CONFIG,
3389 "Converting FascistFirewall and FirewallPorts "
3390 "config options to new format: \"ReachableAddresses %s\"",
3391 new_line->value);
3392 options->ReachableAddresses = new_line;
3393 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3394 smartlist_free(instead);
3395 } else {
3396 /* We do not have FirewallPorts set, so add 80 to
3397 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3398 if (!options->ReachableDirAddresses) {
3399 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3400 new_line->key = tor_strdup("ReachableDirAddresses");
3401 new_line->value = tor_strdup("*:80");
3402 options->ReachableDirAddresses = new_line;
3403 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3404 "to new format: \"ReachableDirAddresses *:80\"");
3406 if (!options->ReachableORAddresses) {
3407 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3408 new_line->key = tor_strdup("ReachableORAddresses");
3409 new_line->value = tor_strdup("*:443");
3410 options->ReachableORAddresses = new_line;
3411 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3412 "to new format: \"ReachableORAddresses *:443\"");
3417 /* Terminate Reachable*Addresses with reject *
3419 for (i=0; i<3; i++) {
3420 config_line_t **linep =
3421 (i==0) ? &options->ReachableAddresses :
3422 (i==1) ? &options->ReachableORAddresses :
3423 &options->ReachableDirAddresses;
3424 if (!*linep)
3425 continue;
3426 /* We need to end with a reject *:*, not an implicit accept *:* */
3427 for (;;) {
3428 linep = &((*linep)->next);
3429 if (!*linep) {
3430 *linep = tor_malloc_zero(sizeof(config_line_t));
3431 (*linep)->key = tor_strdup(
3432 (i==0) ? "ReachableAddresses" :
3433 (i==1) ? "ReachableORAddresses" :
3434 "ReachableDirAddresses");
3435 (*linep)->value = tor_strdup("reject *:*");
3436 break;
3441 if ((options->ReachableAddresses ||
3442 options->ReachableORAddresses ||
3443 options->ReachableDirAddresses ||
3444 options->ClientUseIPv4 == 0) &&
3445 server_mode(options))
3446 REJECT("Servers must be able to freely connect to the rest "
3447 "of the Internet, so they must not set Reachable*Addresses "
3448 "or FascistFirewall or FirewallPorts or ClientUseIPv4 0.");
3450 if (options->UseBridges &&
3451 server_mode(options))
3452 REJECT("Servers must be able to freely connect to the rest "
3453 "of the Internet, so they must not set UseBridges.");
3455 /* If both of these are set, we'll end up with funny behavior where we
3456 * demand enough entrynodes be up and running else we won't build
3457 * circuits, yet we never actually use them. */
3458 if (options->UseBridges && options->EntryNodes)
3459 REJECT("You cannot set both UseBridges and EntryNodes.");
3461 /* If we have UseBridges as 1 and UseEntryGuards as 0, we end up bypassing
3462 * the use of bridges */
3463 if (options->UseBridges && !options->UseEntryGuards)
3464 REJECT("Setting UseBridges requires also setting UseEntryGuards.");
3466 options->MaxMemInQueues =
3467 compute_real_max_mem_in_queues(options->MaxMemInQueues_raw,
3468 server_mode(options));
3469 options->MaxMemInQueues_low_threshold = (options->MaxMemInQueues / 4) * 3;
3471 if (!options->SafeLogging ||
3472 !strcasecmp(options->SafeLogging, "0")) {
3473 options->SafeLogging_ = SAFELOG_SCRUB_NONE;
3474 } else if (!strcasecmp(options->SafeLogging, "relay")) {
3475 options->SafeLogging_ = SAFELOG_SCRUB_RELAY;
3476 } else if (!strcasecmp(options->SafeLogging, "1")) {
3477 options->SafeLogging_ = SAFELOG_SCRUB_ALL;
3478 } else {
3479 tor_asprintf(msg,
3480 "Unrecognized value '%s' in SafeLogging",
3481 escaped(options->SafeLogging));
3482 return -1;
3485 if (compute_publishserverdescriptor(options) < 0) {
3486 tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
3487 return -1;
3490 if ((options->BridgeRelay
3491 || options->PublishServerDescriptor_ & BRIDGE_DIRINFO)
3492 && (options->PublishServerDescriptor_ & V3_DIRINFO)) {
3493 REJECT("Bridges are not supposed to publish router descriptors to the "
3494 "directory authorities. Please correct your "
3495 "PublishServerDescriptor line.");
3498 if (options->BridgeRelay && options->DirPort_set) {
3499 log_warn(LD_CONFIG, "Can't set a DirPort on a bridge relay; disabling "
3500 "DirPort");
3501 config_free_lines(options->DirPort_lines);
3502 options->DirPort_lines = NULL;
3503 options->DirPort_set = 0;
3506 if (server_mode(options) && options->ConnectionPadding != -1) {
3507 REJECT("Relays must use 'auto' for the ConnectionPadding setting.");
3510 if (server_mode(options) && options->ReducedConnectionPadding != 0) {
3511 REJECT("Relays cannot set ReducedConnectionPadding. ");
3514 if (options->BridgeDistribution) {
3515 if (!options->BridgeRelay) {
3516 REJECT("You set BridgeDistribution, but you didn't set BridgeRelay!");
3518 if (check_bridge_distribution_setting(options->BridgeDistribution) < 0) {
3519 REJECT("Invalid BridgeDistribution value.");
3523 if (options->MinUptimeHidServDirectoryV2 < 0) {
3524 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3525 "least 0 seconds. Changing to 0.");
3526 options->MinUptimeHidServDirectoryV2 = 0;
3529 const int min_rendpostperiod =
3530 options->TestingTorNetwork ?
3531 MIN_REND_POST_PERIOD_TESTING : MIN_REND_POST_PERIOD;
3532 if (options->RendPostPeriod < min_rendpostperiod) {
3533 log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
3534 "raising to %d seconds.", min_rendpostperiod);
3535 options->RendPostPeriod = min_rendpostperiod;
3538 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3539 log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3540 MAX_DIR_PERIOD);
3541 options->RendPostPeriod = MAX_DIR_PERIOD;
3544 /* Check the Single Onion Service options */
3545 if (options_validate_single_onion(options, msg) < 0)
3546 return -1;
3548 if (options->CircuitsAvailableTimeout > MAX_CIRCS_AVAILABLE_TIME) {
3549 // options_t is immutable for new code (the above code is older),
3550 // so just make the user fix the value themselves rather than
3551 // silently keep a shadow value lower than what they asked for.
3552 REJECT("CircuitsAvailableTimeout is too large. Max is 24 hours.");
3555 #ifdef ENABLE_TOR2WEB_MODE
3556 if (options->Tor2webMode && options->UseEntryGuards) {
3557 /* tor2web mode clients do not (and should not) use entry guards
3558 * in any meaningful way. Further, tor2web mode causes the hidden
3559 * service client code to do things which break the path bias
3560 * detector, and it's far easier to turn off entry guards (and
3561 * thus the path bias detector with it) than to figure out how to
3562 * make a piece of code which cannot possibly help tor2web mode
3563 * users compatible with tor2web mode.
3565 log_notice(LD_CONFIG,
3566 "Tor2WebMode is enabled; disabling UseEntryGuards.");
3567 options->UseEntryGuards = 0;
3569 #endif /* defined(ENABLE_TOR2WEB_MODE) */
3571 if (options->Tor2webRendezvousPoints && !options->Tor2webMode) {
3572 REJECT("Tor2webRendezvousPoints cannot be set without Tor2webMode.");
3575 if (options->EntryNodes && !options->UseEntryGuards) {
3576 REJECT("If EntryNodes is set, UseEntryGuards must be enabled.");
3579 if (!(options->UseEntryGuards) &&
3580 (options->RendConfigLines != NULL) &&
3581 !rend_service_allow_non_anonymous_connection(options)) {
3582 log_warn(LD_CONFIG,
3583 "UseEntryGuards is disabled, but you have configured one or more "
3584 "hidden services on this Tor instance. Your hidden services "
3585 "will be very easy to locate using a well-known attack -- see "
3586 "http://freehaven.net/anonbib/#hs-attack06 for details.");
3589 if (options->EntryNodes &&
3590 routerset_is_list(options->EntryNodes) &&
3591 (routerset_len(options->EntryNodes) == 1) &&
3592 (options->RendConfigLines != NULL)) {
3593 tor_asprintf(msg,
3594 "You have one single EntryNodes and at least one hidden service "
3595 "configured. This is bad because it's very easy to locate your "
3596 "entry guard which can then lead to the deanonymization of your "
3597 "hidden service -- for more details, see "
3598 "https://trac.torproject.org/projects/tor/ticket/14917. "
3599 "For this reason, the use of one EntryNodes with an hidden "
3600 "service is prohibited until a better solution is found.");
3601 return -1;
3604 /* Inform the hidden service operator that pinning EntryNodes can possibly
3605 * be harmful for the service anonymity. */
3606 if (options->EntryNodes &&
3607 routerset_is_list(options->EntryNodes) &&
3608 (options->RendConfigLines != NULL)) {
3609 log_warn(LD_CONFIG,
3610 "EntryNodes is set with multiple entries and at least one "
3611 "hidden service is configured. Pinning entry nodes can possibly "
3612 "be harmful to the service anonymity. Because of this, we "
3613 "recommend you either don't do that or make sure you know what "
3614 "you are doing. For more details, please look at "
3615 "https://trac.torproject.org/projects/tor/ticket/21155.");
3618 /* Single Onion Services: non-anonymous hidden services */
3619 if (rend_service_non_anonymous_mode_enabled(options)) {
3620 log_warn(LD_CONFIG,
3621 "HiddenServiceNonAnonymousMode is set. Every hidden service on "
3622 "this tor instance is NON-ANONYMOUS. If "
3623 "the HiddenServiceNonAnonymousMode option is changed, Tor will "
3624 "refuse to launch hidden services from the same directories, to "
3625 "protect your anonymity against config errors. This setting is "
3626 "for experimental use only.");
3629 if (!options->LearnCircuitBuildTimeout && options->CircuitBuildTimeout &&
3630 options->CircuitBuildTimeout < RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT) {
3631 log_warn(LD_CONFIG,
3632 "CircuitBuildTimeout is shorter (%d seconds) than the recommended "
3633 "minimum (%d seconds), and LearnCircuitBuildTimeout is disabled. "
3634 "If tor isn't working, raise this value or enable "
3635 "LearnCircuitBuildTimeout.",
3636 options->CircuitBuildTimeout,
3637 RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT );
3638 } else if (!options->LearnCircuitBuildTimeout &&
3639 !options->CircuitBuildTimeout) {
3640 int severity = LOG_NOTICE;
3641 /* Be a little quieter if we've deliberately disabled
3642 * LearnCircuitBuildTimeout. */
3643 if (circuit_build_times_disabled_(options, 1)) {
3644 severity = LOG_INFO;
3646 log_fn(severity, LD_CONFIG, "You disabled LearnCircuitBuildTimeout, but "
3647 "didn't specify a CircuitBuildTimeout. I'll pick a plausible "
3648 "default.");
3651 if (options->PathBiasNoticeRate > 1.0) {
3652 tor_asprintf(msg,
3653 "PathBiasNoticeRate is too high. "
3654 "It must be between 0 and 1.0");
3655 return -1;
3657 if (options->PathBiasWarnRate > 1.0) {
3658 tor_asprintf(msg,
3659 "PathBiasWarnRate is too high. "
3660 "It must be between 0 and 1.0");
3661 return -1;
3663 if (options->PathBiasExtremeRate > 1.0) {
3664 tor_asprintf(msg,
3665 "PathBiasExtremeRate is too high. "
3666 "It must be between 0 and 1.0");
3667 return -1;
3669 if (options->PathBiasNoticeUseRate > 1.0) {
3670 tor_asprintf(msg,
3671 "PathBiasNoticeUseRate is too high. "
3672 "It must be between 0 and 1.0");
3673 return -1;
3675 if (options->PathBiasExtremeUseRate > 1.0) {
3676 tor_asprintf(msg,
3677 "PathBiasExtremeUseRate is too high. "
3678 "It must be between 0 and 1.0");
3679 return -1;
3682 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3683 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3684 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3685 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3688 if (options->MaxCircuitDirtiness > MAX_MAX_CIRCUIT_DIRTINESS) {
3689 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too high; "
3690 "setting to %d days.", MAX_MAX_CIRCUIT_DIRTINESS/86400);
3691 options->MaxCircuitDirtiness = MAX_MAX_CIRCUIT_DIRTINESS;
3694 if (options->CircuitStreamTimeout &&
3695 options->CircuitStreamTimeout < MIN_CIRCUIT_STREAM_TIMEOUT) {
3696 log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
3697 "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
3698 options->CircuitStreamTimeout = MIN_CIRCUIT_STREAM_TIMEOUT;
3701 if (options->HeartbeatPeriod &&
3702 options->HeartbeatPeriod < MIN_HEARTBEAT_PERIOD) {
3703 log_warn(LD_CONFIG, "HeartbeatPeriod option is too short; "
3704 "raising to %d seconds.", MIN_HEARTBEAT_PERIOD);
3705 options->HeartbeatPeriod = MIN_HEARTBEAT_PERIOD;
3708 if (options->KeepalivePeriod < 1)
3709 REJECT("KeepalivePeriod option must be positive.");
3711 if (options->PortForwarding && options->Sandbox) {
3712 REJECT("PortForwarding is not compatible with Sandbox; at most one can "
3713 "be set");
3715 if (options->PortForwarding && options->NoExec) {
3716 COMPLAIN("Both PortForwarding and NoExec are set; PortForwarding will "
3717 "be ignored.");
3720 if (ensure_bandwidth_cap(&options->BandwidthRate,
3721 "BandwidthRate", msg) < 0)
3722 return -1;
3723 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3724 "BandwidthBurst", msg) < 0)
3725 return -1;
3726 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3727 "MaxAdvertisedBandwidth", msg) < 0)
3728 return -1;
3729 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3730 "RelayBandwidthRate", msg) < 0)
3731 return -1;
3732 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3733 "RelayBandwidthBurst", msg) < 0)
3734 return -1;
3735 if (ensure_bandwidth_cap(&options->PerConnBWRate,
3736 "PerConnBWRate", msg) < 0)
3737 return -1;
3738 if (ensure_bandwidth_cap(&options->PerConnBWBurst,
3739 "PerConnBWBurst", msg) < 0)
3740 return -1;
3741 if (ensure_bandwidth_cap(&options->AuthDirFastGuarantee,
3742 "AuthDirFastGuarantee", msg) < 0)
3743 return -1;
3744 if (ensure_bandwidth_cap(&options->AuthDirGuardBWGuarantee,
3745 "AuthDirGuardBWGuarantee", msg) < 0)
3746 return -1;
3748 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3749 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3750 if (options->RelayBandwidthBurst && !options->RelayBandwidthRate)
3751 options->RelayBandwidthRate = options->RelayBandwidthBurst;
3753 if (server_mode(options)) {
3754 const unsigned required_min_bw =
3755 public_server_mode(options) ?
3756 RELAY_REQUIRED_MIN_BANDWIDTH : BRIDGE_REQUIRED_MIN_BANDWIDTH;
3757 const char * const optbridge =
3758 public_server_mode(options) ? "" : "bridge ";
3759 if (options->BandwidthRate < required_min_bw) {
3760 tor_asprintf(msg,
3761 "BandwidthRate is set to %d bytes/second. "
3762 "For %sservers, it must be at least %u.",
3763 (int)options->BandwidthRate, optbridge,
3764 required_min_bw);
3765 return -1;
3766 } else if (options->MaxAdvertisedBandwidth <
3767 required_min_bw/2) {
3768 tor_asprintf(msg,
3769 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3770 "For %sservers, it must be at least %u.",
3771 (int)options->MaxAdvertisedBandwidth, optbridge,
3772 required_min_bw/2);
3773 return -1;
3775 if (options->RelayBandwidthRate &&
3776 options->RelayBandwidthRate < required_min_bw) {
3777 tor_asprintf(msg,
3778 "RelayBandwidthRate is set to %d bytes/second. "
3779 "For %sservers, it must be at least %u.",
3780 (int)options->RelayBandwidthRate, optbridge,
3781 required_min_bw);
3782 return -1;
3786 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3787 REJECT("RelayBandwidthBurst must be at least equal "
3788 "to RelayBandwidthRate.");
3790 if (options->BandwidthRate > options->BandwidthBurst)
3791 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3793 /* if they set relaybandwidth* really high but left bandwidth*
3794 * at the default, raise the defaults. */
3795 if (options->RelayBandwidthRate > options->BandwidthRate)
3796 options->BandwidthRate = options->RelayBandwidthRate;
3797 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3798 options->BandwidthBurst = options->RelayBandwidthBurst;
3800 if (accounting_parse_options(options, 1)<0)
3801 REJECT("Failed to parse accounting options. See logs for details.");
3803 if (options->AccountingMax) {
3804 if (options->RendConfigLines && server_mode(options)) {
3805 log_warn(LD_CONFIG, "Using accounting with a hidden service and an "
3806 "ORPort is risky: your hidden service(s) and your public "
3807 "address will all turn off at the same time, which may alert "
3808 "observers that they are being run by the same party.");
3809 } else if (config_count_key(options->RendConfigLines,
3810 "HiddenServiceDir") > 1) {
3811 log_warn(LD_CONFIG, "Using accounting with multiple hidden services is "
3812 "risky: they will all turn off at the same time, which may "
3813 "alert observers that they are being run by the same party.");
3817 options->AccountingRule = ACCT_MAX;
3818 if (options->AccountingRule_option) {
3819 if (!strcmp(options->AccountingRule_option, "sum"))
3820 options->AccountingRule = ACCT_SUM;
3821 else if (!strcmp(options->AccountingRule_option, "max"))
3822 options->AccountingRule = ACCT_MAX;
3823 else if (!strcmp(options->AccountingRule_option, "in"))
3824 options->AccountingRule = ACCT_IN;
3825 else if (!strcmp(options->AccountingRule_option, "out"))
3826 options->AccountingRule = ACCT_OUT;
3827 else
3828 REJECT("AccountingRule must be 'sum', 'max', 'in', or 'out'");
3831 if (options->DirPort_set && !options->DirCache) {
3832 REJECT("DirPort configured but DirCache disabled. DirPort requires "
3833 "DirCache.");
3836 if (options->BridgeRelay && !options->DirCache) {
3837 REJECT("We're a bridge but DirCache is disabled. BridgeRelay requires "
3838 "DirCache.");
3841 if (server_mode(options)) {
3842 char *dircache_msg = NULL;
3843 if (have_enough_mem_for_dircache(options, 0, &dircache_msg)) {
3844 log_warn(LD_CONFIG, "%s", dircache_msg);
3845 tor_free(dircache_msg);
3849 if (options->HTTPProxy) { /* parse it now */
3850 if (tor_addr_port_lookup(options->HTTPProxy,
3851 &options->HTTPProxyAddr, &options->HTTPProxyPort) < 0)
3852 REJECT("HTTPProxy failed to parse or resolve. Please fix.");
3853 if (options->HTTPProxyPort == 0) { /* give it a default */
3854 options->HTTPProxyPort = 80;
3858 if (options->HTTPProxyAuthenticator) {
3859 if (strlen(options->HTTPProxyAuthenticator) >= 512)
3860 REJECT("HTTPProxyAuthenticator is too long (>= 512 chars).");
3863 if (options->HTTPSProxy) { /* parse it now */
3864 if (tor_addr_port_lookup(options->HTTPSProxy,
3865 &options->HTTPSProxyAddr, &options->HTTPSProxyPort) <0)
3866 REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
3867 if (options->HTTPSProxyPort == 0) { /* give it a default */
3868 options->HTTPSProxyPort = 443;
3872 if (options->HTTPSProxyAuthenticator) {
3873 if (strlen(options->HTTPSProxyAuthenticator) >= 512)
3874 REJECT("HTTPSProxyAuthenticator is too long (>= 512 chars).");
3877 if (options->Socks4Proxy) { /* parse it now */
3878 if (tor_addr_port_lookup(options->Socks4Proxy,
3879 &options->Socks4ProxyAddr,
3880 &options->Socks4ProxyPort) <0)
3881 REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
3882 if (options->Socks4ProxyPort == 0) { /* give it a default */
3883 options->Socks4ProxyPort = 1080;
3887 if (options->Socks5Proxy) { /* parse it now */
3888 if (tor_addr_port_lookup(options->Socks5Proxy,
3889 &options->Socks5ProxyAddr,
3890 &options->Socks5ProxyPort) <0)
3891 REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
3892 if (options->Socks5ProxyPort == 0) { /* give it a default */
3893 options->Socks5ProxyPort = 1080;
3897 /* Check if more than one exclusive proxy type has been enabled. */
3898 if (!!options->Socks4Proxy + !!options->Socks5Proxy +
3899 !!options->HTTPSProxy > 1)
3900 REJECT("You have configured more than one proxy type. "
3901 "(Socks4Proxy|Socks5Proxy|HTTPSProxy)");
3903 /* Check if the proxies will give surprising behavior. */
3904 if (options->HTTPProxy && !(options->Socks4Proxy ||
3905 options->Socks5Proxy ||
3906 options->HTTPSProxy)) {
3907 log_warn(LD_CONFIG, "HTTPProxy configured, but no SOCKS proxy or "
3908 "HTTPS proxy configured. Watch out: this configuration will "
3909 "proxy unencrypted directory connections only.");
3912 if (options->Socks5ProxyUsername) {
3913 size_t len;
3915 len = strlen(options->Socks5ProxyUsername);
3916 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
3917 REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
3919 if (!options->Socks5ProxyPassword)
3920 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3922 len = strlen(options->Socks5ProxyPassword);
3923 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
3924 REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
3925 } else if (options->Socks5ProxyPassword)
3926 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3928 if (options->HashedControlPassword) {
3929 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3930 if (!sl) {
3931 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3932 } else {
3933 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3934 smartlist_free(sl);
3938 if (options->HashedControlSessionPassword) {
3939 smartlist_t *sl = decode_hashed_passwords(
3940 options->HashedControlSessionPassword);
3941 if (!sl) {
3942 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3943 } else {
3944 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3945 smartlist_free(sl);
3949 if (options->OwningControllerProcess) {
3950 const char *validate_pspec_msg = NULL;
3951 if (tor_validate_process_specifier(options->OwningControllerProcess,
3952 &validate_pspec_msg)) {
3953 tor_asprintf(msg, "Bad OwningControllerProcess: %s",
3954 validate_pspec_msg);
3955 return -1;
3959 if ((options->ControlPort_set || world_writable_control_socket) &&
3960 !options->HashedControlPassword &&
3961 !options->HashedControlSessionPassword &&
3962 !options->CookieAuthentication) {
3963 log_warn(LD_CONFIG, "Control%s is %s, but no authentication method "
3964 "has been configured. This means that any program on your "
3965 "computer can reconfigure your Tor. That's bad! You should "
3966 "upgrade your Tor controller as soon as possible.",
3967 options->ControlPort_set ? "Port" : "Socket",
3968 options->ControlPort_set ? "open" : "world writable");
3971 if (options->CookieAuthFileGroupReadable && !options->CookieAuthFile) {
3972 log_warn(LD_CONFIG, "CookieAuthFileGroupReadable is set, but will have "
3973 "no effect: you must specify an explicit CookieAuthFile to "
3974 "have it group-readable.");
3977 if (options->MyFamily_lines && options->BridgeRelay) {
3978 log_warn(LD_CONFIG, "Listing a family for a bridge relay is not "
3979 "supported: it can reveal bridge fingerprints to censors. "
3980 "You should also make sure you aren't listing this bridge's "
3981 "fingerprint in any other MyFamily.");
3983 if (normalize_nickname_list(&options->MyFamily,
3984 options->MyFamily_lines, "MyFamily", msg))
3985 return -1;
3986 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3987 routerset_t *rs = routerset_new();
3988 if (routerset_parse(rs, cl->value, cl->key)) {
3989 routerset_free(rs);
3990 return -1;
3992 routerset_free(rs);
3995 if (validate_addr_policies(options, msg) < 0)
3996 return -1;
3998 /* If FallbackDir is set, we don't UseDefaultFallbackDirs */
3999 if (options->UseDefaultFallbackDirs && options->FallbackDir) {
4000 log_info(LD_CONFIG, "You have set UseDefaultFallbackDirs 1 and "
4001 "FallbackDir(s). Ignoring UseDefaultFallbackDirs, and "
4002 "using the FallbackDir(s) you have set.");
4005 if (validate_dir_servers(options, old_options) < 0)
4006 REJECT("Directory authority/fallback line did not parse. See logs "
4007 "for details.");
4009 if (options->UseBridges && !options->Bridges)
4010 REJECT("If you set UseBridges, you must specify at least one bridge.");
4012 for (cl = options->Bridges; cl; cl = cl->next) {
4013 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
4014 if (!bridge_line)
4015 REJECT("Bridge line did not parse. See logs for details.");
4016 bridge_line_free(bridge_line);
4019 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
4020 if (parse_transport_line(options, cl->value, 1, 0) < 0)
4021 REJECT("Invalid client transport line. See logs for details.");
4024 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
4025 if (parse_transport_line(options, cl->value, 1, 1) < 0)
4026 REJECT("Invalid server transport line. See logs for details.");
4029 if (options->ServerTransportPlugin && !server_mode(options)) {
4030 log_notice(LD_GENERAL, "Tor is not configured as a relay but you specified"
4031 " a ServerTransportPlugin line (%s). The ServerTransportPlugin "
4032 "line will be ignored.",
4033 escaped(options->ServerTransportPlugin->value));
4036 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
4037 /** If get_bindaddr_from_transport_listen_line() fails with
4038 'transport' being NULL, it means that something went wrong
4039 while parsing the ServerTransportListenAddr line. */
4040 char *bindaddr = get_bindaddr_from_transport_listen_line(cl->value, NULL);
4041 if (!bindaddr)
4042 REJECT("ServerTransportListenAddr did not parse. See logs for details.");
4043 tor_free(bindaddr);
4046 if (options->ServerTransportListenAddr && !options->ServerTransportPlugin) {
4047 log_notice(LD_GENERAL, "You need at least a single managed-proxy to "
4048 "specify a transport listen address. The "
4049 "ServerTransportListenAddr line will be ignored.");
4052 for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
4053 /** If get_options_from_transport_options_line() fails with
4054 'transport' being NULL, it means that something went wrong
4055 while parsing the ServerTransportOptions line. */
4056 smartlist_t *options_sl =
4057 get_options_from_transport_options_line(cl->value, NULL);
4058 if (!options_sl)
4059 REJECT("ServerTransportOptions did not parse. See logs for details.");
4061 SMARTLIST_FOREACH(options_sl, char *, cp, tor_free(cp));
4062 smartlist_free(options_sl);
4065 if (options->ConstrainedSockets) {
4066 /* If the user wants to constrain socket buffer use, make sure the desired
4067 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
4068 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
4069 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
4070 options->ConstrainedSockSize % 1024) {
4071 tor_asprintf(msg,
4072 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
4073 "in 1024 byte increments.",
4074 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
4075 return -1;
4077 if (options->DirPort_set) {
4078 /* Providing cached directory entries while system TCP buffers are scarce
4079 * will exacerbate the socket errors. Suggest that this be disabled. */
4080 COMPLAIN("You have requested constrained socket buffers while also "
4081 "serving directory entries via DirPort. It is strongly "
4082 "suggested that you disable serving directory requests when "
4083 "system TCP buffer resources are scarce.");
4087 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
4088 options->V3AuthVotingInterval/2) {
4090 This doesn't work, but it seems like it should:
4091 what code is preventing the interval being less than twice the lead-up?
4092 if (options->TestingTorNetwork) {
4093 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
4094 options->V3AuthVotingInterval) {
4095 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than "
4096 "V3AuthVotingInterval");
4097 } else {
4098 COMPLAIN("V3AuthVoteDelay plus V3AuthDistDelay is more than half "
4099 "V3AuthVotingInterval. This may lead to "
4100 "consensus instability, particularly if clocks drift.");
4102 } else {
4104 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
4105 "V3AuthVotingInterval");
4111 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS) {
4112 if (options->TestingTorNetwork) {
4113 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS_TESTING) {
4114 REJECT("V3AuthVoteDelay is way too low.");
4115 } else {
4116 COMPLAIN("V3AuthVoteDelay is very low. "
4117 "This may lead to failure to vote for a consensus.");
4119 } else {
4120 REJECT("V3AuthVoteDelay is way too low.");
4124 if (options->V3AuthDistDelay < MIN_DIST_SECONDS) {
4125 if (options->TestingTorNetwork) {
4126 if (options->V3AuthDistDelay < MIN_DIST_SECONDS_TESTING) {
4127 REJECT("V3AuthDistDelay is way too low.");
4128 } else {
4129 COMPLAIN("V3AuthDistDelay is very low. "
4130 "This may lead to missing votes in a consensus.");
4132 } else {
4133 REJECT("V3AuthDistDelay is way too low.");
4137 if (options->V3AuthNIntervalsValid < 2)
4138 REJECT("V3AuthNIntervalsValid must be at least 2.");
4140 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
4141 if (options->TestingTorNetwork) {
4142 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL_TESTING) {
4143 REJECT("V3AuthVotingInterval is insanely low.");
4144 } else {
4145 COMPLAIN("V3AuthVotingInterval is very low. "
4146 "This may lead to failure to synchronise for a consensus.");
4148 } else {
4149 REJECT("V3AuthVotingInterval is insanely low.");
4151 } else if (options->V3AuthVotingInterval > 24*60*60) {
4152 REJECT("V3AuthVotingInterval is insanely high.");
4153 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
4154 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
4157 if (hs_config_service_all(options, 1) < 0)
4158 REJECT("Failed to configure rendezvous options. See logs for details.");
4160 /* Parse client-side authorization for hidden services. */
4161 if (rend_parse_service_authorization(options, 1) < 0)
4162 REJECT("Failed to configure client authorization for hidden services. "
4163 "See logs for details.");
4165 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv4,
4166 AF_INET, 1, msg)<0)
4167 return -1;
4168 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv6,
4169 AF_INET6, 1, msg)<0)
4170 return -1;
4172 if (options->TestingTorNetwork &&
4173 !(options->DirAuthorities ||
4174 (options->AlternateDirAuthority &&
4175 options->AlternateBridgeAuthority))) {
4176 REJECT("TestingTorNetwork may only be configured in combination with "
4177 "a non-default set of DirAuthority or both of "
4178 "AlternateDirAuthority and AlternateBridgeAuthority configured.");
4181 #define CHECK_DEFAULT(arg) \
4182 STMT_BEGIN \
4183 if (!options->TestingTorNetwork && \
4184 !options->UsingTestNetworkDefaults_ && \
4185 !config_is_same(&options_format,options, \
4186 default_options,#arg)) { \
4187 REJECT(#arg " may only be changed in testing Tor " \
4188 "networks!"); \
4189 } STMT_END
4190 CHECK_DEFAULT(TestingV3AuthInitialVotingInterval);
4191 CHECK_DEFAULT(TestingV3AuthInitialVoteDelay);
4192 CHECK_DEFAULT(TestingV3AuthInitialDistDelay);
4193 CHECK_DEFAULT(TestingV3AuthVotingStartOffset);
4194 CHECK_DEFAULT(TestingAuthDirTimeToLearnReachability);
4195 CHECK_DEFAULT(TestingEstimatedDescriptorPropagationTime);
4196 CHECK_DEFAULT(TestingServerDownloadSchedule);
4197 CHECK_DEFAULT(TestingClientDownloadSchedule);
4198 CHECK_DEFAULT(TestingServerConsensusDownloadSchedule);
4199 CHECK_DEFAULT(TestingClientConsensusDownloadSchedule);
4200 CHECK_DEFAULT(TestingBridgeDownloadSchedule);
4201 CHECK_DEFAULT(TestingBridgeBootstrapDownloadSchedule);
4202 CHECK_DEFAULT(TestingClientMaxIntervalWithoutRequest);
4203 CHECK_DEFAULT(TestingDirConnectionMaxStall);
4204 CHECK_DEFAULT(TestingConsensusMaxDownloadTries);
4205 CHECK_DEFAULT(TestingDescriptorMaxDownloadTries);
4206 CHECK_DEFAULT(TestingMicrodescMaxDownloadTries);
4207 CHECK_DEFAULT(TestingCertMaxDownloadTries);
4208 CHECK_DEFAULT(TestingAuthKeyLifetime);
4209 CHECK_DEFAULT(TestingLinkCertLifetime);
4210 CHECK_DEFAULT(TestingSigningKeySlop);
4211 CHECK_DEFAULT(TestingAuthKeySlop);
4212 CHECK_DEFAULT(TestingLinkKeySlop);
4213 #undef CHECK_DEFAULT
4215 if (!options->ClientDNSRejectInternalAddresses &&
4216 !(options->DirAuthorities ||
4217 (options->AlternateDirAuthority && options->AlternateBridgeAuthority)))
4218 REJECT("ClientDNSRejectInternalAddresses used for default network.");
4219 if (options->SigningKeyLifetime < options->TestingSigningKeySlop*2)
4220 REJECT("SigningKeyLifetime is too short.");
4221 if (options->TestingLinkCertLifetime < options->TestingAuthKeySlop*2)
4222 REJECT("LinkCertLifetime is too short.");
4223 if (options->TestingAuthKeyLifetime < options->TestingLinkKeySlop*2)
4224 REJECT("TestingAuthKeyLifetime is too short.");
4226 if (options->TestingV3AuthInitialVotingInterval
4227 < MIN_VOTE_INTERVAL_TESTING_INITIAL) {
4228 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
4229 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
4230 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
4231 "30 minutes.");
4234 if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS_TESTING) {
4235 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
4238 if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS_TESTING) {
4239 REJECT("TestingV3AuthInitialDistDelay is way too low.");
4242 if (options->TestingV3AuthInitialVoteDelay +
4243 options->TestingV3AuthInitialDistDelay >=
4244 options->TestingV3AuthInitialVotingInterval) {
4245 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
4246 "must be less than TestingV3AuthInitialVotingInterval");
4249 if (options->TestingV3AuthVotingStartOffset >
4250 MIN(options->TestingV3AuthInitialVotingInterval,
4251 options->V3AuthVotingInterval)) {
4252 REJECT("TestingV3AuthVotingStartOffset is higher than the voting "
4253 "interval.");
4254 } else if (options->TestingV3AuthVotingStartOffset < 0) {
4255 REJECT("TestingV3AuthVotingStartOffset must be non-negative.");
4258 if (options->TestingAuthDirTimeToLearnReachability < 0) {
4259 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
4260 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
4261 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
4264 if (options->TestingEstimatedDescriptorPropagationTime < 0) {
4265 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
4266 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
4267 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
4270 if (options->TestingClientMaxIntervalWithoutRequest < 1) {
4271 REJECT("TestingClientMaxIntervalWithoutRequest is way too low.");
4272 } else if (options->TestingClientMaxIntervalWithoutRequest > 3600) {
4273 COMPLAIN("TestingClientMaxIntervalWithoutRequest is insanely high.");
4276 if (options->TestingDirConnectionMaxStall < 5) {
4277 REJECT("TestingDirConnectionMaxStall is way too low.");
4278 } else if (options->TestingDirConnectionMaxStall > 3600) {
4279 COMPLAIN("TestingDirConnectionMaxStall is insanely high.");
4282 if (options->TestingConsensusMaxDownloadTries < 2) {
4283 REJECT("TestingConsensusMaxDownloadTries must be greater than 2.");
4284 } else if (options->TestingConsensusMaxDownloadTries > 800) {
4285 COMPLAIN("TestingConsensusMaxDownloadTries is insanely high.");
4288 if (options->ClientBootstrapConsensusMaxDownloadTries < 2) {
4289 REJECT("ClientBootstrapConsensusMaxDownloadTries must be greater "
4290 "than 2."
4292 } else if (options->ClientBootstrapConsensusMaxDownloadTries > 800) {
4293 COMPLAIN("ClientBootstrapConsensusMaxDownloadTries is insanely "
4294 "high.");
4297 if (options->ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries
4298 < 2) {
4299 REJECT("ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries must "
4300 "be greater than 2."
4302 } else if (
4303 options->ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries
4304 > 800) {
4305 COMPLAIN("ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries is "
4306 "insanely high.");
4309 if (options->ClientBootstrapConsensusMaxInProgressTries < 1) {
4310 REJECT("ClientBootstrapConsensusMaxInProgressTries must be greater "
4311 "than 0.");
4312 } else if (options->ClientBootstrapConsensusMaxInProgressTries
4313 > 100) {
4314 COMPLAIN("ClientBootstrapConsensusMaxInProgressTries is insanely "
4315 "high.");
4318 if (options->TestingDescriptorMaxDownloadTries < 2) {
4319 REJECT("TestingDescriptorMaxDownloadTries must be greater than 1.");
4320 } else if (options->TestingDescriptorMaxDownloadTries > 800) {
4321 COMPLAIN("TestingDescriptorMaxDownloadTries is insanely high.");
4324 if (options->TestingMicrodescMaxDownloadTries < 2) {
4325 REJECT("TestingMicrodescMaxDownloadTries must be greater than 1.");
4326 } else if (options->TestingMicrodescMaxDownloadTries > 800) {
4327 COMPLAIN("TestingMicrodescMaxDownloadTries is insanely high.");
4330 if (options->TestingCertMaxDownloadTries < 2) {
4331 REJECT("TestingCertMaxDownloadTries must be greater than 1.");
4332 } else if (options->TestingCertMaxDownloadTries > 800) {
4333 COMPLAIN("TestingCertMaxDownloadTries is insanely high.");
4336 if (options->TestingEnableConnBwEvent &&
4337 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4338 REJECT("TestingEnableConnBwEvent may only be changed in testing "
4339 "Tor networks!");
4342 if (options->TestingEnableCellStatsEvent &&
4343 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4344 REJECT("TestingEnableCellStatsEvent may only be changed in testing "
4345 "Tor networks!");
4348 if (options->TestingEnableTbEmptyEvent &&
4349 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4350 REJECT("TestingEnableTbEmptyEvent may only be changed in testing "
4351 "Tor networks!");
4354 if (options->TestingTorNetwork) {
4355 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
4356 "almost unusable in the public Tor network, and is "
4357 "therefore only advised if you are building a "
4358 "testing Tor network!");
4361 if (options->AccelName && !options->HardwareAccel)
4362 options->HardwareAccel = 1;
4363 if (options->AccelDir && !options->AccelName)
4364 REJECT("Can't use hardware crypto accelerator dir without engine name.");
4366 if (options->PublishServerDescriptor)
4367 SMARTLIST_FOREACH(options->PublishServerDescriptor, const char *, pubdes, {
4368 if (!strcmp(pubdes, "1") || !strcmp(pubdes, "0"))
4369 if (smartlist_len(options->PublishServerDescriptor) > 1) {
4370 COMPLAIN("You have passed a list of multiple arguments to the "
4371 "PublishServerDescriptor option that includes 0 or 1. "
4372 "0 or 1 should only be used as the sole argument. "
4373 "This configuration will be rejected in a future release.");
4374 break;
4378 if (options->BridgeRelay == 1 && ! options->ORPort_set)
4379 REJECT("BridgeRelay is 1, ORPort is not set. This is an invalid "
4380 "combination.");
4382 if (options_validate_scheduler(options, msg) < 0) {
4383 return -1;
4386 return 0;
4389 #undef REJECT
4390 #undef COMPLAIN
4392 /* Given the value that the user has set for MaxMemInQueues, compute the
4393 * actual maximum value. We clip this value if it's too low, and autodetect
4394 * it if it's set to 0. */
4395 static uint64_t
4396 compute_real_max_mem_in_queues(const uint64_t val, int log_guess)
4398 uint64_t result;
4400 if (val == 0) {
4401 #define ONE_GIGABYTE (U64_LITERAL(1) << 30)
4402 #define ONE_MEGABYTE (U64_LITERAL(1) << 20)
4403 #if SIZEOF_VOID_P >= 8
4404 #define MAX_DEFAULT_MAXMEM (8*ONE_GIGABYTE)
4405 #else
4406 #define MAX_DEFAULT_MAXMEM (2*ONE_GIGABYTE)
4407 #endif
4408 /* The user didn't pick a memory limit. Choose a very large one
4409 * that is still smaller than the system memory */
4410 static int notice_sent = 0;
4411 size_t ram = 0;
4412 if (get_total_system_memory(&ram) < 0) {
4413 /* We couldn't determine our total system memory! */
4414 #if SIZEOF_VOID_P >= 8
4415 /* 64-bit system. Let's hope for 8 GB. */
4416 result = 8 * ONE_GIGABYTE;
4417 #else
4418 /* (presumably) 32-bit system. Let's hope for 1 GB. */
4419 result = ONE_GIGABYTE;
4420 #endif /* SIZEOF_VOID_P >= 8 */
4421 } else {
4422 /* We detected it, so let's pick 3/4 of the total RAM as our limit. */
4423 const uint64_t avail = (ram / 4) * 3;
4425 /* Make sure it's in range from 0.25 GB to 8 GB. */
4426 if (avail > MAX_DEFAULT_MAXMEM) {
4427 /* If you want to use more than this much RAM, you need to configure
4428 it yourself */
4429 result = MAX_DEFAULT_MAXMEM;
4430 } else if (avail < ONE_GIGABYTE / 4) {
4431 result = ONE_GIGABYTE / 4;
4432 } else {
4433 result = avail;
4436 if (log_guess && ! notice_sent) {
4437 log_notice(LD_CONFIG, "%sMaxMemInQueues is set to "U64_FORMAT" MB. "
4438 "You can override this by setting MaxMemInQueues by hand.",
4439 ram ? "Based on detected system memory, " : "",
4440 U64_PRINTF_ARG(result / ONE_MEGABYTE));
4441 notice_sent = 1;
4443 return result;
4444 } else if (val < ONE_GIGABYTE / 4) {
4445 log_warn(LD_CONFIG, "MaxMemInQueues must be at least 256 MB for now. "
4446 "Ideally, have it as large as you can afford.");
4447 return ONE_GIGABYTE / 4;
4448 } else {
4449 /* The value was fine all along */
4450 return val;
4454 /* If we have less than 300 MB suggest disabling dircache */
4455 #define DIRCACHE_MIN_MEM_MB 300
4456 #define DIRCACHE_MIN_MEM_BYTES (DIRCACHE_MIN_MEM_MB*ONE_MEGABYTE)
4457 #define STRINGIFY(val) #val
4459 /** Create a warning message for emitting if we are a dircache but may not have
4460 * enough system memory, or if we are not a dircache but probably should be.
4461 * Return -1 when a message is returned in *msg*, else return 0. */
4462 STATIC int
4463 have_enough_mem_for_dircache(const or_options_t *options, size_t total_mem,
4464 char **msg)
4466 *msg = NULL;
4467 /* XXX We should possibly be looking at MaxMemInQueues here
4468 * unconditionally. Or we should believe total_mem unconditionally. */
4469 if (total_mem == 0) {
4470 if (get_total_system_memory(&total_mem) < 0) {
4471 total_mem = options->MaxMemInQueues >= SIZE_MAX ?
4472 SIZE_MAX : (size_t)options->MaxMemInQueues;
4475 if (options->DirCache) {
4476 if (total_mem < DIRCACHE_MIN_MEM_BYTES) {
4477 if (options->BridgeRelay) {
4478 *msg = tor_strdup("Running a Bridge with less than "
4479 STRINGIFY(DIRCACHE_MIN_MEM_MB) " MB of memory is not "
4480 "recommended.");
4481 } else {
4482 *msg = tor_strdup("Being a directory cache (default) with less than "
4483 STRINGIFY(DIRCACHE_MIN_MEM_MB) " MB of memory is not "
4484 "recommended and may consume most of the available "
4485 "resources, consider disabling this functionality by "
4486 "setting the DirCache option to 0.");
4489 } else {
4490 if (total_mem >= DIRCACHE_MIN_MEM_BYTES) {
4491 *msg = tor_strdup("DirCache is disabled and we are configured as a "
4492 "relay. This may disqualify us from becoming a guard in the "
4493 "future.");
4496 return *msg == NULL ? 0 : -1;
4498 #undef STRINGIFY
4500 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
4501 * equal strings. */
4502 static int
4503 opt_streq(const char *s1, const char *s2)
4505 return 0 == strcmp_opt(s1, s2);
4508 /** Check if any of the previous options have changed but aren't allowed to. */
4509 static int
4510 options_transition_allowed(const or_options_t *old,
4511 const or_options_t *new_val,
4512 char **msg)
4514 if (!old)
4515 return 0;
4517 if (!opt_streq(old->PidFile, new_val->PidFile)) {
4518 *msg = tor_strdup("PidFile is not allowed to change.");
4519 return -1;
4522 if (old->RunAsDaemon != new_val->RunAsDaemon) {
4523 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
4524 "is not allowed.");
4525 return -1;
4528 if (old->Sandbox != new_val->Sandbox) {
4529 *msg = tor_strdup("While Tor is running, changing Sandbox "
4530 "is not allowed.");
4531 return -1;
4534 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
4535 tor_asprintf(msg,
4536 "While Tor is running, changing DataDirectory "
4537 "(\"%s\"->\"%s\") is not allowed.",
4538 old->DataDirectory, new_val->DataDirectory);
4539 return -1;
4542 if (!opt_streq(old->User, new_val->User)) {
4543 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
4544 return -1;
4547 if (old->KeepBindCapabilities != new_val->KeepBindCapabilities) {
4548 *msg = tor_strdup("While Tor is running, changing KeepBindCapabilities is "
4549 "not allowed.");
4550 return -1;
4553 if (!opt_streq(old->SyslogIdentityTag, new_val->SyslogIdentityTag)) {
4554 *msg = tor_strdup("While Tor is running, changing "
4555 "SyslogIdentityTag is not allowed.");
4556 return -1;
4559 if ((old->HardwareAccel != new_val->HardwareAccel)
4560 || !opt_streq(old->AccelName, new_val->AccelName)
4561 || !opt_streq(old->AccelDir, new_val->AccelDir)) {
4562 *msg = tor_strdup("While Tor is running, changing OpenSSL hardware "
4563 "acceleration engine is not allowed.");
4564 return -1;
4567 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
4568 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
4569 "is not allowed.");
4570 return -1;
4573 if (old->DisableAllSwap != new_val->DisableAllSwap) {
4574 *msg = tor_strdup("While Tor is running, changing DisableAllSwap "
4575 "is not allowed.");
4576 return -1;
4579 if (old->TokenBucketRefillInterval != new_val->TokenBucketRefillInterval) {
4580 *msg = tor_strdup("While Tor is running, changing TokenBucketRefill"
4581 "Interval is not allowed");
4582 return -1;
4585 if (old->HiddenServiceSingleHopMode != new_val->HiddenServiceSingleHopMode) {
4586 *msg = tor_strdup("While Tor is running, changing "
4587 "HiddenServiceSingleHopMode is not allowed.");
4588 return -1;
4591 if (old->HiddenServiceNonAnonymousMode !=
4592 new_val->HiddenServiceNonAnonymousMode) {
4593 *msg = tor_strdup("While Tor is running, changing "
4594 "HiddenServiceNonAnonymousMode is not allowed.");
4595 return -1;
4598 if (old->DisableDebuggerAttachment &&
4599 !new_val->DisableDebuggerAttachment) {
4600 *msg = tor_strdup("While Tor is running, disabling "
4601 "DisableDebuggerAttachment is not allowed.");
4602 return -1;
4605 if (old->NoExec && !new_val->NoExec) {
4606 *msg = tor_strdup("While Tor is running, disabling "
4607 "NoExec is not allowed.");
4608 return -1;
4611 if (sandbox_is_active()) {
4612 #define SB_NOCHANGE_STR(opt) \
4613 do { \
4614 if (! opt_streq(old->opt, new_val->opt)) { \
4615 *msg = tor_strdup("Can't change " #opt " while Sandbox is active"); \
4616 return -1; \
4618 } while (0)
4620 SB_NOCHANGE_STR(Address);
4621 SB_NOCHANGE_STR(ServerDNSResolvConfFile);
4622 SB_NOCHANGE_STR(DirPortFrontPage);
4623 SB_NOCHANGE_STR(CookieAuthFile);
4624 SB_NOCHANGE_STR(ExtORPortCookieAuthFile);
4626 #undef SB_NOCHANGE_STR
4628 if (! config_lines_eq(old->Logs, new_val->Logs)) {
4629 *msg = tor_strdup("Can't change Logs while Sandbox is active");
4630 return -1;
4632 if (old->ConnLimit != new_val->ConnLimit) {
4633 *msg = tor_strdup("Can't change ConnLimit while Sandbox is active");
4634 return -1;
4636 if (server_mode(old) != server_mode(new_val)) {
4637 *msg = tor_strdup("Can't start/stop being a server while "
4638 "Sandbox is active");
4639 return -1;
4643 return 0;
4646 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
4647 * will require us to rotate the CPU and DNS workers; else return 0. */
4648 static int
4649 options_transition_affects_workers(const or_options_t *old_options,
4650 const or_options_t *new_options)
4652 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
4653 old_options->NumCPUs != new_options->NumCPUs ||
4654 !config_lines_eq(old_options->ORPort_lines, new_options->ORPort_lines) ||
4655 old_options->ServerDNSSearchDomains !=
4656 new_options->ServerDNSSearchDomains ||
4657 old_options->SafeLogging_ != new_options->SafeLogging_ ||
4658 old_options->ClientOnly != new_options->ClientOnly ||
4659 server_mode(old_options) != server_mode(new_options) ||
4660 public_server_mode(old_options) != public_server_mode(new_options) ||
4661 !config_lines_eq(old_options->Logs, new_options->Logs) ||
4662 old_options->LogMessageDomains != new_options->LogMessageDomains)
4663 return 1;
4665 /* Check whether log options match. */
4667 /* Nothing that changed matters. */
4668 return 0;
4671 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
4672 * will require us to generate a new descriptor; else return 0. */
4673 static int
4674 options_transition_affects_descriptor(const or_options_t *old_options,
4675 const or_options_t *new_options)
4677 /* XXX We can be smarter here. If your DirPort isn't being
4678 * published and you just turned it off, no need to republish. Etc. */
4679 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
4680 !opt_streq(old_options->Nickname,new_options->Nickname) ||
4681 !opt_streq(old_options->Address,new_options->Address) ||
4682 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
4683 old_options->ExitRelay != new_options->ExitRelay ||
4684 old_options->ExitPolicyRejectPrivate !=
4685 new_options->ExitPolicyRejectPrivate ||
4686 old_options->ExitPolicyRejectLocalInterfaces !=
4687 new_options->ExitPolicyRejectLocalInterfaces ||
4688 old_options->IPv6Exit != new_options->IPv6Exit ||
4689 !config_lines_eq(old_options->ORPort_lines,
4690 new_options->ORPort_lines) ||
4691 !config_lines_eq(old_options->DirPort_lines,
4692 new_options->DirPort_lines) ||
4693 old_options->ClientOnly != new_options->ClientOnly ||
4694 old_options->DisableNetwork != new_options->DisableNetwork ||
4695 old_options->PublishServerDescriptor_ !=
4696 new_options->PublishServerDescriptor_ ||
4697 get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
4698 get_effective_bwburst(old_options) !=
4699 get_effective_bwburst(new_options) ||
4700 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
4701 !opt_streq(old_options->BridgeDistribution,
4702 new_options->BridgeDistribution) ||
4703 !config_lines_eq(old_options->MyFamily, new_options->MyFamily) ||
4704 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
4705 old_options->AccountingMax != new_options->AccountingMax ||
4706 old_options->AccountingRule != new_options->AccountingRule ||
4707 public_server_mode(old_options) != public_server_mode(new_options) ||
4708 old_options->DirCache != new_options->DirCache ||
4709 old_options->AssumeReachable != new_options->AssumeReachable)
4710 return 1;
4712 return 0;
4715 #ifdef _WIN32
4716 /** Return the directory on windows where we expect to find our application
4717 * data. */
4718 static char *
4719 get_windows_conf_root(void)
4721 static int is_set = 0;
4722 static char path[MAX_PATH*2+1];
4723 TCHAR tpath[MAX_PATH] = {0};
4725 LPITEMIDLIST idl;
4726 IMalloc *m;
4727 HRESULT result;
4729 if (is_set)
4730 return path;
4732 /* Find X:\documents and settings\username\application data\ .
4733 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
4735 #ifdef ENABLE_LOCAL_APPDATA
4736 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
4737 #else
4738 #define APPDATA_PATH CSIDL_APPDATA
4739 #endif
4740 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
4741 getcwd(path,MAX_PATH);
4742 is_set = 1;
4743 log_warn(LD_CONFIG,
4744 "I couldn't find your application data folder: are you "
4745 "running an ancient version of Windows 95? Defaulting to \"%s\"",
4746 path);
4747 return path;
4749 /* Convert the path from an "ID List" (whatever that is!) to a path. */
4750 result = SHGetPathFromIDList(idl, tpath);
4751 #ifdef UNICODE
4752 wcstombs(path,tpath,sizeof(path));
4753 path[sizeof(path)-1] = '\0';
4754 #else
4755 strlcpy(path,tpath,sizeof(path));
4756 #endif /* defined(UNICODE) */
4758 /* Now we need to free the memory that the path-idl was stored in. In
4759 * typical Windows fashion, we can't just call 'free()' on it. */
4760 SHGetMalloc(&m);
4761 if (m) {
4762 m->lpVtbl->Free(m, idl);
4763 m->lpVtbl->Release(m);
4765 if (!SUCCEEDED(result)) {
4766 return NULL;
4768 strlcat(path,"\\tor",MAX_PATH);
4769 is_set = 1;
4770 return path;
4772 #endif /* defined(_WIN32) */
4774 /** Return the default location for our torrc file (if <b>defaults_file</b> is
4775 * false), or for the torrc-defaults file (if <b>defaults_file</b> is true). */
4776 static const char *
4777 get_default_conf_file(int defaults_file)
4779 #ifdef DISABLE_SYSTEM_TORRC
4780 (void) defaults_file;
4781 return NULL;
4782 #elif defined(_WIN32)
4783 if (defaults_file) {
4784 static char defaults_path[MAX_PATH+1];
4785 tor_snprintf(defaults_path, MAX_PATH, "%s\\torrc-defaults",
4786 get_windows_conf_root());
4787 return defaults_path;
4788 } else {
4789 static char path[MAX_PATH+1];
4790 tor_snprintf(path, MAX_PATH, "%s\\torrc",
4791 get_windows_conf_root());
4792 return path;
4794 #else
4795 return defaults_file ? CONFDIR "/torrc-defaults" : CONFDIR "/torrc";
4796 #endif /* defined(DISABLE_SYSTEM_TORRC) || ... */
4799 /** Verify whether lst is a list of strings containing valid-looking
4800 * comma-separated nicknames, or NULL. Will normalise <b>lst</b> to prefix '$'
4801 * to any nickname or fingerprint that needs it. Also splits comma-separated
4802 * list elements into multiple elements. Return 0 on success.
4803 * Warn and return -1 on failure.
4805 static int
4806 normalize_nickname_list(config_line_t **normalized_out,
4807 const config_line_t *lst, const char *name,
4808 char **msg)
4810 if (!lst)
4811 return 0;
4813 config_line_t *new_nicknames = NULL;
4814 config_line_t **new_nicknames_next = &new_nicknames;
4816 const config_line_t *cl;
4817 for (cl = lst; cl; cl = cl->next) {
4818 const char *line = cl->value;
4819 if (!line)
4820 continue;
4822 int valid_line = 1;
4823 smartlist_t *sl = smartlist_new();
4824 smartlist_split_string(sl, line, ",",
4825 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
4826 SMARTLIST_FOREACH_BEGIN(sl, char *, s)
4828 char *normalized = NULL;
4829 if (!is_legal_nickname_or_hexdigest(s)) {
4830 // check if first char is dollar
4831 if (s[0] != '$') {
4832 // Try again but with a dollar symbol prepended
4833 char *prepended;
4834 tor_asprintf(&prepended, "$%s", s);
4836 if (is_legal_nickname_or_hexdigest(prepended)) {
4837 // The nickname is valid when it's prepended, set it as the
4838 // normalized version
4839 normalized = prepended;
4840 } else {
4841 // Still not valid, free and fallback to error message
4842 tor_free(prepended);
4846 if (!normalized) {
4847 tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
4848 valid_line = 0;
4849 break;
4851 } else {
4852 normalized = tor_strdup(s);
4855 config_line_t *next = tor_malloc_zero(sizeof(*next));
4856 next->key = tor_strdup(cl->key);
4857 next->value = normalized;
4858 next->next = NULL;
4860 *new_nicknames_next = next;
4861 new_nicknames_next = &next->next;
4862 } SMARTLIST_FOREACH_END(s);
4864 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
4865 smartlist_free(sl);
4867 if (!valid_line) {
4868 config_free_lines(new_nicknames);
4869 return -1;
4873 *normalized_out = new_nicknames;
4875 return 0;
4878 /** Learn config file name from command line arguments, or use the default.
4880 * If <b>defaults_file</b> is true, we're looking for torrc-defaults;
4881 * otherwise, we're looking for the regular torrc_file.
4883 * Set *<b>using_default_fname</b> to true if we're using the default
4884 * configuration file name; or false if we've set it from the command line.
4886 * Set *<b>ignore_missing_torrc</b> to true if we should ignore the resulting
4887 * filename if it doesn't exist.
4889 static char *
4890 find_torrc_filename(config_line_t *cmd_arg,
4891 int defaults_file,
4892 int *using_default_fname, int *ignore_missing_torrc)
4894 char *fname=NULL;
4895 config_line_t *p_index;
4896 const char *fname_opt = defaults_file ? "--defaults-torrc" : "-f";
4897 const char *ignore_opt = defaults_file ? NULL : "--ignore-missing-torrc";
4899 if (defaults_file)
4900 *ignore_missing_torrc = 1;
4902 for (p_index = cmd_arg; p_index; p_index = p_index->next) {
4903 if (!strcmp(p_index->key, fname_opt)) {
4904 if (fname) {
4905 log_warn(LD_CONFIG, "Duplicate %s options on command line.",
4906 fname_opt);
4907 tor_free(fname);
4909 fname = expand_filename(p_index->value);
4912 char *absfname;
4913 absfname = make_path_absolute(fname);
4914 tor_free(fname);
4915 fname = absfname;
4918 *using_default_fname = 0;
4919 } else if (ignore_opt && !strcmp(p_index->key,ignore_opt)) {
4920 *ignore_missing_torrc = 1;
4924 if (*using_default_fname) {
4925 /* didn't find one, try CONFDIR */
4926 const char *dflt = get_default_conf_file(defaults_file);
4927 file_status_t st = file_status(dflt);
4928 if (dflt && (st == FN_FILE || st == FN_EMPTY)) {
4929 fname = tor_strdup(dflt);
4930 } else {
4931 #ifndef _WIN32
4932 char *fn = NULL;
4933 if (!defaults_file) {
4934 fn = expand_filename("~/.torrc");
4936 if (fn) {
4937 file_status_t hmst = file_status(fn);
4938 if (hmst == FN_FILE || hmst == FN_EMPTY || dflt == NULL) {
4939 fname = fn;
4940 } else {
4941 tor_free(fn);
4942 fname = tor_strdup(dflt);
4944 } else {
4945 fname = dflt ? tor_strdup(dflt) : NULL;
4947 #else /* !(!defined(_WIN32)) */
4948 fname = dflt ? tor_strdup(dflt) : NULL;
4949 #endif /* !defined(_WIN32) */
4952 return fname;
4955 /** Read the torrc from standard input and return it as a string.
4956 * Upon failure, return NULL.
4958 static char *
4959 load_torrc_from_stdin(void)
4961 size_t sz_out;
4963 return read_file_to_str_until_eof(STDIN_FILENO,SIZE_MAX,&sz_out);
4966 /** Load a configuration file from disk, setting torrc_fname or
4967 * torrc_defaults_fname if successful.
4969 * If <b>defaults_file</b> is true, load torrc-defaults; otherwise load torrc.
4971 * Return the contents of the file on success, and NULL on failure.
4973 static char *
4974 load_torrc_from_disk(config_line_t *cmd_arg, int defaults_file)
4976 char *fname=NULL;
4977 char *cf = NULL;
4978 int using_default_torrc = 1;
4979 int ignore_missing_torrc = 0;
4980 char **fname_var = defaults_file ? &torrc_defaults_fname : &torrc_fname;
4982 if (*fname_var == NULL) {
4983 fname = find_torrc_filename(cmd_arg, defaults_file,
4984 &using_default_torrc, &ignore_missing_torrc);
4985 tor_free(*fname_var);
4986 *fname_var = fname;
4987 } else {
4988 fname = *fname_var;
4990 log_debug(LD_CONFIG, "Opening config file \"%s\"", fname?fname:"<NULL>");
4992 /* Open config file */
4993 file_status_t st = fname ? file_status(fname) : FN_EMPTY;
4994 if (fname == NULL ||
4995 !(st == FN_FILE || st == FN_EMPTY) ||
4996 !(cf = read_file_to_str(fname,0,NULL))) {
4997 if (using_default_torrc == 1 || ignore_missing_torrc) {
4998 if (!defaults_file)
4999 log_notice(LD_CONFIG, "Configuration file \"%s\" not present, "
5000 "using reasonable defaults.", fname);
5001 tor_free(fname); /* sets fname to NULL */
5002 *fname_var = NULL;
5003 cf = tor_strdup("");
5004 } else {
5005 log_warn(LD_CONFIG,
5006 "Unable to open configuration file \"%s\".", fname);
5007 goto err;
5009 } else {
5010 log_notice(LD_CONFIG, "Read configuration file \"%s\".", fname);
5013 return cf;
5014 err:
5015 tor_free(fname);
5016 *fname_var = NULL;
5017 return NULL;
5020 /** Read a configuration file into <b>options</b>, finding the configuration
5021 * file location based on the command line. After loading the file
5022 * call options_init_from_string() to load the config.
5023 * Return 0 if success, -1 if failure. */
5025 options_init_from_torrc(int argc, char **argv)
5027 char *cf=NULL, *cf_defaults=NULL;
5028 int command;
5029 int retval = -1;
5030 char *command_arg = NULL;
5031 char *errmsg=NULL;
5032 config_line_t *p_index = NULL;
5033 config_line_t *cmdline_only_options = NULL;
5035 /* Go through command-line variables */
5036 if (! have_parsed_cmdline) {
5037 /* Or we could redo the list every time we pass this place.
5038 * It does not really matter */
5039 if (config_parse_commandline(argc, argv, 0, &global_cmdline_options,
5040 &global_cmdline_only_options) < 0) {
5041 goto err;
5043 have_parsed_cmdline = 1;
5045 cmdline_only_options = global_cmdline_only_options;
5047 if (config_line_find(cmdline_only_options, "-h") ||
5048 config_line_find(cmdline_only_options, "--help")) {
5049 print_usage();
5050 exit(0);
5052 if (config_line_find(cmdline_only_options, "--list-torrc-options")) {
5053 /* For validating whether we've documented everything. */
5054 list_torrc_options();
5055 exit(0);
5057 if (config_line_find(cmdline_only_options, "--list-deprecated-options")) {
5058 /* For validating whether what we have deprecated really exists. */
5059 list_deprecated_options();
5060 exit(0);
5063 if (config_line_find(cmdline_only_options, "--version")) {
5064 printf("Tor version %s.\n",get_version());
5065 exit(0);
5068 if (config_line_find(cmdline_only_options, "--library-versions")) {
5069 printf("Tor version %s. \n", get_version());
5070 printf("Library versions\tCompiled\t\tRuntime\n");
5071 printf("Libevent\t\t%-15s\t\t%s\n",
5072 tor_libevent_get_header_version_str(),
5073 tor_libevent_get_version_str());
5074 printf("OpenSSL \t\t%-15s\t\t%s\n",
5075 crypto_openssl_get_header_version_str(),
5076 crypto_openssl_get_version_str());
5077 if (tor_compress_supports_method(ZLIB_METHOD)) {
5078 printf("Zlib \t\t%-15s\t\t%s\n",
5079 tor_compress_version_str(ZLIB_METHOD),
5080 tor_compress_header_version_str(ZLIB_METHOD));
5082 if (tor_compress_supports_method(LZMA_METHOD)) {
5083 printf("Liblzma \t\t%-15s\t\t%s\n",
5084 tor_compress_version_str(LZMA_METHOD),
5085 tor_compress_header_version_str(LZMA_METHOD));
5087 if (tor_compress_supports_method(ZSTD_METHOD)) {
5088 printf("Libzstd \t\t%-15s\t\t%s\n",
5089 tor_compress_version_str(ZSTD_METHOD),
5090 tor_compress_header_version_str(ZSTD_METHOD));
5092 //TODO: Hex versions?
5093 exit(0);
5096 command = CMD_RUN_TOR;
5097 for (p_index = cmdline_only_options; p_index; p_index = p_index->next) {
5098 if (!strcmp(p_index->key,"--keygen")) {
5099 command = CMD_KEYGEN;
5100 } else if (!strcmp(p_index->key, "--key-expiration")) {
5101 command = CMD_KEY_EXPIRATION;
5102 command_arg = p_index->value;
5103 } else if (!strcmp(p_index->key,"--list-fingerprint")) {
5104 command = CMD_LIST_FINGERPRINT;
5105 } else if (!strcmp(p_index->key, "--hash-password")) {
5106 command = CMD_HASH_PASSWORD;
5107 command_arg = p_index->value;
5108 } else if (!strcmp(p_index->key, "--dump-config")) {
5109 command = CMD_DUMP_CONFIG;
5110 command_arg = p_index->value;
5111 } else if (!strcmp(p_index->key, "--verify-config")) {
5112 command = CMD_VERIFY_CONFIG;
5116 if (command == CMD_HASH_PASSWORD) {
5117 cf_defaults = tor_strdup("");
5118 cf = tor_strdup("");
5119 } else {
5120 cf_defaults = load_torrc_from_disk(cmdline_only_options, 1);
5122 const config_line_t *f_line = config_line_find(cmdline_only_options,
5123 "-f");
5125 const int read_torrc_from_stdin =
5126 (f_line != NULL && strcmp(f_line->value, "-") == 0);
5128 if (read_torrc_from_stdin) {
5129 cf = load_torrc_from_stdin();
5130 } else {
5131 cf = load_torrc_from_disk(cmdline_only_options, 0);
5134 if (!cf) {
5135 if (config_line_find(cmdline_only_options, "--allow-missing-torrc")) {
5136 cf = tor_strdup("");
5137 } else {
5138 goto err;
5143 retval = options_init_from_string(cf_defaults, cf, command, command_arg,
5144 &errmsg);
5146 if (retval < 0)
5147 goto err;
5149 if (config_line_find(cmdline_only_options, "--no-passphrase")) {
5150 if (command == CMD_KEYGEN) {
5151 get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_OFF;
5152 } else {
5153 log_err(LD_CONFIG, "--no-passphrase specified without --keygen!");
5154 exit(1);
5158 if (config_line_find(cmdline_only_options, "--newpass")) {
5159 if (command == CMD_KEYGEN) {
5160 get_options_mutable()->change_key_passphrase = 1;
5161 } else {
5162 log_err(LD_CONFIG, "--newpass specified without --keygen!");
5163 exit(1);
5168 const config_line_t *fd_line = config_line_find(cmdline_only_options,
5169 "--passphrase-fd");
5170 if (fd_line) {
5171 if (get_options()->keygen_force_passphrase == FORCE_PASSPHRASE_OFF) {
5172 log_err(LD_CONFIG, "--no-passphrase specified with --passphrase-fd!");
5173 exit(1);
5174 } else if (command != CMD_KEYGEN) {
5175 log_err(LD_CONFIG, "--passphrase-fd specified without --keygen!");
5176 exit(1);
5177 } else {
5178 const char *v = fd_line->value;
5179 int ok = 1;
5180 long fd = tor_parse_long(v, 10, 0, INT_MAX, &ok, NULL);
5181 if (fd < 0 || ok == 0) {
5182 log_err(LD_CONFIG, "Invalid --passphrase-fd value %s", escaped(v));
5183 exit(1);
5185 get_options_mutable()->keygen_passphrase_fd = (int)fd;
5186 get_options_mutable()->use_keygen_passphrase_fd = 1;
5187 get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_ON;
5193 const config_line_t *key_line = config_line_find(cmdline_only_options,
5194 "--master-key");
5195 if (key_line) {
5196 if (command != CMD_KEYGEN) {
5197 log_err(LD_CONFIG, "--master-key without --keygen!");
5198 exit(1);
5199 } else {
5200 get_options_mutable()->master_key_fname = tor_strdup(key_line->value);
5205 err:
5207 tor_free(cf);
5208 tor_free(cf_defaults);
5209 if (errmsg) {
5210 log_warn(LD_CONFIG,"%s", errmsg);
5211 tor_free(errmsg);
5213 return retval < 0 ? -1 : 0;
5216 /** Load the options from the configuration in <b>cf</b>, validate
5217 * them for consistency and take actions based on them.
5219 * Return 0 if success, negative on error:
5220 * * -1 for general errors.
5221 * * -2 for failure to parse/validate,
5222 * * -3 for transition not allowed
5223 * * -4 for error while setting the new options
5225 setopt_err_t
5226 options_init_from_string(const char *cf_defaults, const char *cf,
5227 int command, const char *command_arg,
5228 char **msg)
5230 or_options_t *oldoptions, *newoptions, *newdefaultoptions=NULL;
5231 config_line_t *cl;
5232 int retval;
5233 setopt_err_t err = SETOPT_ERR_MISC;
5234 int cf_has_include = 0;
5235 tor_assert(msg);
5237 oldoptions = global_options; /* get_options unfortunately asserts if
5238 this is the first time we run*/
5240 newoptions = tor_malloc_zero(sizeof(or_options_t));
5241 newoptions->magic_ = OR_OPTIONS_MAGIC;
5242 options_init(newoptions);
5243 newoptions->command = command;
5244 newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
5246 for (int i = 0; i < 2; ++i) {
5247 const char *body = i==0 ? cf_defaults : cf;
5248 if (!body)
5249 continue;
5250 /* get config lines, assign them */
5251 retval = config_get_lines_include(body, &cl, 1,
5252 body == cf ? &cf_has_include : NULL);
5253 if (retval < 0) {
5254 err = SETOPT_ERR_PARSE;
5255 goto err;
5257 retval = config_assign(&options_format, newoptions, cl,
5258 CAL_WARN_DEPRECATIONS, msg);
5259 config_free_lines(cl);
5260 if (retval < 0) {
5261 err = SETOPT_ERR_PARSE;
5262 goto err;
5264 if (i==0)
5265 newdefaultoptions = config_dup(&options_format, newoptions);
5268 if (newdefaultoptions == NULL) {
5269 newdefaultoptions = config_dup(&options_format, global_default_options);
5272 /* Go through command-line variables too */
5273 retval = config_assign(&options_format, newoptions,
5274 global_cmdline_options, CAL_WARN_DEPRECATIONS, msg);
5275 if (retval < 0) {
5276 err = SETOPT_ERR_PARSE;
5277 goto err;
5280 newoptions->IncludeUsed = cf_has_include;
5282 /* If this is a testing network configuration, change defaults
5283 * for a list of dependent config options, re-initialize newoptions
5284 * with the new defaults, and assign all options to it second time. */
5285 if (newoptions->TestingTorNetwork) {
5286 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
5287 * this? We could, for example, make the parsing algorithm do two passes
5288 * over the configuration. If it finds any "suite" options like
5289 * TestingTorNetwork, it could change the defaults before its second pass.
5290 * Not urgent so long as this seems to work, but at any sign of trouble,
5291 * let's clean it up. -NM */
5293 /* Change defaults. */
5294 for (int i = 0; testing_tor_network_defaults[i].name; ++i) {
5295 const config_var_t *new_var = &testing_tor_network_defaults[i];
5296 config_var_t *old_var =
5297 config_find_option_mutable(&options_format, new_var->name);
5298 tor_assert(new_var);
5299 tor_assert(old_var);
5300 old_var->initvalue = new_var->initvalue;
5302 if ((config_find_deprecation(&options_format, new_var->name))) {
5303 log_warn(LD_GENERAL, "Testing options override the deprecated "
5304 "option %s. Is that intentional?",
5305 new_var->name);
5309 /* Clear newoptions and re-initialize them with new defaults. */
5310 or_options_free(newoptions);
5311 or_options_free(newdefaultoptions);
5312 newdefaultoptions = NULL;
5313 newoptions = tor_malloc_zero(sizeof(or_options_t));
5314 newoptions->magic_ = OR_OPTIONS_MAGIC;
5315 options_init(newoptions);
5316 newoptions->command = command;
5317 newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
5319 /* Assign all options a second time. */
5320 for (int i = 0; i < 2; ++i) {
5321 const char *body = i==0 ? cf_defaults : cf;
5322 if (!body)
5323 continue;
5324 /* get config lines, assign them */
5325 retval = config_get_lines_include(body, &cl, 1,
5326 body == cf ? &cf_has_include : NULL);
5327 if (retval < 0) {
5328 err = SETOPT_ERR_PARSE;
5329 goto err;
5331 retval = config_assign(&options_format, newoptions, cl, 0, msg);
5332 config_free_lines(cl);
5333 if (retval < 0) {
5334 err = SETOPT_ERR_PARSE;
5335 goto err;
5337 if (i==0)
5338 newdefaultoptions = config_dup(&options_format, newoptions);
5340 /* Assign command-line variables a second time too */
5341 retval = config_assign(&options_format, newoptions,
5342 global_cmdline_options, 0, msg);
5343 if (retval < 0) {
5344 err = SETOPT_ERR_PARSE;
5345 goto err;
5349 newoptions->IncludeUsed = cf_has_include;
5350 in_option_validation = 1;
5352 /* Validate newoptions */
5353 if (options_validate(oldoptions, newoptions, newdefaultoptions,
5354 0, msg) < 0) {
5355 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
5356 goto err;
5359 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
5360 err = SETOPT_ERR_TRANSITION;
5361 goto err;
5363 in_option_validation = 0;
5365 if (set_options(newoptions, msg)) {
5366 err = SETOPT_ERR_SETTING;
5367 goto err; /* frees and replaces old options */
5370 or_options_free(global_default_options);
5371 global_default_options = newdefaultoptions;
5373 return SETOPT_OK;
5375 err:
5376 in_option_validation = 0;
5377 or_options_free(newoptions);
5378 or_options_free(newdefaultoptions);
5379 if (*msg) {
5380 char *old_msg = *msg;
5381 tor_asprintf(msg, "Failed to parse/validate config: %s", old_msg);
5382 tor_free(old_msg);
5384 return err;
5387 /** Return the location for our configuration file. May return NULL.
5389 const char *
5390 get_torrc_fname(int defaults_fname)
5392 const char *fname = defaults_fname ? torrc_defaults_fname : torrc_fname;
5394 if (fname)
5395 return fname;
5396 else
5397 return get_default_conf_file(defaults_fname);
5400 /** Adjust the address map based on the MapAddress elements in the
5401 * configuration <b>options</b>
5403 void
5404 config_register_addressmaps(const or_options_t *options)
5406 smartlist_t *elts;
5407 config_line_t *opt;
5408 const char *from, *to, *msg;
5410 addressmap_clear_configured();
5411 elts = smartlist_new();
5412 for (opt = options->AddressMap; opt; opt = opt->next) {
5413 smartlist_split_string(elts, opt->value, NULL,
5414 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
5415 if (smartlist_len(elts) < 2) {
5416 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
5417 opt->value);
5418 goto cleanup;
5421 from = smartlist_get(elts,0);
5422 to = smartlist_get(elts,1);
5424 if (to[0] == '.' || from[0] == '.') {
5425 log_warn(LD_CONFIG,"MapAddress '%s' is ambiguous - address starts with a"
5426 "'.'. Ignoring.",opt->value);
5427 goto cleanup;
5430 if (addressmap_register_auto(from, to, 0, ADDRMAPSRC_TORRC, &msg) < 0) {
5431 log_warn(LD_CONFIG,"MapAddress '%s' failed: %s. Ignoring.", opt->value,
5432 msg);
5433 goto cleanup;
5436 if (smartlist_len(elts) > 2)
5437 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
5439 cleanup:
5440 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
5441 smartlist_clear(elts);
5443 smartlist_free(elts);
5446 /** As addressmap_register(), but detect the wildcarded status of "from" and
5447 * "to", and do not steal a reference to <b>to</b>. */
5448 /* XXXX move to connection_edge.c */
5450 addressmap_register_auto(const char *from, const char *to,
5451 time_t expires,
5452 addressmap_entry_source_t addrmap_source,
5453 const char **msg)
5455 int from_wildcard = 0, to_wildcard = 0;
5457 *msg = "whoops, forgot the error message";
5459 if (!strcmp(to, "*") || !strcmp(from, "*")) {
5460 *msg = "can't remap from or to *";
5461 return -1;
5463 /* Detect asterisks in expressions of type: '*.example.com' */
5464 if (!strncmp(from,"*.",2)) {
5465 from += 2;
5466 from_wildcard = 1;
5468 if (!strncmp(to,"*.",2)) {
5469 to += 2;
5470 to_wildcard = 1;
5473 if (to_wildcard && !from_wildcard) {
5474 *msg = "can only use wildcard (i.e. '*.') if 'from' address "
5475 "uses wildcard also";
5476 return -1;
5479 if (address_is_invalid_destination(to, 1)) {
5480 *msg = "destination is invalid";
5481 return -1;
5484 addressmap_register(from, tor_strdup(to), expires, addrmap_source,
5485 from_wildcard, to_wildcard);
5487 return 0;
5491 * Initialize the logs based on the configuration file.
5493 static int
5494 options_init_logs(const or_options_t *old_options, or_options_t *options,
5495 int validate_only)
5497 config_line_t *opt;
5498 int ok;
5499 smartlist_t *elts;
5500 int run_as_daemon =
5501 #ifdef _WIN32
5503 #else
5504 options->RunAsDaemon;
5505 #endif
5507 if (options->LogTimeGranularity <= 0) {
5508 log_warn(LD_CONFIG, "Log time granularity '%d' has to be positive.",
5509 options->LogTimeGranularity);
5510 return -1;
5511 } else if (1000 % options->LogTimeGranularity != 0 &&
5512 options->LogTimeGranularity % 1000 != 0) {
5513 int granularity = options->LogTimeGranularity;
5514 if (granularity < 40) {
5515 do granularity++;
5516 while (1000 % granularity != 0);
5517 } else if (granularity < 1000) {
5518 granularity = 1000 / granularity;
5519 while (1000 % granularity != 0)
5520 granularity--;
5521 granularity = 1000 / granularity;
5522 } else {
5523 granularity = 1000 * ((granularity / 1000) + 1);
5525 log_warn(LD_CONFIG, "Log time granularity '%d' has to be either a "
5526 "divisor or a multiple of 1 second. Changing to "
5527 "'%d'.",
5528 options->LogTimeGranularity, granularity);
5529 if (!validate_only)
5530 set_log_time_granularity(granularity);
5531 } else {
5532 if (!validate_only)
5533 set_log_time_granularity(options->LogTimeGranularity);
5536 ok = 1;
5537 elts = smartlist_new();
5539 for (opt = options->Logs; opt; opt = opt->next) {
5540 log_severity_list_t *severity;
5541 const char *cfg = opt->value;
5542 severity = tor_malloc_zero(sizeof(log_severity_list_t));
5543 if (parse_log_severity_config(&cfg, severity) < 0) {
5544 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
5545 opt->value);
5546 ok = 0; goto cleanup;
5549 smartlist_split_string(elts, cfg, NULL,
5550 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
5552 if (smartlist_len(elts) == 0)
5553 smartlist_add_strdup(elts, "stdout");
5555 if (smartlist_len(elts) == 1 &&
5556 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
5557 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
5558 int err = smartlist_len(elts) &&
5559 !strcasecmp(smartlist_get(elts,0), "stderr");
5560 if (!validate_only) {
5561 if (run_as_daemon) {
5562 log_warn(LD_CONFIG,
5563 "Can't log to %s with RunAsDaemon set; skipping stdout",
5564 err?"stderr":"stdout");
5565 } else {
5566 add_stream_log(severity, err?"<stderr>":"<stdout>",
5567 fileno(err?stderr:stdout));
5570 goto cleanup;
5572 if (smartlist_len(elts) == 1 &&
5573 !strcasecmp(smartlist_get(elts,0), "syslog")) {
5574 #ifdef HAVE_SYSLOG_H
5575 if (!validate_only) {
5576 add_syslog_log(severity, options->SyslogIdentityTag);
5578 #else
5579 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
5580 #endif /* defined(HAVE_SYSLOG_H) */
5581 goto cleanup;
5584 if (smartlist_len(elts) == 2 &&
5585 !strcasecmp(smartlist_get(elts,0), "file")) {
5586 if (!validate_only) {
5587 char *fname = expand_filename(smartlist_get(elts, 1));
5588 /* Truncate if TruncateLogFile is set and we haven't seen this option
5589 line before. */
5590 int truncate_log = 0;
5591 if (options->TruncateLogFile) {
5592 truncate_log = 1;
5593 if (old_options) {
5594 config_line_t *opt2;
5595 for (opt2 = old_options->Logs; opt2; opt2 = opt2->next)
5596 if (!strcmp(opt->value, opt2->value)) {
5597 truncate_log = 0;
5598 break;
5602 if (add_file_log(severity, fname, truncate_log) < 0) {
5603 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
5604 opt->value, strerror(errno));
5605 ok = 0;
5607 tor_free(fname);
5609 goto cleanup;
5612 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
5613 opt->value);
5614 ok = 0; goto cleanup;
5616 cleanup:
5617 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
5618 smartlist_clear(elts);
5619 tor_free(severity);
5621 smartlist_free(elts);
5623 if (ok && !validate_only)
5624 logs_set_domain_logging(options->LogMessageDomains);
5626 return ok?0:-1;
5629 /** Given a smartlist of SOCKS arguments to be passed to a transport
5630 * proxy in <b>args</b>, validate them and return -1 if they are
5631 * corrupted. Return 0 if they seem OK. */
5632 static int
5633 validate_transport_socks_arguments(const smartlist_t *args)
5635 char *socks_string = NULL;
5636 size_t socks_string_len;
5638 tor_assert(args);
5639 tor_assert(smartlist_len(args) > 0);
5641 SMARTLIST_FOREACH_BEGIN(args, const char *, s) {
5642 if (!string_is_key_value(LOG_WARN, s)) { /* items should be k=v items */
5643 log_warn(LD_CONFIG, "'%s' is not a k=v item.", s);
5644 return -1;
5646 } SMARTLIST_FOREACH_END(s);
5648 socks_string = pt_stringify_socks_args(args);
5649 if (!socks_string)
5650 return -1;
5652 socks_string_len = strlen(socks_string);
5653 tor_free(socks_string);
5655 if (socks_string_len > MAX_SOCKS5_AUTH_SIZE_TOTAL) {
5656 log_warn(LD_CONFIG, "SOCKS arguments can't be more than %u bytes (%lu).",
5657 MAX_SOCKS5_AUTH_SIZE_TOTAL,
5658 (unsigned long) socks_string_len);
5659 return -1;
5662 return 0;
5665 /** Deallocate a bridge_line_t structure. */
5666 /* private */ void
5667 bridge_line_free(bridge_line_t *bridge_line)
5669 if (!bridge_line)
5670 return;
5672 if (bridge_line->socks_args) {
5673 SMARTLIST_FOREACH(bridge_line->socks_args, char*, s, tor_free(s));
5674 smartlist_free(bridge_line->socks_args);
5676 tor_free(bridge_line->transport_name);
5677 tor_free(bridge_line);
5680 /** Parse the contents of a string, <b>line</b>, containing a Bridge line,
5681 * into a bridge_line_t.
5683 * Validates that the IP:PORT, fingerprint, and SOCKS arguments (given to the
5684 * Pluggable Transport, if a one was specified) are well-formed.
5686 * Returns NULL If the Bridge line could not be validated, and returns a
5687 * bridge_line_t containing the parsed information otherwise.
5689 * Bridge line format:
5690 * Bridge [transport] IP:PORT [id-fingerprint] [k=v] [k=v] ...
5692 /* private */ bridge_line_t *
5693 parse_bridge_line(const char *line)
5695 smartlist_t *items = NULL;
5696 char *addrport=NULL, *fingerprint=NULL;
5697 char *field=NULL;
5698 bridge_line_t *bridge_line = tor_malloc_zero(sizeof(bridge_line_t));
5700 items = smartlist_new();
5701 smartlist_split_string(items, line, NULL,
5702 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5703 if (smartlist_len(items) < 1) {
5704 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
5705 goto err;
5708 /* first field is either a transport name or addrport */
5709 field = smartlist_get(items, 0);
5710 smartlist_del_keeporder(items, 0);
5712 if (string_is_C_identifier(field)) {
5713 /* It's a transport name. */
5714 bridge_line->transport_name = field;
5715 if (smartlist_len(items) < 1) {
5716 log_warn(LD_CONFIG, "Too few items to Bridge line.");
5717 goto err;
5719 addrport = smartlist_get(items, 0); /* Next field is addrport then. */
5720 smartlist_del_keeporder(items, 0);
5721 } else {
5722 addrport = field;
5725 if (tor_addr_port_parse(LOG_INFO, addrport,
5726 &bridge_line->addr, &bridge_line->port, 443)<0) {
5727 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
5728 goto err;
5731 /* If transports are enabled, next field could be a fingerprint or a
5732 socks argument. If transports are disabled, next field must be
5733 a fingerprint. */
5734 if (smartlist_len(items)) {
5735 if (bridge_line->transport_name) { /* transports enabled: */
5736 field = smartlist_get(items, 0);
5737 smartlist_del_keeporder(items, 0);
5739 /* If it's a key=value pair, then it's a SOCKS argument for the
5740 transport proxy... */
5741 if (string_is_key_value(LOG_DEBUG, field)) {
5742 bridge_line->socks_args = smartlist_new();
5743 smartlist_add(bridge_line->socks_args, field);
5744 } else { /* ...otherwise, it's the bridge fingerprint. */
5745 fingerprint = field;
5748 } else { /* transports disabled: */
5749 fingerprint = smartlist_join_strings(items, "", 0, NULL);
5753 /* Handle fingerprint, if it was provided. */
5754 if (fingerprint) {
5755 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
5756 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
5757 goto err;
5759 if (base16_decode(bridge_line->digest, DIGEST_LEN,
5760 fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
5761 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
5762 goto err;
5766 /* If we are using transports, any remaining items in the smartlist
5767 should be k=v values. */
5768 if (bridge_line->transport_name && smartlist_len(items)) {
5769 if (!bridge_line->socks_args)
5770 bridge_line->socks_args = smartlist_new();
5772 /* append remaining items of 'items' to 'socks_args' */
5773 smartlist_add_all(bridge_line->socks_args, items);
5774 smartlist_clear(items);
5776 tor_assert(smartlist_len(bridge_line->socks_args) > 0);
5779 if (bridge_line->socks_args) {
5780 if (validate_transport_socks_arguments(bridge_line->socks_args) < 0)
5781 goto err;
5784 goto done;
5786 err:
5787 bridge_line_free(bridge_line);
5788 bridge_line = NULL;
5790 done:
5791 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5792 smartlist_free(items);
5793 tor_free(addrport);
5794 tor_free(fingerprint);
5796 return bridge_line;
5799 /** Read the contents of a ClientTransportPlugin or ServerTransportPlugin
5800 * line from <b>line</b>, depending on the value of <b>server</b>. Return 0
5801 * if the line is well-formed, and -1 if it isn't.
5803 * If <b>validate_only</b> is 0, the line is well-formed, and the transport is
5804 * needed by some bridge:
5805 * - If it's an external proxy line, add the transport described in the line to
5806 * our internal transport list.
5807 * - If it's a managed proxy line, launch the managed proxy.
5810 STATIC int
5811 parse_transport_line(const or_options_t *options,
5812 const char *line, int validate_only,
5813 int server)
5816 smartlist_t *items = NULL;
5817 int r;
5818 const char *transports = NULL;
5819 smartlist_t *transport_list = NULL;
5820 char *type = NULL;
5821 char *addrport = NULL;
5822 tor_addr_t addr;
5823 uint16_t port = 0;
5824 int socks_ver = PROXY_NONE;
5826 /* managed proxy options */
5827 int is_managed = 0;
5828 char **proxy_argv = NULL;
5829 char **tmp = NULL;
5830 int proxy_argc, i;
5831 int is_useless_proxy = 1;
5833 int line_length;
5835 /* Split the line into space-separated tokens */
5836 items = smartlist_new();
5837 smartlist_split_string(items, line, NULL,
5838 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5839 line_length = smartlist_len(items);
5841 if (line_length < 3) {
5842 log_warn(LD_CONFIG,
5843 "Too few arguments on %sTransportPlugin line.",
5844 server ? "Server" : "Client");
5845 goto err;
5848 /* Get the first line element, split it to commas into
5849 transport_list (in case it's multiple transports) and validate
5850 the transport names. */
5851 transports = smartlist_get(items, 0);
5852 transport_list = smartlist_new();
5853 smartlist_split_string(transport_list, transports, ",",
5854 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
5855 SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
5856 /* validate transport names */
5857 if (!string_is_C_identifier(transport_name)) {
5858 log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
5859 transport_name);
5860 goto err;
5863 /* see if we actually need the transports provided by this proxy */
5864 if (!validate_only && transport_is_needed(transport_name))
5865 is_useless_proxy = 0;
5866 } SMARTLIST_FOREACH_END(transport_name);
5868 type = smartlist_get(items, 1);
5869 if (!strcmp(type, "exec")) {
5870 is_managed = 1;
5871 } else if (server && !strcmp(type, "proxy")) {
5872 /* 'proxy' syntax only with ServerTransportPlugin */
5873 is_managed = 0;
5874 } else if (!server && !strcmp(type, "socks4")) {
5875 /* 'socks4' syntax only with ClientTransportPlugin */
5876 is_managed = 0;
5877 socks_ver = PROXY_SOCKS4;
5878 } else if (!server && !strcmp(type, "socks5")) {
5879 /* 'socks5' syntax only with ClientTransportPlugin */
5880 is_managed = 0;
5881 socks_ver = PROXY_SOCKS5;
5882 } else {
5883 log_warn(LD_CONFIG,
5884 "Strange %sTransportPlugin type '%s'",
5885 server ? "Server" : "Client", type);
5886 goto err;
5889 if (is_managed && options->Sandbox) {
5890 log_warn(LD_CONFIG,
5891 "Managed proxies are not compatible with Sandbox mode."
5892 "(%sTransportPlugin line was %s)",
5893 server ? "Server" : "Client", escaped(line));
5894 goto err;
5897 if (is_managed && options->NoExec) {
5898 log_warn(LD_CONFIG,
5899 "Managed proxies are not compatible with NoExec mode; ignoring."
5900 "(%sTransportPlugin line was %s)",
5901 server ? "Server" : "Client", escaped(line));
5902 r = 0;
5903 goto done;
5906 if (is_managed) {
5907 /* managed */
5909 if (!server && !validate_only && is_useless_proxy) {
5910 log_info(LD_GENERAL,
5911 "Pluggable transport proxy (%s) does not provide "
5912 "any needed transports and will not be launched.",
5913 line);
5917 * If we are not just validating, use the rest of the line as the
5918 * argv of the proxy to be launched. Also, make sure that we are
5919 * only launching proxies that contribute useful transports.
5922 if (!validate_only && (server || !is_useless_proxy)) {
5923 proxy_argc = line_length - 2;
5924 tor_assert(proxy_argc > 0);
5925 proxy_argv = tor_calloc((proxy_argc + 1), sizeof(char *));
5926 tmp = proxy_argv;
5928 for (i = 0; i < proxy_argc; i++) {
5929 /* store arguments */
5930 *tmp++ = smartlist_get(items, 2);
5931 smartlist_del_keeporder(items, 2);
5933 *tmp = NULL; /* terminated with NULL, just like execve() likes it */
5935 /* kickstart the thing */
5936 if (server) {
5937 pt_kickstart_server_proxy(transport_list, proxy_argv);
5938 } else {
5939 pt_kickstart_client_proxy(transport_list, proxy_argv);
5942 } else {
5943 /* external */
5945 /* ClientTransportPlugins connecting through a proxy is managed only. */
5946 if (!server && (options->Socks4Proxy || options->Socks5Proxy ||
5947 options->HTTPSProxy)) {
5948 log_warn(LD_CONFIG, "You have configured an external proxy with another "
5949 "proxy type. (Socks4Proxy|Socks5Proxy|HTTPSProxy)");
5950 goto err;
5953 if (smartlist_len(transport_list) != 1) {
5954 log_warn(LD_CONFIG,
5955 "You can't have an external proxy with more than "
5956 "one transport.");
5957 goto err;
5960 addrport = smartlist_get(items, 2);
5962 if (tor_addr_port_lookup(addrport, &addr, &port) < 0) {
5963 log_warn(LD_CONFIG,
5964 "Error parsing transport address '%s'", addrport);
5965 goto err;
5968 if (!port) {
5969 log_warn(LD_CONFIG,
5970 "Transport address '%s' has no port.", addrport);
5971 goto err;
5974 if (!validate_only) {
5975 log_info(LD_DIR, "%s '%s' at %s.",
5976 server ? "Server transport" : "Transport",
5977 transports, fmt_addrport(&addr, port));
5979 if (!server) {
5980 transport_add_from_config(&addr, port,
5981 smartlist_get(transport_list, 0),
5982 socks_ver);
5987 r = 0;
5988 goto done;
5990 err:
5991 r = -1;
5993 done:
5994 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5995 smartlist_free(items);
5996 if (transport_list) {
5997 SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
5998 smartlist_free(transport_list);
6001 return r;
6004 /** Given a ServerTransportListenAddr <b>line</b>, return its
6005 * <address:port> string. Return NULL if the line was not
6006 * well-formed.
6008 * If <b>transport</b> is set, return NULL if the line is not
6009 * referring to <b>transport</b>.
6011 * The returned string is allocated on the heap and it's the
6012 * responsibility of the caller to free it. */
6013 static char *
6014 get_bindaddr_from_transport_listen_line(const char *line,const char *transport)
6016 smartlist_t *items = NULL;
6017 const char *parsed_transport = NULL;
6018 char *addrport = NULL;
6019 tor_addr_t addr;
6020 uint16_t port = 0;
6022 items = smartlist_new();
6023 smartlist_split_string(items, line, NULL,
6024 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6026 if (smartlist_len(items) < 2) {
6027 log_warn(LD_CONFIG,"Too few arguments on ServerTransportListenAddr line.");
6028 goto err;
6031 parsed_transport = smartlist_get(items, 0);
6032 addrport = tor_strdup(smartlist_get(items, 1));
6034 /* If 'transport' is given, check if it matches the one on the line */
6035 if (transport && strcmp(transport, parsed_transport))
6036 goto err;
6038 /* Validate addrport */
6039 if (tor_addr_port_parse(LOG_WARN, addrport, &addr, &port, -1)<0) {
6040 log_warn(LD_CONFIG, "Error parsing ServerTransportListenAddr "
6041 "address '%s'", addrport);
6042 goto err;
6045 goto done;
6047 err:
6048 tor_free(addrport);
6049 addrport = NULL;
6051 done:
6052 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
6053 smartlist_free(items);
6055 return addrport;
6058 /** Given a ServerTransportOptions <b>line</b>, return a smartlist
6059 * with the options. Return NULL if the line was not well-formed.
6061 * If <b>transport</b> is set, return NULL if the line is not
6062 * referring to <b>transport</b>.
6064 * The returned smartlist and its strings are allocated on the heap
6065 * and it's the responsibility of the caller to free it. */
6066 smartlist_t *
6067 get_options_from_transport_options_line(const char *line,const char *transport)
6069 smartlist_t *items = smartlist_new();
6070 smartlist_t *options = smartlist_new();
6071 const char *parsed_transport = NULL;
6073 smartlist_split_string(items, line, NULL,
6074 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6076 if (smartlist_len(items) < 2) {
6077 log_warn(LD_CONFIG,"Too few arguments on ServerTransportOptions line.");
6078 goto err;
6081 parsed_transport = smartlist_get(items, 0);
6082 /* If 'transport' is given, check if it matches the one on the line */
6083 if (transport && strcmp(transport, parsed_transport))
6084 goto err;
6086 SMARTLIST_FOREACH_BEGIN(items, const char *, option) {
6087 if (option_sl_idx == 0) /* skip the transport field (first field)*/
6088 continue;
6090 /* validate that it's a k=v value */
6091 if (!string_is_key_value(LOG_WARN, option)) {
6092 log_warn(LD_CONFIG, "%s is not a k=v value.", escaped(option));
6093 goto err;
6096 /* add it to the options smartlist */
6097 smartlist_add_strdup(options, option);
6098 log_debug(LD_CONFIG, "Added %s to the list of options", escaped(option));
6099 } SMARTLIST_FOREACH_END(option);
6101 goto done;
6103 err:
6104 SMARTLIST_FOREACH(options, char*, s, tor_free(s));
6105 smartlist_free(options);
6106 options = NULL;
6108 done:
6109 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
6110 smartlist_free(items);
6112 return options;
6115 /** Given the name of a pluggable transport in <b>transport</b>, check
6116 * the configuration file to see if the user has explicitly asked for
6117 * it to listen on a specific port. Return a <address:port> string if
6118 * so, otherwise NULL. */
6119 char *
6120 get_transport_bindaddr_from_config(const char *transport)
6122 config_line_t *cl;
6123 const or_options_t *options = get_options();
6125 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
6126 char *bindaddr =
6127 get_bindaddr_from_transport_listen_line(cl->value, transport);
6128 if (bindaddr)
6129 return bindaddr;
6132 return NULL;
6135 /** Given the name of a pluggable transport in <b>transport</b>, check
6136 * the configuration file to see if the user has asked us to pass any
6137 * parameters to the pluggable transport. Return a smartlist
6138 * containing the parameters, otherwise NULL. */
6139 smartlist_t *
6140 get_options_for_server_transport(const char *transport)
6142 config_line_t *cl;
6143 const or_options_t *options = get_options();
6145 for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
6146 smartlist_t *options_sl =
6147 get_options_from_transport_options_line(cl->value, transport);
6148 if (options_sl)
6149 return options_sl;
6152 return NULL;
6155 /** Read the contents of a DirAuthority line from <b>line</b>. If
6156 * <b>validate_only</b> is 0, and the line is well-formed, and it
6157 * shares any bits with <b>required_type</b> or <b>required_type</b>
6158 * is NO_DIRINFO (zero), then add the dirserver described in the line
6159 * (minus whatever bits it's missing) as a valid authority.
6160 * Return 0 on success or filtering out by type,
6161 * or -1 if the line isn't well-formed or if we can't add it. */
6162 STATIC int
6163 parse_dir_authority_line(const char *line, dirinfo_type_t required_type,
6164 int validate_only)
6166 smartlist_t *items = NULL;
6167 int r;
6168 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
6169 tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
6170 uint16_t dir_port = 0, or_port = 0;
6171 char digest[DIGEST_LEN];
6172 char v3_digest[DIGEST_LEN];
6173 dirinfo_type_t type = 0;
6174 double weight = 1.0;
6176 memset(v3_digest, 0, sizeof(v3_digest));
6178 items = smartlist_new();
6179 smartlist_split_string(items, line, NULL,
6180 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6181 if (smartlist_len(items) < 1) {
6182 log_warn(LD_CONFIG, "No arguments on DirAuthority line.");
6183 goto err;
6186 if (is_legal_nickname(smartlist_get(items, 0))) {
6187 nickname = smartlist_get(items, 0);
6188 smartlist_del_keeporder(items, 0);
6191 while (smartlist_len(items)) {
6192 char *flag = smartlist_get(items, 0);
6193 if (TOR_ISDIGIT(flag[0]))
6194 break;
6195 if (!strcasecmp(flag, "hs") ||
6196 !strcasecmp(flag, "no-hs")) {
6197 log_warn(LD_CONFIG, "The DirAuthority options 'hs' and 'no-hs' are "
6198 "obsolete; you don't need them any more.");
6199 } else if (!strcasecmp(flag, "bridge")) {
6200 type |= BRIDGE_DIRINFO;
6201 } else if (!strcasecmp(flag, "no-v2")) {
6202 /* obsolete, but may still be contained in DirAuthority lines generated
6203 by various tools */;
6204 } else if (!strcasecmpstart(flag, "orport=")) {
6205 int ok;
6206 char *portstring = flag + strlen("orport=");
6207 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
6208 if (!ok)
6209 log_warn(LD_CONFIG, "Invalid orport '%s' on DirAuthority line.",
6210 portstring);
6211 } else if (!strcmpstart(flag, "weight=")) {
6212 int ok;
6213 const char *wstring = flag + strlen("weight=");
6214 weight = tor_parse_double(wstring, 0, (double)UINT64_MAX, &ok, NULL);
6215 if (!ok) {
6216 log_warn(LD_CONFIG, "Invalid weight '%s' on DirAuthority line.",flag);
6217 weight=1.0;
6219 } else if (!strcasecmpstart(flag, "v3ident=")) {
6220 char *idstr = flag + strlen("v3ident=");
6221 if (strlen(idstr) != HEX_DIGEST_LEN ||
6222 base16_decode(v3_digest, DIGEST_LEN,
6223 idstr, HEX_DIGEST_LEN) != DIGEST_LEN) {
6224 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirAuthority line",
6225 flag);
6226 } else {
6227 type |= V3_DIRINFO|EXTRAINFO_DIRINFO|MICRODESC_DIRINFO;
6229 } else if (!strcasecmpstart(flag, "ipv6=")) {
6230 if (ipv6_addrport_ptr) {
6231 log_warn(LD_CONFIG, "Redundant ipv6 addr/port on DirAuthority line");
6232 } else {
6233 if (tor_addr_port_parse(LOG_WARN, flag+strlen("ipv6="),
6234 &ipv6_addrport.addr, &ipv6_addrport.port,
6235 -1) < 0
6236 || tor_addr_family(&ipv6_addrport.addr) != AF_INET6) {
6237 log_warn(LD_CONFIG, "Bad ipv6 addr/port %s on DirAuthority line",
6238 escaped(flag));
6239 goto err;
6241 ipv6_addrport_ptr = &ipv6_addrport;
6243 } else {
6244 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirAuthority line",
6245 flag);
6247 tor_free(flag);
6248 smartlist_del_keeporder(items, 0);
6251 if (smartlist_len(items) < 2) {
6252 log_warn(LD_CONFIG, "Too few arguments to DirAuthority line.");
6253 goto err;
6255 addrport = smartlist_get(items, 0);
6256 smartlist_del_keeporder(items, 0);
6257 if (addr_port_lookup(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
6258 log_warn(LD_CONFIG, "Error parsing DirAuthority address '%s'", addrport);
6259 goto err;
6261 if (!dir_port) {
6262 log_warn(LD_CONFIG, "Missing port in DirAuthority address '%s'",addrport);
6263 goto err;
6266 fingerprint = smartlist_join_strings(items, "", 0, NULL);
6267 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
6268 log_warn(LD_CONFIG, "Key digest '%s' for DirAuthority is wrong length %d.",
6269 fingerprint, (int)strlen(fingerprint));
6270 goto err;
6272 if (base16_decode(digest, DIGEST_LEN,
6273 fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
6274 log_warn(LD_CONFIG, "Unable to decode DirAuthority key digest.");
6275 goto err;
6278 if (!validate_only && (!required_type || required_type & type)) {
6279 dir_server_t *ds;
6280 if (required_type)
6281 type &= required_type; /* pare down what we think of them as an
6282 * authority for. */
6283 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
6284 address, (int)dir_port, (char*)smartlist_get(items,0));
6285 if (!(ds = trusted_dir_server_new(nickname, address, dir_port, or_port,
6286 ipv6_addrport_ptr,
6287 digest, v3_digest, type, weight)))
6288 goto err;
6289 dir_server_add(ds);
6292 r = 0;
6293 goto done;
6295 err:
6296 r = -1;
6298 done:
6299 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
6300 smartlist_free(items);
6301 tor_free(addrport);
6302 tor_free(address);
6303 tor_free(nickname);
6304 tor_free(fingerprint);
6305 return r;
6308 /** Read the contents of a FallbackDir line from <b>line</b>. If
6309 * <b>validate_only</b> is 0, and the line is well-formed, then add the
6310 * dirserver described in the line as a fallback directory. Return 0 on
6311 * success, or -1 if the line isn't well-formed or if we can't add it. */
6313 parse_dir_fallback_line(const char *line,
6314 int validate_only)
6316 int r = -1;
6317 smartlist_t *items = smartlist_new(), *positional = smartlist_new();
6318 int orport = -1;
6319 uint16_t dirport;
6320 tor_addr_t addr;
6321 int ok;
6322 char id[DIGEST_LEN];
6323 char *address=NULL;
6324 tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
6325 double weight=1.0;
6327 memset(id, 0, sizeof(id));
6328 smartlist_split_string(items, line, NULL,
6329 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6330 SMARTLIST_FOREACH_BEGIN(items, const char *, cp) {
6331 const char *eq = strchr(cp, '=');
6332 ok = 1;
6333 if (! eq) {
6334 smartlist_add(positional, (char*)cp);
6335 continue;
6337 if (!strcmpstart(cp, "orport=")) {
6338 orport = (int)tor_parse_long(cp+strlen("orport="), 10,
6339 1, 65535, &ok, NULL);
6340 } else if (!strcmpstart(cp, "id=")) {
6341 ok = base16_decode(id, DIGEST_LEN, cp+strlen("id="),
6342 strlen(cp)-strlen("id=")) == DIGEST_LEN;
6343 } else if (!strcasecmpstart(cp, "ipv6=")) {
6344 if (ipv6_addrport_ptr) {
6345 log_warn(LD_CONFIG, "Redundant ipv6 addr/port on FallbackDir line");
6346 } else {
6347 if (tor_addr_port_parse(LOG_WARN, cp+strlen("ipv6="),
6348 &ipv6_addrport.addr, &ipv6_addrport.port,
6349 -1) < 0
6350 || tor_addr_family(&ipv6_addrport.addr) != AF_INET6) {
6351 log_warn(LD_CONFIG, "Bad ipv6 addr/port %s on FallbackDir line",
6352 escaped(cp));
6353 goto end;
6355 ipv6_addrport_ptr = &ipv6_addrport;
6357 } else if (!strcmpstart(cp, "weight=")) {
6358 int num_ok;
6359 const char *wstring = cp + strlen("weight=");
6360 weight = tor_parse_double(wstring, 0, (double)UINT64_MAX, &num_ok, NULL);
6361 if (!num_ok) {
6362 log_warn(LD_CONFIG, "Invalid weight '%s' on FallbackDir line.", cp);
6363 weight=1.0;
6367 if (!ok) {
6368 log_warn(LD_CONFIG, "Bad FallbackDir option %s", escaped(cp));
6369 goto end;
6371 } SMARTLIST_FOREACH_END(cp);
6373 if (smartlist_len(positional) != 1) {
6374 log_warn(LD_CONFIG, "Couldn't parse FallbackDir line %s", escaped(line));
6375 goto end;
6378 if (tor_digest_is_zero(id)) {
6379 log_warn(LD_CONFIG, "Missing identity on FallbackDir line");
6380 goto end;
6383 if (orport <= 0) {
6384 log_warn(LD_CONFIG, "Missing orport on FallbackDir line");
6385 goto end;
6388 if (tor_addr_port_split(LOG_INFO, smartlist_get(positional, 0),
6389 &address, &dirport) < 0 ||
6390 tor_addr_parse(&addr, address)<0) {
6391 log_warn(LD_CONFIG, "Couldn't parse address:port %s on FallbackDir line",
6392 (const char*)smartlist_get(positional, 0));
6393 goto end;
6396 if (!validate_only) {
6397 dir_server_t *ds;
6398 ds = fallback_dir_server_new(&addr, dirport, orport, ipv6_addrport_ptr,
6399 id, weight);
6400 if (!ds) {
6401 log_warn(LD_CONFIG, "Couldn't create FallbackDir %s", escaped(line));
6402 goto end;
6404 dir_server_add(ds);
6407 r = 0;
6409 end:
6410 SMARTLIST_FOREACH(items, char *, cp, tor_free(cp));
6411 smartlist_free(items);
6412 smartlist_free(positional);
6413 tor_free(address);
6414 return r;
6417 /** Allocate and return a new port_cfg_t with reasonable defaults. */
6418 STATIC port_cfg_t *
6419 port_cfg_new(size_t namelen)
6421 tor_assert(namelen <= SIZE_T_CEILING - sizeof(port_cfg_t) - 1);
6422 port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t) + namelen + 1);
6423 cfg->entry_cfg.ipv4_traffic = 1;
6424 cfg->entry_cfg.ipv6_traffic = 1;
6425 cfg->entry_cfg.dns_request = 1;
6426 cfg->entry_cfg.onion_traffic = 1;
6427 cfg->entry_cfg.prefer_ipv6_virtaddr = 1;
6428 return cfg;
6431 /** Free all storage held in <b>port</b> */
6432 STATIC void
6433 port_cfg_free(port_cfg_t *port)
6435 tor_free(port);
6438 /** Warn for every port in <b>ports</b> of type <b>listener_type</b> that is
6439 * on a publicly routable address. */
6440 static void
6441 warn_nonlocal_client_ports(const smartlist_t *ports,
6442 const char *portname,
6443 const int listener_type)
6445 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
6446 if (port->type != listener_type)
6447 continue;
6448 if (port->is_unix_addr) {
6449 /* Unix sockets aren't accessible over a network. */
6450 } else if (!tor_addr_is_internal(&port->addr, 1)) {
6451 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
6452 "Other people on the Internet might find your computer and "
6453 "use it as an open proxy. Please don't allow this unless you "
6454 "have a good reason.",
6455 fmt_addrport(&port->addr, port->port), portname);
6456 } else if (!tor_addr_is_loopback(&port->addr)) {
6457 log_notice(LD_CONFIG, "You configured a non-loopback address '%s' "
6458 "for %sPort. This allows everybody on your local network to "
6459 "use your machine as a proxy. Make sure this is what you "
6460 "wanted.",
6461 fmt_addrport(&port->addr, port->port), portname);
6463 } SMARTLIST_FOREACH_END(port);
6466 /** Warn for every Extended ORPort port in <b>ports</b> that is on a
6467 * publicly routable address. */
6468 static void
6469 warn_nonlocal_ext_orports(const smartlist_t *ports, const char *portname)
6471 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
6472 if (port->type != CONN_TYPE_EXT_OR_LISTENER)
6473 continue;
6474 if (port->is_unix_addr)
6475 continue;
6476 /* XXX maybe warn even if address is RFC1918? */
6477 if (!tor_addr_is_internal(&port->addr, 1)) {
6478 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
6479 "This is not advised; this address is supposed to only be "
6480 "exposed on localhost so that your pluggable transport "
6481 "proxies can connect to it.",
6482 fmt_addrport(&port->addr, port->port), portname);
6484 } SMARTLIST_FOREACH_END(port);
6487 /** Given a list of port_cfg_t in <b>ports</b>, warn if any controller port
6488 * there is listening on any non-loopback address. If <b>forbid_nonlocal</b>
6489 * is true, then emit a stronger warning and remove the port from the list.
6491 static void
6492 warn_nonlocal_controller_ports(smartlist_t *ports, unsigned forbid_nonlocal)
6494 int warned = 0;
6495 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
6496 if (port->type != CONN_TYPE_CONTROL_LISTENER)
6497 continue;
6498 if (port->is_unix_addr)
6499 continue;
6500 if (!tor_addr_is_loopback(&port->addr)) {
6501 if (forbid_nonlocal) {
6502 if (!warned)
6503 log_warn(LD_CONFIG,
6504 "You have a ControlPort set to accept "
6505 "unauthenticated connections from a non-local address. "
6506 "This means that programs not running on your computer "
6507 "can reconfigure your Tor, without even having to guess a "
6508 "password. That's so bad that I'm closing your ControlPort "
6509 "for you. If you need to control your Tor remotely, try "
6510 "enabling authentication and using a tool like stunnel or "
6511 "ssh to encrypt remote access.");
6512 warned = 1;
6513 port_cfg_free(port);
6514 SMARTLIST_DEL_CURRENT(ports, port);
6515 } else {
6516 log_warn(LD_CONFIG, "You have a ControlPort set to accept "
6517 "connections from a non-local address. This means that "
6518 "programs not running on your computer can reconfigure your "
6519 "Tor. That's pretty bad, since the controller "
6520 "protocol isn't encrypted! Maybe you should just listen on "
6521 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
6522 "remote connections to your control port.");
6523 return; /* No point in checking the rest */
6526 } SMARTLIST_FOREACH_END(port);
6530 * Take a string (<b>line</b>) that begins with either an address:port, a
6531 * port, or an AF_UNIX address, optionally quoted, prefixed with
6532 * "unix:". Parse that line, and on success, set <b>addrport_out</b> to a new
6533 * string containing the beginning portion (without prefix). Iff there was a
6534 * unix: prefix, set <b>is_unix_out</b> to true. On success, also set
6535 * <b>rest_out</b> to point to the part of the line after the address portion.
6537 * Return 0 on success, -1 on failure.
6540 port_cfg_line_extract_addrport(const char *line,
6541 char **addrport_out,
6542 int *is_unix_out,
6543 const char **rest_out)
6545 tor_assert(line);
6546 tor_assert(addrport_out);
6547 tor_assert(is_unix_out);
6548 tor_assert(rest_out);
6550 line = eat_whitespace(line);
6552 if (!strcmpstart(line, unix_q_socket_prefix)) {
6553 // It starts with unix:"
6554 size_t sz;
6555 *is_unix_out = 1;
6556 *addrport_out = NULL;
6557 line += strlen(unix_socket_prefix); /*No q: Keep the quote */
6558 *rest_out = unescape_string(line, addrport_out, &sz);
6559 if (!*rest_out || (*addrport_out && sz != strlen(*addrport_out))) {
6560 tor_free(*addrport_out);
6561 return -1;
6563 *rest_out = eat_whitespace(*rest_out);
6564 return 0;
6565 } else {
6566 // Is there a unix: prefix?
6567 if (!strcmpstart(line, unix_socket_prefix)) {
6568 line += strlen(unix_socket_prefix);
6569 *is_unix_out = 1;
6570 } else {
6571 *is_unix_out = 0;
6574 const char *end = find_whitespace(line);
6575 if (BUG(!end)) {
6576 end = strchr(line, '\0'); // LCOV_EXCL_LINE -- this can't be NULL
6578 tor_assert(end && end >= line);
6579 *addrport_out = tor_strndup(line, end - line);
6580 *rest_out = eat_whitespace(end);
6581 return 0;
6585 static void
6586 warn_client_dns_cache(const char *option, int disabling)
6588 if (disabling)
6589 return;
6591 warn_deprecated_option(option,
6592 "Client-side DNS cacheing enables a wide variety of route-"
6593 "capture attacks. If a single bad exit node lies to you about "
6594 "an IP address, cacheing that address would make you visit "
6595 "an address of the attacker's choice every time you connected "
6596 "to your destination.");
6600 * Validate the configured bridge distribution method from a BridgeDistribution
6601 * config line.
6603 * The input <b>bd</b>, is a string taken from the BridgeDistribution config
6604 * line (if present). If the option wasn't set, return 0 immediately. The
6605 * BridgeDistribution option is then validated. Currently valid, recognised
6606 * options are:
6608 * - "none"
6609 * - "any"
6610 * - "https"
6611 * - "email"
6612 * - "moat"
6613 * - "hyphae"
6615 * If the option string is unrecognised, a warning will be logged and 0 is
6616 * returned. If the option string contains an invalid character, -1 is
6617 * returned.
6619 STATIC int
6620 check_bridge_distribution_setting(const char *bd)
6622 if (bd == NULL)
6623 return 0;
6625 const char *RECOGNIZED[] = {
6626 "none", "any", "https", "email", "moat", "hyphae"
6628 unsigned i;
6629 for (i = 0; i < ARRAY_LENGTH(RECOGNIZED); ++i) {
6630 if (!strcmp(bd, RECOGNIZED[i]))
6631 return 0;
6634 const char *cp = bd;
6635 // Method = (KeywordChar | "_") +
6636 while (TOR_ISALNUM(*cp) || *cp == '-' || *cp == '_')
6637 ++cp;
6639 if (*cp == 0) {
6640 log_warn(LD_CONFIG, "Unrecognized BridgeDistribution value %s. I'll "
6641 "assume you know what you are doing...", escaped(bd));
6642 return 0; // we reached the end of the string; all is well
6643 } else {
6644 return -1; // we found a bad character in the string.
6649 * Parse port configuration for a single port type.
6651 * Read entries of the "FooPort" type from the list <b>ports</b>. Syntax is
6652 * that FooPort can have any number of entries of the format
6653 * "[Address:][Port] IsolationOptions".
6655 * In log messages, describe the port type as <b>portname</b>.
6657 * If no address is specified, default to <b>defaultaddr</b>. If no
6658 * FooPort is given, default to defaultport (if 0, there is no default).
6660 * If CL_PORT_NO_STREAM_OPTIONS is set in <b>flags</b>, do not allow stream
6661 * isolation options in the FooPort entries.
6663 * If CL_PORT_WARN_NONLOCAL is set in <b>flags</b>, warn if any of the
6664 * ports are not on a local address. If CL_PORT_FORBID_NONLOCAL is set,
6665 * this is a control port with no password set: don't even allow it.
6667 * If CL_PORT_SERVER_OPTIONS is set in <b>flags</b>, do not allow stream
6668 * isolation options in the FooPort entries; instead allow the
6669 * server-port option set.
6671 * If CL_PORT_TAKES_HOSTNAMES is set in <b>flags</b>, allow the options
6672 * {No,}IPv{4,6}Traffic.
6674 * On success, if <b>out</b> is given, add a new port_cfg_t entry to
6675 * <b>out</b> for every port that the client should listen on. Return 0
6676 * on success, -1 on failure.
6678 STATIC int
6679 parse_port_config(smartlist_t *out,
6680 const config_line_t *ports,
6681 const char *portname,
6682 int listener_type,
6683 const char *defaultaddr,
6684 int defaultport,
6685 const unsigned flags)
6687 smartlist_t *elts;
6688 int retval = -1;
6689 const unsigned is_control = (listener_type == CONN_TYPE_CONTROL_LISTENER);
6690 const unsigned is_ext_orport = (listener_type == CONN_TYPE_EXT_OR_LISTENER);
6691 const unsigned allow_no_stream_options = flags & CL_PORT_NO_STREAM_OPTIONS;
6692 const unsigned use_server_options = flags & CL_PORT_SERVER_OPTIONS;
6693 const unsigned warn_nonlocal = flags & CL_PORT_WARN_NONLOCAL;
6694 const unsigned forbid_nonlocal = flags & CL_PORT_FORBID_NONLOCAL;
6695 const unsigned default_to_group_writable =
6696 flags & CL_PORT_DFLT_GROUP_WRITABLE;
6697 const unsigned takes_hostnames = flags & CL_PORT_TAKES_HOSTNAMES;
6698 const unsigned is_unix_socket = flags & CL_PORT_IS_UNIXSOCKET;
6699 int got_zero_port=0, got_nonzero_port=0;
6700 char *unix_socket_path = NULL;
6702 /* If there's no FooPort, then maybe make a default one. */
6703 if (! ports) {
6704 if (defaultport && defaultaddr && out) {
6705 port_cfg_t *cfg = port_cfg_new(is_unix_socket ? strlen(defaultaddr) : 0);
6706 cfg->type = listener_type;
6707 if (is_unix_socket) {
6708 tor_addr_make_unspec(&cfg->addr);
6709 memcpy(cfg->unix_addr, defaultaddr, strlen(defaultaddr) + 1);
6710 cfg->is_unix_addr = 1;
6711 } else {
6712 cfg->port = defaultport;
6713 tor_addr_parse(&cfg->addr, defaultaddr);
6715 cfg->entry_cfg.session_group = SESSION_GROUP_UNSET;
6716 cfg->entry_cfg.isolation_flags = ISO_DEFAULT;
6717 smartlist_add(out, cfg);
6719 return 0;
6722 /* At last we can actually parse the FooPort lines. The syntax is:
6723 * [Addr:](Port|auto) [Options].*/
6724 elts = smartlist_new();
6725 char *addrport = NULL;
6727 for (; ports; ports = ports->next) {
6728 tor_addr_t addr;
6729 int port;
6730 int sessiongroup = SESSION_GROUP_UNSET;
6731 unsigned isolation = ISO_DEFAULT;
6732 int prefer_no_auth = 0;
6733 int socks_iso_keep_alive = 0;
6735 uint16_t ptmp=0;
6736 int ok;
6737 /* This must be kept in sync with port_cfg_new's defaults */
6738 int no_listen = 0, no_advertise = 0, all_addrs = 0,
6739 bind_ipv4_only = 0, bind_ipv6_only = 0,
6740 ipv4_traffic = 1, ipv6_traffic = 1, prefer_ipv6 = 0, dns_request = 1,
6741 onion_traffic = 1,
6742 cache_ipv4 = 0, use_cached_ipv4 = 0,
6743 cache_ipv6 = 0, use_cached_ipv6 = 0,
6744 prefer_ipv6_automap = 1, world_writable = 0, group_writable = 0,
6745 relax_dirmode_check = 0,
6746 has_used_unix_socket_only_option = 0;
6748 int is_unix_tagged_addr = 0;
6749 const char *rest_of_line = NULL;
6750 if (port_cfg_line_extract_addrport(ports->value,
6751 &addrport, &is_unix_tagged_addr, &rest_of_line)<0) {
6752 log_warn(LD_CONFIG, "Invalid %sPort line with unparsable address",
6753 portname);
6754 goto err;
6756 if (strlen(addrport) == 0) {
6757 log_warn(LD_CONFIG, "Invalid %sPort line with no address", portname);
6758 goto err;
6761 /* Split the remainder... */
6762 smartlist_split_string(elts, rest_of_line, NULL,
6763 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
6765 /* Let's start to check if it's a Unix socket path. */
6766 if (is_unix_tagged_addr) {
6767 #ifndef HAVE_SYS_UN_H
6768 log_warn(LD_CONFIG, "Unix sockets not supported on this system.");
6769 goto err;
6770 #endif
6771 unix_socket_path = addrport;
6772 addrport = NULL;
6775 if (unix_socket_path &&
6776 ! conn_listener_type_supports_af_unix(listener_type)) {
6777 log_warn(LD_CONFIG, "%sPort does not support unix sockets", portname);
6778 goto err;
6781 if (unix_socket_path) {
6782 port = 1;
6783 } else if (is_unix_socket) {
6784 if (BUG(!addrport))
6785 goto err; // LCOV_EXCL_LINE unreachable, but coverity can't tell that
6786 unix_socket_path = tor_strdup(addrport);
6787 if (!strcmp(addrport, "0"))
6788 port = 0;
6789 else
6790 port = 1;
6791 } else if (!strcmp(addrport, "auto")) {
6792 port = CFG_AUTO_PORT;
6793 int af = tor_addr_parse(&addr, defaultaddr);
6794 tor_assert(af >= 0);
6795 } else if (!strcasecmpend(addrport, ":auto")) {
6796 char *addrtmp = tor_strndup(addrport, strlen(addrport)-5);
6797 port = CFG_AUTO_PORT;
6798 if (tor_addr_port_lookup(addrtmp, &addr, &ptmp)<0 || ptmp) {
6799 log_warn(LD_CONFIG, "Invalid address '%s' for %sPort",
6800 escaped(addrport), portname);
6801 tor_free(addrtmp);
6802 goto err;
6804 tor_free(addrtmp);
6805 } else {
6806 /* Try parsing integer port before address, because, who knows?
6807 "9050" might be a valid address. */
6808 port = (int) tor_parse_long(addrport, 10, 0, 65535, &ok, NULL);
6809 if (ok) {
6810 int af = tor_addr_parse(&addr, defaultaddr);
6811 tor_assert(af >= 0);
6812 } else if (tor_addr_port_lookup(addrport, &addr, &ptmp) == 0) {
6813 if (ptmp == 0) {
6814 log_warn(LD_CONFIG, "%sPort line has address but no port", portname);
6815 goto err;
6817 port = ptmp;
6818 } else {
6819 log_warn(LD_CONFIG, "Couldn't parse address %s for %sPort",
6820 escaped(addrport), portname);
6821 goto err;
6825 if (unix_socket_path && default_to_group_writable)
6826 group_writable = 1;
6828 /* Now parse the rest of the options, if any. */
6829 if (use_server_options) {
6830 /* This is a server port; parse advertising options */
6831 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
6832 if (!strcasecmp(elt, "NoAdvertise")) {
6833 no_advertise = 1;
6834 } else if (!strcasecmp(elt, "NoListen")) {
6835 no_listen = 1;
6836 #if 0
6837 /* not implemented yet. */
6838 } else if (!strcasecmp(elt, "AllAddrs")) {
6840 all_addrs = 1;
6841 #endif /* 0 */
6842 } else if (!strcasecmp(elt, "IPv4Only")) {
6843 bind_ipv4_only = 1;
6844 } else if (!strcasecmp(elt, "IPv6Only")) {
6845 bind_ipv6_only = 1;
6846 } else {
6847 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6848 portname, escaped(elt));
6850 } SMARTLIST_FOREACH_END(elt);
6852 if (no_advertise && no_listen) {
6853 log_warn(LD_CONFIG, "Tried to set both NoListen and NoAdvertise "
6854 "on %sPort line '%s'",
6855 portname, escaped(ports->value));
6856 goto err;
6858 if (bind_ipv4_only && bind_ipv6_only) {
6859 log_warn(LD_CONFIG, "Tried to set both IPv4Only and IPv6Only "
6860 "on %sPort line '%s'",
6861 portname, escaped(ports->value));
6862 goto err;
6864 if (bind_ipv4_only && tor_addr_family(&addr) == AF_INET6) {
6865 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv6",
6866 portname);
6867 goto err;
6869 if (bind_ipv6_only && tor_addr_family(&addr) == AF_INET) {
6870 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv4",
6871 portname);
6872 goto err;
6874 } else {
6875 /* This is a client port; parse isolation options */
6876 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
6877 int no = 0, isoflag = 0;
6878 const char *elt_orig = elt;
6880 if (!strcasecmpstart(elt, "SessionGroup=")) {
6881 int group = (int)tor_parse_long(elt+strlen("SessionGroup="),
6882 10, 0, INT_MAX, &ok, NULL);
6883 if (!ok || !allow_no_stream_options) {
6884 log_warn(LD_CONFIG, "Invalid %sPort option '%s'",
6885 portname, escaped(elt));
6886 goto err;
6888 if (sessiongroup >= 0) {
6889 log_warn(LD_CONFIG, "Multiple SessionGroup options on %sPort",
6890 portname);
6891 goto err;
6893 sessiongroup = group;
6894 continue;
6897 if (!strcasecmpstart(elt, "No")) {
6898 no = 1;
6899 elt += 2;
6902 if (!strcasecmp(elt, "GroupWritable")) {
6903 group_writable = !no;
6904 has_used_unix_socket_only_option = 1;
6905 continue;
6906 } else if (!strcasecmp(elt, "WorldWritable")) {
6907 world_writable = !no;
6908 has_used_unix_socket_only_option = 1;
6909 continue;
6910 } else if (!strcasecmp(elt, "RelaxDirModeCheck")) {
6911 relax_dirmode_check = !no;
6912 has_used_unix_socket_only_option = 1;
6913 continue;
6916 if (allow_no_stream_options) {
6917 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6918 portname, escaped(elt));
6919 continue;
6922 if (takes_hostnames) {
6923 if (!strcasecmp(elt, "IPv4Traffic")) {
6924 ipv4_traffic = ! no;
6925 continue;
6926 } else if (!strcasecmp(elt, "IPv6Traffic")) {
6927 ipv6_traffic = ! no;
6928 continue;
6929 } else if (!strcasecmp(elt, "PreferIPv6")) {
6930 prefer_ipv6 = ! no;
6931 continue;
6932 } else if (!strcasecmp(elt, "DNSRequest")) {
6933 dns_request = ! no;
6934 continue;
6935 } else if (!strcasecmp(elt, "OnionTraffic")) {
6936 onion_traffic = ! no;
6937 continue;
6938 } else if (!strcasecmp(elt, "OnionTrafficOnly")) {
6939 /* Only connect to .onion addresses. Equivalent to
6940 * NoDNSRequest, NoIPv4Traffic, NoIPv6Traffic. The option
6941 * NoOnionTrafficOnly is not supported, it's too confusing. */
6942 if (no) {
6943 log_warn(LD_CONFIG, "Unsupported %sPort option 'No%s'. Use "
6944 "DNSRequest, IPv4Traffic, and/or IPv6Traffic instead.",
6945 portname, escaped(elt));
6946 } else {
6947 ipv4_traffic = ipv6_traffic = dns_request = 0;
6949 continue;
6952 if (!strcasecmp(elt, "CacheIPv4DNS")) {
6953 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6954 cache_ipv4 = ! no;
6955 continue;
6956 } else if (!strcasecmp(elt, "CacheIPv6DNS")) {
6957 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6958 cache_ipv6 = ! no;
6959 continue;
6960 } else if (!strcasecmp(elt, "CacheDNS")) {
6961 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6962 cache_ipv4 = cache_ipv6 = ! no;
6963 continue;
6964 } else if (!strcasecmp(elt, "UseIPv4Cache")) {
6965 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6966 use_cached_ipv4 = ! no;
6967 continue;
6968 } else if (!strcasecmp(elt, "UseIPv6Cache")) {
6969 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6970 use_cached_ipv6 = ! no;
6971 continue;
6972 } else if (!strcasecmp(elt, "UseDNSCache")) {
6973 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6974 use_cached_ipv4 = use_cached_ipv6 = ! no;
6975 continue;
6976 } else if (!strcasecmp(elt, "PreferIPv6Automap")) {
6977 prefer_ipv6_automap = ! no;
6978 continue;
6979 } else if (!strcasecmp(elt, "PreferSOCKSNoAuth")) {
6980 prefer_no_auth = ! no;
6981 continue;
6982 } else if (!strcasecmp(elt, "KeepAliveIsolateSOCKSAuth")) {
6983 socks_iso_keep_alive = ! no;
6984 continue;
6987 if (!strcasecmpend(elt, "s"))
6988 elt[strlen(elt)-1] = '\0'; /* kill plurals. */
6990 if (!strcasecmp(elt, "IsolateDestPort")) {
6991 isoflag = ISO_DESTPORT;
6992 } else if (!strcasecmp(elt, "IsolateDestAddr")) {
6993 isoflag = ISO_DESTADDR;
6994 } else if (!strcasecmp(elt, "IsolateSOCKSAuth")) {
6995 isoflag = ISO_SOCKSAUTH;
6996 } else if (!strcasecmp(elt, "IsolateClientProtocol")) {
6997 isoflag = ISO_CLIENTPROTO;
6998 } else if (!strcasecmp(elt, "IsolateClientAddr")) {
6999 isoflag = ISO_CLIENTADDR;
7000 } else {
7001 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
7002 portname, escaped(elt_orig));
7005 if (no) {
7006 isolation &= ~isoflag;
7007 } else {
7008 isolation |= isoflag;
7010 } SMARTLIST_FOREACH_END(elt);
7013 if (port)
7014 got_nonzero_port = 1;
7015 else
7016 got_zero_port = 1;
7018 if (dns_request == 0 && listener_type == CONN_TYPE_AP_DNS_LISTENER) {
7019 log_warn(LD_CONFIG, "You have a %sPort entry with DNS disabled; that "
7020 "won't work.", portname);
7021 goto err;
7024 if (ipv4_traffic == 0 && ipv6_traffic == 0 && onion_traffic == 0
7025 && listener_type != CONN_TYPE_AP_DNS_LISTENER) {
7026 log_warn(LD_CONFIG, "You have a %sPort entry with all of IPv4 and "
7027 "IPv6 and .onion disabled; that won't work.", portname);
7028 goto err;
7031 if (dns_request == 1 && ipv4_traffic == 0 && ipv6_traffic == 0
7032 && listener_type != CONN_TYPE_AP_DNS_LISTENER) {
7033 log_warn(LD_CONFIG, "You have a %sPort entry with DNSRequest enabled, "
7034 "but IPv4 and IPv6 disabled; DNS-based sites won't work.",
7035 portname);
7036 goto err;
7039 if ( has_used_unix_socket_only_option && ! unix_socket_path) {
7040 log_warn(LD_CONFIG, "You have a %sPort entry with GroupWritable, "
7041 "WorldWritable, or RelaxDirModeCheck, but it is not a "
7042 "unix socket.", portname);
7043 goto err;
7046 if (!(isolation & ISO_SOCKSAUTH) && socks_iso_keep_alive) {
7047 log_warn(LD_CONFIG, "You have a %sPort entry with both "
7048 "NoIsolateSOCKSAuth and KeepAliveIsolateSOCKSAuth set.",
7049 portname);
7050 goto err;
7053 if (unix_socket_path && (isolation & ISO_CLIENTADDR)) {
7054 /* `IsolateClientAddr` is nonsensical in the context of AF_LOCAL.
7055 * just silently remove the isolation flag.
7057 isolation &= ~ISO_CLIENTADDR;
7060 if (out && port) {
7061 size_t namelen = unix_socket_path ? strlen(unix_socket_path) : 0;
7062 port_cfg_t *cfg = port_cfg_new(namelen);
7063 if (unix_socket_path) {
7064 tor_addr_make_unspec(&cfg->addr);
7065 memcpy(cfg->unix_addr, unix_socket_path, namelen + 1);
7066 cfg->is_unix_addr = 1;
7067 tor_free(unix_socket_path);
7068 } else {
7069 tor_addr_copy(&cfg->addr, &addr);
7070 cfg->port = port;
7072 cfg->type = listener_type;
7073 cfg->is_world_writable = world_writable;
7074 cfg->is_group_writable = group_writable;
7075 cfg->relax_dirmode_check = relax_dirmode_check;
7076 cfg->entry_cfg.isolation_flags = isolation;
7077 cfg->entry_cfg.session_group = sessiongroup;
7078 cfg->server_cfg.no_advertise = no_advertise;
7079 cfg->server_cfg.no_listen = no_listen;
7080 cfg->server_cfg.all_addrs = all_addrs;
7081 cfg->server_cfg.bind_ipv4_only = bind_ipv4_only;
7082 cfg->server_cfg.bind_ipv6_only = bind_ipv6_only;
7083 cfg->entry_cfg.ipv4_traffic = ipv4_traffic;
7084 cfg->entry_cfg.ipv6_traffic = ipv6_traffic;
7085 cfg->entry_cfg.prefer_ipv6 = prefer_ipv6;
7086 cfg->entry_cfg.dns_request = dns_request;
7087 cfg->entry_cfg.onion_traffic = onion_traffic;
7088 cfg->entry_cfg.cache_ipv4_answers = cache_ipv4;
7089 cfg->entry_cfg.cache_ipv6_answers = cache_ipv6;
7090 cfg->entry_cfg.use_cached_ipv4_answers = use_cached_ipv4;
7091 cfg->entry_cfg.use_cached_ipv6_answers = use_cached_ipv6;
7092 cfg->entry_cfg.prefer_ipv6_virtaddr = prefer_ipv6_automap;
7093 cfg->entry_cfg.socks_prefer_no_auth = prefer_no_auth;
7094 if (! (isolation & ISO_SOCKSAUTH))
7095 cfg->entry_cfg.socks_prefer_no_auth = 1;
7096 cfg->entry_cfg.socks_iso_keep_alive = socks_iso_keep_alive;
7098 smartlist_add(out, cfg);
7100 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
7101 smartlist_clear(elts);
7102 tor_free(addrport);
7103 tor_free(unix_socket_path);
7106 if (warn_nonlocal && out) {
7107 if (is_control)
7108 warn_nonlocal_controller_ports(out, forbid_nonlocal);
7109 else if (is_ext_orport)
7110 warn_nonlocal_ext_orports(out, portname);
7111 else
7112 warn_nonlocal_client_ports(out, portname, listener_type);
7115 if (got_zero_port && got_nonzero_port) {
7116 log_warn(LD_CONFIG, "You specified a nonzero %sPort along with '%sPort 0' "
7117 "in the same configuration. Did you mean to disable %sPort or "
7118 "not?", portname, portname, portname);
7119 goto err;
7122 retval = 0;
7123 err:
7124 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
7125 smartlist_free(elts);
7126 tor_free(unix_socket_path);
7127 tor_free(addrport);
7128 return retval;
7131 /** Return the number of ports which are actually going to listen with type
7132 * <b>listenertype</b>. Do not count no_listen ports. Only count unix
7133 * sockets if count_sockets is true. */
7134 static int
7135 count_real_listeners(const smartlist_t *ports, int listenertype,
7136 int count_sockets)
7138 int n = 0;
7139 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
7140 if (port->server_cfg.no_listen)
7141 continue;
7142 if (!count_sockets && port->is_unix_addr)
7143 continue;
7144 if (port->type != listenertype)
7145 continue;
7146 ++n;
7147 } SMARTLIST_FOREACH_END(port);
7148 return n;
7151 /** Parse all ports from <b>options</b>. On success, set *<b>n_ports_out</b>
7152 * to the number of ports that are listed, update the *Port_set values in
7153 * <b>options</b>, and return 0. On failure, set *<b>msg</b> to a
7154 * description of the problem and return -1.
7156 * If <b>validate_only</b> is false, set configured_client_ports to the
7157 * new list of ports parsed from <b>options</b>.
7159 static int
7160 parse_ports(or_options_t *options, int validate_only,
7161 char **msg, int *n_ports_out,
7162 int *world_writable_control_socket)
7164 smartlist_t *ports;
7165 int retval = -1;
7167 ports = smartlist_new();
7169 *n_ports_out = 0;
7171 const unsigned gw_flag = options->SocksSocketsGroupWritable ?
7172 CL_PORT_DFLT_GROUP_WRITABLE : 0;
7173 if (parse_port_config(ports,
7174 options->SocksPort_lines,
7175 "Socks", CONN_TYPE_AP_LISTENER,
7176 "127.0.0.1", 9050,
7177 ((validate_only ? 0 : CL_PORT_WARN_NONLOCAL)
7178 | CL_PORT_TAKES_HOSTNAMES | gw_flag)) < 0) {
7179 *msg = tor_strdup("Invalid SocksPort configuration");
7180 goto err;
7182 if (parse_port_config(ports,
7183 options->DNSPort_lines,
7184 "DNS", CONN_TYPE_AP_DNS_LISTENER,
7185 "127.0.0.1", 0,
7186 CL_PORT_WARN_NONLOCAL|CL_PORT_TAKES_HOSTNAMES) < 0) {
7187 *msg = tor_strdup("Invalid DNSPort configuration");
7188 goto err;
7190 if (parse_port_config(ports,
7191 options->TransPort_lines,
7192 "Trans", CONN_TYPE_AP_TRANS_LISTENER,
7193 "127.0.0.1", 0,
7194 CL_PORT_WARN_NONLOCAL) < 0) {
7195 *msg = tor_strdup("Invalid TransPort configuration");
7196 goto err;
7198 if (parse_port_config(ports,
7199 options->NATDPort_lines,
7200 "NATD", CONN_TYPE_AP_NATD_LISTENER,
7201 "127.0.0.1", 0,
7202 CL_PORT_WARN_NONLOCAL) < 0) {
7203 *msg = tor_strdup("Invalid NatdPort configuration");
7204 goto err;
7206 if (parse_port_config(ports,
7207 options->HTTPTunnelPort_lines,
7208 "HTTP Tunnel", CONN_TYPE_AP_HTTP_CONNECT_LISTENER,
7209 "127.0.0.1", 0,
7210 ((validate_only ? 0 : CL_PORT_WARN_NONLOCAL)
7211 | CL_PORT_TAKES_HOSTNAMES | gw_flag)) < 0) {
7212 *msg = tor_strdup("Invalid HTTPTunnelPort configuration");
7213 goto err;
7216 unsigned control_port_flags = CL_PORT_NO_STREAM_OPTIONS |
7217 CL_PORT_WARN_NONLOCAL;
7218 const int any_passwords = (options->HashedControlPassword ||
7219 options->HashedControlSessionPassword ||
7220 options->CookieAuthentication);
7221 if (! any_passwords)
7222 control_port_flags |= CL_PORT_FORBID_NONLOCAL;
7223 if (options->ControlSocketsGroupWritable)
7224 control_port_flags |= CL_PORT_DFLT_GROUP_WRITABLE;
7226 if (parse_port_config(ports,
7227 options->ControlPort_lines,
7228 "Control", CONN_TYPE_CONTROL_LISTENER,
7229 "127.0.0.1", 0,
7230 control_port_flags) < 0) {
7231 *msg = tor_strdup("Invalid ControlPort configuration");
7232 goto err;
7235 if (parse_port_config(ports, options->ControlSocket,
7236 "ControlSocket",
7237 CONN_TYPE_CONTROL_LISTENER, NULL, 0,
7238 control_port_flags | CL_PORT_IS_UNIXSOCKET) < 0) {
7239 *msg = tor_strdup("Invalid ControlSocket configuration");
7240 goto err;
7243 if (! options->ClientOnly) {
7244 if (parse_port_config(ports,
7245 options->ORPort_lines,
7246 "OR", CONN_TYPE_OR_LISTENER,
7247 "0.0.0.0", 0,
7248 CL_PORT_SERVER_OPTIONS) < 0) {
7249 *msg = tor_strdup("Invalid ORPort configuration");
7250 goto err;
7252 if (parse_port_config(ports,
7253 options->ExtORPort_lines,
7254 "ExtOR", CONN_TYPE_EXT_OR_LISTENER,
7255 "127.0.0.1", 0,
7256 CL_PORT_SERVER_OPTIONS|CL_PORT_WARN_NONLOCAL) < 0) {
7257 *msg = tor_strdup("Invalid ExtORPort configuration");
7258 goto err;
7260 if (parse_port_config(ports,
7261 options->DirPort_lines,
7262 "Dir", CONN_TYPE_DIR_LISTENER,
7263 "0.0.0.0", 0,
7264 CL_PORT_SERVER_OPTIONS) < 0) {
7265 *msg = tor_strdup("Invalid DirPort configuration");
7266 goto err;
7270 int n_low_ports = 0;
7271 if (check_server_ports(ports, options, &n_low_ports) < 0) {
7272 *msg = tor_strdup("Misconfigured server ports");
7273 goto err;
7275 if (have_low_ports < 0)
7276 have_low_ports = (n_low_ports > 0);
7278 *n_ports_out = smartlist_len(ports);
7280 retval = 0;
7282 /* Update the *Port_set options. The !! here is to force a boolean out of
7283 an integer. */
7284 options->ORPort_set =
7285 !! count_real_listeners(ports, CONN_TYPE_OR_LISTENER, 0);
7286 options->SocksPort_set =
7287 !! count_real_listeners(ports, CONN_TYPE_AP_LISTENER, 1);
7288 options->TransPort_set =
7289 !! count_real_listeners(ports, CONN_TYPE_AP_TRANS_LISTENER, 1);
7290 options->NATDPort_set =
7291 !! count_real_listeners(ports, CONN_TYPE_AP_NATD_LISTENER, 1);
7292 options->HTTPTunnelPort_set =
7293 !! count_real_listeners(ports, CONN_TYPE_AP_HTTP_CONNECT_LISTENER, 1);
7294 /* Use options->ControlSocket to test if a control socket is set */
7295 options->ControlPort_set =
7296 !! count_real_listeners(ports, CONN_TYPE_CONTROL_LISTENER, 0);
7297 options->DirPort_set =
7298 !! count_real_listeners(ports, CONN_TYPE_DIR_LISTENER, 0);
7299 options->DNSPort_set =
7300 !! count_real_listeners(ports, CONN_TYPE_AP_DNS_LISTENER, 1);
7301 options->ExtORPort_set =
7302 !! count_real_listeners(ports, CONN_TYPE_EXT_OR_LISTENER, 0);
7304 if (world_writable_control_socket) {
7305 SMARTLIST_FOREACH(ports, port_cfg_t *, p,
7306 if (p->type == CONN_TYPE_CONTROL_LISTENER &&
7307 p->is_unix_addr &&
7308 p->is_world_writable) {
7309 *world_writable_control_socket = 1;
7310 break;
7314 if (!validate_only) {
7315 if (configured_ports) {
7316 SMARTLIST_FOREACH(configured_ports,
7317 port_cfg_t *, p, port_cfg_free(p));
7318 smartlist_free(configured_ports);
7320 configured_ports = ports;
7321 ports = NULL; /* prevent free below. */
7324 err:
7325 if (ports) {
7326 SMARTLIST_FOREACH(ports, port_cfg_t *, p, port_cfg_free(p));
7327 smartlist_free(ports);
7329 return retval;
7332 /* Does port bind to IPv4? */
7333 static int
7334 port_binds_ipv4(const port_cfg_t *port)
7336 return tor_addr_family(&port->addr) == AF_INET ||
7337 (tor_addr_family(&port->addr) == AF_UNSPEC
7338 && !port->server_cfg.bind_ipv6_only);
7341 /* Does port bind to IPv6? */
7342 static int
7343 port_binds_ipv6(const port_cfg_t *port)
7345 return tor_addr_family(&port->addr) == AF_INET6 ||
7346 (tor_addr_family(&port->addr) == AF_UNSPEC
7347 && !port->server_cfg.bind_ipv4_only);
7350 /** Given a list of <b>port_cfg_t</b> in <b>ports</b>, check them for internal
7351 * consistency and warn as appropriate. Set *<b>n_low_ports_out</b> to the
7352 * number of sub-1024 ports we will be binding. */
7353 static int
7354 check_server_ports(const smartlist_t *ports,
7355 const or_options_t *options,
7356 int *n_low_ports_out)
7358 int n_orport_advertised = 0;
7359 int n_orport_advertised_ipv4 = 0;
7360 int n_orport_listeners = 0;
7361 int n_dirport_advertised = 0;
7362 int n_dirport_listeners = 0;
7363 int n_low_port = 0;
7364 int r = 0;
7366 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
7367 if (port->type == CONN_TYPE_DIR_LISTENER) {
7368 if (! port->server_cfg.no_advertise)
7369 ++n_dirport_advertised;
7370 if (! port->server_cfg.no_listen)
7371 ++n_dirport_listeners;
7372 } else if (port->type == CONN_TYPE_OR_LISTENER) {
7373 if (! port->server_cfg.no_advertise) {
7374 ++n_orport_advertised;
7375 if (port_binds_ipv4(port))
7376 ++n_orport_advertised_ipv4;
7378 if (! port->server_cfg.no_listen)
7379 ++n_orport_listeners;
7380 } else {
7381 continue;
7383 #ifndef _WIN32
7384 if (!port->server_cfg.no_listen && port->port < 1024)
7385 ++n_low_port;
7386 #endif
7387 } SMARTLIST_FOREACH_END(port);
7389 if (n_orport_advertised && !n_orport_listeners) {
7390 log_warn(LD_CONFIG, "We are advertising an ORPort, but not actually "
7391 "listening on one.");
7392 r = -1;
7394 if (n_orport_listeners && !n_orport_advertised) {
7395 log_warn(LD_CONFIG, "We are listening on an ORPort, but not advertising "
7396 "any ORPorts. This will keep us from building a %s "
7397 "descriptor, and make us impossible to use.",
7398 options->BridgeRelay ? "bridge" : "router");
7399 r = -1;
7401 if (n_dirport_advertised && !n_dirport_listeners) {
7402 log_warn(LD_CONFIG, "We are advertising a DirPort, but not actually "
7403 "listening on one.");
7404 r = -1;
7406 if (n_dirport_advertised > 1) {
7407 log_warn(LD_CONFIG, "Can't advertise more than one DirPort.");
7408 r = -1;
7410 if (n_orport_advertised && !n_orport_advertised_ipv4 &&
7411 !options->BridgeRelay) {
7412 log_warn(LD_CONFIG, "Configured non-bridge only to listen on an IPv6 "
7413 "address.");
7414 r = -1;
7417 if (n_low_port && options->AccountingMax &&
7418 (!have_capability_support() || options->KeepBindCapabilities == 0)) {
7419 const char *extra = "";
7420 if (options->KeepBindCapabilities == 0 && have_capability_support())
7421 extra = ", and you have disabled KeepBindCapabilities.";
7422 log_warn(LD_CONFIG,
7423 "You have set AccountingMax to use hibernation. You have also "
7424 "chosen a low DirPort or OrPort%s."
7425 "This combination can make Tor stop "
7426 "working when it tries to re-attach the port after a period of "
7427 "hibernation. Please choose a different port or turn off "
7428 "hibernation unless you know this combination will work on your "
7429 "platform.", extra);
7432 if (n_low_ports_out)
7433 *n_low_ports_out = n_low_port;
7435 return r;
7438 /** Return a list of port_cfg_t for client ports parsed from the
7439 * options. */
7440 MOCK_IMPL(const smartlist_t *,
7441 get_configured_ports,(void))
7443 if (!configured_ports)
7444 configured_ports = smartlist_new();
7445 return configured_ports;
7448 /** Return an address:port string representation of the address
7449 * where the first <b>listener_type</b> listener waits for
7450 * connections. Return NULL if we couldn't find a listener. The
7451 * string is allocated on the heap and it's the responsibility of the
7452 * caller to free it after use.
7454 * This function is meant to be used by the pluggable transport proxy
7455 * spawning code, please make sure that it fits your purposes before
7456 * using it. */
7457 char *
7458 get_first_listener_addrport_string(int listener_type)
7460 static const char *ipv4_localhost = "127.0.0.1";
7461 static const char *ipv6_localhost = "[::1]";
7462 const char *address;
7463 uint16_t port;
7464 char *string = NULL;
7466 if (!configured_ports)
7467 return NULL;
7469 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
7470 if (cfg->server_cfg.no_listen)
7471 continue;
7473 if (cfg->type == listener_type &&
7474 tor_addr_family(&cfg->addr) != AF_UNSPEC) {
7476 /* We found the first listener of the type we are interested in! */
7478 /* If a listener is listening on INADDR_ANY, assume that it's
7479 also listening on 127.0.0.1, and point the transport proxy
7480 there: */
7481 if (tor_addr_is_null(&cfg->addr))
7482 address = tor_addr_is_v4(&cfg->addr) ? ipv4_localhost : ipv6_localhost;
7483 else
7484 address = fmt_and_decorate_addr(&cfg->addr);
7486 /* If a listener is configured with port 'auto', we are forced
7487 to iterate all listener connections and find out in which
7488 port it ended up listening: */
7489 if (cfg->port == CFG_AUTO_PORT) {
7490 port = router_get_active_listener_port_by_type_af(listener_type,
7491 tor_addr_family(&cfg->addr));
7492 if (!port)
7493 return NULL;
7494 } else {
7495 port = cfg->port;
7498 tor_asprintf(&string, "%s:%u", address, port);
7500 return string;
7503 } SMARTLIST_FOREACH_END(cfg);
7505 return NULL;
7508 /** Return the first advertised port of type <b>listener_type</b> in
7509 * <b>address_family</b>. Returns 0 when no port is found, and when passed
7510 * AF_UNSPEC. */
7512 get_first_advertised_port_by_type_af(int listener_type, int address_family)
7514 if (address_family == AF_UNSPEC)
7515 return 0;
7517 const smartlist_t *conf_ports = get_configured_ports();
7518 SMARTLIST_FOREACH_BEGIN(conf_ports, const port_cfg_t *, cfg) {
7519 if (cfg->type == listener_type &&
7520 !cfg->server_cfg.no_advertise) {
7521 if ((address_family == AF_INET && port_binds_ipv4(cfg)) ||
7522 (address_family == AF_INET6 && port_binds_ipv6(cfg))) {
7523 return cfg->port;
7526 } SMARTLIST_FOREACH_END(cfg);
7527 return 0;
7530 /** Return the first advertised address of type <b>listener_type</b> in
7531 * <b>address_family</b>. Returns NULL if there is no advertised address,
7532 * and when passed AF_UNSPEC. */
7533 const tor_addr_t *
7534 get_first_advertised_addr_by_type_af(int listener_type, int address_family)
7536 if (address_family == AF_UNSPEC)
7537 return NULL;
7538 if (!configured_ports)
7539 return NULL;
7540 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
7541 if (cfg->type == listener_type &&
7542 !cfg->server_cfg.no_advertise) {
7543 if ((address_family == AF_INET && port_binds_ipv4(cfg)) ||
7544 (address_family == AF_INET6 && port_binds_ipv6(cfg))) {
7545 return &cfg->addr;
7548 } SMARTLIST_FOREACH_END(cfg);
7549 return NULL;
7552 /** Return 1 if a port exists of type <b>listener_type</b> on <b>addr</b> and
7553 * <b>port</b>. If <b>check_wildcard</b> is true, INADDR[6]_ANY and AF_UNSPEC
7554 * addresses match any address of the appropriate family; and port -1 matches
7555 * any port.
7556 * To match auto ports, pass CFG_PORT_AUTO. (Does not match on the actual
7557 * automatically chosen listener ports.) */
7559 port_exists_by_type_addr_port(int listener_type, const tor_addr_t *addr,
7560 int port, int check_wildcard)
7562 if (!configured_ports || !addr)
7563 return 0;
7564 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
7565 if (cfg->type == listener_type) {
7566 if (cfg->port == port || (check_wildcard && port == -1)) {
7567 /* Exact match */
7568 if (tor_addr_eq(&cfg->addr, addr)) {
7569 return 1;
7571 /* Skip wildcard matches if we're not doing them */
7572 if (!check_wildcard) {
7573 continue;
7575 /* Wildcard matches IPv4 */
7576 const int cfg_v4 = port_binds_ipv4(cfg);
7577 const int cfg_any_v4 = tor_addr_is_null(&cfg->addr) && cfg_v4;
7578 const int addr_v4 = tor_addr_family(addr) == AF_INET ||
7579 tor_addr_family(addr) == AF_UNSPEC;
7580 const int addr_any_v4 = tor_addr_is_null(&cfg->addr) && addr_v4;
7581 if ((cfg_any_v4 && addr_v4) || (cfg_v4 && addr_any_v4)) {
7582 return 1;
7584 /* Wildcard matches IPv6 */
7585 const int cfg_v6 = port_binds_ipv6(cfg);
7586 const int cfg_any_v6 = tor_addr_is_null(&cfg->addr) && cfg_v6;
7587 const int addr_v6 = tor_addr_family(addr) == AF_INET6 ||
7588 tor_addr_family(addr) == AF_UNSPEC;
7589 const int addr_any_v6 = tor_addr_is_null(&cfg->addr) && addr_v6;
7590 if ((cfg_any_v6 && addr_v6) || (cfg_v6 && addr_any_v6)) {
7591 return 1;
7595 } SMARTLIST_FOREACH_END(cfg);
7596 return 0;
7599 /* Like port_exists_by_type_addr_port, but accepts a host-order IPv4 address
7600 * instead. */
7602 port_exists_by_type_addr32h_port(int listener_type, uint32_t addr_ipv4h,
7603 int port, int check_wildcard)
7605 tor_addr_t ipv4;
7606 tor_addr_from_ipv4h(&ipv4, addr_ipv4h);
7607 return port_exists_by_type_addr_port(listener_type, &ipv4, port,
7608 check_wildcard);
7611 /** Adjust the value of options->DataDirectory, or fill it in if it's
7612 * absent. Return 0 on success, -1 on failure. */
7613 static int
7614 normalize_data_directory(or_options_t *options)
7616 #ifdef _WIN32
7617 char *p;
7618 if (options->DataDirectory)
7619 return 0; /* all set */
7620 p = tor_malloc(MAX_PATH);
7621 strlcpy(p,get_windows_conf_root(),MAX_PATH);
7622 options->DataDirectory = p;
7623 return 0;
7624 #else /* !(defined(_WIN32)) */
7625 const char *d = options->DataDirectory;
7626 if (!d)
7627 d = "~/.tor";
7629 if (strncmp(d,"~/",2) == 0) {
7630 char *fn = expand_filename(d);
7631 if (!fn) {
7632 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
7633 return -1;
7635 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
7636 /* If our homedir is /, we probably don't want to use it. */
7637 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
7638 * want. */
7639 log_warn(LD_CONFIG,
7640 "Default DataDirectory is \"~/.tor\". This expands to "
7641 "\"%s\", which is probably not what you want. Using "
7642 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
7643 tor_free(fn);
7644 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
7646 tor_free(options->DataDirectory);
7647 options->DataDirectory = fn;
7649 return 0;
7650 #endif /* defined(_WIN32) */
7653 /** Check and normalize the value of options->DataDirectory; return 0 if it
7654 * is sane, -1 otherwise. */
7655 static int
7656 validate_data_directory(or_options_t *options)
7658 if (normalize_data_directory(options) < 0)
7659 return -1;
7660 tor_assert(options->DataDirectory);
7661 if (strlen(options->DataDirectory) > (512-128)) {
7662 log_warn(LD_CONFIG, "DataDirectory is too long.");
7663 return -1;
7665 return 0;
7668 /** This string must remain the same forevermore. It is how we
7669 * recognize that the torrc file doesn't need to be backed up. */
7670 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
7671 "if you edit it, comments will not be preserved"
7672 /** This string can change; it tries to give the reader an idea
7673 * that editing this file by hand is not a good plan. */
7674 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
7675 "to torrc.orig.1 or similar, and Tor will ignore it"
7677 /** Save a configuration file for the configuration in <b>options</b>
7678 * into the file <b>fname</b>. If the file already exists, and
7679 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
7680 * replace it. Return 0 on success, -1 on failure. */
7681 static int
7682 write_configuration_file(const char *fname, const or_options_t *options)
7684 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
7685 int rename_old = 0, r;
7687 if (!fname)
7688 return -1;
7690 switch (file_status(fname)) {
7691 /* create backups of old config files, even if they're empty */
7692 case FN_FILE:
7693 case FN_EMPTY:
7694 old_val = read_file_to_str(fname, 0, NULL);
7695 if (!old_val || strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
7696 rename_old = 1;
7698 tor_free(old_val);
7699 break;
7700 case FN_NOENT:
7701 break;
7702 case FN_ERROR:
7703 case FN_DIR:
7704 default:
7705 log_warn(LD_CONFIG,
7706 "Config file \"%s\" is not a file? Failing.", fname);
7707 return -1;
7710 if (!(new_conf = options_dump(options, OPTIONS_DUMP_MINIMAL))) {
7711 log_warn(LD_BUG, "Couldn't get configuration string");
7712 goto err;
7715 tor_asprintf(&new_val, "%s\n%s\n\n%s",
7716 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
7718 if (rename_old) {
7719 int i = 1;
7720 char *fn_tmp = NULL;
7721 while (1) {
7722 tor_asprintf(&fn_tmp, "%s.orig.%d", fname, i);
7723 if (file_status(fn_tmp) == FN_NOENT)
7724 break;
7725 tor_free(fn_tmp);
7726 ++i;
7728 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
7729 if (tor_rename(fname, fn_tmp) < 0) {//XXXX sandbox doesn't allow
7730 log_warn(LD_FS,
7731 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
7732 fname, fn_tmp, strerror(errno));
7733 tor_free(fn_tmp);
7734 goto err;
7736 tor_free(fn_tmp);
7739 if (write_str_to_file(fname, new_val, 0) < 0)
7740 goto err;
7742 r = 0;
7743 goto done;
7744 err:
7745 r = -1;
7746 done:
7747 tor_free(new_val);
7748 tor_free(new_conf);
7749 return r;
7753 * Save the current configuration file value to disk. Return 0 on
7754 * success, -1 on failure.
7757 options_save_current(void)
7759 /* This fails if we can't write to our configuration file.
7761 * If we try falling back to datadirectory or something, we have a better
7762 * chance of saving the configuration, but a better chance of doing
7763 * something the user never expected. */
7764 return write_configuration_file(get_torrc_fname(0), get_options());
7767 /** Return the number of cpus configured in <b>options</b>. If we are
7768 * told to auto-detect the number of cpus, return the auto-detected number. */
7770 get_num_cpus(const or_options_t *options)
7772 if (options->NumCPUs == 0) {
7773 int n = compute_num_cpus();
7774 return (n >= 1) ? n : 1;
7775 } else {
7776 return options->NumCPUs;
7781 * Initialize the libevent library.
7783 static void
7784 init_libevent(const or_options_t *options)
7786 tor_libevent_cfg cfg;
7788 tor_assert(options);
7790 configure_libevent_logging();
7791 /* If the kernel complains that some method (say, epoll) doesn't
7792 * exist, we don't care about it, since libevent will cope.
7794 suppress_libevent_log_msg("Function not implemented");
7796 memset(&cfg, 0, sizeof(cfg));
7797 cfg.num_cpus = get_num_cpus(options);
7798 cfg.msec_per_tick = options->TokenBucketRefillInterval;
7800 tor_libevent_initialize(&cfg);
7802 suppress_libevent_log_msg(NULL);
7805 /** Return a newly allocated string holding a filename relative to the data
7806 * directory. If <b>sub1</b> is present, it is the first path component after
7807 * the data directory. If <b>sub2</b> is also present, it is the second path
7808 * component after the data directory. If <b>suffix</b> is present, it
7809 * is appended to the filename.
7811 * Examples:
7812 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
7813 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
7814 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
7815 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
7817 * Note: Consider using the get_datadir_fname* macros in or.h.
7819 MOCK_IMPL(char *,
7820 options_get_datadir_fname2_suffix,(const or_options_t *options,
7821 const char *sub1, const char *sub2,
7822 const char *suffix))
7824 char *fname = NULL;
7825 size_t len;
7826 tor_assert(options);
7827 tor_assert(options->DataDirectory);
7828 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
7829 len = strlen(options->DataDirectory);
7830 if (sub1) {
7831 len += strlen(sub1)+1;
7832 if (sub2)
7833 len += strlen(sub2)+1;
7835 if (suffix)
7836 len += strlen(suffix);
7837 len++;
7838 fname = tor_malloc(len);
7839 if (sub1) {
7840 if (sub2) {
7841 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
7842 options->DataDirectory, sub1, sub2);
7843 } else {
7844 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
7845 options->DataDirectory, sub1);
7847 } else {
7848 strlcpy(fname, options->DataDirectory, len);
7850 if (suffix)
7851 strlcat(fname, suffix, len);
7852 return fname;
7855 /** Check wether the data directory has a private subdirectory
7856 * <b>subdir</b>. If not, try to create it. Return 0 on success,
7857 * -1 otherwise. */
7859 check_or_create_data_subdir(const char *subdir)
7861 char *statsdir = get_datadir_fname(subdir);
7862 int return_val = 0;
7864 if (check_private_dir(statsdir, CPD_CREATE, get_options()->User) < 0) {
7865 log_warn(LD_HIST, "Unable to create %s/ directory!", subdir);
7866 return_val = -1;
7868 tor_free(statsdir);
7869 return return_val;
7872 /** Create a file named <b>fname</b> with contents <b>str</b> in the
7873 * subdirectory <b>subdir</b> of the data directory. <b>descr</b>
7874 * should be a short description of the file's content and will be
7875 * used for the warning message, if it's present and the write process
7876 * fails. Return 0 on success, -1 otherwise.*/
7878 write_to_data_subdir(const char* subdir, const char* fname,
7879 const char* str, const char* descr)
7881 char *filename = get_datadir_fname2(subdir, fname);
7882 int return_val = 0;
7884 if (write_str_to_file(filename, str, 0) < 0) {
7885 log_warn(LD_HIST, "Unable to write %s to disk!", descr ? descr : fname);
7886 return_val = -1;
7888 tor_free(filename);
7889 return return_val;
7892 /** Given a file name check to see whether the file exists but has not been
7893 * modified for a very long time. If so, remove it. */
7894 void
7895 remove_file_if_very_old(const char *fname, time_t now)
7897 #define VERY_OLD_FILE_AGE (28*24*60*60)
7898 struct stat st;
7900 log_debug(LD_FS, "stat()ing %s", fname);
7901 if (stat(sandbox_intern_string(fname), &st)==0 &&
7902 st.st_mtime < now-VERY_OLD_FILE_AGE) {
7903 char buf[ISO_TIME_LEN+1];
7904 format_local_iso_time(buf, st.st_mtime);
7905 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
7906 "Removing it.", fname, buf);
7907 if (unlink(fname) != 0) {
7908 log_warn(LD_FS, "Failed to unlink %s: %s",
7909 fname, strerror(errno));
7914 /** Return a smartlist of ports that must be forwarded by
7915 * tor-fw-helper. The smartlist contains the ports in a string format
7916 * that is understandable by tor-fw-helper. */
7917 smartlist_t *
7918 get_list_of_ports_to_forward(void)
7920 smartlist_t *ports_to_forward = smartlist_new();
7921 int port = 0;
7923 /** XXX TODO tor-fw-helper does not support forwarding ports to
7924 other hosts than the local one. If the user is binding to a
7925 different IP address, tor-fw-helper won't work. */
7926 port = router_get_advertised_or_port(get_options()); /* Get ORPort */
7927 if (port)
7928 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
7930 port = router_get_advertised_dir_port(get_options(), 0); /* Get DirPort */
7931 if (port)
7932 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
7934 /* Get ports of transport proxies */
7936 smartlist_t *transport_ports = get_transport_proxy_ports();
7937 if (transport_ports) {
7938 smartlist_add_all(ports_to_forward, transport_ports);
7939 smartlist_free(transport_ports);
7943 if (!smartlist_len(ports_to_forward)) {
7944 smartlist_free(ports_to_forward);
7945 ports_to_forward = NULL;
7948 return ports_to_forward;
7951 /** Helper to implement GETINFO functions about configuration variables (not
7952 * their values). Given a "config/names" question, set *<b>answer</b> to a
7953 * new string describing the supported configuration variables and their
7954 * types. */
7956 getinfo_helper_config(control_connection_t *conn,
7957 const char *question, char **answer,
7958 const char **errmsg)
7960 (void) conn;
7961 (void) errmsg;
7962 if (!strcmp(question, "config/names")) {
7963 smartlist_t *sl = smartlist_new();
7964 int i;
7965 for (i = 0; option_vars_[i].name; ++i) {
7966 const config_var_t *var = &option_vars_[i];
7967 const char *type;
7968 /* don't tell controller about triple-underscore options */
7969 if (!strncmp(option_vars_[i].name, "___", 3))
7970 continue;
7971 switch (var->type) {
7972 case CONFIG_TYPE_STRING: type = "String"; break;
7973 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
7974 case CONFIG_TYPE_UINT: type = "Integer"; break;
7975 case CONFIG_TYPE_INT: type = "SignedInteger"; break;
7976 case CONFIG_TYPE_PORT: type = "Port"; break;
7977 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
7978 case CONFIG_TYPE_MSEC_INTERVAL: type = "TimeMsecInterval"; break;
7979 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
7980 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
7981 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
7982 case CONFIG_TYPE_AUTOBOOL: type = "Boolean+Auto"; break;
7983 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
7984 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
7985 case CONFIG_TYPE_CSV: type = "CommaList"; break;
7986 case CONFIG_TYPE_CSV_INTERVAL: type = "TimeIntervalCommaList"; break;
7987 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
7988 case CONFIG_TYPE_LINELIST_S: type = "Dependent"; break;
7989 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
7990 default:
7991 case CONFIG_TYPE_OBSOLETE:
7992 type = NULL; break;
7994 if (!type)
7995 continue;
7996 smartlist_add_asprintf(sl, "%s %s\n",var->name,type);
7998 *answer = smartlist_join_strings(sl, "", 0, NULL);
7999 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
8000 smartlist_free(sl);
8001 } else if (!strcmp(question, "config/defaults")) {
8002 smartlist_t *sl = smartlist_new();
8003 int dirauth_lines_seen = 0, fallback_lines_seen = 0;
8004 for (int i = 0; option_vars_[i].name; ++i) {
8005 const config_var_t *var = &option_vars_[i];
8006 if (var->initvalue != NULL) {
8007 if (strcmp(option_vars_[i].name, "DirAuthority") == 0) {
8009 * Count dirauth lines we have a default for; we'll use the
8010 * count later to decide whether to add the defaults manually
8012 ++dirauth_lines_seen;
8014 if (strcmp(option_vars_[i].name, "FallbackDir") == 0) {
8016 * Similarly count fallback lines, so that we can decided later
8017 * to add the defaults manually.
8019 ++fallback_lines_seen;
8021 char *val = esc_for_log(var->initvalue);
8022 smartlist_add_asprintf(sl, "%s %s\n",var->name,val);
8023 tor_free(val);
8027 if (dirauth_lines_seen == 0) {
8029 * We didn't see any directory authorities with default values,
8030 * so add the list of default authorities manually.
8034 * default_authorities is defined earlier in this file and
8035 * is a const char ** NULL-terminated array of dirauth config
8036 * lines.
8038 for (const char **i = default_authorities; *i != NULL; ++i) {
8039 char *val = esc_for_log(*i);
8040 smartlist_add_asprintf(sl, "DirAuthority %s\n", val);
8041 tor_free(val);
8045 if (fallback_lines_seen == 0 &&
8046 get_options()->UseDefaultFallbackDirs == 1) {
8048 * We didn't see any explicitly configured fallback mirrors,
8049 * so add the defaults to the list manually.
8051 * default_fallbacks is included earlier in this file and
8052 * is a const char ** NULL-terminated array of fallback config lines.
8054 const char **i;
8056 for (i = default_fallbacks; *i != NULL; ++i) {
8057 char *val = esc_for_log(*i);
8058 smartlist_add_asprintf(sl, "FallbackDir %s\n", val);
8059 tor_free(val);
8063 *answer = smartlist_join_strings(sl, "", 0, NULL);
8064 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
8065 smartlist_free(sl);
8067 return 0;
8070 /* Check whether an address has already been set against the options
8071 * depending on address family and destination type. Any exsting
8072 * value will lead to a fail, even if it is the same value. If not
8073 * set and not only validating, copy it into this location too.
8074 * Returns 0 on success or -1 if this address is already set.
8076 static int
8077 verify_and_store_outbound_address(sa_family_t family, tor_addr_t *addr,
8078 outbound_addr_t type, or_options_t *options, int validate_only)
8080 if (type>=OUTBOUND_ADDR_MAX || (family!=AF_INET && family!=AF_INET6)) {
8081 return -1;
8083 int fam_index=0;
8084 if (family==AF_INET6) {
8085 fam_index=1;
8087 tor_addr_t *dest=&options->OutboundBindAddresses[type][fam_index];
8088 if (!tor_addr_is_null(dest)) {
8089 return -1;
8091 if (!validate_only) {
8092 tor_addr_copy(dest, addr);
8094 return 0;
8097 /* Parse a list of address lines for a specific destination type.
8098 * Will store them into the options if not validate_only. If a
8099 * problem occurs, a suitable error message is store in msg.
8100 * Returns 0 on success or -1 if any address is already set.
8102 static int
8103 parse_outbound_address_lines(const config_line_t *lines, outbound_addr_t type,
8104 or_options_t *options, int validate_only, char **msg)
8106 tor_addr_t addr;
8107 sa_family_t family;
8108 while (lines) {
8109 family = tor_addr_parse(&addr, lines->value);
8110 if (verify_and_store_outbound_address(family, &addr, type,
8111 options, validate_only)) {
8112 if (msg)
8113 tor_asprintf(msg, "Multiple%s%s outbound bind addresses "
8114 "configured: %s",
8115 family==AF_INET?" IPv4":(family==AF_INET6?" IPv6":""),
8116 type==OUTBOUND_ADDR_OR?" OR":
8117 (type==OUTBOUND_ADDR_EXIT?" exit":""), lines->value);
8118 return -1;
8120 lines = lines->next;
8122 return 0;
8125 /** Parse outbound bind address option lines. If <b>validate_only</b>
8126 * is not 0 update OutboundBindAddresses in <b>options</b>.
8127 * Only one address can be set for any of these values.
8128 * On failure, set <b>msg</b> (if provided) to a newly allocated string
8129 * containing a description of the problem and return -1.
8131 static int
8132 parse_outbound_addresses(or_options_t *options, int validate_only, char **msg)
8134 if (!validate_only) {
8135 memset(&options->OutboundBindAddresses, 0,
8136 sizeof(options->OutboundBindAddresses));
8139 if (parse_outbound_address_lines(options->OutboundBindAddress,
8140 OUTBOUND_ADDR_EXIT_AND_OR, options,
8141 validate_only, msg) < 0) {
8142 goto err;
8145 if (parse_outbound_address_lines(options->OutboundBindAddressOR,
8146 OUTBOUND_ADDR_OR, options, validate_only,
8147 msg) < 0) {
8148 goto err;
8151 if (parse_outbound_address_lines(options->OutboundBindAddressExit,
8152 OUTBOUND_ADDR_EXIT, options, validate_only,
8153 msg) < 0) {
8154 goto err;
8157 return 0;
8158 err:
8159 return -1;
8162 /** Load one of the geoip files, <a>family</a> determining which
8163 * one. <a>default_fname</a> is used if on Windows and
8164 * <a>fname</a> equals "<default>". */
8165 static void
8166 config_load_geoip_file_(sa_family_t family,
8167 const char *fname,
8168 const char *default_fname)
8170 #ifdef _WIN32
8171 char *free_fname = NULL; /* Used to hold any temporary-allocated value */
8172 /* XXXX Don't use this "<default>" junk; make our filename options
8173 * understand prefixes somehow. -NM */
8174 if (!strcmp(fname, "<default>")) {
8175 const char *conf_root = get_windows_conf_root();
8176 tor_asprintf(&free_fname, "%s\\%s", conf_root, default_fname);
8177 fname = free_fname;
8179 geoip_load_file(family, fname);
8180 tor_free(free_fname);
8181 #else /* !(defined(_WIN32)) */
8182 (void)default_fname;
8183 geoip_load_file(family, fname);
8184 #endif /* defined(_WIN32) */
8187 /** Load geoip files for IPv4 and IPv6 if <a>options</a> and
8188 * <a>old_options</a> indicate we should. */
8189 static void
8190 config_maybe_load_geoip_files_(const or_options_t *options,
8191 const or_options_t *old_options)
8193 /* XXXX Reload GeoIPFile on SIGHUP. -NM */
8195 if (options->GeoIPFile &&
8196 ((!old_options || !opt_streq(old_options->GeoIPFile,
8197 options->GeoIPFile))
8198 || !geoip_is_loaded(AF_INET)))
8199 config_load_geoip_file_(AF_INET, options->GeoIPFile, "geoip");
8200 if (options->GeoIPv6File &&
8201 ((!old_options || !opt_streq(old_options->GeoIPv6File,
8202 options->GeoIPv6File))
8203 || !geoip_is_loaded(AF_INET6)))
8204 config_load_geoip_file_(AF_INET6, options->GeoIPv6File, "geoip6");
8207 /** Initialize cookie authentication (used so far by the ControlPort
8208 * and Extended ORPort).
8210 * Allocate memory and create a cookie (of length <b>cookie_len</b>)
8211 * in <b>cookie_out</b>.
8212 * Then write it down to <b>fname</b> and prepend it with <b>header</b>.
8214 * If <b>group_readable</b> is set, set <b>fname</b> to be readable
8215 * by the default GID.
8217 * If the whole procedure was successful, set
8218 * <b>cookie_is_set_out</b> to True. */
8220 init_cookie_authentication(const char *fname, const char *header,
8221 int cookie_len, int group_readable,
8222 uint8_t **cookie_out, int *cookie_is_set_out)
8224 char cookie_file_str_len = strlen(header) + cookie_len;
8225 char *cookie_file_str = tor_malloc(cookie_file_str_len);
8226 int retval = -1;
8228 /* We don't want to generate a new cookie every time we call
8229 * options_act(). One should be enough. */
8230 if (*cookie_is_set_out) {
8231 retval = 0; /* we are all set */
8232 goto done;
8235 /* If we've already set the cookie, free it before re-setting
8236 it. This can happen if we previously generated a cookie, but
8237 couldn't write it to a disk. */
8238 if (*cookie_out)
8239 tor_free(*cookie_out);
8241 /* Generate the cookie */
8242 *cookie_out = tor_malloc(cookie_len);
8243 crypto_rand((char *)*cookie_out, cookie_len);
8245 /* Create the string that should be written on the file. */
8246 memcpy(cookie_file_str, header, strlen(header));
8247 memcpy(cookie_file_str+strlen(header), *cookie_out, cookie_len);
8248 if (write_bytes_to_file(fname, cookie_file_str, cookie_file_str_len, 1)) {
8249 log_warn(LD_FS,"Error writing auth cookie to %s.", escaped(fname));
8250 goto done;
8253 #ifndef _WIN32
8254 if (group_readable) {
8255 if (chmod(fname, 0640)) {
8256 log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
8259 #else /* !(!defined(_WIN32)) */
8260 (void) group_readable;
8261 #endif /* !defined(_WIN32) */
8263 /* Success! */
8264 log_info(LD_GENERAL, "Generated auth cookie file in '%s'.", escaped(fname));
8265 *cookie_is_set_out = 1;
8266 retval = 0;
8268 done:
8269 memwipe(cookie_file_str, 0, cookie_file_str_len);
8270 tor_free(cookie_file_str);
8271 return retval;