Refactor UseEntryNodes so the original configured value is preserved
[tor.git] / src / or / config.c
blob48f1ab98e7f0f4d3094e59b2fec14eee8b4e3c72
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-2016, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file config.c
9 * \brief Code to parse and interpret configuration files.
10 **/
12 #define CONFIG_PRIVATE
13 #include "or.h"
14 #include "compat.h"
15 #include "addressmap.h"
16 #include "channel.h"
17 #include "circuitbuild.h"
18 #include "circuitlist.h"
19 #include "circuitmux.h"
20 #include "circuitmux_ewma.h"
21 #include "circuitstats.h"
22 #include "config.h"
23 #include "connection.h"
24 #include "connection_edge.h"
25 #include "connection_or.h"
26 #include "control.h"
27 #include "confparse.h"
28 #include "cpuworker.h"
29 #include "dirserv.h"
30 #include "dirvote.h"
31 #include "dns.h"
32 #include "entrynodes.h"
33 #include "geoip.h"
34 #include "hibernate.h"
35 #include "main.h"
36 #include "networkstatus.h"
37 #include "nodelist.h"
38 #include "policies.h"
39 #include "relay.h"
40 #include "rendclient.h"
41 #include "rendservice.h"
42 #include "rephist.h"
43 #include "router.h"
44 #include "sandbox.h"
45 #include "util.h"
46 #include "routerlist.h"
47 #include "routerset.h"
48 #include "scheduler.h"
49 #include "statefile.h"
50 #include "transports.h"
51 #include "ext_orport.h"
52 #include "torgzip.h"
53 #ifdef _WIN32
54 #include <shlobj.h>
55 #endif
57 #include "procmon.h"
59 #ifdef HAVE_SYSTEMD
60 # if defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__)
61 /* Systemd's use of gcc's __INCLUDE_LEVEL__ extension macro appears to confuse
62 * Coverity. Here's a kludge to unconfuse it.
64 # define __INCLUDE_LEVEL__ 2
65 # endif
66 #include <systemd/sd-daemon.h>
67 #endif
69 /* Prefix used to indicate a Unix socket in a FooPort configuration. */
70 static const char unix_socket_prefix[] = "unix:";
72 /** A list of abbreviations and aliases to map command-line options, obsolete
73 * option names, or alternative option names, to their current values. */
74 static config_abbrev_t option_abbrevs_[] = {
75 PLURAL(AuthDirBadDirCC),
76 PLURAL(AuthDirBadExitCC),
77 PLURAL(AuthDirInvalidCC),
78 PLURAL(AuthDirRejectCC),
79 PLURAL(EntryNode),
80 PLURAL(ExcludeNode),
81 PLURAL(Tor2webRendezvousPoint),
82 PLURAL(FirewallPort),
83 PLURAL(LongLivedPort),
84 PLURAL(HiddenServiceNode),
85 PLURAL(HiddenServiceExcludeNode),
86 PLURAL(NumCPU),
87 PLURAL(RendNode),
88 PLURAL(RecommendedPackage),
89 PLURAL(RendExcludeNode),
90 PLURAL(StrictEntryNode),
91 PLURAL(StrictExitNode),
92 PLURAL(StrictNode),
93 { "l", "Log", 1, 0},
94 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
95 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
96 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
97 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
98 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
99 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
100 { "DirServer", "DirAuthority", 0, 0}, /* XXXX later, make this warn? */
101 { "MaxConn", "ConnLimit", 0, 1},
102 { "MaxMemInCellQueues", "MaxMemInQueues", 0, 0},
103 { "ORBindAddress", "ORListenAddress", 0, 0},
104 { "DirBindAddress", "DirListenAddress", 0, 0},
105 { "SocksBindAddress", "SocksListenAddress", 0, 0},
106 { "UseHelperNodes", "UseEntryGuards", 0, 0},
107 { "NumHelperNodes", "NumEntryGuards", 0, 0},
108 { "UseEntryNodes", "UseEntryGuards", 0, 0},
109 { "NumEntryNodes", "NumEntryGuards", 0, 0},
110 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
111 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
112 { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0},
113 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
114 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
115 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
116 { "VirtualAddrNetwork", "VirtualAddrNetworkIPv4", 0, 0},
117 { NULL, NULL, 0, 0},
120 /** An entry for config_vars: "The option <b>name</b> has type
121 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
122 * or_options_t.<b>member</b>"
124 #define VAR(name,conftype,member,initvalue) \
125 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
126 initvalue }
127 /** As VAR, but the option name and member name are the same. */
128 #define V(member,conftype,initvalue) \
129 VAR(#member, conftype, member, initvalue)
130 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
131 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
133 #define VPORT(member,conftype,initvalue) \
134 VAR(#member, conftype, member ## _lines, initvalue)
136 /** Array of configuration options. Until we disallow nonstandard
137 * abbreviations, order is significant, since the first matching option will
138 * be chosen first.
140 static config_var_t option_vars_[] = {
141 V(AccountingMax, MEMUNIT, "0 bytes"),
142 VAR("AccountingRule", STRING, AccountingRule_option, "max"),
143 V(AccountingStart, STRING, NULL),
144 V(Address, STRING, NULL),
145 V(AllowDotExit, BOOL, "0"),
146 V(AllowInvalidNodes, CSV, "middle,rendezvous"),
147 V(AllowNonRFC953Hostnames, BOOL, "0"),
148 V(AllowSingleHopCircuits, BOOL, "0"),
149 V(AllowSingleHopExits, BOOL, "0"),
150 V(AlternateBridgeAuthority, LINELIST, NULL),
151 V(AlternateDirAuthority, LINELIST, NULL),
152 OBSOLETE("AlternateHSAuthority"),
153 V(AssumeReachable, BOOL, "0"),
154 OBSOLETE("AuthDirBadDir"),
155 OBSOLETE("AuthDirBadDirCCs"),
156 V(AuthDirBadExit, LINELIST, NULL),
157 V(AuthDirBadExitCCs, CSV, ""),
158 V(AuthDirInvalid, LINELIST, NULL),
159 V(AuthDirInvalidCCs, CSV, ""),
160 V(AuthDirFastGuarantee, MEMUNIT, "100 KB"),
161 V(AuthDirGuardBWGuarantee, MEMUNIT, "2 MB"),
162 V(AuthDirPinKeys, BOOL, "0"),
163 V(AuthDirReject, LINELIST, NULL),
164 V(AuthDirRejectCCs, CSV, ""),
165 OBSOLETE("AuthDirRejectUnlisted"),
166 OBSOLETE("AuthDirListBadDirs"),
167 V(AuthDirListBadExits, BOOL, "0"),
168 V(AuthDirMaxServersPerAddr, UINT, "2"),
169 V(AuthDirMaxServersPerAuthAddr,UINT, "5"),
170 V(AuthDirHasIPv6Connectivity, BOOL, "0"),
171 VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
172 V(AutomapHostsOnResolve, BOOL, "0"),
173 V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
174 V(AvoidDiskWrites, BOOL, "0"),
175 V(BandwidthBurst, MEMUNIT, "1 GB"),
176 V(BandwidthRate, MEMUNIT, "1 GB"),
177 V(BridgeAuthoritativeDir, BOOL, "0"),
178 VAR("Bridge", LINELIST, Bridges, NULL),
179 V(BridgePassword, STRING, NULL),
180 V(BridgeRecordUsageByCountry, BOOL, "1"),
181 V(BridgeRelay, BOOL, "0"),
182 V(CellStatistics, BOOL, "0"),
183 V(LearnCircuitBuildTimeout, BOOL, "1"),
184 V(CircuitBuildTimeout, INTERVAL, "0"),
185 V(CircuitIdleTimeout, INTERVAL, "1 hour"),
186 V(CircuitStreamTimeout, INTERVAL, "0"),
187 V(CircuitPriorityHalflife, DOUBLE, "-100.0"), /*negative:'Use default'*/
188 V(ClientDNSRejectInternalAddresses, BOOL,"1"),
189 V(ClientOnly, BOOL, "0"),
190 V(ClientPreferIPv6ORPort, AUTOBOOL, "auto"),
191 V(ClientPreferIPv6DirPort, AUTOBOOL, "auto"),
192 V(ClientRejectInternalAddresses, BOOL, "1"),
193 V(ClientTransportPlugin, LINELIST, NULL),
194 V(ClientUseIPv6, BOOL, "0"),
195 V(ClientUseIPv4, BOOL, "1"),
196 V(ConsensusParams, STRING, NULL),
197 V(ConnLimit, UINT, "1000"),
198 V(ConnDirectionStatistics, BOOL, "0"),
199 V(ConstrainedSockets, BOOL, "0"),
200 V(ConstrainedSockSize, MEMUNIT, "8192"),
201 V(ContactInfo, STRING, NULL),
202 V(ControlListenAddress, LINELIST, NULL),
203 VPORT(ControlPort, LINELIST, NULL),
204 V(ControlPortFileGroupReadable,BOOL, "0"),
205 V(ControlPortWriteToFile, FILENAME, NULL),
206 V(ControlSocket, LINELIST, NULL),
207 V(ControlSocketsGroupWritable, BOOL, "0"),
208 V(SocksSocketsGroupWritable, BOOL, "0"),
209 V(CookieAuthentication, BOOL, "0"),
210 V(CookieAuthFileGroupReadable, BOOL, "0"),
211 V(CookieAuthFile, STRING, NULL),
212 V(CountPrivateBandwidth, BOOL, "0"),
213 V(DataDirectory, FILENAME, NULL),
214 V(DataDirectoryGroupReadable, BOOL, "0"),
215 V(DisableOOSCheck, BOOL, "1"),
216 V(DisableNetwork, BOOL, "0"),
217 V(DirAllowPrivateAddresses, BOOL, "0"),
218 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
219 V(DirListenAddress, LINELIST, NULL),
220 V(DirPolicy, LINELIST, NULL),
221 VPORT(DirPort, LINELIST, NULL),
222 V(DirPortFrontPage, FILENAME, NULL),
223 VAR("DirReqStatistics", BOOL, DirReqStatistics_option, "1"),
224 VAR("DirAuthority", LINELIST, DirAuthorities, NULL),
225 V(DirCache, BOOL, "1"),
226 V(DirAuthorityFallbackRate, DOUBLE, "1.0"),
227 V(DisableAllSwap, BOOL, "0"),
228 V(DisableDebuggerAttachment, BOOL, "1"),
229 OBSOLETE("DisableIOCP"),
230 OBSOLETE("DisableV2DirectoryInfo_"),
231 OBSOLETE("DynamicDHGroups"),
232 VPORT(DNSPort, LINELIST, NULL),
233 V(DNSListenAddress, LINELIST, NULL),
234 V(DownloadExtraInfo, BOOL, "0"),
235 V(TestingEnableConnBwEvent, BOOL, "0"),
236 V(TestingEnableCellStatsEvent, BOOL, "0"),
237 V(TestingEnableTbEmptyEvent, BOOL, "0"),
238 V(EnforceDistinctSubnets, BOOL, "1"),
239 V(EntryNodes, ROUTERSET, NULL),
240 V(EntryStatistics, BOOL, "0"),
241 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
242 V(ExcludeNodes, ROUTERSET, NULL),
243 V(ExcludeExitNodes, ROUTERSET, NULL),
244 V(ExcludeSingleHopRelays, BOOL, "1"),
245 V(ExitNodes, ROUTERSET, NULL),
246 V(ExitPolicy, LINELIST, NULL),
247 V(ExitPolicyRejectPrivate, BOOL, "1"),
248 V(ExitPolicyRejectLocalInterfaces, BOOL, "0"),
249 V(ExitPortStatistics, BOOL, "0"),
250 V(ExtendAllowPrivateAddresses, BOOL, "0"),
251 V(ExitRelay, AUTOBOOL, "auto"),
252 VPORT(ExtORPort, LINELIST, NULL),
253 V(ExtORPortCookieAuthFile, STRING, NULL),
254 V(ExtORPortCookieAuthFileGroupReadable, BOOL, "0"),
255 V(ExtraInfoStatistics, BOOL, "1"),
256 V(FallbackDir, LINELIST, NULL),
257 V(UseDefaultFallbackDirs, BOOL, "1"),
259 OBSOLETE("FallbackNetworkstatusFile"),
260 V(FascistFirewall, BOOL, "0"),
261 V(FirewallPorts, CSV, ""),
262 V(FastFirstHopPK, AUTOBOOL, "auto"),
263 V(FetchDirInfoEarly, BOOL, "0"),
264 V(FetchDirInfoExtraEarly, BOOL, "0"),
265 V(FetchServerDescriptors, BOOL, "1"),
266 V(FetchHidServDescriptors, BOOL, "1"),
267 V(FetchUselessDescriptors, BOOL, "0"),
268 OBSOLETE("FetchV2Networkstatus"),
269 V(GeoIPExcludeUnknown, AUTOBOOL, "auto"),
270 #ifdef _WIN32
271 V(GeoIPFile, FILENAME, "<default>"),
272 V(GeoIPv6File, FILENAME, "<default>"),
273 #else
274 V(GeoIPFile, FILENAME,
275 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
276 V(GeoIPv6File, FILENAME,
277 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip6"),
278 #endif
279 OBSOLETE("Group"),
280 V(GuardLifetime, INTERVAL, "0 minutes"),
281 V(HardwareAccel, BOOL, "0"),
282 V(HeartbeatPeriod, INTERVAL, "6 hours"),
283 V(AccelName, STRING, NULL),
284 V(AccelDir, FILENAME, NULL),
285 V(HashedControlPassword, LINELIST, NULL),
286 OBSOLETE("HidServDirectoryV2"),
287 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
288 VAR("HiddenServiceDirGroupReadable", LINELIST_S, RendConfigLines, NULL),
289 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
290 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
291 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
292 VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
293 VAR("HiddenServiceAllowUnknownPorts",LINELIST_S, RendConfigLines, NULL),
294 VAR("HiddenServiceMaxStreams",LINELIST_S, RendConfigLines, NULL),
295 VAR("HiddenServiceMaxStreamsCloseCircuit",LINELIST_S, RendConfigLines, NULL),
296 VAR("HiddenServiceNumIntroductionPoints", LINELIST_S, RendConfigLines, NULL),
297 V(HiddenServiceStatistics, BOOL, "1"),
298 V(HidServAuth, LINELIST, NULL),
299 V(CloseHSClientCircuitsImmediatelyOnTimeout, BOOL, "0"),
300 V(CloseHSServiceRendCircuitsImmediatelyOnTimeout, BOOL, "0"),
301 V(OnionServiceSingleHopMode, BOOL, "0"),
302 V(OnionServiceNonAnonymousMode,BOOL, "0"),
303 V(HTTPProxy, STRING, NULL),
304 V(HTTPProxyAuthenticator, STRING, NULL),
305 V(HTTPSProxy, STRING, NULL),
306 V(HTTPSProxyAuthenticator, STRING, NULL),
307 V(IPv6Exit, BOOL, "0"),
308 VAR("ServerTransportPlugin", LINELIST, ServerTransportPlugin, NULL),
309 V(ServerTransportListenAddr, LINELIST, NULL),
310 V(ServerTransportOptions, LINELIST, NULL),
311 V(SigningKeyLifetime, INTERVAL, "30 days"),
312 V(Socks4Proxy, STRING, NULL),
313 V(Socks5Proxy, STRING, NULL),
314 V(Socks5ProxyUsername, STRING, NULL),
315 V(Socks5ProxyPassword, STRING, NULL),
316 V(KeepalivePeriod, INTERVAL, "5 minutes"),
317 V(KeepBindCapabilities, AUTOBOOL, "auto"),
318 VAR("Log", LINELIST, Logs, NULL),
319 V(LogMessageDomains, BOOL, "0"),
320 V(LogTimeGranularity, MSEC_INTERVAL, "1 second"),
321 V(TruncateLogFile, BOOL, "0"),
322 V(SyslogIdentityTag, STRING, NULL),
323 V(LongLivedPorts, CSV,
324 "21,22,706,1863,5050,5190,5222,5223,6523,6667,6697,8300"),
325 VAR("MapAddress", LINELIST, AddressMap, NULL),
326 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
327 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
328 V(MaxClientCircuitsPending, UINT, "32"),
329 VAR("MaxMemInQueues", MEMUNIT, MaxMemInQueues_raw, "0"),
330 OBSOLETE("MaxOnionsPending"),
331 V(MaxOnionQueueDelay, MSEC_INTERVAL, "1750 msec"),
332 V(MaxUnparseableDescSizeToLog, MEMUNIT, "10 MB"),
333 V(MinMeasuredBWsForAuthToIgnoreAdvertised, INT, "500"),
334 V(MyFamily, STRING, NULL),
335 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
336 OBSOLETE("NamingAuthoritativeDirectory"),
337 V(NATDListenAddress, LINELIST, NULL),
338 VPORT(NATDPort, LINELIST, NULL),
339 V(Nickname, STRING, NULL),
340 V(PredictedPortsRelevanceTime, INTERVAL, "1 hour"),
341 V(WarnUnsafeSocks, BOOL, "1"),
342 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
343 V(NumCPUs, UINT, "0"),
344 V(NumDirectoryGuards, UINT, "0"),
345 V(NumEntryGuards, UINT, "0"),
346 V(OfflineMasterKey, BOOL, "0"),
347 V(ORListenAddress, LINELIST, NULL),
348 VPORT(ORPort, LINELIST, NULL),
349 V(OutboundBindAddress, LINELIST, NULL),
351 OBSOLETE("PathBiasDisableRate"),
352 V(PathBiasCircThreshold, INT, "-1"),
353 V(PathBiasNoticeRate, DOUBLE, "-1"),
354 V(PathBiasWarnRate, DOUBLE, "-1"),
355 V(PathBiasExtremeRate, DOUBLE, "-1"),
356 V(PathBiasScaleThreshold, INT, "-1"),
357 OBSOLETE("PathBiasScaleFactor"),
358 OBSOLETE("PathBiasMultFactor"),
359 V(PathBiasDropGuards, AUTOBOOL, "0"),
360 OBSOLETE("PathBiasUseCloseCounts"),
362 V(PathBiasUseThreshold, INT, "-1"),
363 V(PathBiasNoticeUseRate, DOUBLE, "-1"),
364 V(PathBiasExtremeUseRate, DOUBLE, "-1"),
365 V(PathBiasScaleUseThreshold, INT, "-1"),
367 V(PathsNeededToBuildCircuits, DOUBLE, "-1"),
368 V(PerConnBWBurst, MEMUNIT, "0"),
369 V(PerConnBWRate, MEMUNIT, "0"),
370 V(PidFile, STRING, NULL),
371 V(TestingTorNetwork, BOOL, "0"),
372 V(TestingMinExitFlagThreshold, MEMUNIT, "0"),
373 V(TestingMinFastFlagThreshold, MEMUNIT, "0"),
375 V(TestingLinkCertLifetime, INTERVAL, "2 days"),
376 V(TestingAuthKeyLifetime, INTERVAL, "2 days"),
377 V(TestingLinkKeySlop, INTERVAL, "3 hours"),
378 V(TestingAuthKeySlop, INTERVAL, "3 hours"),
379 V(TestingSigningKeySlop, INTERVAL, "1 day"),
381 V(OptimisticData, AUTOBOOL, "auto"),
382 V(PortForwarding, BOOL, "0"),
383 V(PortForwardingHelper, FILENAME, "tor-fw-helper"),
384 OBSOLETE("PreferTunneledDirConns"),
385 V(ProtocolWarnings, BOOL, "0"),
386 V(PublishServerDescriptor, CSV, "1"),
387 V(PublishHidServDescriptors, BOOL, "1"),
388 V(ReachableAddresses, LINELIST, NULL),
389 V(ReachableDirAddresses, LINELIST, NULL),
390 V(ReachableORAddresses, LINELIST, NULL),
391 V(RecommendedVersions, LINELIST, NULL),
392 V(RecommendedClientVersions, LINELIST, NULL),
393 V(RecommendedServerVersions, LINELIST, NULL),
394 V(RecommendedPackages, LINELIST, NULL),
395 V(RefuseUnknownExits, AUTOBOOL, "auto"),
396 V(RejectPlaintextPorts, CSV, ""),
397 V(RelayBandwidthBurst, MEMUNIT, "0"),
398 V(RelayBandwidthRate, MEMUNIT, "0"),
399 V(RendPostPeriod, INTERVAL, "1 hour"),
400 V(RephistTrackTime, INTERVAL, "24 hours"),
401 V(RunAsDaemon, BOOL, "0"),
402 OBSOLETE("RunTesting"), // currently unused
403 V(Sandbox, BOOL, "0"),
404 V(SafeLogging, STRING, "1"),
405 V(SafeSocks, BOOL, "0"),
406 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
407 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
408 V(ServerDNSDetectHijacking, BOOL, "1"),
409 V(ServerDNSRandomizeCase, BOOL, "1"),
410 V(ServerDNSResolvConfFile, STRING, NULL),
411 V(ServerDNSSearchDomains, BOOL, "0"),
412 V(ServerDNSTestAddresses, CSV,
413 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
414 V(SchedulerLowWaterMark__, MEMUNIT, "100 MB"),
415 V(SchedulerHighWaterMark__, MEMUNIT, "101 MB"),
416 V(SchedulerMaxFlushCells__, UINT, "1000"),
417 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
418 V(SocksListenAddress, LINELIST, NULL),
419 V(SocksPolicy, LINELIST, NULL),
420 VPORT(SocksPort, LINELIST, NULL),
421 V(SocksTimeout, INTERVAL, "2 minutes"),
422 V(SSLKeyLifetime, INTERVAL, "0"),
423 OBSOLETE("StrictEntryNodes"),
424 OBSOLETE("StrictExitNodes"),
425 V(StrictNodes, BOOL, "0"),
426 OBSOLETE("Support022HiddenServices"),
427 V(TestSocks, BOOL, "0"),
428 V(TokenBucketRefillInterval, MSEC_INTERVAL, "100 msec"),
429 V(Tor2webMode, BOOL, "0"),
430 V(Tor2webRendezvousPoints, ROUTERSET, NULL),
431 V(TLSECGroup, STRING, NULL),
432 V(TrackHostExits, CSV, NULL),
433 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
434 V(TransListenAddress, LINELIST, NULL),
435 VPORT(TransPort, LINELIST, NULL),
436 V(TransProxyType, STRING, "default"),
437 OBSOLETE("TunnelDirConns"),
438 V(UpdateBridgesFromAuthority, BOOL, "0"),
439 V(UseBridges, BOOL, "0"),
440 VAR("UseEntryGuards", BOOL, UseEntryGuards_option, "1"),
441 V(UseEntryGuardsAsDirGuards, BOOL, "1"),
442 V(UseGuardFraction, AUTOBOOL, "auto"),
443 V(UseMicrodescriptors, AUTOBOOL, "auto"),
444 OBSOLETE("UseNTorHandshake"),
445 V(User, STRING, NULL),
446 OBSOLETE("UserspaceIOCPBuffers"),
447 V(AuthDirSharedRandomness, BOOL, "1"),
448 OBSOLETE("V1AuthoritativeDirectory"),
449 OBSOLETE("V2AuthoritativeDirectory"),
450 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
451 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
452 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
453 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
454 V(TestingV3AuthVotingStartOffset, INTERVAL, "0"),
455 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
456 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
457 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
458 V(V3AuthNIntervalsValid, UINT, "3"),
459 V(V3AuthUseLegacyKey, BOOL, "0"),
460 V(V3BandwidthsFile, FILENAME, NULL),
461 V(GuardfractionFile, FILENAME, NULL),
462 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
463 OBSOLETE("VoteOnHidServDirectoriesV2"),
464 V(VirtualAddrNetworkIPv4, STRING, "127.192.0.0/10"),
465 V(VirtualAddrNetworkIPv6, STRING, "[FE80::]/10"),
466 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
467 OBSOLETE("UseFilteringSSLBufferevents"),
468 OBSOLETE("__UseFilteringSSLBufferevents"),
469 VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
470 VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
471 VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
472 VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
473 VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
474 NULL),
475 VAR("__OwningControllerProcess",STRING,OwningControllerProcess, NULL),
476 V(MinUptimeHidServDirectoryV2, INTERVAL, "96 hours"),
477 V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 60, 60, 120, "
478 "300, 900, 2147483647"),
479 V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 60, 300, 600, "
480 "2147483647"),
481 V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
482 "300, 600, 1800, 1800, 1800, 1800, "
483 "1800, 3600, 7200"),
484 V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
485 "300, 600, 1800, 3600, 3600, 3600, "
486 "10800, 21600, 43200"),
487 /* With the ClientBootstrapConsensus*Download* below:
488 * Clients with only authorities will try:
489 * - 3 authorities over 10 seconds, then wait 60 minutes.
490 * Clients with authorities and fallbacks will try:
491 * - 2 authorities and 4 fallbacks over 21 seconds, then wait 60 minutes.
492 * Clients will also retry when an application request arrives.
493 * After a number of failed reqests, clients retry every 3 days + 1 hour.
495 * Clients used to try 2 authorities over 10 seconds, then wait for
496 * 60 minutes or an application request.
498 * When clients have authorities and fallbacks available, they use these
499 * schedules: (we stagger the times to avoid thundering herds) */
500 V(ClientBootstrapConsensusAuthorityDownloadSchedule, CSV_INTERVAL,
501 "10, 11, 3600, 10800, 25200, 54000, 111600, 262800" /* 3 days + 1 hour */),
502 V(ClientBootstrapConsensusFallbackDownloadSchedule, CSV_INTERVAL,
503 "0, 1, 4, 11, 3600, 10800, 25200, 54000, 111600, 262800"),
504 /* When clients only have authorities available, they use this schedule: */
505 V(ClientBootstrapConsensusAuthorityOnlyDownloadSchedule, CSV_INTERVAL,
506 "0, 3, 7, 3600, 10800, 25200, 54000, 111600, 262800"),
507 /* We don't want to overwhelm slow networks (or mirrors whose replies are
508 * blocked), but we also don't want to fail if only some mirrors are
509 * blackholed. Clients will try 3 directories simultaneously.
510 * (Relays never use simultaneous connections.) */
511 V(ClientBootstrapConsensusMaxInProgressTries, UINT, "3"),
512 V(TestingBridgeDownloadSchedule, CSV_INTERVAL, "3600, 900, 900, 3600"),
513 V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "10 minutes"),
514 V(TestingDirConnectionMaxStall, INTERVAL, "5 minutes"),
515 V(TestingConsensusMaxDownloadTries, UINT, "8"),
516 /* Since we try connections rapidly and simultaneously, we can afford
517 * to give up earlier. (This protects against overloading directories.) */
518 V(ClientBootstrapConsensusMaxDownloadTries, UINT, "7"),
519 /* We want to give up much earlier if we're only using authorities. */
520 V(ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries, UINT, "4"),
521 V(TestingDescriptorMaxDownloadTries, UINT, "8"),
522 V(TestingMicrodescMaxDownloadTries, UINT, "8"),
523 V(TestingCertMaxDownloadTries, UINT, "8"),
524 V(TestingDirAuthVoteExit, ROUTERSET, NULL),
525 V(TestingDirAuthVoteExitIsStrict, BOOL, "0"),
526 V(TestingDirAuthVoteGuard, ROUTERSET, NULL),
527 V(TestingDirAuthVoteGuardIsStrict, BOOL, "0"),
528 V(TestingDirAuthVoteHSDir, ROUTERSET, NULL),
529 V(TestingDirAuthVoteHSDirIsStrict, BOOL, "0"),
530 VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "0"),
532 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
535 /** Override default values with these if the user sets the TestingTorNetwork
536 * option. */
537 static const config_var_t testing_tor_network_defaults[] = {
538 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
539 V(DirAllowPrivateAddresses, BOOL, "1"),
540 V(EnforceDistinctSubnets, BOOL, "0"),
541 V(AssumeReachable, BOOL, "1"),
542 V(AuthDirMaxServersPerAddr, UINT, "0"),
543 V(AuthDirMaxServersPerAuthAddr,UINT, "0"),
544 V(ClientBootstrapConsensusAuthorityDownloadSchedule, CSV_INTERVAL,
545 "0, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
546 V(ClientBootstrapConsensusFallbackDownloadSchedule, CSV_INTERVAL,
547 "0, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
548 V(ClientBootstrapConsensusAuthorityOnlyDownloadSchedule, CSV_INTERVAL,
549 "0, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
550 V(ClientBootstrapConsensusMaxDownloadTries, UINT, "80"),
551 V(ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries, UINT, "80"),
552 V(ClientDNSRejectInternalAddresses, BOOL,"0"), // deprecated in 0.2.9.2-alpha
553 V(ClientRejectInternalAddresses, BOOL, "0"),
554 V(CountPrivateBandwidth, BOOL, "1"),
555 V(ExitPolicyRejectPrivate, BOOL, "0"),
556 V(ExtendAllowPrivateAddresses, BOOL, "1"),
557 V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
558 V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
559 V(V3AuthDistDelay, INTERVAL, "20 seconds"),
560 V(TestingV3AuthInitialVotingInterval, INTERVAL, "150 seconds"),
561 V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
562 V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
563 V(TestingV3AuthVotingStartOffset, INTERVAL, "0"),
564 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
565 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
566 V(MinUptimeHidServDirectoryV2, INTERVAL, "0 minutes"),
567 V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 5, 10, 15, "
568 "20, 30, 60"),
569 V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, 15, 20, "
570 "30, 60"),
571 V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
572 "15, 20, 30, 60"),
573 V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
574 "15, 20, 30, 60"),
575 V(TestingBridgeDownloadSchedule, CSV_INTERVAL, "60, 30, 30, 60"),
576 V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "5 seconds"),
577 V(TestingDirConnectionMaxStall, INTERVAL, "30 seconds"),
578 V(TestingConsensusMaxDownloadTries, UINT, "80"),
579 V(TestingDescriptorMaxDownloadTries, UINT, "80"),
580 V(TestingMicrodescMaxDownloadTries, UINT, "80"),
581 V(TestingCertMaxDownloadTries, UINT, "80"),
582 V(TestingEnableConnBwEvent, BOOL, "1"),
583 V(TestingEnableCellStatsEvent, BOOL, "1"),
584 V(TestingEnableTbEmptyEvent, BOOL, "1"),
585 VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "1"),
586 V(RendPostPeriod, INTERVAL, "2 minutes"),
588 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
591 #undef VAR
592 #undef V
593 #undef OBSOLETE
595 static const config_deprecation_t option_deprecation_notes_[] = {
596 /* Deprecated since 0.2.9.2-alpha... */
597 { "AllowDotExit", "Unrestricted use of the .exit notation can be used for "
598 "a wide variety of application-level attacks." },
599 { "AllowInvalidNodes", "There is no reason to enable this option; at best "
600 "it will make you easier to track." },
601 { "AllowSingleHopCircuits", "Almost no relays actually allow single-hop "
602 "exits, making this option pointless." },
603 { "AllowSingleHopExits", "Turning this on will make your relay easier "
604 "to abuse." },
605 { "ClientDNSRejectInternalAddresses", "Turning this on makes your client "
606 "easier to fingerprint, and may open you to esoteric attacks." },
607 { "ExcludeSingleHopRelays", "Turning it on makes your client easier to "
608 "fingerprint." },
609 { "FastFirstHopPK", "Changing this option does not make your client more "
610 "secure, but does make it easier to fingerprint." },
611 { "CloseHSClientCircuitsImmediatelyOnTimeout", "This option makes your "
612 "client easier to fingerprint." },
613 { "CloseHSServiceRendCircuitsImmediatelyOnTimeout", "This option makes "
614 "your hidden services easier to fingerprint." },
615 { "WarnUnsafeSocks", "Changing this option makes it easier for you "
616 "to accidentally lose your anonymity by leaking DNS information" },
617 { "TLSECGroup", "The default is a nice secure choice; the other option "
618 "is less secure." },
619 { "ControlListenAddress", "Use ControlPort instead." },
620 { "DirListenAddress", "Use DirPort instead, possibly with the "
621 "NoAdvertise sub-option" },
622 { "DNSListenAddress", "Use DNSPort instead." },
623 { "SocksListenAddress", "Use SocksPort instead." },
624 { "TransListenAddress", "Use TransPort instead." },
625 { "NATDListenAddress", "Use NATDPort instead." },
626 { "ORListenAddress", "Use ORPort instead, possibly with the "
627 "NoAdvertise sub-option" },
628 /* End of options deprecated since 0.2.9.2-alpha. */
630 { NULL, NULL }
633 #ifdef _WIN32
634 static char *get_windows_conf_root(void);
635 #endif
636 static int options_act_reversible(const or_options_t *old_options, char **msg);
637 static int options_transition_allowed(const or_options_t *old,
638 const or_options_t *new,
639 char **msg);
640 static int options_transition_affects_workers(
641 const or_options_t *old_options, const or_options_t *new_options);
642 static int options_transition_affects_descriptor(
643 const or_options_t *old_options, const or_options_t *new_options);
644 static int check_nickname_list(char **lst, const char *name, char **msg);
645 static char *get_bindaddr_from_transport_listen_line(const char *line,
646 const char *transport);
647 static int parse_ports(or_options_t *options, int validate_only,
648 char **msg_out, int *n_ports_out,
649 int *world_writable_control_socket);
650 static int check_server_ports(const smartlist_t *ports,
651 const or_options_t *options,
652 int *num_low_ports_out);
654 static int validate_data_directory(or_options_t *options);
655 static int write_configuration_file(const char *fname,
656 const or_options_t *options);
657 static int options_init_logs(const or_options_t *old_options,
658 or_options_t *options, int validate_only);
660 static void init_libevent(const or_options_t *options);
661 static int opt_streq(const char *s1, const char *s2);
662 static int parse_outbound_addresses(or_options_t *options, int validate_only,
663 char **msg);
664 static void config_maybe_load_geoip_files_(const or_options_t *options,
665 const or_options_t *old_options);
666 static int options_validate_cb(void *old_options, void *options,
667 void *default_options,
668 int from_setconf, char **msg);
669 static uint64_t compute_real_max_mem_in_queues(const uint64_t val,
670 int log_guess);
672 /** Magic value for or_options_t. */
673 #define OR_OPTIONS_MAGIC 9090909
675 /** Configuration format for or_options_t. */
676 STATIC config_format_t options_format = {
677 sizeof(or_options_t),
678 OR_OPTIONS_MAGIC,
679 STRUCT_OFFSET(or_options_t, magic_),
680 option_abbrevs_,
681 option_deprecation_notes_,
682 option_vars_,
683 options_validate_cb,
684 NULL
688 * Functions to read and write the global options pointer.
691 /** Command-line and config-file options. */
692 static or_options_t *global_options = NULL;
693 /** The fallback options_t object; this is where we look for options not
694 * in torrc before we fall back to Tor's defaults. */
695 static or_options_t *global_default_options = NULL;
696 /** Name of most recently read torrc file. */
697 static char *torrc_fname = NULL;
698 /** Name of the most recently read torrc-defaults file.*/
699 static char *torrc_defaults_fname;
700 /** Configuration options set by command line. */
701 static config_line_t *global_cmdline_options = NULL;
702 /** Non-configuration options set by the command line */
703 static config_line_t *global_cmdline_only_options = NULL;
704 /** Boolean: Have we parsed the command line? */
705 static int have_parsed_cmdline = 0;
706 /** Contents of most recently read DirPortFrontPage file. */
707 static char *global_dirfrontpagecontents = NULL;
708 /** List of port_cfg_t for all configured ports. */
709 static smartlist_t *configured_ports = NULL;
711 /** Return the contents of our frontpage string, or NULL if not configured. */
712 MOCK_IMPL(const char*,
713 get_dirportfrontpage, (void))
715 return global_dirfrontpagecontents;
718 /** Returns the currently configured options. */
719 MOCK_IMPL(or_options_t *,
720 get_options_mutable, (void))
722 tor_assert(global_options);
723 return global_options;
726 /** Returns the currently configured options */
727 MOCK_IMPL(const or_options_t *,
728 get_options,(void))
730 return get_options_mutable();
733 /** Change the current global options to contain <b>new_val</b> instead of
734 * their current value; take action based on the new value; free the old value
735 * as necessary. Returns 0 on success, -1 on failure.
738 set_options(or_options_t *new_val, char **msg)
740 int i;
741 smartlist_t *elements;
742 config_line_t *line;
743 or_options_t *old_options = global_options;
744 global_options = new_val;
745 /* Note that we pass the *old* options below, for comparison. It
746 * pulls the new options directly out of global_options. */
747 if (options_act_reversible(old_options, msg)<0) {
748 tor_assert(*msg);
749 global_options = old_options;
750 return -1;
752 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
753 log_err(LD_BUG,
754 "Acting on config options left us in a broken state. Dying.");
755 exit(1);
757 /* Issues a CONF_CHANGED event to notify controller of the change. If Tor is
758 * just starting up then the old_options will be undefined. */
759 if (old_options && old_options != global_options) {
760 elements = smartlist_new();
761 for (i=0; options_format.vars[i].name; ++i) {
762 const config_var_t *var = &options_format.vars[i];
763 const char *var_name = var->name;
764 if (var->type == CONFIG_TYPE_LINELIST_S ||
765 var->type == CONFIG_TYPE_OBSOLETE) {
766 continue;
768 if (!config_is_same(&options_format, new_val, old_options, var_name)) {
769 line = config_get_assigned_option(&options_format, new_val,
770 var_name, 1);
772 if (line) {
773 config_line_t *next;
774 for (; line; line = next) {
775 next = line->next;
776 smartlist_add(elements, line->key);
777 smartlist_add(elements, line->value);
778 tor_free(line);
780 } else {
781 smartlist_add(elements, tor_strdup(options_format.vars[i].name));
782 smartlist_add(elements, NULL);
786 control_event_conf_changed(elements);
787 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
788 smartlist_free(elements);
791 if (old_options != global_options)
792 or_options_free(old_options);
794 return 0;
797 extern const char tor_git_revision[]; /* from tor_main.c */
799 /** The version of this Tor process, as parsed. */
800 static char *the_tor_version = NULL;
801 /** A shorter version of this Tor process's version, for export in our router
802 * descriptor. (Does not include the git version, if any.) */
803 static char *the_short_tor_version = NULL;
805 /** Return the current Tor version. */
806 const char *
807 get_version(void)
809 if (the_tor_version == NULL) {
810 if (strlen(tor_git_revision)) {
811 tor_asprintf(&the_tor_version, "%s (git-%s)", get_short_version(),
812 tor_git_revision);
813 } else {
814 the_tor_version = tor_strdup(get_short_version());
817 return the_tor_version;
820 /** Return the current Tor version, without any git tag. */
821 const char *
822 get_short_version(void)
825 if (the_short_tor_version == NULL) {
826 #ifdef TOR_BUILD_TAG
827 tor_asprintf(&the_short_tor_version, "%s (%s)", VERSION, TOR_BUILD_TAG);
828 #else
829 the_short_tor_version = tor_strdup(VERSION);
830 #endif
832 return the_short_tor_version;
835 /** Release additional memory allocated in options
837 STATIC void
838 or_options_free(or_options_t *options)
840 if (!options)
841 return;
843 routerset_free(options->ExcludeExitNodesUnion_);
844 if (options->NodeFamilySets) {
845 SMARTLIST_FOREACH(options->NodeFamilySets, routerset_t *,
846 rs, routerset_free(rs));
847 smartlist_free(options->NodeFamilySets);
849 tor_free(options->BridgePassword_AuthDigest_);
850 tor_free(options->command_arg);
851 tor_free(options->master_key_fname);
852 config_free(&options_format, options);
855 /** Release all memory and resources held by global configuration structures.
857 void
858 config_free_all(void)
860 or_options_free(global_options);
861 global_options = NULL;
862 or_options_free(global_default_options);
863 global_default_options = NULL;
865 config_free_lines(global_cmdline_options);
866 global_cmdline_options = NULL;
868 config_free_lines(global_cmdline_only_options);
869 global_cmdline_only_options = NULL;
871 if (configured_ports) {
872 SMARTLIST_FOREACH(configured_ports,
873 port_cfg_t *, p, port_cfg_free(p));
874 smartlist_free(configured_ports);
875 configured_ports = NULL;
878 tor_free(torrc_fname);
879 tor_free(torrc_defaults_fname);
880 tor_free(global_dirfrontpagecontents);
882 tor_free(the_short_tor_version);
883 tor_free(the_tor_version);
886 /** Make <b>address</b> -- a piece of information related to our operation as
887 * a client -- safe to log according to the settings in options->SafeLogging,
888 * and return it.
890 * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
892 const char *
893 safe_str_client(const char *address)
895 tor_assert(address);
896 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
897 return "[scrubbed]";
898 else
899 return address;
902 /** Make <b>address</b> -- a piece of information of unspecified sensitivity
903 * -- safe to log according to the settings in options->SafeLogging, and
904 * return it.
906 * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
907 * otherwise.)
909 const char *
910 safe_str(const char *address)
912 tor_assert(address);
913 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
914 return "[scrubbed]";
915 else
916 return address;
919 /** Equivalent to escaped(safe_str_client(address)). See reentrancy note on
920 * escaped(): don't use this outside the main thread, or twice in the same
921 * log statement. */
922 const char *
923 escaped_safe_str_client(const char *address)
925 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
926 return "[scrubbed]";
927 else
928 return escaped(address);
931 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
932 * escaped(): don't use this outside the main thread, or twice in the same
933 * log statement. */
934 const char *
935 escaped_safe_str(const char *address)
937 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
938 return "[scrubbed]";
939 else
940 return escaped(address);
943 /** List of default directory authorities */
945 static const char *default_authorities[] = {
946 "moria1 orport=9101 "
947 "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
948 "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
949 "tor26 orport=443 "
950 "v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
951 "ipv6=[2001:858:2:2:aabb:0:563b:1526]:443 "
952 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
953 "dizum orport=443 "
954 "v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
955 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
956 "Bifroest orport=443 bridge "
957 "37.218.247.217:80 1D8F 3A91 C37C 5D1C 4C19 B1AD 1D0C FBE8 BF72 D8E1",
958 "gabelmoo orport=443 "
959 "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
960 "ipv6=[2001:638:a000:4140::ffff:189]:443 "
961 "131.188.40.189:80 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
962 "dannenberg orport=443 "
963 "v3ident=0232AF901C31A04EE9848595AF9BB7620D4C5B2E "
964 "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
965 "maatuska orport=80 "
966 "v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
967 "ipv6=[2001:67c:289c::9]:80 "
968 "171.25.193.9:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
969 "Faravahar orport=443 "
970 "v3ident=EFCBE720AB3A82B99F9E953CD5BF50F7EEFC7B97 "
971 "154.35.175.225:80 CF6D 0AAF B385 BE71 B8E1 11FC 5CFF 4B47 9237 33BC",
972 "longclaw orport=443 "
973 "v3ident=23D15D965BC35114467363C165C4F724B64B4F66 "
974 "ipv6=[2620:13:4000:8000:60:f3ff:fea1:7cff]:443 "
975 "199.254.238.52:80 74A9 1064 6BCE EFBC D2E8 74FC 1DC9 9743 0F96 8145",
976 NULL
979 /** List of fallback directory authorities. The list is generated by opt-in of
980 * relays that meet certain stability criteria.
982 static const char *default_fallbacks[] = {
983 #include "fallback_dirs.inc"
984 NULL
987 /** Add the default directory authorities directly into the trusted dir list,
988 * but only add them insofar as they share bits with <b>type</b>.
989 * Each authority's bits are restricted to the bits shared with <b>type</b>.
990 * If <b>type</b> is ALL_DIRINFO or NO_DIRINFO (zero), add all authorities. */
991 STATIC void
992 add_default_trusted_dir_authorities(dirinfo_type_t type)
994 int i;
995 for (i=0; default_authorities[i]; i++) {
996 if (parse_dir_authority_line(default_authorities[i], type, 0)<0) {
997 log_err(LD_BUG, "Couldn't parse internal DirAuthority line %s",
998 default_authorities[i]);
1003 /** Add the default fallback directory servers into the fallback directory
1004 * server list. */
1005 MOCK_IMPL(void,
1006 add_default_fallback_dir_servers,(void))
1008 int i;
1009 for (i=0; default_fallbacks[i]; i++) {
1010 if (parse_dir_fallback_line(default_fallbacks[i], 0)<0) {
1011 log_err(LD_BUG, "Couldn't parse internal FallbackDir line %s",
1012 default_fallbacks[i]);
1017 /** Look at all the config options for using alternate directory
1018 * authorities, and make sure none of them are broken. Also, warn the
1019 * user if we changed any dangerous ones.
1021 static int
1022 validate_dir_servers(or_options_t *options, or_options_t *old_options)
1024 config_line_t *cl;
1026 if (options->DirAuthorities &&
1027 (options->AlternateDirAuthority || options->AlternateBridgeAuthority)) {
1028 log_warn(LD_CONFIG,
1029 "You cannot set both DirAuthority and Alternate*Authority.");
1030 return -1;
1033 /* do we want to complain to the user about being partitionable? */
1034 if ((options->DirAuthorities &&
1035 (!old_options ||
1036 !config_lines_eq(options->DirAuthorities,
1037 old_options->DirAuthorities))) ||
1038 (options->AlternateDirAuthority &&
1039 (!old_options ||
1040 !config_lines_eq(options->AlternateDirAuthority,
1041 old_options->AlternateDirAuthority)))) {
1042 log_warn(LD_CONFIG,
1043 "You have used DirAuthority or AlternateDirAuthority to "
1044 "specify alternate directory authorities in "
1045 "your configuration. This is potentially dangerous: it can "
1046 "make you look different from all other Tor users, and hurt "
1047 "your anonymity. Even if you've specified the same "
1048 "authorities as Tor uses by default, the defaults could "
1049 "change in the future. Be sure you know what you're doing.");
1052 /* Now go through the four ways you can configure an alternate
1053 * set of directory authorities, and make sure none are broken. */
1054 for (cl = options->DirAuthorities; cl; cl = cl->next)
1055 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1056 return -1;
1057 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1058 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1059 return -1;
1060 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1061 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1062 return -1;
1063 for (cl = options->FallbackDir; cl; cl = cl->next)
1064 if (parse_dir_fallback_line(cl->value, 1)<0)
1065 return -1;
1066 return 0;
1069 /** Look at all the config options and assign new dir authorities
1070 * as appropriate.
1073 consider_adding_dir_servers(const or_options_t *options,
1074 const or_options_t *old_options)
1076 config_line_t *cl;
1077 int need_to_update =
1078 !smartlist_len(router_get_trusted_dir_servers()) ||
1079 !smartlist_len(router_get_fallback_dir_servers()) || !old_options ||
1080 !config_lines_eq(options->DirAuthorities, old_options->DirAuthorities) ||
1081 !config_lines_eq(options->FallbackDir, old_options->FallbackDir) ||
1082 (options->UseDefaultFallbackDirs != old_options->UseDefaultFallbackDirs) ||
1083 !config_lines_eq(options->AlternateBridgeAuthority,
1084 old_options->AlternateBridgeAuthority) ||
1085 !config_lines_eq(options->AlternateDirAuthority,
1086 old_options->AlternateDirAuthority);
1088 if (!need_to_update)
1089 return 0; /* all done */
1091 /* "You cannot set both DirAuthority and Alternate*Authority."
1092 * Checking that this restriction holds allows us to simplify
1093 * the unit tests. */
1094 tor_assert(!(options->DirAuthorities &&
1095 (options->AlternateDirAuthority
1096 || options->AlternateBridgeAuthority)));
1098 /* Start from a clean slate. */
1099 clear_dir_servers();
1101 if (!options->DirAuthorities) {
1102 /* then we may want some of the defaults */
1103 dirinfo_type_t type = NO_DIRINFO;
1104 if (!options->AlternateBridgeAuthority) {
1105 type |= BRIDGE_DIRINFO;
1107 if (!options->AlternateDirAuthority) {
1108 type |= V3_DIRINFO | EXTRAINFO_DIRINFO | MICRODESC_DIRINFO;
1109 /* Only add the default fallback directories when the DirAuthorities,
1110 * AlternateDirAuthority, and FallbackDir directory config options
1111 * are set to their defaults, and when UseDefaultFallbackDirs is 1. */
1112 if (!options->FallbackDir && options->UseDefaultFallbackDirs) {
1113 add_default_fallback_dir_servers();
1116 /* if type == NO_DIRINFO, we don't want to add any of the
1117 * default authorities, because we've replaced them all */
1118 if (type != NO_DIRINFO)
1119 add_default_trusted_dir_authorities(type);
1122 for (cl = options->DirAuthorities; cl; cl = cl->next)
1123 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1124 return -1;
1125 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1126 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1127 return -1;
1128 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1129 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1130 return -1;
1131 for (cl = options->FallbackDir; cl; cl = cl->next)
1132 if (parse_dir_fallback_line(cl->value, 0)<0)
1133 return -1;
1134 return 0;
1137 /* Helps determine flags to pass to switch_id. */
1138 static int have_low_ports = -1;
1140 /** Fetch the active option list, and take actions based on it. All of the
1141 * things we do should survive being done repeatedly. If present,
1142 * <b>old_options</b> contains the previous value of the options.
1144 * Return 0 if all goes well, return -1 if things went badly.
1146 static int
1147 options_act_reversible(const or_options_t *old_options, char **msg)
1149 smartlist_t *new_listeners = smartlist_new();
1150 smartlist_t *replaced_listeners = smartlist_new();
1151 static int libevent_initialized = 0;
1152 or_options_t *options = get_options_mutable();
1153 int running_tor = options->command == CMD_RUN_TOR;
1154 int set_conn_limit = 0;
1155 int r = -1;
1156 int logs_marked = 0, logs_initialized = 0;
1157 int old_min_log_level = get_min_log_level();
1159 /* Daemonize _first_, since we only want to open most of this stuff in
1160 * the subprocess. Libevent bases can't be reliably inherited across
1161 * processes. */
1162 if (running_tor && options->RunAsDaemon) {
1163 /* No need to roll back, since you can't change the value. */
1164 start_daemon();
1167 #ifdef HAVE_SYSTEMD
1168 /* Our PID may have changed, inform supervisor */
1169 sd_notifyf(0, "MAINPID=%ld\n", (long int)getpid());
1170 #endif
1172 #ifndef HAVE_SYS_UN_H
1173 if (options->ControlSocket || options->ControlSocketsGroupWritable) {
1174 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported "
1175 "on this OS/with this build.");
1176 goto rollback;
1178 #else
1179 if (options->ControlSocketsGroupWritable && !options->ControlSocket) {
1180 *msg = tor_strdup("Setting ControlSocketGroupWritable without setting"
1181 "a ControlSocket makes no sense.");
1182 goto rollback;
1184 #endif
1186 if (running_tor) {
1187 int n_ports=0;
1188 /* We need to set the connection limit before we can open the listeners. */
1189 if (! sandbox_is_active()) {
1190 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1191 &options->ConnLimit_) < 0) {
1192 *msg = tor_strdup("Problem with ConnLimit value. "
1193 "See logs for details.");
1194 goto rollback;
1196 set_conn_limit = 1;
1197 } else {
1198 tor_assert(old_options);
1199 options->ConnLimit_ = old_options->ConnLimit_;
1202 /* Set up libevent. (We need to do this before we can register the
1203 * listeners as listeners.) */
1204 if (running_tor && !libevent_initialized) {
1205 init_libevent(options);
1206 libevent_initialized = 1;
1208 /* This has to come up after libevent is initialized. */
1209 control_initialize_event_queue();
1212 * Initialize the scheduler - this has to come after
1213 * options_init_from_torrc() sets up libevent - why yes, that seems
1214 * completely sensible to hide the libevent setup in the option parsing
1215 * code! It also needs to happen before init_keys(), so it needs to
1216 * happen here too. How yucky. */
1217 scheduler_init();
1220 /* Adjust the port configuration so we can launch listeners. */
1221 if (parse_ports(options, 0, msg, &n_ports, NULL)) {
1222 if (!*msg)
1223 *msg = tor_strdup("Unexpected problem parsing port config");
1224 goto rollback;
1227 /* Set the hibernation state appropriately.*/
1228 consider_hibernation(time(NULL));
1230 /* Launch the listeners. (We do this before we setuid, so we can bind to
1231 * ports under 1024.) We don't want to rebind if we're hibernating. If
1232 * networking is disabled, this will close all but the control listeners,
1233 * but disable those. */
1234 if (!we_are_hibernating()) {
1235 if (retry_all_listeners(replaced_listeners, new_listeners,
1236 options->DisableNetwork) < 0) {
1237 *msg = tor_strdup("Failed to bind one of the listener ports.");
1238 goto rollback;
1241 if (options->DisableNetwork) {
1242 /* Aggressively close non-controller stuff, NOW */
1243 log_notice(LD_NET, "DisableNetwork is set. Tor will not make or accept "
1244 "non-control network connections. Shutting down all existing "
1245 "connections.");
1246 connection_mark_all_noncontrol_connections();
1247 /* We can't complete circuits until the network is re-enabled. */
1248 note_that_we_maybe_cant_complete_circuits();
1252 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1253 /* Open /dev/pf before dropping privileges. */
1254 if (options->TransPort_set &&
1255 options->TransProxyType_parsed == TPT_DEFAULT) {
1256 if (get_pf_socket() < 0) {
1257 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1258 goto rollback;
1261 #endif
1263 /* Attempt to lock all current and future memory with mlockall() only once */
1264 if (options->DisableAllSwap) {
1265 if (tor_mlockall() == -1) {
1266 *msg = tor_strdup("DisableAllSwap failure. Do you have proper "
1267 "permissions?");
1268 goto done;
1272 /* Setuid/setgid as appropriate */
1273 if (options->User) {
1274 tor_assert(have_low_ports != -1);
1275 unsigned switch_id_flags = 0;
1276 if (options->KeepBindCapabilities == 1) {
1277 switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
1278 switch_id_flags |= SWITCH_ID_WARN_IF_NO_CAPS;
1280 if (options->KeepBindCapabilities == -1 && have_low_ports) {
1281 switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
1283 if (switch_id(options->User, switch_id_flags) != 0) {
1284 /* No need to roll back, since you can't change the value. */
1285 *msg = tor_strdup("Problem with User value. See logs for details.");
1286 goto done;
1290 /* Ensure data directory is private; create if possible. */
1291 cpd_check_t cpd_opts = running_tor ? CPD_CREATE : CPD_CHECK;
1292 if (options->DataDirectoryGroupReadable)
1293 cpd_opts |= CPD_GROUP_READ;
1294 if (check_private_dir(options->DataDirectory,
1295 cpd_opts,
1296 options->User)<0) {
1297 tor_asprintf(msg,
1298 "Couldn't access/create private data directory \"%s\"",
1299 options->DataDirectory);
1301 goto done;
1302 /* No need to roll back, since you can't change the value. */
1305 #ifndef _WIN32
1306 if (options->DataDirectoryGroupReadable) {
1307 /* Only new dirs created get new opts, also enforce group read. */
1308 if (chmod(options->DataDirectory, 0750)) {
1309 log_warn(LD_FS,"Unable to make %s group-readable: %s",
1310 options->DataDirectory, strerror(errno));
1313 #endif
1315 /* Bail out at this point if we're not going to be a client or server:
1316 * we don't run Tor itself. */
1317 if (!running_tor)
1318 goto commit;
1320 mark_logs_temp(); /* Close current logs once new logs are open. */
1321 logs_marked = 1;
1322 /* Configure the tor_log(s) */
1323 if (options_init_logs(old_options, options, 0)<0) {
1324 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1325 goto rollback;
1327 logs_initialized = 1;
1329 commit:
1330 r = 0;
1331 if (logs_marked) {
1332 log_severity_list_t *severity =
1333 tor_malloc_zero(sizeof(log_severity_list_t));
1334 close_temp_logs();
1335 add_callback_log(severity, control_event_logmsg);
1336 control_adjust_event_log_severity();
1337 tor_free(severity);
1338 tor_log_update_sigsafe_err_fds();
1340 if (logs_initialized) {
1341 flush_log_messages_from_startup();
1345 const char *badness = NULL;
1346 int bad_safelog = 0, bad_severity = 0, new_badness = 0;
1347 if (options->SafeLogging_ != SAFELOG_SCRUB_ALL) {
1348 bad_safelog = 1;
1349 if (!old_options || old_options->SafeLogging_ != options->SafeLogging_)
1350 new_badness = 1;
1352 if (get_min_log_level() >= LOG_INFO) {
1353 bad_severity = 1;
1354 if (get_min_log_level() != old_min_log_level)
1355 new_badness = 1;
1357 if (bad_safelog && bad_severity)
1358 badness = "you disabled SafeLogging, and "
1359 "you're logging more than \"notice\"";
1360 else if (bad_safelog)
1361 badness = "you disabled SafeLogging";
1362 else
1363 badness = "you're logging more than \"notice\"";
1364 if (new_badness)
1365 log_warn(LD_GENERAL, "Your log may contain sensitive information - %s. "
1366 "Don't log unless it serves an important reason. "
1367 "Overwrite the log afterwards.", badness);
1370 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1372 int marked = conn->marked_for_close;
1373 log_notice(LD_NET, "Closing old %s on %s:%d",
1374 conn_type_to_string(conn->type), conn->address, conn->port);
1375 connection_close_immediate(conn);
1376 if (!marked) {
1377 connection_mark_for_close(conn);
1381 if (set_conn_limit) {
1383 * If we adjusted the conn limit, recompute the OOS threshold too
1385 * How many possible sockets to keep in reserve? If we have lots of
1386 * possible sockets, keep this below a limit and set ConnLimit_high_thresh
1387 * very close to ConnLimit_, but if ConnLimit_ is low, shrink it in
1388 * proportion.
1390 * Somewhat arbitrarily, set socks_in_reserve to 5% of ConnLimit_, but
1391 * cap it at 64.
1393 int socks_in_reserve = options->ConnLimit_ / 20;
1394 if (socks_in_reserve > 64) socks_in_reserve = 64;
1396 options->ConnLimit_high_thresh = options->ConnLimit_ - socks_in_reserve;
1397 options->ConnLimit_low_thresh = (options->ConnLimit_ / 4) * 3;
1398 log_info(LD_GENERAL,
1399 "Recomputed OOS thresholds: ConnLimit %d, ConnLimit_ %d, "
1400 "ConnLimit_high_thresh %d, ConnLimit_low_thresh %d",
1401 options->ConnLimit, options->ConnLimit_,
1402 options->ConnLimit_high_thresh,
1403 options->ConnLimit_low_thresh);
1405 /* Give the OOS handler a chance with the new thresholds */
1406 connection_check_oos(get_n_open_sockets(), 0);
1409 goto done;
1411 rollback:
1412 r = -1;
1413 tor_assert(*msg);
1415 if (logs_marked) {
1416 rollback_log_changes();
1417 control_adjust_event_log_severity();
1420 if (set_conn_limit && old_options)
1421 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1422 &options->ConnLimit_);
1424 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1426 log_notice(LD_NET, "Closing partially-constructed %s on %s:%d",
1427 conn_type_to_string(conn->type), conn->address, conn->port);
1428 connection_close_immediate(conn);
1429 connection_mark_for_close(conn);
1432 done:
1433 smartlist_free(new_listeners);
1434 smartlist_free(replaced_listeners);
1435 return r;
1438 /** If we need to have a GEOIP ip-to-country map to run with our configured
1439 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1441 options_need_geoip_info(const or_options_t *options, const char **reason_out)
1443 int bridge_usage =
1444 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1445 int routerset_usage =
1446 routerset_needs_geoip(options->EntryNodes) ||
1447 routerset_needs_geoip(options->ExitNodes) ||
1448 routerset_needs_geoip(options->ExcludeExitNodes) ||
1449 routerset_needs_geoip(options->ExcludeNodes) ||
1450 routerset_needs_geoip(options->Tor2webRendezvousPoints);
1452 if (routerset_usage && reason_out) {
1453 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1454 "countries, and we need GEOIP information to figure out which ones they "
1455 "are.";
1456 } else if (bridge_usage && reason_out) {
1457 *reason_out = "We've been configured to see which countries can access "
1458 "us as a bridge, and we need GEOIP information to tell which countries "
1459 "clients are in.";
1461 return bridge_usage || routerset_usage;
1464 /** Return the bandwidthrate that we are going to report to the authorities
1465 * based on the config options. */
1466 uint32_t
1467 get_effective_bwrate(const or_options_t *options)
1469 uint64_t bw = options->BandwidthRate;
1470 if (bw > options->MaxAdvertisedBandwidth)
1471 bw = options->MaxAdvertisedBandwidth;
1472 if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1473 bw = options->RelayBandwidthRate;
1474 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1475 return (uint32_t)bw;
1478 /** Return the bandwidthburst that we are going to report to the authorities
1479 * based on the config options. */
1480 uint32_t
1481 get_effective_bwburst(const or_options_t *options)
1483 uint64_t bw = options->BandwidthBurst;
1484 if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1485 bw = options->RelayBandwidthBurst;
1486 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1487 return (uint32_t)bw;
1490 /** Return True if any changes from <b>old_options</b> to
1491 * <b>new_options</b> needs us to refresh our TLS context. */
1492 static int
1493 options_transition_requires_fresh_tls_context(const or_options_t *old_options,
1494 const or_options_t *new_options)
1496 tor_assert(new_options);
1498 if (!old_options)
1499 return 0;
1501 if (!opt_streq(old_options->TLSECGroup, new_options->TLSECGroup))
1502 return 1;
1504 return 0;
1507 /** Fetch the active option list, and take actions based on it. All of the
1508 * things we do should survive being done repeatedly. If present,
1509 * <b>old_options</b> contains the previous value of the options.
1511 * Return 0 if all goes well, return -1 if it's time to die.
1513 * Note: We haven't moved all the "act on new configuration" logic
1514 * here yet. Some is still in do_hup() and other places.
1516 STATIC int
1517 options_act(const or_options_t *old_options)
1519 config_line_t *cl;
1520 or_options_t *options = get_options_mutable();
1521 int running_tor = options->command == CMD_RUN_TOR;
1522 char *msg=NULL;
1523 const int transition_affects_workers =
1524 old_options && options_transition_affects_workers(old_options, options);
1525 int old_ewma_enabled;
1527 /* disable ptrace and later, other basic debugging techniques */
1529 /* Remember if we already disabled debugger attachment */
1530 static int disabled_debugger_attach = 0;
1531 /* Remember if we already warned about being configured not to disable
1532 * debugger attachment */
1533 static int warned_debugger_attach = 0;
1534 /* Don't disable debugger attachment when we're running the unit tests. */
1535 if (options->DisableDebuggerAttachment && !disabled_debugger_attach &&
1536 running_tor) {
1537 int ok = tor_disable_debugger_attach();
1538 /* LCOV_EXCL_START the warned_debugger_attach is 0 can't reach inside. */
1539 if (warned_debugger_attach && ok == 1) {
1540 log_notice(LD_CONFIG, "Disabled attaching debuggers for unprivileged "
1541 "users.");
1543 /* LCOV_EXCL_STOP */
1544 disabled_debugger_attach = (ok == 1);
1545 } else if (!options->DisableDebuggerAttachment &&
1546 !warned_debugger_attach) {
1547 log_notice(LD_CONFIG, "Not disabling debugger attaching for "
1548 "unprivileged users.");
1549 warned_debugger_attach = 1;
1553 /* Write control ports to disk as appropriate */
1554 control_ports_write_to_file();
1556 if (running_tor && !have_lockfile()) {
1557 if (try_locking(options, 1) < 0)
1558 return -1;
1561 if (consider_adding_dir_servers(options, old_options) < 0)
1562 return -1;
1564 if (rend_non_anonymous_mode_enabled(options)) {
1565 log_warn(LD_GENERAL, "This copy of Tor was compiled or configured to run "
1566 "in a non-anonymous mode. It will provide NO ANONYMITY.");
1569 #ifdef ENABLE_TOR2WEB_MODE
1570 /* LCOV_EXCL_START */
1571 if (!options->Tor2webMode) {
1572 log_err(LD_CONFIG, "This copy of Tor was compiled to run in "
1573 "'tor2web mode'. It can only be run with the Tor2webMode torrc "
1574 "option enabled.");
1575 return -1;
1577 /* LCOV_EXCL_STOP */
1578 #else
1579 if (options->Tor2webMode) {
1580 log_err(LD_CONFIG, "This copy of Tor was not compiled to run in "
1581 "'tor2web mode'. It cannot be run with the Tor2webMode torrc "
1582 "option enabled. To enable Tor2webMode recompile with the "
1583 "--enable-tor2web-mode option.");
1584 return -1;
1586 #endif
1588 /* If we are a bridge with a pluggable transport proxy but no
1589 Extended ORPort, inform the user that they are missing out. */
1590 if (server_mode(options) && options->ServerTransportPlugin &&
1591 !options->ExtORPort_lines) {
1592 log_notice(LD_CONFIG, "We use pluggable transports but the Extended "
1593 "ORPort is disabled. Tor and your pluggable transports proxy "
1594 "communicate with each other via the Extended ORPort so it "
1595 "is suggested you enable it: it will also allow your Bridge "
1596 "to collect statistics about its clients that use pluggable "
1597 "transports. Please enable it using the ExtORPort torrc option "
1598 "(e.g. set 'ExtORPort auto').");
1601 if (options->Bridges) {
1602 mark_bridge_list();
1603 for (cl = options->Bridges; cl; cl = cl->next) {
1604 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
1605 if (!bridge_line) {
1606 log_warn(LD_BUG,
1607 "Previously validated Bridge line could not be added!");
1608 return -1;
1610 bridge_add_from_config(bridge_line);
1612 sweep_bridge_list();
1615 if (running_tor && rend_config_services(options, 0)<0) {
1616 log_warn(LD_BUG,
1617 "Previously validated hidden services line could not be added!");
1618 return -1;
1621 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1622 log_warn(LD_BUG, "Previously validated client authorization for "
1623 "hidden services could not be added!");
1624 return -1;
1627 /* Load state */
1628 if (! or_state_loaded() && running_tor) {
1629 if (or_state_load())
1630 return -1;
1631 rep_hist_load_mtbf_data(time(NULL));
1634 /* If we have an ExtORPort, initialize its auth cookie. */
1635 if (running_tor &&
1636 init_ext_or_cookie_authentication(!!options->ExtORPort_lines) < 0) {
1637 log_warn(LD_CONFIG,"Error creating Extended ORPort cookie file.");
1638 return -1;
1641 mark_transport_list();
1642 pt_prepare_proxy_list_for_config_read();
1643 if (!options->DisableNetwork) {
1644 if (options->ClientTransportPlugin) {
1645 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
1646 if (parse_transport_line(options, cl->value, 0, 0) < 0) {
1647 log_warn(LD_BUG,
1648 "Previously validated ClientTransportPlugin line "
1649 "could not be added!");
1650 return -1;
1655 if (options->ServerTransportPlugin && server_mode(options)) {
1656 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
1657 if (parse_transport_line(options, cl->value, 0, 1) < 0) {
1658 log_warn(LD_BUG,
1659 "Previously validated ServerTransportPlugin line "
1660 "could not be added!");
1661 return -1;
1666 sweep_transport_list();
1667 sweep_proxy_list();
1669 /* Start the PT proxy configuration. By doing this configuration
1670 here, we also figure out which proxies need to be restarted and
1671 which not. */
1672 if (pt_proxies_configuration_pending() && !net_is_disabled())
1673 pt_configure_remaining_proxies();
1675 /* Bail out at this point if we're not going to be a client or server:
1676 * we want to not fork, and to log stuff to stderr. */
1677 if (!running_tor)
1678 return 0;
1680 /* Finish backgrounding the process */
1681 if (options->RunAsDaemon) {
1682 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1683 finish_daemon(options->DataDirectory);
1686 /* We want to reinit keys as needed before we do much of anything else:
1687 keys are important, and other things can depend on them. */
1688 if (transition_affects_workers ||
1689 (options->V3AuthoritativeDir && (!old_options ||
1690 !old_options->V3AuthoritativeDir))) {
1691 if (init_keys() < 0) {
1692 log_warn(LD_BUG,"Error initializing keys; exiting");
1693 return -1;
1695 } else if (old_options &&
1696 options_transition_requires_fresh_tls_context(old_options,
1697 options)) {
1698 if (router_initialize_tls_context() < 0) {
1699 log_warn(LD_BUG,"Error initializing TLS context.");
1700 return -1;
1704 /* Write our PID to the PID file. If we do not have write permissions we
1705 * will log a warning */
1706 if (options->PidFile && !sandbox_is_active()) {
1707 write_pidfile(options->PidFile);
1710 /* Register addressmap directives */
1711 config_register_addressmaps(options);
1712 parse_virtual_addr_network(options->VirtualAddrNetworkIPv4, AF_INET,0,NULL);
1713 parse_virtual_addr_network(options->VirtualAddrNetworkIPv6, AF_INET6,0,NULL);
1715 /* Update address policies. */
1716 if (policies_parse_from_options(options) < 0) {
1717 /* This should be impossible, but let's be sure. */
1718 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1719 return -1;
1722 if (init_control_cookie_authentication(options->CookieAuthentication) < 0) {
1723 log_warn(LD_CONFIG,"Error creating control cookie authentication file.");
1724 return -1;
1727 monitor_owning_controller_process(options->OwningControllerProcess);
1729 /* We must create new keys after we poison the directories, because our
1730 * poisoning code checks for existing keys, and refuses to modify their
1731 * directories. */
1733 /* If we use the insecure OnionServiceSingleHopMode, make sure we poison any
1734 new hidden service directories, so that we never accidentally launch the
1735 non-anonymous hidden services thinking they are anonymous. */
1736 if (running_tor && rend_service_allow_non_anonymous_connection(options)) {
1737 if (options->RendConfigLines && !num_rend_services()) {
1738 log_warn(LD_BUG,"Error: hidden services configured, but not parsed.");
1739 return -1;
1741 if (rend_service_poison_new_single_onion_dirs(NULL) < 0) {
1742 log_warn(LD_GENERAL,"Failed to mark new hidden services as Single "
1743 "Onion.");
1744 return -1;
1748 /* reload keys as needed for rendezvous services. */
1749 if (rend_service_load_all_keys(NULL)<0) {
1750 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1751 return -1;
1754 /* Set up scheduler thresholds */
1755 scheduler_set_watermarks((uint32_t)options->SchedulerLowWaterMark__,
1756 (uint32_t)options->SchedulerHighWaterMark__,
1757 (options->SchedulerMaxFlushCells__ > 0) ?
1758 options->SchedulerMaxFlushCells__ : 1000);
1760 /* Set up accounting */
1761 if (accounting_parse_options(options, 0)<0) {
1762 log_warn(LD_CONFIG,"Error in accounting options");
1763 return -1;
1765 if (accounting_is_enabled(options))
1766 configure_accounting(time(NULL));
1768 old_ewma_enabled = cell_ewma_enabled();
1769 /* Change the cell EWMA settings */
1770 cell_ewma_set_scale_factor(options, networkstatus_get_latest_consensus());
1771 /* If we just enabled ewma, set the cmux policy on all active channels */
1772 if (cell_ewma_enabled() && !old_ewma_enabled) {
1773 channel_set_cmux_policy_everywhere(&ewma_policy);
1774 } else if (!cell_ewma_enabled() && old_ewma_enabled) {
1775 /* Turn it off everywhere */
1776 channel_set_cmux_policy_everywhere(NULL);
1779 /* Update the BridgePassword's hashed version as needed. We store this as a
1780 * digest so that we can do side-channel-proof comparisons on it.
1782 if (options->BridgePassword) {
1783 char *http_authenticator;
1784 http_authenticator = alloc_http_authenticator(options->BridgePassword);
1785 if (!http_authenticator) {
1786 log_warn(LD_BUG, "Unable to allocate HTTP authenticator. Not setting "
1787 "BridgePassword.");
1788 return -1;
1790 options->BridgePassword_AuthDigest_ = tor_malloc(DIGEST256_LEN);
1791 crypto_digest256(options->BridgePassword_AuthDigest_,
1792 http_authenticator, strlen(http_authenticator),
1793 DIGEST_SHA256);
1794 tor_free(http_authenticator);
1797 if (parse_outbound_addresses(options, 0, &msg) < 0) {
1798 log_warn(LD_BUG, "Failed parsing outbound bind addresses: %s", msg);
1799 tor_free(msg);
1800 return -1;
1803 config_maybe_load_geoip_files_(options, old_options);
1805 if (geoip_is_loaded(AF_INET) && options->GeoIPExcludeUnknown) {
1806 /* ExcludeUnknown is true or "auto" */
1807 const int is_auto = options->GeoIPExcludeUnknown == -1;
1808 int changed;
1810 changed = routerset_add_unknown_ccs(&options->ExcludeNodes, is_auto);
1811 changed += routerset_add_unknown_ccs(&options->ExcludeExitNodes, is_auto);
1813 if (changed)
1814 routerset_add_unknown_ccs(&options->ExcludeExitNodesUnion_, is_auto);
1817 /* Check for transitions that need action. */
1818 if (old_options) {
1819 int revise_trackexithosts = 0;
1820 int revise_automap_entries = 0;
1821 if ((options->UseEntryGuards && !old_options->UseEntryGuards) ||
1822 options->UseBridges != old_options->UseBridges ||
1823 (options->UseBridges &&
1824 !config_lines_eq(options->Bridges, old_options->Bridges)) ||
1825 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes) ||
1826 !routerset_equal(old_options->ExcludeExitNodes,
1827 options->ExcludeExitNodes) ||
1828 !routerset_equal(old_options->EntryNodes, options->EntryNodes) ||
1829 !routerset_equal(old_options->ExitNodes, options->ExitNodes) ||
1830 !routerset_equal(old_options->Tor2webRendezvousPoints,
1831 options->Tor2webRendezvousPoints) ||
1832 options->StrictNodes != old_options->StrictNodes) {
1833 log_info(LD_CIRC,
1834 "Changed to using entry guards or bridges, or changed "
1835 "preferred or excluded node lists. "
1836 "Abandoning previous circuits.");
1837 circuit_mark_all_unused_circs();
1838 circuit_mark_all_dirty_circs_as_unusable();
1839 revise_trackexithosts = 1;
1842 if (!smartlist_strings_eq(old_options->TrackHostExits,
1843 options->TrackHostExits))
1844 revise_trackexithosts = 1;
1846 if (revise_trackexithosts)
1847 addressmap_clear_excluded_trackexithosts(options);
1849 if (!options->AutomapHostsOnResolve &&
1850 old_options->AutomapHostsOnResolve) {
1851 revise_automap_entries = 1;
1852 } else {
1853 if (!smartlist_strings_eq(old_options->AutomapHostsSuffixes,
1854 options->AutomapHostsSuffixes))
1855 revise_automap_entries = 1;
1856 else if (!opt_streq(old_options->VirtualAddrNetworkIPv4,
1857 options->VirtualAddrNetworkIPv4) ||
1858 !opt_streq(old_options->VirtualAddrNetworkIPv6,
1859 options->VirtualAddrNetworkIPv6))
1860 revise_automap_entries = 1;
1863 if (revise_automap_entries)
1864 addressmap_clear_invalid_automaps(options);
1866 /* How long should we delay counting bridge stats after becoming a bridge?
1867 * We use this so we don't count people who used our bridge thinking it is
1868 * a relay. If you change this, don't forget to change the log message
1869 * below. It's 4 hours (the time it takes to stop being used by clients)
1870 * plus some extra time for clock skew. */
1871 #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
1873 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
1874 int was_relay = 0;
1875 if (options->BridgeRelay) {
1876 time_t int_start = time(NULL);
1877 if (config_lines_eq(old_options->ORPort_lines,options->ORPort_lines)) {
1878 int_start += RELAY_BRIDGE_STATS_DELAY;
1879 was_relay = 1;
1881 geoip_bridge_stats_init(int_start);
1882 log_info(LD_CONFIG, "We are acting as a bridge now. Starting new "
1883 "GeoIP stats interval%s.", was_relay ? " in 6 "
1884 "hours from now" : "");
1885 } else {
1886 geoip_bridge_stats_term();
1887 log_info(LD_GENERAL, "We are no longer acting as a bridge. "
1888 "Forgetting GeoIP stats.");
1892 if (transition_affects_workers) {
1893 log_info(LD_GENERAL,
1894 "Worker-related options changed. Rotating workers.");
1896 if (server_mode(options) && !server_mode(old_options)) {
1897 cpu_init();
1898 ip_address_changed(0);
1899 if (have_completed_a_circuit() || !any_predicted_circuits(time(NULL)))
1900 inform_testing_reachability();
1902 cpuworkers_rotate_keyinfo();
1903 if (dns_reset())
1904 return -1;
1905 } else {
1906 if (dns_reset())
1907 return -1;
1910 if (options->PerConnBWRate != old_options->PerConnBWRate ||
1911 options->PerConnBWBurst != old_options->PerConnBWBurst)
1912 connection_or_update_token_buckets(get_connection_array(), options);
1915 /* Only collect directory-request statistics on relays and bridges. */
1916 options->DirReqStatistics = options->DirReqStatistics_option &&
1917 server_mode(options);
1919 if (options->CellStatistics || options->DirReqStatistics ||
1920 options->EntryStatistics || options->ExitPortStatistics ||
1921 options->ConnDirectionStatistics ||
1922 options->HiddenServiceStatistics ||
1923 options->BridgeAuthoritativeDir) {
1924 time_t now = time(NULL);
1925 int print_notice = 0;
1927 /* Only collect other relay-only statistics on relays. */
1928 if (!public_server_mode(options)) {
1929 options->CellStatistics = 0;
1930 options->EntryStatistics = 0;
1931 options->ConnDirectionStatistics = 0;
1932 options->HiddenServiceStatistics = 0;
1933 options->ExitPortStatistics = 0;
1936 if ((!old_options || !old_options->CellStatistics) &&
1937 options->CellStatistics) {
1938 rep_hist_buffer_stats_init(now);
1939 print_notice = 1;
1941 if ((!old_options || !old_options->DirReqStatistics) &&
1942 options->DirReqStatistics) {
1943 if (geoip_is_loaded(AF_INET)) {
1944 geoip_dirreq_stats_init(now);
1945 print_notice = 1;
1946 } else {
1947 /* disable statistics collection since we have no geoip file */
1948 options->DirReqStatistics = 0;
1949 if (options->ORPort_set)
1950 log_notice(LD_CONFIG, "Configured to measure directory request "
1951 "statistics, but no GeoIP database found. "
1952 "Please specify a GeoIP database using the "
1953 "GeoIPFile option.");
1956 if ((!old_options || !old_options->EntryStatistics) &&
1957 options->EntryStatistics && !should_record_bridge_info(options)) {
1958 if (geoip_is_loaded(AF_INET) || geoip_is_loaded(AF_INET6)) {
1959 geoip_entry_stats_init(now);
1960 print_notice = 1;
1961 } else {
1962 options->EntryStatistics = 0;
1963 log_notice(LD_CONFIG, "Configured to measure entry node "
1964 "statistics, but no GeoIP database found. "
1965 "Please specify a GeoIP database using the "
1966 "GeoIPFile option.");
1969 if ((!old_options || !old_options->ExitPortStatistics) &&
1970 options->ExitPortStatistics) {
1971 rep_hist_exit_stats_init(now);
1972 print_notice = 1;
1974 if ((!old_options || !old_options->ConnDirectionStatistics) &&
1975 options->ConnDirectionStatistics) {
1976 rep_hist_conn_stats_init(now);
1978 if ((!old_options || !old_options->HiddenServiceStatistics) &&
1979 options->HiddenServiceStatistics) {
1980 log_info(LD_CONFIG, "Configured to measure hidden service statistics.");
1981 rep_hist_hs_stats_init(now);
1983 if ((!old_options || !old_options->BridgeAuthoritativeDir) &&
1984 options->BridgeAuthoritativeDir) {
1985 rep_hist_desc_stats_init(now);
1986 print_notice = 1;
1988 if (print_notice)
1989 log_notice(LD_CONFIG, "Configured to measure statistics. Look for "
1990 "the *-stats files that will first be written to the "
1991 "data directory in 24 hours from now.");
1994 /* If we used to have statistics enabled but we just disabled them,
1995 stop gathering them. */
1996 if (old_options && old_options->CellStatistics &&
1997 !options->CellStatistics)
1998 rep_hist_buffer_stats_term();
1999 if (old_options && old_options->DirReqStatistics &&
2000 !options->DirReqStatistics)
2001 geoip_dirreq_stats_term();
2002 if (old_options && old_options->EntryStatistics &&
2003 !options->EntryStatistics)
2004 geoip_entry_stats_term();
2005 if (old_options && old_options->HiddenServiceStatistics &&
2006 !options->HiddenServiceStatistics)
2007 rep_hist_hs_stats_term();
2008 if (old_options && old_options->ExitPortStatistics &&
2009 !options->ExitPortStatistics)
2010 rep_hist_exit_stats_term();
2011 if (old_options && old_options->ConnDirectionStatistics &&
2012 !options->ConnDirectionStatistics)
2013 rep_hist_conn_stats_term();
2014 if (old_options && old_options->BridgeAuthoritativeDir &&
2015 !options->BridgeAuthoritativeDir)
2016 rep_hist_desc_stats_term();
2018 /* Check if we need to parse and add the EntryNodes config option. */
2019 if (options->EntryNodes &&
2020 (!old_options ||
2021 !routerset_equal(old_options->EntryNodes,options->EntryNodes) ||
2022 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes)))
2023 entry_nodes_should_be_added();
2025 /* Since our options changed, we might need to regenerate and upload our
2026 * server descriptor.
2028 if (!old_options ||
2029 options_transition_affects_descriptor(old_options, options))
2030 mark_my_descriptor_dirty("config change");
2032 /* We may need to reschedule some directory stuff if our status changed. */
2033 if (old_options) {
2034 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
2035 dirvote_recalculate_timing(options, time(NULL));
2036 if (!bool_eq(directory_fetches_dir_info_early(options),
2037 directory_fetches_dir_info_early(old_options)) ||
2038 !bool_eq(directory_fetches_dir_info_later(options),
2039 directory_fetches_dir_info_later(old_options))) {
2040 /* Make sure update_router_have_minimum_dir_info() gets called. */
2041 router_dir_info_changed();
2042 /* We might need to download a new consensus status later or sooner than
2043 * we had expected. */
2044 update_consensus_networkstatus_fetch_time(time(NULL));
2048 /* Load the webpage we're going to serve every time someone asks for '/' on
2049 our DirPort. */
2050 tor_free(global_dirfrontpagecontents);
2051 if (options->DirPortFrontPage) {
2052 global_dirfrontpagecontents =
2053 read_file_to_str(options->DirPortFrontPage, 0, NULL);
2054 if (!global_dirfrontpagecontents) {
2055 log_warn(LD_CONFIG,
2056 "DirPortFrontPage file '%s' not found. Continuing anyway.",
2057 options->DirPortFrontPage);
2061 return 0;
2064 typedef enum {
2065 TAKES_NO_ARGUMENT = 0,
2066 ARGUMENT_NECESSARY = 1,
2067 ARGUMENT_OPTIONAL = 2
2068 } takes_argument_t;
2070 static const struct {
2071 const char *name;
2072 takes_argument_t takes_argument;
2073 } CMDLINE_ONLY_OPTIONS[] = {
2074 { "-f", ARGUMENT_NECESSARY },
2075 { "--allow-missing-torrc", TAKES_NO_ARGUMENT },
2076 { "--defaults-torrc", ARGUMENT_NECESSARY },
2077 { "--hash-password", ARGUMENT_NECESSARY },
2078 { "--dump-config", ARGUMENT_OPTIONAL },
2079 { "--list-fingerprint", TAKES_NO_ARGUMENT },
2080 { "--keygen", TAKES_NO_ARGUMENT },
2081 { "--newpass", TAKES_NO_ARGUMENT },
2082 { "--no-passphrase", TAKES_NO_ARGUMENT },
2083 { "--passphrase-fd", ARGUMENT_NECESSARY },
2084 { "--verify-config", TAKES_NO_ARGUMENT },
2085 { "--ignore-missing-torrc", TAKES_NO_ARGUMENT },
2086 { "--quiet", TAKES_NO_ARGUMENT },
2087 { "--hush", TAKES_NO_ARGUMENT },
2088 { "--version", TAKES_NO_ARGUMENT },
2089 { "--library-versions", TAKES_NO_ARGUMENT },
2090 { "-h", TAKES_NO_ARGUMENT },
2091 { "--help", TAKES_NO_ARGUMENT },
2092 { "--list-torrc-options", TAKES_NO_ARGUMENT },
2093 { "--list-deprecated-options",TAKES_NO_ARGUMENT },
2094 { "--nt-service", TAKES_NO_ARGUMENT },
2095 { "-nt-service", TAKES_NO_ARGUMENT },
2096 { NULL, 0 },
2099 /** Helper: Read a list of configuration options from the command line. If
2100 * successful, or if ignore_errors is set, put them in *<b>result</b>, put the
2101 * commandline-only options in *<b>cmdline_result</b>, and return 0;
2102 * otherwise, return -1 and leave *<b>result</b> and <b>cmdline_result</b>
2103 * alone. */
2105 config_parse_commandline(int argc, char **argv, int ignore_errors,
2106 config_line_t **result,
2107 config_line_t **cmdline_result)
2109 config_line_t *param = NULL;
2111 config_line_t *front = NULL;
2112 config_line_t **new = &front;
2114 config_line_t *front_cmdline = NULL;
2115 config_line_t **new_cmdline = &front_cmdline;
2117 char *s, *arg;
2118 int i = 1;
2120 while (i < argc) {
2121 unsigned command = CONFIG_LINE_NORMAL;
2122 takes_argument_t want_arg = ARGUMENT_NECESSARY;
2123 int is_cmdline = 0;
2124 int j;
2126 for (j = 0; CMDLINE_ONLY_OPTIONS[j].name != NULL; ++j) {
2127 if (!strcmp(argv[i], CMDLINE_ONLY_OPTIONS[j].name)) {
2128 is_cmdline = 1;
2129 want_arg = CMDLINE_ONLY_OPTIONS[j].takes_argument;
2130 break;
2134 s = argv[i];
2136 /* Each keyword may be prefixed with one or two dashes. */
2137 if (*s == '-')
2138 s++;
2139 if (*s == '-')
2140 s++;
2141 /* Figure out the command, if any. */
2142 if (*s == '+') {
2143 s++;
2144 command = CONFIG_LINE_APPEND;
2145 } else if (*s == '/') {
2146 s++;
2147 command = CONFIG_LINE_CLEAR;
2148 /* A 'clear' command has no argument. */
2149 want_arg = 0;
2152 const int is_last = (i == argc-1);
2154 if (want_arg == ARGUMENT_NECESSARY && is_last) {
2155 if (ignore_errors) {
2156 arg = tor_strdup("");
2157 } else {
2158 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
2159 argv[i]);
2160 config_free_lines(front);
2161 config_free_lines(front_cmdline);
2162 return -1;
2164 } else if (want_arg == ARGUMENT_OPTIONAL && is_last) {
2165 arg = tor_strdup("");
2166 } else {
2167 arg = (want_arg != TAKES_NO_ARGUMENT) ? tor_strdup(argv[i+1]) :
2168 tor_strdup("");
2171 param = tor_malloc_zero(sizeof(config_line_t));
2172 param->key = is_cmdline ? tor_strdup(argv[i]) :
2173 tor_strdup(config_expand_abbrev(&options_format, s, 1, 1));
2174 param->value = arg;
2175 param->command = command;
2176 param->next = NULL;
2177 log_debug(LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
2178 param->key, param->value);
2180 if (is_cmdline) {
2181 *new_cmdline = param;
2182 new_cmdline = &((*new_cmdline)->next);
2183 } else {
2184 *new = param;
2185 new = &((*new)->next);
2188 i += want_arg ? 2 : 1;
2190 *cmdline_result = front_cmdline;
2191 *result = front;
2192 return 0;
2195 /** Return true iff key is a valid configuration option. */
2197 option_is_recognized(const char *key)
2199 const config_var_t *var = config_find_option(&options_format, key);
2200 return (var != NULL);
2203 /** Return the canonical name of a configuration option, or NULL
2204 * if no such option exists. */
2205 const char *
2206 option_get_canonical_name(const char *key)
2208 const config_var_t *var = config_find_option(&options_format, key);
2209 return var ? var->name : NULL;
2212 /** Return a canonical list of the options assigned for key.
2214 config_line_t *
2215 option_get_assignment(const or_options_t *options, const char *key)
2217 return config_get_assigned_option(&options_format, options, key, 1);
2220 /** Try assigning <b>list</b> to the global options. You do this by duping
2221 * options, assigning list to the new one, then validating it. If it's
2222 * ok, then throw out the old one and stick with the new one. Else,
2223 * revert to old and return failure. Return SETOPT_OK on success, or
2224 * a setopt_err_t on failure.
2226 * If not success, point *<b>msg</b> to a newly allocated string describing
2227 * what went wrong.
2229 setopt_err_t
2230 options_trial_assign(config_line_t *list, unsigned flags, char **msg)
2232 int r;
2233 or_options_t *trial_options = config_dup(&options_format, get_options());
2235 if ((r=config_assign(&options_format, trial_options,
2236 list, flags, msg)) < 0) {
2237 or_options_free(trial_options);
2238 return r;
2241 if (options_validate(get_options_mutable(), trial_options,
2242 global_default_options, 1, msg) < 0) {
2243 or_options_free(trial_options);
2244 return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2247 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2248 or_options_free(trial_options);
2249 return SETOPT_ERR_TRANSITION;
2252 if (set_options(trial_options, msg)<0) {
2253 or_options_free(trial_options);
2254 return SETOPT_ERR_SETTING;
2257 /* we liked it. put it in place. */
2258 return SETOPT_OK;
2261 /** Print a usage message for tor. */
2262 static void
2263 print_usage(void)
2265 printf(
2266 "Copyright (c) 2001-2004, Roger Dingledine\n"
2267 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2268 "Copyright (c) 2007-2016, The Tor Project, Inc.\n\n"
2269 "tor -f <torrc> [args]\n"
2270 "See man page for options, or https://www.torproject.org/ for "
2271 "documentation.\n");
2274 /** Print all non-obsolete torrc options. */
2275 static void
2276 list_torrc_options(void)
2278 int i;
2279 for (i = 0; option_vars_[i].name; ++i) {
2280 const config_var_t *var = &option_vars_[i];
2281 if (var->type == CONFIG_TYPE_OBSOLETE ||
2282 var->type == CONFIG_TYPE_LINELIST_V)
2283 continue;
2284 printf("%s\n", var->name);
2288 /** Print all deprecated but non-obsolete torrc options. */
2289 static void
2290 list_deprecated_options(void)
2292 const config_deprecation_t *d;
2293 for (d = option_deprecation_notes_; d->name; ++d) {
2294 printf("%s\n", d->name);
2298 /** Last value actually set by resolve_my_address. */
2299 static uint32_t last_resolved_addr = 0;
2301 /** Accessor for last_resolved_addr from outside this file. */
2302 uint32_t
2303 get_last_resolved_addr(void)
2305 return last_resolved_addr;
2308 /** Reset last_resolved_addr from outside this file. */
2309 void
2310 reset_last_resolved_addr(void)
2312 last_resolved_addr = 0;
2316 * Attempt getting our non-local (as judged by tor_addr_is_internal()
2317 * function) IP address using following techniques, listed in
2318 * order from best (most desirable, try first) to worst (least
2319 * desirable, try if everything else fails).
2321 * First, attempt using <b>options-\>Address</b> to get our
2322 * non-local IP address.
2324 * If <b>options-\>Address</b> represents a non-local IP address,
2325 * consider it ours.
2327 * If <b>options-\>Address</b> is a DNS name that resolves to
2328 * a non-local IP address, consider this IP address ours.
2330 * If <b>options-\>Address</b> is NULL, fall back to getting local
2331 * hostname and using it in above-described ways to try and
2332 * get our IP address.
2334 * In case local hostname cannot be resolved to a non-local IP
2335 * address, try getting an IP address of network interface
2336 * in hopes it will be non-local one.
2338 * Fail if one or more of the following is true:
2339 * - DNS name in <b>options-\>Address</b> cannot be resolved.
2340 * - <b>options-\>Address</b> is a local host address.
2341 * - Attempt to getting local hostname fails.
2342 * - Attempt to getting network interface address fails.
2344 * Return 0 if all is well, or -1 if we can't find a suitable
2345 * public IP address.
2347 * If we are returning 0:
2348 * - Put our public IP address (in host order) into *<b>addr_out</b>.
2349 * - If <b>method_out</b> is non-NULL, set *<b>method_out</b> to a static
2350 * string describing how we arrived at our answer.
2351 * - "CONFIGURED" - parsed from IP address string in
2352 * <b>options-\>Address</b>
2353 * - "RESOLVED" - resolved from DNS name in <b>options-\>Address</b>
2354 * - "GETHOSTNAME" - resolved from a local hostname.
2355 * - "INTERFACE" - retrieved from a network interface.
2356 * - If <b>hostname_out</b> is non-NULL, and we resolved a hostname to
2357 * get our address, set *<b>hostname_out</b> to a newly allocated string
2358 * holding that hostname. (If we didn't get our address by resolving a
2359 * hostname, set *<b>hostname_out</b> to NULL.)
2361 * XXXX ipv6
2364 resolve_my_address(int warn_severity, const or_options_t *options,
2365 uint32_t *addr_out,
2366 const char **method_out, char **hostname_out)
2368 struct in_addr in;
2369 uint32_t addr; /* host order */
2370 char hostname[256];
2371 const char *method_used;
2372 const char *hostname_used;
2373 int explicit_ip=1;
2374 int explicit_hostname=1;
2375 int from_interface=0;
2376 char *addr_string = NULL;
2377 const char *address = options->Address;
2378 int notice_severity = warn_severity <= LOG_NOTICE ?
2379 LOG_NOTICE : warn_severity;
2381 tor_addr_t myaddr;
2382 tor_assert(addr_out);
2385 * Step one: Fill in 'hostname' to be our best guess.
2388 if (address && *address) {
2389 strlcpy(hostname, address, sizeof(hostname));
2390 } else { /* then we need to guess our address */
2391 explicit_ip = 0; /* it's implicit */
2392 explicit_hostname = 0; /* it's implicit */
2394 if (tor_gethostname(hostname, sizeof(hostname)) < 0) {
2395 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2396 return -1;
2398 log_debug(LD_CONFIG, "Guessed local host name as '%s'", hostname);
2402 * Step two: Now that we know 'hostname', parse it or resolve it. If
2403 * it doesn't parse or resolve, look at the interface address. Set 'addr'
2404 * to be our (host-order) 32-bit answer.
2407 if (tor_inet_aton(hostname, &in) == 0) {
2408 /* then we have to resolve it */
2409 explicit_ip = 0;
2410 if (tor_lookup_hostname(hostname, &addr)) { /* failed to resolve */
2411 uint32_t interface_ip; /* host order */
2413 if (explicit_hostname) {
2414 log_fn(warn_severity, LD_CONFIG,
2415 "Could not resolve local Address '%s'. Failing.", hostname);
2416 return -1;
2418 log_fn(notice_severity, LD_CONFIG,
2419 "Could not resolve guessed local hostname '%s'. "
2420 "Trying something else.", hostname);
2421 if (get_interface_address(warn_severity, &interface_ip)) {
2422 log_fn(warn_severity, LD_CONFIG,
2423 "Could not get local interface IP address. Failing.");
2424 return -1;
2426 from_interface = 1;
2427 addr = interface_ip;
2428 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2429 "local interface. Using that.", fmt_addr32(addr));
2430 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2431 } else { /* resolved hostname into addr */
2432 tor_addr_from_ipv4h(&myaddr, addr);
2434 if (!explicit_hostname &&
2435 tor_addr_is_internal(&myaddr, 0)) {
2436 tor_addr_t interface_ip;
2438 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2439 "resolves to a private IP address (%s). Trying something "
2440 "else.", hostname, fmt_addr32(addr));
2442 if (get_interface_address6(warn_severity, AF_INET, &interface_ip)<0) {
2443 log_fn(warn_severity, LD_CONFIG,
2444 "Could not get local interface IP address. Too bad.");
2445 } else if (tor_addr_is_internal(&interface_ip, 0)) {
2446 log_fn(notice_severity, LD_CONFIG,
2447 "Interface IP address '%s' is a private address too. "
2448 "Ignoring.", fmt_addr(&interface_ip));
2449 } else {
2450 from_interface = 1;
2451 addr = tor_addr_to_ipv4h(&interface_ip);
2452 log_fn(notice_severity, LD_CONFIG,
2453 "Learned IP address '%s' for local interface."
2454 " Using that.", fmt_addr32(addr));
2455 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2459 } else {
2460 addr = ntohl(in.s_addr); /* set addr so that addr_string is not
2461 * illformed */
2465 * Step three: Check whether 'addr' is an internal IP address, and error
2466 * out if it is and we don't want that.
2469 tor_addr_from_ipv4h(&myaddr,addr);
2471 addr_string = tor_dup_ip(addr);
2472 if (tor_addr_is_internal(&myaddr, 0)) {
2473 /* make sure we're ok with publishing an internal IP */
2474 if (!options->DirAuthorities && !options->AlternateDirAuthority) {
2475 /* if they are using the default authorities, disallow internal IPs
2476 * always. */
2477 log_fn(warn_severity, LD_CONFIG,
2478 "Address '%s' resolves to private IP address '%s'. "
2479 "Tor servers that use the default DirAuthorities must have "
2480 "public IP addresses.", hostname, addr_string);
2481 tor_free(addr_string);
2482 return -1;
2484 if (!explicit_ip) {
2485 /* even if they've set their own authorities, require an explicit IP if
2486 * they're using an internal address. */
2487 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2488 "IP address '%s'. Please set the Address config option to be "
2489 "the IP address you want to use.", hostname, addr_string);
2490 tor_free(addr_string);
2491 return -1;
2496 * Step four: We have a winner! 'addr' is our answer for sure, and
2497 * 'addr_string' is its string form. Fill out the various fields to
2498 * say how we decided it.
2501 log_debug(LD_CONFIG, "Resolved Address to '%s'.", addr_string);
2503 if (explicit_ip) {
2504 method_used = "CONFIGURED";
2505 hostname_used = NULL;
2506 } else if (explicit_hostname) {
2507 method_used = "RESOLVED";
2508 hostname_used = hostname;
2509 } else if (from_interface) {
2510 method_used = "INTERFACE";
2511 hostname_used = NULL;
2512 } else {
2513 method_used = "GETHOSTNAME";
2514 hostname_used = hostname;
2517 *addr_out = addr;
2518 if (method_out)
2519 *method_out = method_used;
2520 if (hostname_out)
2521 *hostname_out = hostname_used ? tor_strdup(hostname_used) : NULL;
2524 * Step five: Check if the answer has changed since last time (or if
2525 * there was no last time), and if so call various functions to keep
2526 * us up-to-date.
2529 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2530 /* Leave this as a notice, regardless of the requested severity,
2531 * at least until dynamic IP address support becomes bulletproof. */
2532 log_notice(LD_NET,
2533 "Your IP address seems to have changed to %s "
2534 "(METHOD=%s%s%s). Updating.",
2535 addr_string, method_used,
2536 hostname_used ? " HOSTNAME=" : "",
2537 hostname_used ? hostname_used : "");
2538 ip_address_changed(0);
2541 if (last_resolved_addr != *addr_out) {
2542 control_event_server_status(LOG_NOTICE,
2543 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s%s%s",
2544 addr_string, method_used,
2545 hostname_used ? " HOSTNAME=" : "",
2546 hostname_used ? hostname_used : "");
2548 last_resolved_addr = *addr_out;
2551 * And finally, clean up and return success.
2554 tor_free(addr_string);
2555 return 0;
2558 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2559 * on a private network.
2561 MOCK_IMPL(int,
2562 is_local_addr, (const tor_addr_t *addr))
2564 if (tor_addr_is_internal(addr, 0))
2565 return 1;
2566 /* Check whether ip is on the same /24 as we are. */
2567 if (get_options()->EnforceDistinctSubnets == 0)
2568 return 0;
2569 if (tor_addr_family(addr) == AF_INET) {
2570 uint32_t ip = tor_addr_to_ipv4h(addr);
2572 /* It's possible that this next check will hit before the first time
2573 * resolve_my_address actually succeeds. (For clients, it is likely that
2574 * resolve_my_address will never be called at all). In those cases,
2575 * last_resolved_addr will be 0, and so checking to see whether ip is on
2576 * the same /24 as last_resolved_addr will be the same as checking whether
2577 * it was on net 0, which is already done by tor_addr_is_internal.
2579 if ((last_resolved_addr & (uint32_t)0xffffff00ul)
2580 == (ip & (uint32_t)0xffffff00ul))
2581 return 1;
2583 return 0;
2586 /** Return a new empty or_options_t. Used for testing. */
2587 or_options_t *
2588 options_new(void)
2590 return config_new(&options_format);
2593 /** Set <b>options</b> to hold reasonable defaults for most options.
2594 * Each option defaults to zero. */
2595 void
2596 options_init(or_options_t *options)
2598 config_init(&options_format, options);
2601 /** Return a string containing a possible configuration file that would give
2602 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2603 * include options that are the same as Tor's defaults.
2605 char *
2606 options_dump(const or_options_t *options, int how_to_dump)
2608 const or_options_t *use_defaults;
2609 int minimal;
2610 switch (how_to_dump) {
2611 case OPTIONS_DUMP_MINIMAL:
2612 use_defaults = global_default_options;
2613 minimal = 1;
2614 break;
2615 case OPTIONS_DUMP_DEFAULTS:
2616 use_defaults = NULL;
2617 minimal = 1;
2618 break;
2619 case OPTIONS_DUMP_ALL:
2620 use_defaults = NULL;
2621 minimal = 0;
2622 break;
2623 default:
2624 log_warn(LD_BUG, "Bogus value for how_to_dump==%d", how_to_dump);
2625 return NULL;
2628 return config_dump(&options_format, use_defaults, options, minimal, 0);
2631 /** Return 0 if every element of sl is a string holding a decimal
2632 * representation of a port number, or if sl is NULL.
2633 * Otherwise set *msg and return -1. */
2634 static int
2635 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2637 int i;
2638 tor_assert(name);
2640 if (!sl)
2641 return 0;
2643 SMARTLIST_FOREACH(sl, const char *, cp,
2645 i = atoi(cp);
2646 if (i < 1 || i > 65535) {
2647 tor_asprintf(msg, "Port '%s' out of range in %s", cp, name);
2648 return -1;
2651 return 0;
2654 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2655 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2656 * Else return 0.
2658 static int
2659 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2661 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2662 /* This handles an understandable special case where somebody says "2gb"
2663 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2664 --*value;
2666 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2667 tor_asprintf(msg, "%s ("U64_FORMAT") must be at most %d",
2668 desc, U64_PRINTF_ARG(*value),
2669 ROUTER_MAX_DECLARED_BANDWIDTH);
2670 return -1;
2672 return 0;
2675 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2676 * and write it to <b>options</b>-\>PublishServerDescriptor_. Treat "1"
2677 * as "v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2678 * Treat "0" as "".
2679 * Return 0 on success or -1 if not a recognized authority type (in which
2680 * case the value of PublishServerDescriptor_ is undefined). */
2681 static int
2682 compute_publishserverdescriptor(or_options_t *options)
2684 smartlist_t *list = options->PublishServerDescriptor;
2685 dirinfo_type_t *auth = &options->PublishServerDescriptor_;
2686 *auth = NO_DIRINFO;
2687 if (!list) /* empty list, answer is none */
2688 return 0;
2689 SMARTLIST_FOREACH_BEGIN(list, const char *, string) {
2690 if (!strcasecmp(string, "v1"))
2691 log_warn(LD_CONFIG, "PublishServerDescriptor v1 has no effect, because "
2692 "there are no v1 directory authorities anymore.");
2693 else if (!strcmp(string, "1"))
2694 if (options->BridgeRelay)
2695 *auth |= BRIDGE_DIRINFO;
2696 else
2697 *auth |= V3_DIRINFO;
2698 else if (!strcasecmp(string, "v2"))
2699 log_warn(LD_CONFIG, "PublishServerDescriptor v2 has no effect, because "
2700 "there are no v2 directory authorities anymore.");
2701 else if (!strcasecmp(string, "v3"))
2702 *auth |= V3_DIRINFO;
2703 else if (!strcasecmp(string, "bridge"))
2704 *auth |= BRIDGE_DIRINFO;
2705 else if (!strcasecmp(string, "hidserv"))
2706 log_warn(LD_CONFIG,
2707 "PublishServerDescriptor hidserv is invalid. See "
2708 "PublishHidServDescriptors.");
2709 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2710 /* no authority */;
2711 else
2712 return -1;
2713 } SMARTLIST_FOREACH_END(string);
2714 return 0;
2717 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2718 * services can overload the directory system. */
2719 #define MIN_REND_POST_PERIOD (10*60)
2720 #define MIN_REND_POST_PERIOD_TESTING (5)
2722 /** Higest allowable value for PredictedPortsRelevanceTime; if this is
2723 * too high, our selection of exits will decrease for an extended
2724 * period of time to an uncomfortable level .*/
2725 #define MAX_PREDICTED_CIRCS_RELEVANCE (60*60)
2727 /** Highest allowable value for RendPostPeriod. */
2728 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2730 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2731 * will generate too many circuits and potentially overload the network. */
2732 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2734 /** Highest allowable value for MaxCircuitDirtiness: prevents time_t
2735 * overflows. */
2736 #define MAX_MAX_CIRCUIT_DIRTINESS (30*24*60*60)
2738 /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
2739 * will generate too many circuits and potentially overload the network. */
2740 #define MIN_CIRCUIT_STREAM_TIMEOUT 10
2742 /** Lowest allowable value for HeartbeatPeriod; if this is too low, we might
2743 * expose more information than we're comfortable with. */
2744 #define MIN_HEARTBEAT_PERIOD (30*60)
2746 /** Lowest recommended value for CircuitBuildTimeout; if it is set too low
2747 * and LearnCircuitBuildTimeout is off, the failure rate for circuit
2748 * construction may be very high. In that case, if it is set below this
2749 * threshold emit a warning.
2750 * */
2751 #define RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT (10)
2753 static int
2754 options_validate_cb(void *old_options, void *options, void *default_options,
2755 int from_setconf, char **msg)
2757 return options_validate(old_options, options, default_options,
2758 from_setconf, msg);
2761 #define REJECT(arg) \
2762 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2763 #if defined(__GNUC__) && __GNUC__ <= 3
2764 #define COMPLAIN(args...) \
2765 STMT_BEGIN log_warn(LD_CONFIG, args); STMT_END
2766 #else
2767 #define COMPLAIN(args, ...) \
2768 STMT_BEGIN log_warn(LD_CONFIG, args, ##__VA_ARGS__); STMT_END
2769 #endif
2771 /** Log a warning message iff <b>filepath</b> is not absolute.
2772 * Warning message must contain option name <b>option</b> and
2773 * an absolute path that <b>filepath</b> will resolve to.
2775 * In case <b>filepath</b> is absolute, do nothing.
2777 static void
2778 warn_if_option_path_is_relative(const char *option,
2779 char *filepath)
2781 if (filepath && path_is_relative(filepath)) {
2782 char *abs_path = make_path_absolute(filepath);
2783 COMPLAIN("Path for %s (%s) is relative and will resolve to %s."
2784 " Is this what you wanted?", option, filepath, abs_path);
2785 tor_free(abs_path);
2789 /** Scan <b>options</b> for occurances of relative file/directory
2790 * path and log a warning whenever it is found.
2792 static void
2793 warn_about_relative_paths(or_options_t *options)
2795 tor_assert(options);
2797 warn_if_option_path_is_relative("CookieAuthFile",
2798 options->CookieAuthFile);
2799 warn_if_option_path_is_relative("ExtORPortCookieAuthFile",
2800 options->ExtORPortCookieAuthFile);
2801 warn_if_option_path_is_relative("DirPortFrontPage",
2802 options->DirPortFrontPage);
2803 warn_if_option_path_is_relative("V3BandwidthsFile",
2804 options->V3BandwidthsFile);
2805 warn_if_option_path_is_relative("ControlPortWriteToFile",
2806 options->ControlPortWriteToFile);
2807 warn_if_option_path_is_relative("GeoIPFile",options->GeoIPFile);
2808 warn_if_option_path_is_relative("GeoIPv6File",options->GeoIPv6File);
2809 warn_if_option_path_is_relative("Log",options->DebugLogFile);
2810 warn_if_option_path_is_relative("AccelDir",options->AccelDir);
2811 warn_if_option_path_is_relative("DataDirectory",options->DataDirectory);
2812 warn_if_option_path_is_relative("PidFile",options->PidFile);
2814 for (config_line_t *hs_line = options->RendConfigLines; hs_line;
2815 hs_line = hs_line->next) {
2816 if (!strcasecmp(hs_line->key, "HiddenServiceDir"))
2817 warn_if_option_path_is_relative("HiddenServiceDir",hs_line->value);
2821 /* Validate options related to OnionServiceSingleHopMode.
2822 * Modifies some options that are incompatible with OnionServiceSingleHopMode.
2823 * On failure returns -1, and sets *msg to an error string.
2824 * Returns 0 on success. */
2825 STATIC int
2826 options_validate_single_onion(or_options_t *options, char **msg)
2828 /* You must set OnionServiceNonAnonymousMode to 1 to use
2829 * OnionServiceSingleHopMode */
2830 if (options->OnionServiceSingleHopMode &&
2831 !rend_service_non_anonymous_mode_enabled(options)) {
2832 REJECT("OnionServiceSingleHopMode does not provide any server anonymity. "
2833 "It must be used with OnionServiceNonAnonymousMode set to 1.");
2836 /* If you have OnionServiceNonAnonymousMode set, you must use
2837 * OnionServiceSingleHopMode. */
2838 if (rend_service_non_anonymous_mode_enabled(options) &&
2839 !options->OnionServiceSingleHopMode) {
2840 REJECT("OnionServiceNonAnonymousMode does not provide any server "
2841 "anonymity. It must be used with OnionServiceSingleHopMode set to "
2842 "1.");
2845 /* If you run an anonymous client with an active Single Onion service, the
2846 * client loses anonymity. */
2847 const int client_port_set = (options->SocksPort_set ||
2848 options->TransPort_set ||
2849 options->NATDPort_set ||
2850 options->DNSPort_set);
2851 if (options->OnionServiceSingleHopMode && client_port_set &&
2852 !options->Tor2webMode) {
2853 REJECT("OnionServiceSingleHopMode is incompatible with using Tor as an "
2854 "anonymous client. Please set Socks/Trans/NATD/DNSPort to 0, or "
2855 "OnionServiceSingleHopMode to 0, or use the non-anonymous "
2856 "Tor2webMode.");
2859 /* If you run a hidden service in non-anonymous mode, the hidden service
2860 * loses anonymity, even if SOCKSPort / Tor2web mode isn't used. */
2861 if (!options->OnionServiceSingleHopMode && options->RendConfigLines
2862 && options->Tor2webMode) {
2863 REJECT("Non-anonymous (Tor2web) mode is incompatible with using Tor as a "
2864 "hidden service. Please remove all HiddenServiceDir lines, or use "
2865 "a version of tor compiled without --enable-tor2web-mode, or use "
2866 "the non-anonymous OnionServiceSingleHopMode.");
2869 if (options->OnionServiceSingleHopMode
2870 && options->UseEntryGuards) {
2871 /* Single Onion services do not (and should not) use entry guards
2872 * in any meaningful way. Further, Single Onions causes the hidden
2873 * service code to do things which break the path bias
2874 * detector, and it's far easier to turn off entry guards (and
2875 * thus the path bias detector with it) than to figure out how to
2876 * make a piece of code which cannot possibly help Single Onions,
2877 * compatible with OnionServiceSingleHopMode.
2879 log_notice(LD_CONFIG,
2880 "OnionServiceSingleHopMode is enabled; disabling "
2881 "UseEntryGuards.");
2882 options->UseEntryGuards = 0;
2885 /* Check if existing hidden service keys were created with a different
2886 * setting of OnionServiceNonAnonymousMode, and refuse to launch if they
2887 * have. We'll poison new keys in options_act() just before we create them.
2889 if (rend_service_list_verify_single_onion_poison(NULL, options) < 0) {
2890 log_warn(LD_GENERAL, "We are configured with OnionServiceSingleHopMode "
2891 "%d, but one or more hidden service keys were created in %s "
2892 "mode. This is not allowed.",
2893 rend_service_non_anonymous_mode_enabled(options) ? 1 : 0,
2894 rend_service_non_anonymous_mode_enabled(options) ?
2895 "an anonymous" : "a non-anonymous"
2897 return -1;
2900 return 0;
2903 /** Return 0 if every setting in <b>options</b> is reasonable, is a
2904 * permissible transition from <b>old_options</b>, and none of the
2905 * testing-only settings differ from <b>default_options</b> unless in
2906 * testing mode. Else return -1. Should have no side effects, except for
2907 * normalizing the contents of <b>options</b>.
2909 * On error, tor_strdup an error explanation into *<b>msg</b>.
2911 * XXX
2912 * If <b>from_setconf</b>, we were called by the controller, and our
2913 * Log line should stay empty. If it's 0, then give us a default log
2914 * if there are no logs defined.
2916 STATIC int
2917 options_validate(or_options_t *old_options, or_options_t *options,
2918 or_options_t *default_options, int from_setconf, char **msg)
2920 int i;
2921 config_line_t *cl;
2922 const char *uname = get_uname();
2923 int n_ports=0;
2924 int world_writable_control_socket=0;
2926 tor_assert(msg);
2927 *msg = NULL;
2929 /* Set UseEntryGuards from the configured value, before we check it below.
2930 * We change UseEntryGuards whenn it's incompatible with other options,
2931 * but leave UseEntryGuards_option with the original value.
2932 * Always use the value of UseEntryGuards, not UseEntryGuards_option. */
2933 options->UseEntryGuards = options->UseEntryGuards_option;
2935 warn_about_relative_paths(options);
2937 if (server_mode(options) &&
2938 (!strcmpstart(uname, "Windows 95") ||
2939 !strcmpstart(uname, "Windows 98") ||
2940 !strcmpstart(uname, "Windows Me"))) {
2941 log_warn(LD_CONFIG, "Tor is running as a server, but you are "
2942 "running %s; this probably won't work. See "
2943 "https://www.torproject.org/docs/faq.html#BestOSForRelay "
2944 "for details.", uname);
2947 if (parse_ports(options, 1, msg, &n_ports,
2948 &world_writable_control_socket) < 0)
2949 return -1;
2951 if (parse_outbound_addresses(options, 1, msg) < 0)
2952 return -1;
2954 if (validate_data_directory(options)<0)
2955 REJECT("Invalid DataDirectory");
2957 if (options->Nickname == NULL) {
2958 if (server_mode(options)) {
2959 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
2961 } else {
2962 if (!is_legal_nickname(options->Nickname)) {
2963 tor_asprintf(msg,
2964 "Nickname '%s', nicknames must be between 1 and 19 characters "
2965 "inclusive, and must contain only the characters [a-zA-Z0-9].",
2966 options->Nickname);
2967 return -1;
2971 if (server_mode(options) && !options->ContactInfo)
2972 log_notice(LD_CONFIG, "Your ContactInfo config option is not set. "
2973 "Please consider setting it, so we can contact you if your server is "
2974 "misconfigured or something else goes wrong.");
2976 /* Special case on first boot if no Log options are given. */
2977 if (!options->Logs && !options->RunAsDaemon && !from_setconf) {
2978 if (quiet_level == 0)
2979 config_line_append(&options->Logs, "Log", "notice stdout");
2980 else if (quiet_level == 1)
2981 config_line_append(&options->Logs, "Log", "warn stdout");
2984 /* Validate the tor_log(s) */
2985 if (options_init_logs(old_options, options, 1)<0)
2986 REJECT("Failed to validate Log options. See logs for details.");
2988 if (authdir_mode(options)) {
2989 /* confirm that our address isn't broken, so we can complain now */
2990 uint32_t tmp;
2991 if (resolve_my_address(LOG_WARN, options, &tmp, NULL, NULL) < 0)
2992 REJECT("Failed to resolve/guess local address. See logs for details.");
2995 if (server_mode(options) && options->RendConfigLines)
2996 log_warn(LD_CONFIG,
2997 "Tor is currently configured as a relay and a hidden service. "
2998 "That's not very secure: you should probably run your hidden service "
2999 "in a separate Tor process, at least -- see "
3000 "https://trac.torproject.org/8742");
3002 /* XXXX require that the only port not be DirPort? */
3003 /* XXXX require that at least one port be listened-upon. */
3004 if (n_ports == 0 && !options->RendConfigLines)
3005 log_warn(LD_CONFIG,
3006 "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
3007 "undefined, and there aren't any hidden services configured. "
3008 "Tor will still run, but probably won't do anything.");
3010 options->TransProxyType_parsed = TPT_DEFAULT;
3011 #ifdef USE_TRANSPARENT
3012 if (options->TransProxyType) {
3013 if (!strcasecmp(options->TransProxyType, "default")) {
3014 options->TransProxyType_parsed = TPT_DEFAULT;
3015 } else if (!strcasecmp(options->TransProxyType, "pf-divert")) {
3016 #if !defined(__OpenBSD__) && !defined( DARWIN )
3017 /* Later versions of OS X have pf */
3018 REJECT("pf-divert is a OpenBSD-specific "
3019 "and OS X/Darwin-specific feature.");
3020 #else
3021 options->TransProxyType_parsed = TPT_PF_DIVERT;
3022 #endif
3023 } else if (!strcasecmp(options->TransProxyType, "tproxy")) {
3024 #if !defined(__linux__)
3025 REJECT("TPROXY is a Linux-specific feature.");
3026 #else
3027 options->TransProxyType_parsed = TPT_TPROXY;
3028 #endif
3029 } else if (!strcasecmp(options->TransProxyType, "ipfw")) {
3030 #ifndef KERNEL_MAY_SUPPORT_IPFW
3031 /* Earlier versions of OS X have ipfw */
3032 REJECT("ipfw is a FreeBSD-specific"
3033 "and OS X/Darwin-specific feature.");
3034 #else
3035 options->TransProxyType_parsed = TPT_IPFW;
3036 #endif
3037 } else {
3038 REJECT("Unrecognized value for TransProxyType");
3041 if (strcasecmp(options->TransProxyType, "default") &&
3042 !options->TransPort_set) {
3043 REJECT("Cannot use TransProxyType without any valid TransPort or "
3044 "TransListenAddress.");
3047 #else
3048 if (options->TransPort_set)
3049 REJECT("TransPort and TransListenAddress are disabled "
3050 "in this build.");
3051 #endif
3053 if (options->TokenBucketRefillInterval <= 0
3054 || options->TokenBucketRefillInterval > 1000) {
3055 REJECT("TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
3058 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3059 options->ExcludeExitNodesUnion_ = routerset_new();
3060 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeExitNodes);
3061 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeNodes);
3064 if (options->SchedulerLowWaterMark__ == 0 ||
3065 options->SchedulerLowWaterMark__ > UINT32_MAX) {
3066 log_warn(LD_GENERAL, "Bad SchedulerLowWaterMark__ option");
3067 return -1;
3068 } else if (options->SchedulerHighWaterMark__ <=
3069 options->SchedulerLowWaterMark__ ||
3070 options->SchedulerHighWaterMark__ > UINT32_MAX) {
3071 log_warn(LD_GENERAL, "Bad SchedulerHighWaterMark option");
3072 return -1;
3075 if (options->NodeFamilies) {
3076 options->NodeFamilySets = smartlist_new();
3077 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3078 routerset_t *rs = routerset_new();
3079 if (routerset_parse(rs, cl->value, cl->key) == 0) {
3080 smartlist_add(options->NodeFamilySets, rs);
3081 } else {
3082 routerset_free(rs);
3087 if (options->TLSECGroup && (strcasecmp(options->TLSECGroup, "P256") &&
3088 strcasecmp(options->TLSECGroup, "P224"))) {
3089 COMPLAIN("Unrecognized TLSECGroup: Falling back to the default.");
3090 tor_free(options->TLSECGroup);
3092 if (!evaluate_ecgroup_for_tls(options->TLSECGroup)) {
3093 REJECT("Unsupported TLSECGroup.");
3096 if (options->ExcludeNodes && options->StrictNodes) {
3097 COMPLAIN("You have asked to exclude certain relays from all positions "
3098 "in your circuits. Expect hidden services and other Tor "
3099 "features to be broken in unpredictable ways.");
3102 for (cl = options->RecommendedPackages; cl; cl = cl->next) {
3103 if (! validate_recommended_package_line(cl->value)) {
3104 log_warn(LD_CONFIG, "Invalid RecommendedPackage line %s will be ignored",
3105 escaped(cl->value));
3109 if (options->AuthoritativeDir) {
3110 if (!options->ContactInfo && !options->TestingTorNetwork)
3111 REJECT("Authoritative directory servers must set ContactInfo");
3112 if (!options->RecommendedClientVersions)
3113 options->RecommendedClientVersions =
3114 config_lines_dup(options->RecommendedVersions);
3115 if (!options->RecommendedServerVersions)
3116 options->RecommendedServerVersions =
3117 config_lines_dup(options->RecommendedVersions);
3118 if (options->VersioningAuthoritativeDir &&
3119 (!options->RecommendedClientVersions ||
3120 !options->RecommendedServerVersions))
3121 REJECT("Versioning authoritative dir servers must set "
3122 "Recommended*Versions.");
3123 if (options->UseEntryGuards) {
3124 log_info(LD_CONFIG, "Authoritative directory servers can't set "
3125 "UseEntryGuards. Disabling.");
3126 options->UseEntryGuards = 0;
3128 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
3129 log_info(LD_CONFIG, "Authoritative directories always try to download "
3130 "extra-info documents. Setting DownloadExtraInfo.");
3131 options->DownloadExtraInfo = 1;
3133 if (!(options->BridgeAuthoritativeDir ||
3134 options->V3AuthoritativeDir))
3135 REJECT("AuthoritativeDir is set, but none of "
3136 "(Bridge/V3)AuthoritativeDir is set.");
3137 /* If we have a v3bandwidthsfile and it's broken, complain on startup */
3138 if (options->V3BandwidthsFile && !old_options) {
3139 dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
3141 /* same for guardfraction file */
3142 if (options->GuardfractionFile && !old_options) {
3143 dirserv_read_guardfraction_file(options->GuardfractionFile, NULL);
3147 if (options->AuthoritativeDir && !options->DirPort_set)
3148 REJECT("Running as authoritative directory, but no DirPort set.");
3150 if (options->AuthoritativeDir && !options->ORPort_set)
3151 REJECT("Running as authoritative directory, but no ORPort set.");
3153 if (options->AuthoritativeDir && options->ClientOnly)
3154 REJECT("Running as authoritative directory, but ClientOnly also set.");
3156 if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
3157 REJECT("FetchDirInfoExtraEarly requires that you also set "
3158 "FetchDirInfoEarly");
3160 if (options->ConnLimit <= 0) {
3161 tor_asprintf(msg,
3162 "ConnLimit must be greater than 0, but was set to %d",
3163 options->ConnLimit);
3164 return -1;
3167 if (options->PathsNeededToBuildCircuits >= 0.0) {
3168 if (options->PathsNeededToBuildCircuits < 0.25) {
3169 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too low. Increasing "
3170 "to 0.25");
3171 options->PathsNeededToBuildCircuits = 0.25;
3172 } else if (options->PathsNeededToBuildCircuits > 0.95) {
3173 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too high. Decreasing "
3174 "to 0.95");
3175 options->PathsNeededToBuildCircuits = 0.95;
3179 if (options->MaxClientCircuitsPending <= 0 ||
3180 options->MaxClientCircuitsPending > MAX_MAX_CLIENT_CIRCUITS_PENDING) {
3181 tor_asprintf(msg,
3182 "MaxClientCircuitsPending must be between 1 and %d, but "
3183 "was set to %d", MAX_MAX_CLIENT_CIRCUITS_PENDING,
3184 options->MaxClientCircuitsPending);
3185 return -1;
3188 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3189 return -1;
3191 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3192 return -1;
3194 if (validate_ports_csv(options->RejectPlaintextPorts,
3195 "RejectPlaintextPorts", msg) < 0)
3196 return -1;
3198 if (validate_ports_csv(options->WarnPlaintextPorts,
3199 "WarnPlaintextPorts", msg) < 0)
3200 return -1;
3202 if (options->FascistFirewall && !options->ReachableAddresses) {
3203 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3204 /* We already have firewall ports set, so migrate them to
3205 * ReachableAddresses, which will set ReachableORAddresses and
3206 * ReachableDirAddresses if they aren't set explicitly. */
3207 smartlist_t *instead = smartlist_new();
3208 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3209 new_line->key = tor_strdup("ReachableAddresses");
3210 /* If we're configured with the old format, we need to prepend some
3211 * open ports. */
3212 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3214 int p = atoi(portno);
3215 if (p<0) continue;
3216 smartlist_add_asprintf(instead, "*:%d", p);
3218 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3219 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3220 log_notice(LD_CONFIG,
3221 "Converting FascistFirewall and FirewallPorts "
3222 "config options to new format: \"ReachableAddresses %s\"",
3223 new_line->value);
3224 options->ReachableAddresses = new_line;
3225 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3226 smartlist_free(instead);
3227 } else {
3228 /* We do not have FirewallPorts set, so add 80 to
3229 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3230 if (!options->ReachableDirAddresses) {
3231 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3232 new_line->key = tor_strdup("ReachableDirAddresses");
3233 new_line->value = tor_strdup("*:80");
3234 options->ReachableDirAddresses = new_line;
3235 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3236 "to new format: \"ReachableDirAddresses *:80\"");
3238 if (!options->ReachableORAddresses) {
3239 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3240 new_line->key = tor_strdup("ReachableORAddresses");
3241 new_line->value = tor_strdup("*:443");
3242 options->ReachableORAddresses = new_line;
3243 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3244 "to new format: \"ReachableORAddresses *:443\"");
3249 /* Terminate Reachable*Addresses with reject *
3251 for (i=0; i<3; i++) {
3252 config_line_t **linep =
3253 (i==0) ? &options->ReachableAddresses :
3254 (i==1) ? &options->ReachableORAddresses :
3255 &options->ReachableDirAddresses;
3256 if (!*linep)
3257 continue;
3258 /* We need to end with a reject *:*, not an implicit accept *:* */
3259 for (;;) {
3260 linep = &((*linep)->next);
3261 if (!*linep) {
3262 *linep = tor_malloc_zero(sizeof(config_line_t));
3263 (*linep)->key = tor_strdup(
3264 (i==0) ? "ReachableAddresses" :
3265 (i==1) ? "ReachableORAddresses" :
3266 "ReachableDirAddresses");
3267 (*linep)->value = tor_strdup("reject *:*");
3268 break;
3273 if ((options->ReachableAddresses ||
3274 options->ReachableORAddresses ||
3275 options->ReachableDirAddresses ||
3276 options->ClientUseIPv4 == 0) &&
3277 server_mode(options))
3278 REJECT("Servers must be able to freely connect to the rest "
3279 "of the Internet, so they must not set Reachable*Addresses "
3280 "or FascistFirewall or FirewallPorts or ClientUseIPv4 0.");
3282 /* We check if Reachable*Addresses blocks all addresses in
3283 * parse_reachable_addresses(). */
3285 #define WARN_PLEASE_USE_IPV6_LOG_MSG \
3286 "ClientPreferIPv6%sPort 1 is ignored unless tor is using IPv6. " \
3287 "Please set ClientUseIPv6 1, ClientUseIPv4 0, or configure bridges."
3289 if (!fascist_firewall_use_ipv6(options)
3290 && options->ClientPreferIPv6ORPort == 1)
3291 log_warn(LD_CONFIG, WARN_PLEASE_USE_IPV6_LOG_MSG, "OR");
3293 if (!fascist_firewall_use_ipv6(options)
3294 && options->ClientPreferIPv6DirPort == 1)
3295 log_warn(LD_CONFIG, WARN_PLEASE_USE_IPV6_LOG_MSG, "Dir");
3297 #undef WARN_PLEASE_USE_IPV6_LOG_MSG
3299 if (options->UseBridges &&
3300 server_mode(options))
3301 REJECT("Servers must be able to freely connect to the rest "
3302 "of the Internet, so they must not set UseBridges.");
3304 /* If both of these are set, we'll end up with funny behavior where we
3305 * demand enough entrynodes be up and running else we won't build
3306 * circuits, yet we never actually use them. */
3307 if (options->UseBridges && options->EntryNodes)
3308 REJECT("You cannot set both UseBridges and EntryNodes.");
3310 options->MaxMemInQueues =
3311 compute_real_max_mem_in_queues(options->MaxMemInQueues_raw,
3312 server_mode(options));
3313 options->MaxMemInQueues_low_threshold = (options->MaxMemInQueues / 4) * 3;
3315 options->AllowInvalid_ = 0;
3317 if (options->AllowInvalidNodes) {
3318 SMARTLIST_FOREACH_BEGIN(options->AllowInvalidNodes, const char *, cp) {
3319 if (!strcasecmp(cp, "entry"))
3320 options->AllowInvalid_ |= ALLOW_INVALID_ENTRY;
3321 else if (!strcasecmp(cp, "exit"))
3322 options->AllowInvalid_ |= ALLOW_INVALID_EXIT;
3323 else if (!strcasecmp(cp, "middle"))
3324 options->AllowInvalid_ |= ALLOW_INVALID_MIDDLE;
3325 else if (!strcasecmp(cp, "introduction"))
3326 options->AllowInvalid_ |= ALLOW_INVALID_INTRODUCTION;
3327 else if (!strcasecmp(cp, "rendezvous"))
3328 options->AllowInvalid_ |= ALLOW_INVALID_RENDEZVOUS;
3329 else {
3330 tor_asprintf(msg,
3331 "Unrecognized value '%s' in AllowInvalidNodes", cp);
3332 return -1;
3334 } SMARTLIST_FOREACH_END(cp);
3337 if (!options->SafeLogging ||
3338 !strcasecmp(options->SafeLogging, "0")) {
3339 options->SafeLogging_ = SAFELOG_SCRUB_NONE;
3340 } else if (!strcasecmp(options->SafeLogging, "relay")) {
3341 options->SafeLogging_ = SAFELOG_SCRUB_RELAY;
3342 } else if (!strcasecmp(options->SafeLogging, "1")) {
3343 options->SafeLogging_ = SAFELOG_SCRUB_ALL;
3344 } else {
3345 tor_asprintf(msg,
3346 "Unrecognized value '%s' in SafeLogging",
3347 escaped(options->SafeLogging));
3348 return -1;
3351 if (compute_publishserverdescriptor(options) < 0) {
3352 tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
3353 return -1;
3356 if ((options->BridgeRelay
3357 || options->PublishServerDescriptor_ & BRIDGE_DIRINFO)
3358 && (options->PublishServerDescriptor_ & V3_DIRINFO)) {
3359 REJECT("Bridges are not supposed to publish router descriptors to the "
3360 "directory authorities. Please correct your "
3361 "PublishServerDescriptor line.");
3364 if (options->BridgeRelay && options->DirPort_set) {
3365 log_warn(LD_CONFIG, "Can't set a DirPort on a bridge relay; disabling "
3366 "DirPort");
3367 config_free_lines(options->DirPort_lines);
3368 options->DirPort_lines = NULL;
3369 options->DirPort_set = 0;
3372 if (options->MinUptimeHidServDirectoryV2 < 0) {
3373 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3374 "least 0 seconds. Changing to 0.");
3375 options->MinUptimeHidServDirectoryV2 = 0;
3378 const int min_rendpostperiod =
3379 options->TestingTorNetwork ?
3380 MIN_REND_POST_PERIOD_TESTING : MIN_REND_POST_PERIOD;
3381 if (options->RendPostPeriod < min_rendpostperiod) {
3382 log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
3383 "raising to %d seconds.", min_rendpostperiod);
3384 options->RendPostPeriod = min_rendpostperiod;;
3387 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3388 log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3389 MAX_DIR_PERIOD);
3390 options->RendPostPeriod = MAX_DIR_PERIOD;
3393 if (options->PredictedPortsRelevanceTime >
3394 MAX_PREDICTED_CIRCS_RELEVANCE) {
3395 log_warn(LD_CONFIG, "PredictedPortsRelevanceTime is too large; "
3396 "clipping to %ds.", MAX_PREDICTED_CIRCS_RELEVANCE);
3397 options->PredictedPortsRelevanceTime = MAX_PREDICTED_CIRCS_RELEVANCE;
3400 /* Check the Single Onion Service options */
3401 if (options_validate_single_onion(options, msg) < 0)
3402 return -1;
3404 #ifdef ENABLE_TOR2WEB_MODE
3405 if (options->Tor2webMode && options->UseEntryGuards) {
3406 /* tor2web mode clients do not (and should not) use entry guards
3407 * in any meaningful way. Further, tor2web mode causes the hidden
3408 * service client code to do things which break the path bias
3409 * detector, and it's far easier to turn off entry guards (and
3410 * thus the path bias detector with it) than to figure out how to
3411 * make a piece of code which cannot possibly help tor2web mode
3412 * users compatible with tor2web mode.
3414 log_notice(LD_CONFIG,
3415 "Tor2WebMode is enabled; disabling UseEntryGuards.");
3416 options->UseEntryGuards = 0;
3418 #endif
3420 if (options->Tor2webRendezvousPoints && !options->Tor2webMode) {
3421 REJECT("Tor2webRendezvousPoints cannot be set without Tor2webMode.");
3424 if (options->EntryNodes && !options->UseEntryGuards) {
3425 REJECT("If EntryNodes is set, UseEntryGuards must be enabled.");
3428 if (!(options->UseEntryGuards) &&
3429 (options->RendConfigLines != NULL) &&
3430 !rend_service_non_anonymous_mode_enabled(options)) {
3431 log_warn(LD_CONFIG,
3432 "UseEntryGuards is disabled, but you have configured one or more "
3433 "hidden services on this Tor instance. Your hidden services "
3434 "will be very easy to locate using a well-known attack -- see "
3435 "http://freehaven.net/anonbib/#hs-attack06 for details.");
3438 if (options->EntryNodes &&
3439 routerset_is_list(options->EntryNodes) &&
3440 (routerset_len(options->EntryNodes) == 1) &&
3441 (options->RendConfigLines != NULL)) {
3442 tor_asprintf(msg,
3443 "You have one single EntryNodes and at least one hidden service "
3444 "configured. This is bad because it's very easy to locate your "
3445 "entry guard which can then lead to the deanonymization of your "
3446 "hidden service -- for more details, see "
3447 "https://trac.torproject.org/projects/tor/ticket/14917. "
3448 "For this reason, the use of one EntryNodes with an hidden "
3449 "service is prohibited until a better solution is found.");
3450 return -1;
3453 /* OnionServiceSingleHopMode: one hop between the onion service server and
3454 * intro and rendezvous points */
3455 if (options->OnionServiceSingleHopMode) {
3456 log_warn(LD_CONFIG,
3457 "OnionServiceSingleHopMode is set. Every hidden service on this "
3458 "tor instance is NON-ANONYMOUS. If OnionServiceSingleHopMode is "
3459 "disabled, Tor will refuse to launch hidden services from the "
3460 "same directories, to protect against config errors. This "
3461 "setting is for experimental use only.");
3464 if (!options->LearnCircuitBuildTimeout && options->CircuitBuildTimeout &&
3465 options->CircuitBuildTimeout < RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT) {
3466 log_warn(LD_CONFIG,
3467 "CircuitBuildTimeout is shorter (%d seconds) than the recommended "
3468 "minimum (%d seconds), and LearnCircuitBuildTimeout is disabled. "
3469 "If tor isn't working, raise this value or enable "
3470 "LearnCircuitBuildTimeout.",
3471 options->CircuitBuildTimeout,
3472 RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT );
3473 } else if (!options->LearnCircuitBuildTimeout &&
3474 !options->CircuitBuildTimeout) {
3475 int severity = LOG_NOTICE;
3476 /* Be a little quieter if we've deliberately disabled
3477 * LearnCircuitBuildTimeout. */
3478 if (circuit_build_times_disabled()) {
3479 severity = LOG_INFO;
3481 log_fn(severity, LD_CONFIG, "You disabled LearnCircuitBuildTimeout, but "
3482 "didn't specify a CircuitBuildTimeout. I'll pick a plausible "
3483 "default.");
3486 if (options->PathBiasNoticeRate > 1.0) {
3487 tor_asprintf(msg,
3488 "PathBiasNoticeRate is too high. "
3489 "It must be between 0 and 1.0");
3490 return -1;
3492 if (options->PathBiasWarnRate > 1.0) {
3493 tor_asprintf(msg,
3494 "PathBiasWarnRate is too high. "
3495 "It must be between 0 and 1.0");
3496 return -1;
3498 if (options->PathBiasExtremeRate > 1.0) {
3499 tor_asprintf(msg,
3500 "PathBiasExtremeRate is too high. "
3501 "It must be between 0 and 1.0");
3502 return -1;
3504 if (options->PathBiasNoticeUseRate > 1.0) {
3505 tor_asprintf(msg,
3506 "PathBiasNoticeUseRate is too high. "
3507 "It must be between 0 and 1.0");
3508 return -1;
3510 if (options->PathBiasExtremeUseRate > 1.0) {
3511 tor_asprintf(msg,
3512 "PathBiasExtremeUseRate is too high. "
3513 "It must be between 0 and 1.0");
3514 return -1;
3517 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3518 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3519 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3520 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3523 if (options->MaxCircuitDirtiness > MAX_MAX_CIRCUIT_DIRTINESS) {
3524 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too high; "
3525 "setting to %d days.", MAX_MAX_CIRCUIT_DIRTINESS/86400);
3526 options->MaxCircuitDirtiness = MAX_MAX_CIRCUIT_DIRTINESS;
3529 if (options->CircuitStreamTimeout &&
3530 options->CircuitStreamTimeout < MIN_CIRCUIT_STREAM_TIMEOUT) {
3531 log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
3532 "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
3533 options->CircuitStreamTimeout = MIN_CIRCUIT_STREAM_TIMEOUT;
3536 if (options->HeartbeatPeriod &&
3537 options->HeartbeatPeriod < MIN_HEARTBEAT_PERIOD) {
3538 log_warn(LD_CONFIG, "HeartbeatPeriod option is too short; "
3539 "raising to %d seconds.", MIN_HEARTBEAT_PERIOD);
3540 options->HeartbeatPeriod = MIN_HEARTBEAT_PERIOD;
3543 if (options->KeepalivePeriod < 1)
3544 REJECT("KeepalivePeriod option must be positive.");
3546 if (options->PortForwarding && options->Sandbox) {
3547 REJECT("PortForwarding is not compatible with Sandbox; at most one can "
3548 "be set");
3551 if (ensure_bandwidth_cap(&options->BandwidthRate,
3552 "BandwidthRate", msg) < 0)
3553 return -1;
3554 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3555 "BandwidthBurst", msg) < 0)
3556 return -1;
3557 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3558 "MaxAdvertisedBandwidth", msg) < 0)
3559 return -1;
3560 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3561 "RelayBandwidthRate", msg) < 0)
3562 return -1;
3563 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3564 "RelayBandwidthBurst", msg) < 0)
3565 return -1;
3566 if (ensure_bandwidth_cap(&options->PerConnBWRate,
3567 "PerConnBWRate", msg) < 0)
3568 return -1;
3569 if (ensure_bandwidth_cap(&options->PerConnBWBurst,
3570 "PerConnBWBurst", msg) < 0)
3571 return -1;
3572 if (ensure_bandwidth_cap(&options->AuthDirFastGuarantee,
3573 "AuthDirFastGuarantee", msg) < 0)
3574 return -1;
3575 if (ensure_bandwidth_cap(&options->AuthDirGuardBWGuarantee,
3576 "AuthDirGuardBWGuarantee", msg) < 0)
3577 return -1;
3579 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3580 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3581 if (options->RelayBandwidthBurst && !options->RelayBandwidthRate)
3582 options->RelayBandwidthRate = options->RelayBandwidthBurst;
3584 if (server_mode(options)) {
3585 const unsigned required_min_bw =
3586 public_server_mode(options) ?
3587 RELAY_REQUIRED_MIN_BANDWIDTH : BRIDGE_REQUIRED_MIN_BANDWIDTH;
3588 const char * const optbridge =
3589 public_server_mode(options) ? "" : "bridge ";
3590 if (options->BandwidthRate < required_min_bw) {
3591 tor_asprintf(msg,
3592 "BandwidthRate is set to %d bytes/second. "
3593 "For %sservers, it must be at least %u.",
3594 (int)options->BandwidthRate, optbridge,
3595 required_min_bw);
3596 return -1;
3597 } else if (options->MaxAdvertisedBandwidth <
3598 required_min_bw/2) {
3599 tor_asprintf(msg,
3600 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3601 "For %sservers, it must be at least %u.",
3602 (int)options->MaxAdvertisedBandwidth, optbridge,
3603 required_min_bw/2);
3604 return -1;
3606 if (options->RelayBandwidthRate &&
3607 options->RelayBandwidthRate < required_min_bw) {
3608 tor_asprintf(msg,
3609 "RelayBandwidthRate is set to %d bytes/second. "
3610 "For %sservers, it must be at least %u.",
3611 (int)options->RelayBandwidthRate, optbridge,
3612 required_min_bw);
3613 return -1;
3617 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3618 REJECT("RelayBandwidthBurst must be at least equal "
3619 "to RelayBandwidthRate.");
3621 if (options->BandwidthRate > options->BandwidthBurst)
3622 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3624 /* if they set relaybandwidth* really high but left bandwidth*
3625 * at the default, raise the defaults. */
3626 if (options->RelayBandwidthRate > options->BandwidthRate)
3627 options->BandwidthRate = options->RelayBandwidthRate;
3628 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3629 options->BandwidthBurst = options->RelayBandwidthBurst;
3631 if (accounting_parse_options(options, 1)<0)
3632 REJECT("Failed to parse accounting options. See logs for details.");
3634 if (options->AccountingMax) {
3635 if (options->RendConfigLines && server_mode(options)) {
3636 log_warn(LD_CONFIG, "Using accounting with a hidden service and an "
3637 "ORPort is risky: your hidden service(s) and your public "
3638 "address will all turn off at the same time, which may alert "
3639 "observers that they are being run by the same party.");
3640 } else if (config_count_key(options->RendConfigLines,
3641 "HiddenServiceDir") > 1) {
3642 log_warn(LD_CONFIG, "Using accounting with multiple hidden services is "
3643 "risky: they will all turn off at the same time, which may "
3644 "alert observers that they are being run by the same party.");
3648 options->AccountingRule = ACCT_MAX;
3649 if (options->AccountingRule_option) {
3650 if (!strcmp(options->AccountingRule_option, "sum"))
3651 options->AccountingRule = ACCT_SUM;
3652 else if (!strcmp(options->AccountingRule_option, "max"))
3653 options->AccountingRule = ACCT_MAX;
3654 else if (!strcmp(options->AccountingRule_option, "in"))
3655 options->AccountingRule = ACCT_IN;
3656 else if (!strcmp(options->AccountingRule_option, "out"))
3657 options->AccountingRule = ACCT_OUT;
3658 else
3659 REJECT("AccountingRule must be 'sum', 'max', 'in', or 'out'");
3662 if (options->DirPort_set && !options->DirCache) {
3663 REJECT("DirPort configured but DirCache disabled. DirPort requires "
3664 "DirCache.");
3667 if (options->BridgeRelay && !options->DirCache) {
3668 REJECT("We're a bridge but DirCache is disabled. BridgeRelay requires "
3669 "DirCache.");
3672 if (server_mode(options)) {
3673 char *dircache_msg = NULL;
3674 if (have_enough_mem_for_dircache(options, 0, &dircache_msg)) {
3675 log_warn(LD_CONFIG, "%s", dircache_msg);
3676 tor_free(dircache_msg);
3680 if (options->HTTPProxy) { /* parse it now */
3681 if (tor_addr_port_lookup(options->HTTPProxy,
3682 &options->HTTPProxyAddr, &options->HTTPProxyPort) < 0)
3683 REJECT("HTTPProxy failed to parse or resolve. Please fix.");
3684 if (options->HTTPProxyPort == 0) { /* give it a default */
3685 options->HTTPProxyPort = 80;
3689 if (options->HTTPProxyAuthenticator) {
3690 if (strlen(options->HTTPProxyAuthenticator) >= 512)
3691 REJECT("HTTPProxyAuthenticator is too long (>= 512 chars).");
3694 if (options->HTTPSProxy) { /* parse it now */
3695 if (tor_addr_port_lookup(options->HTTPSProxy,
3696 &options->HTTPSProxyAddr, &options->HTTPSProxyPort) <0)
3697 REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
3698 if (options->HTTPSProxyPort == 0) { /* give it a default */
3699 options->HTTPSProxyPort = 443;
3703 if (options->HTTPSProxyAuthenticator) {
3704 if (strlen(options->HTTPSProxyAuthenticator) >= 512)
3705 REJECT("HTTPSProxyAuthenticator is too long (>= 512 chars).");
3708 if (options->Socks4Proxy) { /* parse it now */
3709 if (tor_addr_port_lookup(options->Socks4Proxy,
3710 &options->Socks4ProxyAddr,
3711 &options->Socks4ProxyPort) <0)
3712 REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
3713 if (options->Socks4ProxyPort == 0) { /* give it a default */
3714 options->Socks4ProxyPort = 1080;
3718 if (options->Socks5Proxy) { /* parse it now */
3719 if (tor_addr_port_lookup(options->Socks5Proxy,
3720 &options->Socks5ProxyAddr,
3721 &options->Socks5ProxyPort) <0)
3722 REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
3723 if (options->Socks5ProxyPort == 0) { /* give it a default */
3724 options->Socks5ProxyPort = 1080;
3728 /* Check if more than one exclusive proxy type has been enabled. */
3729 if (!!options->Socks4Proxy + !!options->Socks5Proxy +
3730 !!options->HTTPSProxy > 1)
3731 REJECT("You have configured more than one proxy type. "
3732 "(Socks4Proxy|Socks5Proxy|HTTPSProxy)");
3734 /* Check if the proxies will give surprising behavior. */
3735 if (options->HTTPProxy && !(options->Socks4Proxy ||
3736 options->Socks5Proxy ||
3737 options->HTTPSProxy)) {
3738 log_warn(LD_CONFIG, "HTTPProxy configured, but no SOCKS proxy or "
3739 "HTTPS proxy configured. Watch out: this configuration will "
3740 "proxy unencrypted directory connections only.");
3743 if (options->Socks5ProxyUsername) {
3744 size_t len;
3746 len = strlen(options->Socks5ProxyUsername);
3747 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
3748 REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
3750 if (!options->Socks5ProxyPassword)
3751 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3753 len = strlen(options->Socks5ProxyPassword);
3754 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
3755 REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
3756 } else if (options->Socks5ProxyPassword)
3757 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3759 if (options->HashedControlPassword) {
3760 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3761 if (!sl) {
3762 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3763 } else {
3764 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3765 smartlist_free(sl);
3769 if (options->HashedControlSessionPassword) {
3770 smartlist_t *sl = decode_hashed_passwords(
3771 options->HashedControlSessionPassword);
3772 if (!sl) {
3773 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3774 } else {
3775 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3776 smartlist_free(sl);
3780 if (options->OwningControllerProcess) {
3781 const char *validate_pspec_msg = NULL;
3782 if (tor_validate_process_specifier(options->OwningControllerProcess,
3783 &validate_pspec_msg)) {
3784 tor_asprintf(msg, "Bad OwningControllerProcess: %s",
3785 validate_pspec_msg);
3786 return -1;
3790 if ((options->ControlPort_set || world_writable_control_socket) &&
3791 !options->HashedControlPassword &&
3792 !options->HashedControlSessionPassword &&
3793 !options->CookieAuthentication) {
3794 log_warn(LD_CONFIG, "Control%s is %s, but no authentication method "
3795 "has been configured. This means that any program on your "
3796 "computer can reconfigure your Tor. That's bad! You should "
3797 "upgrade your Tor controller as soon as possible.",
3798 options->ControlPort_set ? "Port" : "Socket",
3799 options->ControlPort_set ? "open" : "world writable");
3802 if (options->CookieAuthFileGroupReadable && !options->CookieAuthFile) {
3803 log_warn(LD_CONFIG, "CookieAuthFileGroupReadable is set, but will have "
3804 "no effect: you must specify an explicit CookieAuthFile to "
3805 "have it group-readable.");
3808 if (options->MyFamily && options->BridgeRelay) {
3809 log_warn(LD_CONFIG, "Listing a family for a bridge relay is not "
3810 "supported: it can reveal bridge fingerprints to censors. "
3811 "You should also make sure you aren't listing this bridge's "
3812 "fingerprint in any other MyFamily.");
3814 if (check_nickname_list(&options->MyFamily, "MyFamily", msg))
3815 return -1;
3816 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3817 routerset_t *rs = routerset_new();
3818 if (routerset_parse(rs, cl->value, cl->key)) {
3819 routerset_free(rs);
3820 return -1;
3822 routerset_free(rs);
3825 if (validate_addr_policies(options, msg) < 0)
3826 return -1;
3828 /* If FallbackDir is set, we don't UseDefaultFallbackDirs */
3829 if (options->UseDefaultFallbackDirs && options->FallbackDir) {
3830 log_info(LD_CONFIG, "You have set UseDefaultFallbackDirs 1 and "
3831 "FallbackDir(s). Ignoring UseDefaultFallbackDirs, and "
3832 "using the FallbackDir(s) you have set.");
3835 if (validate_dir_servers(options, old_options) < 0)
3836 REJECT("Directory authority/fallback line did not parse. See logs "
3837 "for details.");
3839 if (options->UseBridges && !options->Bridges)
3840 REJECT("If you set UseBridges, you must specify at least one bridge.");
3842 for (cl = options->Bridges; cl; cl = cl->next) {
3843 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
3844 if (!bridge_line)
3845 REJECT("Bridge line did not parse. See logs for details.");
3846 bridge_line_free(bridge_line);
3849 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
3850 if (parse_transport_line(options, cl->value, 1, 0) < 0)
3851 REJECT("Invalid client transport line. See logs for details.");
3854 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
3855 if (parse_transport_line(options, cl->value, 1, 1) < 0)
3856 REJECT("Invalid server transport line. See logs for details.");
3859 if (options->ServerTransportPlugin && !server_mode(options)) {
3860 log_notice(LD_GENERAL, "Tor is not configured as a relay but you specified"
3861 " a ServerTransportPlugin line (%s). The ServerTransportPlugin "
3862 "line will be ignored.",
3863 escaped(options->ServerTransportPlugin->value));
3866 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
3867 /** If get_bindaddr_from_transport_listen_line() fails with
3868 'transport' being NULL, it means that something went wrong
3869 while parsing the ServerTransportListenAddr line. */
3870 char *bindaddr = get_bindaddr_from_transport_listen_line(cl->value, NULL);
3871 if (!bindaddr)
3872 REJECT("ServerTransportListenAddr did not parse. See logs for details.");
3873 tor_free(bindaddr);
3876 if (options->ServerTransportListenAddr && !options->ServerTransportPlugin) {
3877 log_notice(LD_GENERAL, "You need at least a single managed-proxy to "
3878 "specify a transport listen address. The "
3879 "ServerTransportListenAddr line will be ignored.");
3882 for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
3883 /** If get_options_from_transport_options_line() fails with
3884 'transport' being NULL, it means that something went wrong
3885 while parsing the ServerTransportOptions line. */
3886 smartlist_t *options_sl =
3887 get_options_from_transport_options_line(cl->value, NULL);
3888 if (!options_sl)
3889 REJECT("ServerTransportOptions did not parse. See logs for details.");
3891 SMARTLIST_FOREACH(options_sl, char *, cp, tor_free(cp));
3892 smartlist_free(options_sl);
3895 if (options->ConstrainedSockets) {
3896 /* If the user wants to constrain socket buffer use, make sure the desired
3897 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3898 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3899 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3900 options->ConstrainedSockSize % 1024) {
3901 tor_asprintf(msg,
3902 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3903 "in 1024 byte increments.",
3904 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3905 return -1;
3907 if (options->DirPort_set) {
3908 /* Providing cached directory entries while system TCP buffers are scarce
3909 * will exacerbate the socket errors. Suggest that this be disabled. */
3910 COMPLAIN("You have requested constrained socket buffers while also "
3911 "serving directory entries via DirPort. It is strongly "
3912 "suggested that you disable serving directory requests when "
3913 "system TCP buffer resources are scarce.");
3917 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3918 options->V3AuthVotingInterval/2) {
3920 This doesn't work, but it seems like it should:
3921 what code is preventing the interval being less than twice the lead-up?
3922 if (options->TestingTorNetwork) {
3923 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3924 options->V3AuthVotingInterval) {
3925 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than "
3926 "V3AuthVotingInterval");
3927 } else {
3928 COMPLAIN("V3AuthVoteDelay plus V3AuthDistDelay is more than half "
3929 "V3AuthVotingInterval. This may lead to "
3930 "consensus instability, particularly if clocks drift.");
3932 } else {
3934 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3935 "V3AuthVotingInterval");
3941 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS) {
3942 if (options->TestingTorNetwork) {
3943 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS_TESTING) {
3944 REJECT("V3AuthVoteDelay is way too low.");
3945 } else {
3946 COMPLAIN("V3AuthVoteDelay is very low. "
3947 "This may lead to failure to vote for a consensus.");
3949 } else {
3950 REJECT("V3AuthVoteDelay is way too low.");
3954 if (options->V3AuthDistDelay < MIN_DIST_SECONDS) {
3955 if (options->TestingTorNetwork) {
3956 if (options->V3AuthDistDelay < MIN_DIST_SECONDS_TESTING) {
3957 REJECT("V3AuthDistDelay is way too low.");
3958 } else {
3959 COMPLAIN("V3AuthDistDelay is very low. "
3960 "This may lead to missing votes in a consensus.");
3962 } else {
3963 REJECT("V3AuthDistDelay is way too low.");
3967 if (options->V3AuthNIntervalsValid < 2)
3968 REJECT("V3AuthNIntervalsValid must be at least 2.");
3970 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3971 if (options->TestingTorNetwork) {
3972 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL_TESTING) {
3973 REJECT("V3AuthVotingInterval is insanely low.");
3974 } else {
3975 COMPLAIN("V3AuthVotingInterval is very low. "
3976 "This may lead to failure to synchronise for a consensus.");
3978 } else {
3979 REJECT("V3AuthVotingInterval is insanely low.");
3981 } else if (options->V3AuthVotingInterval > 24*60*60) {
3982 REJECT("V3AuthVotingInterval is insanely high.");
3983 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3984 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3987 if (rend_config_services(options, 1) < 0)
3988 REJECT("Failed to configure rendezvous options. See logs for details.");
3990 /* Parse client-side authorization for hidden services. */
3991 if (rend_parse_service_authorization(options, 1) < 0)
3992 REJECT("Failed to configure client authorization for hidden services. "
3993 "See logs for details.");
3995 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv4,
3996 AF_INET, 1, msg)<0)
3997 return -1;
3998 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv6,
3999 AF_INET6, 1, msg)<0)
4000 return -1;
4002 if (options->TestingTorNetwork &&
4003 !(options->DirAuthorities ||
4004 (options->AlternateDirAuthority &&
4005 options->AlternateBridgeAuthority))) {
4006 REJECT("TestingTorNetwork may only be configured in combination with "
4007 "a non-default set of DirAuthority or both of "
4008 "AlternateDirAuthority and AlternateBridgeAuthority configured.");
4011 if (options->AllowSingleHopExits && !options->DirAuthorities) {
4012 COMPLAIN("You have set AllowSingleHopExits; now your relay will allow "
4013 "others to make one-hop exits. However, since by default most "
4014 "clients avoid relays that set this option, most clients will "
4015 "ignore you.");
4018 #define CHECK_DEFAULT(arg) \
4019 STMT_BEGIN \
4020 if (!options->TestingTorNetwork && \
4021 !options->UsingTestNetworkDefaults_ && \
4022 !config_is_same(&options_format,options, \
4023 default_options,#arg)) { \
4024 REJECT(#arg " may only be changed in testing Tor " \
4025 "networks!"); \
4026 } STMT_END
4027 CHECK_DEFAULT(TestingV3AuthInitialVotingInterval);
4028 CHECK_DEFAULT(TestingV3AuthInitialVoteDelay);
4029 CHECK_DEFAULT(TestingV3AuthInitialDistDelay);
4030 CHECK_DEFAULT(TestingV3AuthVotingStartOffset);
4031 CHECK_DEFAULT(TestingAuthDirTimeToLearnReachability);
4032 CHECK_DEFAULT(TestingEstimatedDescriptorPropagationTime);
4033 CHECK_DEFAULT(TestingServerDownloadSchedule);
4034 CHECK_DEFAULT(TestingClientDownloadSchedule);
4035 CHECK_DEFAULT(TestingServerConsensusDownloadSchedule);
4036 CHECK_DEFAULT(TestingClientConsensusDownloadSchedule);
4037 CHECK_DEFAULT(TestingBridgeDownloadSchedule);
4038 CHECK_DEFAULT(TestingClientMaxIntervalWithoutRequest);
4039 CHECK_DEFAULT(TestingDirConnectionMaxStall);
4040 CHECK_DEFAULT(TestingConsensusMaxDownloadTries);
4041 CHECK_DEFAULT(TestingDescriptorMaxDownloadTries);
4042 CHECK_DEFAULT(TestingMicrodescMaxDownloadTries);
4043 CHECK_DEFAULT(TestingCertMaxDownloadTries);
4044 CHECK_DEFAULT(TestingAuthKeyLifetime);
4045 CHECK_DEFAULT(TestingLinkCertLifetime);
4046 CHECK_DEFAULT(TestingSigningKeySlop);
4047 CHECK_DEFAULT(TestingAuthKeySlop);
4048 CHECK_DEFAULT(TestingLinkKeySlop);
4049 #undef CHECK_DEFAULT
4051 if (options->SigningKeyLifetime < options->TestingSigningKeySlop*2)
4052 REJECT("SigningKeyLifetime is too short.");
4053 if (options->TestingLinkCertLifetime < options->TestingAuthKeySlop*2)
4054 REJECT("LinkCertLifetime is too short.");
4055 if (options->TestingAuthKeyLifetime < options->TestingLinkKeySlop*2)
4056 REJECT("TestingAuthKeyLifetime is too short.");
4058 if (options->TestingV3AuthInitialVotingInterval
4059 < MIN_VOTE_INTERVAL_TESTING_INITIAL) {
4060 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
4061 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
4062 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
4063 "30 minutes.");
4066 if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS_TESTING) {
4067 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
4070 if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS_TESTING) {
4071 REJECT("TestingV3AuthInitialDistDelay is way too low.");
4074 if (options->TestingV3AuthInitialVoteDelay +
4075 options->TestingV3AuthInitialDistDelay >=
4076 options->TestingV3AuthInitialVotingInterval) {
4077 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
4078 "must be less than TestingV3AuthInitialVotingInterval");
4081 if (options->TestingV3AuthVotingStartOffset >
4082 MIN(options->TestingV3AuthInitialVotingInterval,
4083 options->V3AuthVotingInterval)) {
4084 REJECT("TestingV3AuthVotingStartOffset is higher than the voting "
4085 "interval.");
4086 } else if (options->TestingV3AuthVotingStartOffset < 0) {
4087 REJECT("TestingV3AuthVotingStartOffset must be non-negative.");
4090 if (options->TestingAuthDirTimeToLearnReachability < 0) {
4091 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
4092 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
4093 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
4096 if (options->TestingEstimatedDescriptorPropagationTime < 0) {
4097 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
4098 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
4099 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
4102 if (options->TestingClientMaxIntervalWithoutRequest < 1) {
4103 REJECT("TestingClientMaxIntervalWithoutRequest is way too low.");
4104 } else if (options->TestingClientMaxIntervalWithoutRequest > 3600) {
4105 COMPLAIN("TestingClientMaxIntervalWithoutRequest is insanely high.");
4108 if (options->TestingDirConnectionMaxStall < 5) {
4109 REJECT("TestingDirConnectionMaxStall is way too low.");
4110 } else if (options->TestingDirConnectionMaxStall > 3600) {
4111 COMPLAIN("TestingDirConnectionMaxStall is insanely high.");
4114 if (options->TestingConsensusMaxDownloadTries < 2) {
4115 REJECT("TestingConsensusMaxDownloadTries must be greater than 2.");
4116 } else if (options->TestingConsensusMaxDownloadTries > 800) {
4117 COMPLAIN("TestingConsensusMaxDownloadTries is insanely high.");
4120 if (options->ClientBootstrapConsensusMaxDownloadTries < 2) {
4121 REJECT("ClientBootstrapConsensusMaxDownloadTries must be greater "
4122 "than 2."
4124 } else if (options->ClientBootstrapConsensusMaxDownloadTries > 800) {
4125 COMPLAIN("ClientBootstrapConsensusMaxDownloadTries is insanely "
4126 "high.");
4129 if (options->ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries
4130 < 2) {
4131 REJECT("ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries must "
4132 "be greater than 2."
4134 } else if (
4135 options->ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries
4136 > 800) {
4137 COMPLAIN("ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries is "
4138 "insanely high.");
4141 if (options->ClientBootstrapConsensusMaxInProgressTries < 1) {
4142 REJECT("ClientBootstrapConsensusMaxInProgressTries must be greater "
4143 "than 0.");
4144 } else if (options->ClientBootstrapConsensusMaxInProgressTries
4145 > 100) {
4146 COMPLAIN("ClientBootstrapConsensusMaxInProgressTries is insanely "
4147 "high.");
4150 if (options->TestingDescriptorMaxDownloadTries < 2) {
4151 REJECT("TestingDescriptorMaxDownloadTries must be greater than 1.");
4152 } else if (options->TestingDescriptorMaxDownloadTries > 800) {
4153 COMPLAIN("TestingDescriptorMaxDownloadTries is insanely high.");
4156 if (options->TestingMicrodescMaxDownloadTries < 2) {
4157 REJECT("TestingMicrodescMaxDownloadTries must be greater than 1.");
4158 } else if (options->TestingMicrodescMaxDownloadTries > 800) {
4159 COMPLAIN("TestingMicrodescMaxDownloadTries is insanely high.");
4162 if (options->TestingCertMaxDownloadTries < 2) {
4163 REJECT("TestingCertMaxDownloadTries must be greater than 1.");
4164 } else if (options->TestingCertMaxDownloadTries > 800) {
4165 COMPLAIN("TestingCertMaxDownloadTries is insanely high.");
4168 if (options->TestingEnableConnBwEvent &&
4169 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4170 REJECT("TestingEnableConnBwEvent may only be changed in testing "
4171 "Tor networks!");
4174 if (options->TestingEnableCellStatsEvent &&
4175 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4176 REJECT("TestingEnableCellStatsEvent may only be changed in testing "
4177 "Tor networks!");
4180 if (options->TestingEnableTbEmptyEvent &&
4181 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4182 REJECT("TestingEnableTbEmptyEvent may only be changed in testing "
4183 "Tor networks!");
4186 if (options->TestingTorNetwork) {
4187 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
4188 "almost unusable in the public Tor network, and is "
4189 "therefore only advised if you are building a "
4190 "testing Tor network!");
4193 if (options->AccelName && !options->HardwareAccel)
4194 options->HardwareAccel = 1;
4195 if (options->AccelDir && !options->AccelName)
4196 REJECT("Can't use hardware crypto accelerator dir without engine name.");
4198 if (options->PublishServerDescriptor)
4199 SMARTLIST_FOREACH(options->PublishServerDescriptor, const char *, pubdes, {
4200 if (!strcmp(pubdes, "1") || !strcmp(pubdes, "0"))
4201 if (smartlist_len(options->PublishServerDescriptor) > 1) {
4202 COMPLAIN("You have passed a list of multiple arguments to the "
4203 "PublishServerDescriptor option that includes 0 or 1. "
4204 "0 or 1 should only be used as the sole argument. "
4205 "This configuration will be rejected in a future release.");
4206 break;
4210 if (options->BridgeRelay == 1 && ! options->ORPort_set)
4211 REJECT("BridgeRelay is 1, ORPort is not set. This is an invalid "
4212 "combination.");
4214 return 0;
4217 #undef REJECT
4218 #undef COMPLAIN
4220 /* Given the value that the user has set for MaxMemInQueues, compute the
4221 * actual maximum value. We clip this value if it's too low, and autodetect
4222 * it if it's set to 0. */
4223 static uint64_t
4224 compute_real_max_mem_in_queues(const uint64_t val, int log_guess)
4226 uint64_t result;
4228 if (val == 0) {
4229 #define ONE_GIGABYTE (U64_LITERAL(1) << 30)
4230 #define ONE_MEGABYTE (U64_LITERAL(1) << 20)
4231 #if SIZEOF_VOID_P >= 8
4232 #define MAX_DEFAULT_MAXMEM (8*ONE_GIGABYTE)
4233 #else
4234 #define MAX_DEFAULT_MAXMEM (2*ONE_GIGABYTE)
4235 #endif
4236 /* The user didn't pick a memory limit. Choose a very large one
4237 * that is still smaller than the system memory */
4238 static int notice_sent = 0;
4239 size_t ram = 0;
4240 if (get_total_system_memory(&ram) < 0) {
4241 /* We couldn't determine our total system memory! */
4242 #if SIZEOF_VOID_P >= 8
4243 /* 64-bit system. Let's hope for 8 GB. */
4244 result = 8 * ONE_GIGABYTE;
4245 #else
4246 /* (presumably) 32-bit system. Let's hope for 1 GB. */
4247 result = ONE_GIGABYTE;
4248 #endif
4249 } else {
4250 /* We detected it, so let's pick 3/4 of the total RAM as our limit. */
4251 const uint64_t avail = (ram / 4) * 3;
4253 /* Make sure it's in range from 0.25 GB to 8 GB. */
4254 if (avail > MAX_DEFAULT_MAXMEM) {
4255 /* If you want to use more than this much RAM, you need to configure
4256 it yourself */
4257 result = MAX_DEFAULT_MAXMEM;
4258 } else if (avail < ONE_GIGABYTE / 4) {
4259 result = ONE_GIGABYTE / 4;
4260 } else {
4261 result = avail;
4264 if (log_guess && ! notice_sent) {
4265 log_notice(LD_CONFIG, "%sMaxMemInQueues is set to "U64_FORMAT" MB. "
4266 "You can override this by setting MaxMemInQueues by hand.",
4267 ram ? "Based on detected system memory, " : "",
4268 U64_PRINTF_ARG(result / ONE_MEGABYTE));
4269 notice_sent = 1;
4271 return result;
4272 } else if (val < ONE_GIGABYTE / 4) {
4273 log_warn(LD_CONFIG, "MaxMemInQueues must be at least 256 MB for now. "
4274 "Ideally, have it as large as you can afford.");
4275 return ONE_GIGABYTE / 4;
4276 } else {
4277 /* The value was fine all along */
4278 return val;
4282 /* If we have less than 300 MB suggest disabling dircache */
4283 #define DIRCACHE_MIN_MB_BANDWIDTH 300
4284 #define DIRCACHE_MIN_BANDWIDTH (DIRCACHE_MIN_MB_BANDWIDTH*ONE_MEGABYTE)
4285 #define STRINGIFY(val) #val
4287 /** Create a warning message for emitting if we are a dircache but may not have
4288 * enough system memory, or if we are not a dircache but probably should be.
4289 * Return -1 when a message is returned in *msg*, else return 0. */
4290 STATIC int
4291 have_enough_mem_for_dircache(const or_options_t *options, size_t total_mem,
4292 char **msg)
4294 *msg = NULL;
4295 /* XXX We should possibly be looking at MaxMemInQueues here
4296 * unconditionally. Or we should believe total_mem unconditionally. */
4297 if (total_mem == 0) {
4298 if (get_total_system_memory(&total_mem) < 0) {
4299 total_mem = options->MaxMemInQueues >= SIZE_MAX ?
4300 SIZE_MAX : (size_t)options->MaxMemInQueues;
4303 if (options->DirCache) {
4304 if (total_mem < DIRCACHE_MIN_BANDWIDTH) {
4305 if (options->BridgeRelay) {
4306 *msg = tor_strdup("Running a Bridge with less than "
4307 STRINGIFY(DIRCACHE_MIN_MB_BANDWIDTH) " MB of memory is "
4308 "not recommended.");
4309 } else {
4310 *msg = tor_strdup("Being a directory cache (default) with less than "
4311 STRINGIFY(DIRCACHE_MIN_MB_BANDWIDTH) " MB of memory is "
4312 "not recommended and may consume most of the available "
4313 "resources, consider disabling this functionality by "
4314 "setting the DirCache option to 0.");
4317 } else {
4318 if (total_mem >= DIRCACHE_MIN_BANDWIDTH) {
4319 *msg = tor_strdup("DirCache is disabled and we are configured as a "
4320 "relay. This may disqualify us from becoming a guard in the "
4321 "future.");
4324 return *msg == NULL ? 0 : -1;
4326 #undef STRINGIFY
4328 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
4329 * equal strings. */
4330 static int
4331 opt_streq(const char *s1, const char *s2)
4333 return 0 == strcmp_opt(s1, s2);
4336 /** Check if any of the previous options have changed but aren't allowed to. */
4337 static int
4338 options_transition_allowed(const or_options_t *old,
4339 const or_options_t *new_val,
4340 char **msg)
4342 if (!old)
4343 return 0;
4345 if (!opt_streq(old->PidFile, new_val->PidFile)) {
4346 *msg = tor_strdup("PidFile is not allowed to change.");
4347 return -1;
4350 if (old->RunAsDaemon != new_val->RunAsDaemon) {
4351 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
4352 "is not allowed.");
4353 return -1;
4356 if (old->Sandbox != new_val->Sandbox) {
4357 *msg = tor_strdup("While Tor is running, changing Sandbox "
4358 "is not allowed.");
4359 return -1;
4362 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
4363 tor_asprintf(msg,
4364 "While Tor is running, changing DataDirectory "
4365 "(\"%s\"->\"%s\") is not allowed.",
4366 old->DataDirectory, new_val->DataDirectory);
4367 return -1;
4370 if (!opt_streq(old->User, new_val->User)) {
4371 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
4372 return -1;
4375 if (old->KeepBindCapabilities != new_val->KeepBindCapabilities) {
4376 *msg = tor_strdup("While Tor is running, changing KeepBindCapabilities is "
4377 "not allowed.");
4378 return -1;
4381 if (!opt_streq(old->SyslogIdentityTag, new_val->SyslogIdentityTag)) {
4382 *msg = tor_strdup("While Tor is running, changing "
4383 "SyslogIdentityTag is not allowed.");
4384 return -1;
4387 if ((old->HardwareAccel != new_val->HardwareAccel)
4388 || !opt_streq(old->AccelName, new_val->AccelName)
4389 || !opt_streq(old->AccelDir, new_val->AccelDir)) {
4390 *msg = tor_strdup("While Tor is running, changing OpenSSL hardware "
4391 "acceleration engine is not allowed.");
4392 return -1;
4395 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
4396 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
4397 "is not allowed.");
4398 return -1;
4401 if (old->DisableAllSwap != new_val->DisableAllSwap) {
4402 *msg = tor_strdup("While Tor is running, changing DisableAllSwap "
4403 "is not allowed.");
4404 return -1;
4407 if (old->TokenBucketRefillInterval != new_val->TokenBucketRefillInterval) {
4408 *msg = tor_strdup("While Tor is running, changing TokenBucketRefill"
4409 "Interval is not allowed");
4410 return -1;
4413 if (old->OnionServiceSingleHopMode != new_val->OnionServiceSingleHopMode) {
4414 *msg = tor_strdup("While Tor is running, changing "
4415 "OnionServiceSingleHopMode is not allowed.");
4416 return -1;
4419 if (old->OnionServiceNonAnonymousMode !=
4420 new_val->OnionServiceNonAnonymousMode) {
4421 *msg = tor_strdup("While Tor is running, changing "
4422 "OnionServiceNonAnonymousMode is not allowed.");
4423 return -1;
4426 if (old->DisableDebuggerAttachment &&
4427 !new_val->DisableDebuggerAttachment) {
4428 *msg = tor_strdup("While Tor is running, disabling "
4429 "DisableDebuggerAttachment is not allowed.");
4430 return -1;
4433 if (sandbox_is_active()) {
4434 #define SB_NOCHANGE_STR(opt) \
4435 do { \
4436 if (! opt_streq(old->opt, new_val->opt)) { \
4437 *msg = tor_strdup("Can't change " #opt " while Sandbox is active"); \
4438 return -1; \
4440 } while (0)
4442 SB_NOCHANGE_STR(Address);
4443 SB_NOCHANGE_STR(PidFile);
4444 SB_NOCHANGE_STR(ServerDNSResolvConfFile);
4445 SB_NOCHANGE_STR(DirPortFrontPage);
4446 SB_NOCHANGE_STR(CookieAuthFile);
4447 SB_NOCHANGE_STR(ExtORPortCookieAuthFile);
4449 #undef SB_NOCHANGE_STR
4451 if (! config_lines_eq(old->Logs, new_val->Logs)) {
4452 *msg = tor_strdup("Can't change Logs while Sandbox is active");
4453 return -1;
4455 if (old->ConnLimit != new_val->ConnLimit) {
4456 *msg = tor_strdup("Can't change ConnLimit while Sandbox is active");
4457 return -1;
4459 if (server_mode(old) != server_mode(new_val)) {
4460 *msg = tor_strdup("Can't start/stop being a server while "
4461 "Sandbox is active");
4462 return -1;
4466 return 0;
4469 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
4470 * will require us to rotate the CPU and DNS workers; else return 0. */
4471 static int
4472 options_transition_affects_workers(const or_options_t *old_options,
4473 const or_options_t *new_options)
4475 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
4476 old_options->NumCPUs != new_options->NumCPUs ||
4477 !config_lines_eq(old_options->ORPort_lines, new_options->ORPort_lines) ||
4478 old_options->ServerDNSSearchDomains !=
4479 new_options->ServerDNSSearchDomains ||
4480 old_options->SafeLogging_ != new_options->SafeLogging_ ||
4481 old_options->ClientOnly != new_options->ClientOnly ||
4482 public_server_mode(old_options) != public_server_mode(new_options) ||
4483 !config_lines_eq(old_options->Logs, new_options->Logs) ||
4484 old_options->LogMessageDomains != new_options->LogMessageDomains)
4485 return 1;
4487 /* Check whether log options match. */
4489 /* Nothing that changed matters. */
4490 return 0;
4493 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
4494 * will require us to generate a new descriptor; else return 0. */
4495 static int
4496 options_transition_affects_descriptor(const or_options_t *old_options,
4497 const or_options_t *new_options)
4499 /* XXX We can be smarter here. If your DirPort isn't being
4500 * published and you just turned it off, no need to republish. Etc. */
4501 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
4502 !opt_streq(old_options->Nickname,new_options->Nickname) ||
4503 !opt_streq(old_options->Address,new_options->Address) ||
4504 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
4505 old_options->ExitRelay != new_options->ExitRelay ||
4506 old_options->ExitPolicyRejectPrivate !=
4507 new_options->ExitPolicyRejectPrivate ||
4508 old_options->ExitPolicyRejectLocalInterfaces !=
4509 new_options->ExitPolicyRejectLocalInterfaces ||
4510 old_options->IPv6Exit != new_options->IPv6Exit ||
4511 !config_lines_eq(old_options->ORPort_lines,
4512 new_options->ORPort_lines) ||
4513 !config_lines_eq(old_options->DirPort_lines,
4514 new_options->DirPort_lines) ||
4515 old_options->ClientOnly != new_options->ClientOnly ||
4516 old_options->DisableNetwork != new_options->DisableNetwork ||
4517 old_options->PublishServerDescriptor_ !=
4518 new_options->PublishServerDescriptor_ ||
4519 get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
4520 get_effective_bwburst(old_options) !=
4521 get_effective_bwburst(new_options) ||
4522 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
4523 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
4524 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
4525 old_options->AccountingMax != new_options->AccountingMax ||
4526 old_options->AccountingRule != new_options->AccountingRule ||
4527 public_server_mode(old_options) != public_server_mode(new_options) ||
4528 old_options->DirCache != new_options->DirCache ||
4529 old_options->AssumeReachable != new_options->AssumeReachable)
4530 return 1;
4532 return 0;
4535 #ifdef _WIN32
4536 /** Return the directory on windows where we expect to find our application
4537 * data. */
4538 static char *
4539 get_windows_conf_root(void)
4541 static int is_set = 0;
4542 static char path[MAX_PATH*2+1];
4543 TCHAR tpath[MAX_PATH] = {0};
4545 LPITEMIDLIST idl;
4546 IMalloc *m;
4547 HRESULT result;
4549 if (is_set)
4550 return path;
4552 /* Find X:\documents and settings\username\application data\ .
4553 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
4555 #ifdef ENABLE_LOCAL_APPDATA
4556 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
4557 #else
4558 #define APPDATA_PATH CSIDL_APPDATA
4559 #endif
4560 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
4561 getcwd(path,MAX_PATH);
4562 is_set = 1;
4563 log_warn(LD_CONFIG,
4564 "I couldn't find your application data folder: are you "
4565 "running an ancient version of Windows 95? Defaulting to \"%s\"",
4566 path);
4567 return path;
4569 /* Convert the path from an "ID List" (whatever that is!) to a path. */
4570 result = SHGetPathFromIDList(idl, tpath);
4571 #ifdef UNICODE
4572 wcstombs(path,tpath,sizeof(path));
4573 path[sizeof(path)-1] = '\0';
4574 #else
4575 strlcpy(path,tpath,sizeof(path));
4576 #endif
4578 /* Now we need to free the memory that the path-idl was stored in. In
4579 * typical Windows fashion, we can't just call 'free()' on it. */
4580 SHGetMalloc(&m);
4581 if (m) {
4582 m->lpVtbl->Free(m, idl);
4583 m->lpVtbl->Release(m);
4585 if (!SUCCEEDED(result)) {
4586 return NULL;
4588 strlcat(path,"\\tor",MAX_PATH);
4589 is_set = 1;
4590 return path;
4592 #endif
4594 /** Return the default location for our torrc file (if <b>defaults_file</b> is
4595 * false), or for the torrc-defaults file (if <b>defaults_file</b> is true). */
4596 static const char *
4597 get_default_conf_file(int defaults_file)
4599 #ifdef DISABLE_SYSTEM_TORRC
4600 (void) defaults_file;
4601 return NULL;
4602 #elif defined(_WIN32)
4603 if (defaults_file) {
4604 static char defaults_path[MAX_PATH+1];
4605 tor_snprintf(defaults_path, MAX_PATH, "%s\\torrc-defaults",
4606 get_windows_conf_root());
4607 return defaults_path;
4608 } else {
4609 static char path[MAX_PATH+1];
4610 tor_snprintf(path, MAX_PATH, "%s\\torrc",
4611 get_windows_conf_root());
4612 return path;
4614 #else
4615 return defaults_file ? CONFDIR "/torrc-defaults" : CONFDIR "/torrc";
4616 #endif
4619 /** Verify whether lst is a string containing valid-looking comma-separated
4620 * nicknames, or NULL. Will normalise <b>lst</b> to prefix '$' to any nickname
4621 * or fingerprint that needs it. Return 0 on success.
4622 * Warn and return -1 on failure.
4624 static int
4625 check_nickname_list(char **lst, const char *name, char **msg)
4627 int r = 0;
4628 smartlist_t *sl;
4629 int changes = 0;
4631 if (!*lst)
4632 return 0;
4633 sl = smartlist_new();
4635 smartlist_split_string(sl, *lst, ",",
4636 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
4638 SMARTLIST_FOREACH_BEGIN(sl, char *, s)
4640 if (!is_legal_nickname_or_hexdigest(s)) {
4641 // check if first char is dollar
4642 if (s[0] != '$') {
4643 // Try again but with a dollar symbol prepended
4644 char *prepended;
4645 tor_asprintf(&prepended, "$%s", s);
4647 if (is_legal_nickname_or_hexdigest(prepended)) {
4648 // The nickname is valid when it's prepended, swap the current
4649 // version with a prepended one
4650 tor_free(s);
4651 SMARTLIST_REPLACE_CURRENT(sl, s, prepended);
4652 changes = 1;
4653 continue;
4656 // Still not valid, free and fallback to error message
4657 tor_free(prepended);
4660 tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
4661 r = -1;
4662 break;
4665 SMARTLIST_FOREACH_END(s);
4667 // Replace the caller's nickname list with a fixed one
4668 if (changes && r == 0) {
4669 char *newNicknames = smartlist_join_strings(sl, ", ", 0, NULL);
4670 tor_free(*lst);
4671 *lst = newNicknames;
4674 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
4675 smartlist_free(sl);
4677 return r;
4680 /** Learn config file name from command line arguments, or use the default.
4682 * If <b>defaults_file</b> is true, we're looking for torrc-defaults;
4683 * otherwise, we're looking for the regular torrc_file.
4685 * Set *<b>using_default_fname</b> to true if we're using the default
4686 * configuration file name; or false if we've set it from the command line.
4688 * Set *<b>ignore_missing_torrc</b> to true if we should ignore the resulting
4689 * filename if it doesn't exist.
4691 static char *
4692 find_torrc_filename(config_line_t *cmd_arg,
4693 int defaults_file,
4694 int *using_default_fname, int *ignore_missing_torrc)
4696 char *fname=NULL;
4697 config_line_t *p_index;
4698 const char *fname_opt = defaults_file ? "--defaults-torrc" : "-f";
4699 const char *ignore_opt = defaults_file ? NULL : "--ignore-missing-torrc";
4701 if (defaults_file)
4702 *ignore_missing_torrc = 1;
4704 for (p_index = cmd_arg; p_index; p_index = p_index->next) {
4705 if (!strcmp(p_index->key, fname_opt)) {
4706 if (fname) {
4707 log_warn(LD_CONFIG, "Duplicate %s options on command line.",
4708 fname_opt);
4709 tor_free(fname);
4711 fname = expand_filename(p_index->value);
4714 char *absfname;
4715 absfname = make_path_absolute(fname);
4716 tor_free(fname);
4717 fname = absfname;
4720 *using_default_fname = 0;
4721 } else if (ignore_opt && !strcmp(p_index->key,ignore_opt)) {
4722 *ignore_missing_torrc = 1;
4726 if (*using_default_fname) {
4727 /* didn't find one, try CONFDIR */
4728 const char *dflt = get_default_conf_file(defaults_file);
4729 file_status_t st = file_status(dflt);
4730 if (dflt && (st == FN_FILE || st == FN_EMPTY)) {
4731 fname = tor_strdup(dflt);
4732 } else {
4733 #ifndef _WIN32
4734 char *fn = NULL;
4735 if (!defaults_file) {
4736 fn = expand_filename("~/.torrc");
4738 if (fn) {
4739 file_status_t hmst = file_status(fn);
4740 if (hmst == FN_FILE || hmst == FN_EMPTY || dflt == NULL) {
4741 fname = fn;
4742 } else {
4743 tor_free(fn);
4744 fname = tor_strdup(dflt);
4746 } else {
4747 fname = dflt ? tor_strdup(dflt) : NULL;
4749 #else
4750 fname = dflt ? tor_strdup(dflt) : NULL;
4751 #endif
4754 return fname;
4757 /** Read the torrc from standard input and return it as a string.
4758 * Upon failure, return NULL.
4760 static char *
4761 load_torrc_from_stdin(void)
4763 size_t sz_out;
4765 return read_file_to_str_until_eof(STDIN_FILENO,SIZE_MAX,&sz_out);
4768 /** Load a configuration file from disk, setting torrc_fname or
4769 * torrc_defaults_fname if successful.
4771 * If <b>defaults_file</b> is true, load torrc-defaults; otherwise load torrc.
4773 * Return the contents of the file on success, and NULL on failure.
4775 static char *
4776 load_torrc_from_disk(config_line_t *cmd_arg, int defaults_file)
4778 char *fname=NULL;
4779 char *cf = NULL;
4780 int using_default_torrc = 1;
4781 int ignore_missing_torrc = 0;
4782 char **fname_var = defaults_file ? &torrc_defaults_fname : &torrc_fname;
4784 if (*fname_var == NULL) {
4785 fname = find_torrc_filename(cmd_arg, defaults_file,
4786 &using_default_torrc, &ignore_missing_torrc);
4787 tor_free(*fname_var);
4788 *fname_var = fname;
4789 } else {
4790 fname = *fname_var;
4792 log_debug(LD_CONFIG, "Opening config file \"%s\"", fname?fname:"<NULL>");
4794 /* Open config file */
4795 file_status_t st = fname ? file_status(fname) : FN_EMPTY;
4796 if (fname == NULL ||
4797 !(st == FN_FILE || st == FN_EMPTY) ||
4798 !(cf = read_file_to_str(fname,0,NULL))) {
4799 if (using_default_torrc == 1 || ignore_missing_torrc) {
4800 if (!defaults_file)
4801 log_notice(LD_CONFIG, "Configuration file \"%s\" not present, "
4802 "using reasonable defaults.", fname);
4803 tor_free(fname); /* sets fname to NULL */
4804 *fname_var = NULL;
4805 cf = tor_strdup("");
4806 } else {
4807 log_warn(LD_CONFIG,
4808 "Unable to open configuration file \"%s\".", fname);
4809 goto err;
4811 } else {
4812 log_notice(LD_CONFIG, "Read configuration file \"%s\".", fname);
4815 return cf;
4816 err:
4817 tor_free(fname);
4818 *fname_var = NULL;
4819 return NULL;
4822 /** Read a configuration file into <b>options</b>, finding the configuration
4823 * file location based on the command line. After loading the file
4824 * call options_init_from_string() to load the config.
4825 * Return 0 if success, -1 if failure. */
4827 options_init_from_torrc(int argc, char **argv)
4829 char *cf=NULL, *cf_defaults=NULL;
4830 int command;
4831 int retval = -1;
4832 char *command_arg = NULL;
4833 char *errmsg=NULL;
4834 config_line_t *p_index = NULL;
4835 config_line_t *cmdline_only_options = NULL;
4837 /* Go through command-line variables */
4838 if (! have_parsed_cmdline) {
4839 /* Or we could redo the list every time we pass this place.
4840 * It does not really matter */
4841 if (config_parse_commandline(argc, argv, 0, &global_cmdline_options,
4842 &global_cmdline_only_options) < 0) {
4843 goto err;
4845 have_parsed_cmdline = 1;
4847 cmdline_only_options = global_cmdline_only_options;
4849 if (config_line_find(cmdline_only_options, "-h") ||
4850 config_line_find(cmdline_only_options, "--help")) {
4851 print_usage();
4852 exit(0);
4854 if (config_line_find(cmdline_only_options, "--list-torrc-options")) {
4855 /* For validating whether we've documented everything. */
4856 list_torrc_options();
4857 exit(0);
4859 if (config_line_find(cmdline_only_options, "--list-deprecated-options")) {
4860 /* For validating whether what we have deprecated really exists. */
4861 list_deprecated_options();
4862 exit(0);
4865 if (config_line_find(cmdline_only_options, "--version")) {
4866 printf("Tor version %s.\n",get_version());
4867 exit(0);
4870 if (config_line_find(cmdline_only_options, "--library-versions")) {
4871 printf("Tor version %s. \n", get_version());
4872 printf("Library versions\tCompiled\t\tRuntime\n");
4873 printf("Libevent\t\t%-15s\t\t%s\n",
4874 tor_libevent_get_header_version_str(),
4875 tor_libevent_get_version_str());
4876 printf("OpenSSL \t\t%-15s\t\t%s\n",
4877 crypto_openssl_get_header_version_str(),
4878 crypto_openssl_get_version_str());
4879 printf("Zlib \t\t%-15s\t\t%s\n",
4880 tor_zlib_get_header_version_str(),
4881 tor_zlib_get_version_str());
4882 //TODO: Hex versions?
4883 exit(0);
4886 command = CMD_RUN_TOR;
4887 for (p_index = cmdline_only_options; p_index; p_index = p_index->next) {
4888 if (!strcmp(p_index->key,"--keygen")) {
4889 command = CMD_KEYGEN;
4890 } else if (!strcmp(p_index->key,"--list-fingerprint")) {
4891 command = CMD_LIST_FINGERPRINT;
4892 } else if (!strcmp(p_index->key, "--hash-password")) {
4893 command = CMD_HASH_PASSWORD;
4894 command_arg = p_index->value;
4895 } else if (!strcmp(p_index->key, "--dump-config")) {
4896 command = CMD_DUMP_CONFIG;
4897 command_arg = p_index->value;
4898 } else if (!strcmp(p_index->key, "--verify-config")) {
4899 command = CMD_VERIFY_CONFIG;
4903 if (command == CMD_HASH_PASSWORD) {
4904 cf_defaults = tor_strdup("");
4905 cf = tor_strdup("");
4906 } else {
4907 cf_defaults = load_torrc_from_disk(cmdline_only_options, 1);
4909 const config_line_t *f_line = config_line_find(cmdline_only_options,
4910 "-f");
4912 const int read_torrc_from_stdin =
4913 (f_line != NULL && strcmp(f_line->value, "-") == 0);
4915 if (read_torrc_from_stdin) {
4916 cf = load_torrc_from_stdin();
4917 } else {
4918 cf = load_torrc_from_disk(cmdline_only_options, 0);
4921 if (!cf) {
4922 if (config_line_find(cmdline_only_options, "--allow-missing-torrc")) {
4923 cf = tor_strdup("");
4924 } else {
4925 goto err;
4930 retval = options_init_from_string(cf_defaults, cf, command, command_arg,
4931 &errmsg);
4933 if (retval < 0)
4934 goto err;
4936 if (config_line_find(cmdline_only_options, "--no-passphrase")) {
4937 if (command == CMD_KEYGEN) {
4938 get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_OFF;
4939 } else {
4940 log_err(LD_CONFIG, "--no-passphrase specified without --keygen!");
4941 exit(1);
4945 if (config_line_find(cmdline_only_options, "--newpass")) {
4946 if (command == CMD_KEYGEN) {
4947 get_options_mutable()->change_key_passphrase = 1;
4948 } else {
4949 log_err(LD_CONFIG, "--newpass specified without --keygen!");
4950 exit(1);
4955 const config_line_t *fd_line = config_line_find(cmdline_only_options,
4956 "--passphrase-fd");
4957 if (fd_line) {
4958 if (get_options()->keygen_force_passphrase == FORCE_PASSPHRASE_OFF) {
4959 log_err(LD_CONFIG, "--no-passphrase specified with --passphrase-fd!");
4960 exit(1);
4961 } else if (command != CMD_KEYGEN) {
4962 log_err(LD_CONFIG, "--passphrase-fd specified without --keygen!");
4963 exit(1);
4964 } else {
4965 const char *v = fd_line->value;
4966 int ok = 1;
4967 long fd = tor_parse_long(v, 10, 0, INT_MAX, &ok, NULL);
4968 if (fd < 0 || ok == 0) {
4969 log_err(LD_CONFIG, "Invalid --passphrase-fd value %s", escaped(v));
4970 exit(1);
4972 get_options_mutable()->keygen_passphrase_fd = (int)fd;
4973 get_options_mutable()->use_keygen_passphrase_fd = 1;
4974 get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_ON;
4980 const config_line_t *key_line = config_line_find(cmdline_only_options,
4981 "--master-key");
4982 if (key_line) {
4983 if (command != CMD_KEYGEN) {
4984 log_err(LD_CONFIG, "--master-key without --keygen!");
4985 exit(1);
4986 } else {
4987 get_options_mutable()->master_key_fname = tor_strdup(key_line->value);
4992 err:
4994 tor_free(cf);
4995 tor_free(cf_defaults);
4996 if (errmsg) {
4997 log_warn(LD_CONFIG,"%s", errmsg);
4998 tor_free(errmsg);
5000 return retval < 0 ? -1 : 0;
5003 /** Load the options from the configuration in <b>cf</b>, validate
5004 * them for consistency and take actions based on them.
5006 * Return 0 if success, negative on error:
5007 * * -1 for general errors.
5008 * * -2 for failure to parse/validate,
5009 * * -3 for transition not allowed
5010 * * -4 for error while setting the new options
5012 setopt_err_t
5013 options_init_from_string(const char *cf_defaults, const char *cf,
5014 int command, const char *command_arg,
5015 char **msg)
5017 or_options_t *oldoptions, *newoptions, *newdefaultoptions=NULL;
5018 config_line_t *cl;
5019 int retval;
5020 setopt_err_t err = SETOPT_ERR_MISC;
5021 tor_assert(msg);
5023 oldoptions = global_options; /* get_options unfortunately asserts if
5024 this is the first time we run*/
5026 newoptions = tor_malloc_zero(sizeof(or_options_t));
5027 newoptions->magic_ = OR_OPTIONS_MAGIC;
5028 options_init(newoptions);
5029 newoptions->command = command;
5030 newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
5032 for (int i = 0; i < 2; ++i) {
5033 const char *body = i==0 ? cf_defaults : cf;
5034 if (!body)
5035 continue;
5036 /* get config lines, assign them */
5037 retval = config_get_lines(body, &cl, 1);
5038 if (retval < 0) {
5039 err = SETOPT_ERR_PARSE;
5040 goto err;
5042 retval = config_assign(&options_format, newoptions, cl,
5043 CAL_WARN_DEPRECATIONS, msg);
5044 config_free_lines(cl);
5045 if (retval < 0) {
5046 err = SETOPT_ERR_PARSE;
5047 goto err;
5049 if (i==0)
5050 newdefaultoptions = config_dup(&options_format, newoptions);
5053 if (newdefaultoptions == NULL) {
5054 newdefaultoptions = config_dup(&options_format, global_default_options);
5057 /* Go through command-line variables too */
5058 retval = config_assign(&options_format, newoptions,
5059 global_cmdline_options, CAL_WARN_DEPRECATIONS, msg);
5060 if (retval < 0) {
5061 err = SETOPT_ERR_PARSE;
5062 goto err;
5065 /* If this is a testing network configuration, change defaults
5066 * for a list of dependent config options, re-initialize newoptions
5067 * with the new defaults, and assign all options to it second time. */
5068 if (newoptions->TestingTorNetwork) {
5069 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
5070 * this? We could, for example, make the parsing algorithm do two passes
5071 * over the configuration. If it finds any "suite" options like
5072 * TestingTorNetwork, it could change the defaults before its second pass.
5073 * Not urgent so long as this seems to work, but at any sign of trouble,
5074 * let's clean it up. -NM */
5076 /* Change defaults. */
5077 for (int i = 0; testing_tor_network_defaults[i].name; ++i) {
5078 const config_var_t *new_var = &testing_tor_network_defaults[i];
5079 config_var_t *old_var =
5080 config_find_option_mutable(&options_format, new_var->name);
5081 tor_assert(new_var);
5082 tor_assert(old_var);
5083 old_var->initvalue = new_var->initvalue;
5085 if ((config_find_deprecation(&options_format, new_var->name))) {
5086 log_warn(LD_GENERAL, "Testing options override the deprecated "
5087 "option %s. Is that intentional?",
5088 new_var->name);
5092 /* Clear newoptions and re-initialize them with new defaults. */
5093 or_options_free(newoptions);
5094 or_options_free(newdefaultoptions);
5095 newdefaultoptions = NULL;
5096 newoptions = tor_malloc_zero(sizeof(or_options_t));
5097 newoptions->magic_ = OR_OPTIONS_MAGIC;
5098 options_init(newoptions);
5099 newoptions->command = command;
5100 newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
5102 /* Assign all options a second time. */
5103 for (int i = 0; i < 2; ++i) {
5104 const char *body = i==0 ? cf_defaults : cf;
5105 if (!body)
5106 continue;
5107 /* get config lines, assign them */
5108 retval = config_get_lines(body, &cl, 1);
5109 if (retval < 0) {
5110 err = SETOPT_ERR_PARSE;
5111 goto err;
5113 retval = config_assign(&options_format, newoptions, cl, 0, msg);
5114 config_free_lines(cl);
5115 if (retval < 0) {
5116 err = SETOPT_ERR_PARSE;
5117 goto err;
5119 if (i==0)
5120 newdefaultoptions = config_dup(&options_format, newoptions);
5122 /* Assign command-line variables a second time too */
5123 retval = config_assign(&options_format, newoptions,
5124 global_cmdline_options, 0, msg);
5125 if (retval < 0) {
5126 err = SETOPT_ERR_PARSE;
5127 goto err;
5131 /* Validate newoptions */
5132 if (options_validate(oldoptions, newoptions, newdefaultoptions,
5133 0, msg) < 0) {
5134 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
5135 goto err;
5138 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
5139 err = SETOPT_ERR_TRANSITION;
5140 goto err;
5143 if (set_options(newoptions, msg)) {
5144 err = SETOPT_ERR_SETTING;
5145 goto err; /* frees and replaces old options */
5147 or_options_free(global_default_options);
5148 global_default_options = newdefaultoptions;
5150 return SETOPT_OK;
5152 err:
5153 or_options_free(newoptions);
5154 or_options_free(newdefaultoptions);
5155 if (*msg) {
5156 char *old_msg = *msg;
5157 tor_asprintf(msg, "Failed to parse/validate config: %s", old_msg);
5158 tor_free(old_msg);
5160 return err;
5163 /** Return the location for our configuration file. May return NULL.
5165 const char *
5166 get_torrc_fname(int defaults_fname)
5168 const char *fname = defaults_fname ? torrc_defaults_fname : torrc_fname;
5170 if (fname)
5171 return fname;
5172 else
5173 return get_default_conf_file(defaults_fname);
5176 /** Adjust the address map based on the MapAddress elements in the
5177 * configuration <b>options</b>
5179 void
5180 config_register_addressmaps(const or_options_t *options)
5182 smartlist_t *elts;
5183 config_line_t *opt;
5184 const char *from, *to, *msg;
5186 addressmap_clear_configured();
5187 elts = smartlist_new();
5188 for (opt = options->AddressMap; opt; opt = opt->next) {
5189 smartlist_split_string(elts, opt->value, NULL,
5190 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
5191 if (smartlist_len(elts) < 2) {
5192 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
5193 opt->value);
5194 goto cleanup;
5197 from = smartlist_get(elts,0);
5198 to = smartlist_get(elts,1);
5200 if (to[0] == '.' || from[0] == '.') {
5201 log_warn(LD_CONFIG,"MapAddress '%s' is ambiguous - address starts with a"
5202 "'.'. Ignoring.",opt->value);
5203 goto cleanup;
5206 if (addressmap_register_auto(from, to, 0, ADDRMAPSRC_TORRC, &msg) < 0) {
5207 log_warn(LD_CONFIG,"MapAddress '%s' failed: %s. Ignoring.", opt->value,
5208 msg);
5209 goto cleanup;
5212 if (smartlist_len(elts) > 2)
5213 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
5215 cleanup:
5216 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
5217 smartlist_clear(elts);
5219 smartlist_free(elts);
5222 /** As addressmap_register(), but detect the wildcarded status of "from" and
5223 * "to", and do not steal a reference to <b>to</b>. */
5224 /* XXXX move to connection_edge.c */
5226 addressmap_register_auto(const char *from, const char *to,
5227 time_t expires,
5228 addressmap_entry_source_t addrmap_source,
5229 const char **msg)
5231 int from_wildcard = 0, to_wildcard = 0;
5233 *msg = "whoops, forgot the error message";
5234 if (1) {
5235 if (!strcmp(to, "*") || !strcmp(from, "*")) {
5236 *msg = "can't remap from or to *";
5237 return -1;
5239 /* Detect asterisks in expressions of type: '*.example.com' */
5240 if (!strncmp(from,"*.",2)) {
5241 from += 2;
5242 from_wildcard = 1;
5244 if (!strncmp(to,"*.",2)) {
5245 to += 2;
5246 to_wildcard = 1;
5249 if (to_wildcard && !from_wildcard) {
5250 *msg = "can only use wildcard (i.e. '*.') if 'from' address "
5251 "uses wildcard also";
5252 return -1;
5255 if (address_is_invalid_destination(to, 1)) {
5256 *msg = "destination is invalid";
5257 return -1;
5260 addressmap_register(from, tor_strdup(to), expires, addrmap_source,
5261 from_wildcard, to_wildcard);
5263 return 0;
5267 * Initialize the logs based on the configuration file.
5269 static int
5270 options_init_logs(const or_options_t *old_options, or_options_t *options,
5271 int validate_only)
5273 config_line_t *opt;
5274 int ok;
5275 smartlist_t *elts;
5276 int run_as_daemon =
5277 #ifdef _WIN32
5279 #else
5280 options->RunAsDaemon;
5281 #endif
5283 if (options->LogTimeGranularity <= 0) {
5284 log_warn(LD_CONFIG, "Log time granularity '%d' has to be positive.",
5285 options->LogTimeGranularity);
5286 return -1;
5287 } else if (1000 % options->LogTimeGranularity != 0 &&
5288 options->LogTimeGranularity % 1000 != 0) {
5289 int granularity = options->LogTimeGranularity;
5290 if (granularity < 40) {
5291 do granularity++;
5292 while (1000 % granularity != 0);
5293 } else if (granularity < 1000) {
5294 granularity = 1000 / granularity;
5295 while (1000 % granularity != 0)
5296 granularity--;
5297 granularity = 1000 / granularity;
5298 } else {
5299 granularity = 1000 * ((granularity / 1000) + 1);
5301 log_warn(LD_CONFIG, "Log time granularity '%d' has to be either a "
5302 "divisor or a multiple of 1 second. Changing to "
5303 "'%d'.",
5304 options->LogTimeGranularity, granularity);
5305 if (!validate_only)
5306 set_log_time_granularity(granularity);
5307 } else {
5308 if (!validate_only)
5309 set_log_time_granularity(options->LogTimeGranularity);
5312 ok = 1;
5313 elts = smartlist_new();
5315 for (opt = options->Logs; opt; opt = opt->next) {
5316 log_severity_list_t *severity;
5317 const char *cfg = opt->value;
5318 severity = tor_malloc_zero(sizeof(log_severity_list_t));
5319 if (parse_log_severity_config(&cfg, severity) < 0) {
5320 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
5321 opt->value);
5322 ok = 0; goto cleanup;
5325 smartlist_split_string(elts, cfg, NULL,
5326 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
5328 if (smartlist_len(elts) == 0)
5329 smartlist_add(elts, tor_strdup("stdout"));
5331 if (smartlist_len(elts) == 1 &&
5332 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
5333 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
5334 int err = smartlist_len(elts) &&
5335 !strcasecmp(smartlist_get(elts,0), "stderr");
5336 if (!validate_only) {
5337 if (run_as_daemon) {
5338 log_warn(LD_CONFIG,
5339 "Can't log to %s with RunAsDaemon set; skipping stdout",
5340 err?"stderr":"stdout");
5341 } else {
5342 add_stream_log(severity, err?"<stderr>":"<stdout>",
5343 fileno(err?stderr:stdout));
5346 goto cleanup;
5348 if (smartlist_len(elts) == 1 &&
5349 !strcasecmp(smartlist_get(elts,0), "syslog")) {
5350 #ifdef HAVE_SYSLOG_H
5351 if (!validate_only) {
5352 add_syslog_log(severity, options->SyslogIdentityTag);
5354 #else
5355 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
5356 #endif
5357 goto cleanup;
5360 if (smartlist_len(elts) == 2 &&
5361 !strcasecmp(smartlist_get(elts,0), "file")) {
5362 if (!validate_only) {
5363 char *fname = expand_filename(smartlist_get(elts, 1));
5364 /* Truncate if TruncateLogFile is set and we haven't seen this option
5365 line before. */
5366 int truncate_log = 0;
5367 if (options->TruncateLogFile) {
5368 truncate_log = 1;
5369 if (old_options) {
5370 config_line_t *opt2;
5371 for (opt2 = old_options->Logs; opt2; opt2 = opt2->next)
5372 if (!strcmp(opt->value, opt2->value)) {
5373 truncate_log = 0;
5374 break;
5378 if (add_file_log(severity, fname, truncate_log) < 0) {
5379 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
5380 opt->value, strerror(errno));
5381 ok = 0;
5383 tor_free(fname);
5385 goto cleanup;
5388 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
5389 opt->value);
5390 ok = 0; goto cleanup;
5392 cleanup:
5393 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
5394 smartlist_clear(elts);
5395 tor_free(severity);
5397 smartlist_free(elts);
5399 if (ok && !validate_only)
5400 logs_set_domain_logging(options->LogMessageDomains);
5402 return ok?0:-1;
5405 /** Given a smartlist of SOCKS arguments to be passed to a transport
5406 * proxy in <b>args</b>, validate them and return -1 if they are
5407 * corrupted. Return 0 if they seem OK. */
5408 static int
5409 validate_transport_socks_arguments(const smartlist_t *args)
5411 char *socks_string = NULL;
5412 size_t socks_string_len;
5414 tor_assert(args);
5415 tor_assert(smartlist_len(args) > 0);
5417 SMARTLIST_FOREACH_BEGIN(args, const char *, s) {
5418 if (!string_is_key_value(LOG_WARN, s)) { /* items should be k=v items */
5419 log_warn(LD_CONFIG, "'%s' is not a k=v item.", s);
5420 return -1;
5422 } SMARTLIST_FOREACH_END(s);
5424 socks_string = pt_stringify_socks_args(args);
5425 if (!socks_string)
5426 return -1;
5428 socks_string_len = strlen(socks_string);
5429 tor_free(socks_string);
5431 if (socks_string_len > MAX_SOCKS5_AUTH_SIZE_TOTAL) {
5432 log_warn(LD_CONFIG, "SOCKS arguments can't be more than %u bytes (%lu).",
5433 MAX_SOCKS5_AUTH_SIZE_TOTAL,
5434 (unsigned long) socks_string_len);
5435 return -1;
5438 return 0;
5441 /** Deallocate a bridge_line_t structure. */
5442 /* private */ void
5443 bridge_line_free(bridge_line_t *bridge_line)
5445 if (!bridge_line)
5446 return;
5448 if (bridge_line->socks_args) {
5449 SMARTLIST_FOREACH(bridge_line->socks_args, char*, s, tor_free(s));
5450 smartlist_free(bridge_line->socks_args);
5452 tor_free(bridge_line->transport_name);
5453 tor_free(bridge_line);
5456 /** Read the contents of a Bridge line from <b>line</b>. Return 0
5457 * if the line is well-formed, and -1 if it isn't. If
5458 * <b>validate_only</b> is 0, and the line is well-formed, then add
5459 * the bridge described in the line to our internal bridge list.
5461 * Bridge line format:
5462 * Bridge [transport] IP:PORT [id-fingerprint] [k=v] [k=v] ...
5464 /* private */ bridge_line_t *
5465 parse_bridge_line(const char *line)
5467 smartlist_t *items = NULL;
5468 char *addrport=NULL, *fingerprint=NULL;
5469 char *field=NULL;
5470 bridge_line_t *bridge_line = tor_malloc_zero(sizeof(bridge_line_t));
5472 items = smartlist_new();
5473 smartlist_split_string(items, line, NULL,
5474 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5475 if (smartlist_len(items) < 1) {
5476 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
5477 goto err;
5480 /* first field is either a transport name or addrport */
5481 field = smartlist_get(items, 0);
5482 smartlist_del_keeporder(items, 0);
5484 if (string_is_C_identifier(field)) {
5485 /* It's a transport name. */
5486 bridge_line->transport_name = field;
5487 if (smartlist_len(items) < 1) {
5488 log_warn(LD_CONFIG, "Too few items to Bridge line.");
5489 goto err;
5491 addrport = smartlist_get(items, 0); /* Next field is addrport then. */
5492 smartlist_del_keeporder(items, 0);
5493 } else {
5494 addrport = field;
5497 if (tor_addr_port_parse(LOG_INFO, addrport,
5498 &bridge_line->addr, &bridge_line->port, 443)<0) {
5499 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
5500 goto err;
5503 /* If transports are enabled, next field could be a fingerprint or a
5504 socks argument. If transports are disabled, next field must be
5505 a fingerprint. */
5506 if (smartlist_len(items)) {
5507 if (bridge_line->transport_name) { /* transports enabled: */
5508 field = smartlist_get(items, 0);
5509 smartlist_del_keeporder(items, 0);
5511 /* If it's a key=value pair, then it's a SOCKS argument for the
5512 transport proxy... */
5513 if (string_is_key_value(LOG_DEBUG, field)) {
5514 bridge_line->socks_args = smartlist_new();
5515 smartlist_add(bridge_line->socks_args, field);
5516 } else { /* ...otherwise, it's the bridge fingerprint. */
5517 fingerprint = field;
5520 } else { /* transports disabled: */
5521 fingerprint = smartlist_join_strings(items, "", 0, NULL);
5525 /* Handle fingerprint, if it was provided. */
5526 if (fingerprint) {
5527 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
5528 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
5529 goto err;
5531 if (base16_decode(bridge_line->digest, DIGEST_LEN,
5532 fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
5533 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
5534 goto err;
5538 /* If we are using transports, any remaining items in the smartlist
5539 should be k=v values. */
5540 if (bridge_line->transport_name && smartlist_len(items)) {
5541 if (!bridge_line->socks_args)
5542 bridge_line->socks_args = smartlist_new();
5544 /* append remaining items of 'items' to 'socks_args' */
5545 smartlist_add_all(bridge_line->socks_args, items);
5546 smartlist_clear(items);
5548 tor_assert(smartlist_len(bridge_line->socks_args) > 0);
5551 if (bridge_line->socks_args) {
5552 if (validate_transport_socks_arguments(bridge_line->socks_args) < 0)
5553 goto err;
5556 goto done;
5558 err:
5559 bridge_line_free(bridge_line);
5560 bridge_line = NULL;
5562 done:
5563 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5564 smartlist_free(items);
5565 tor_free(addrport);
5566 tor_free(fingerprint);
5568 return bridge_line;
5571 /** Read the contents of a ClientTransportPlugin or ServerTransportPlugin
5572 * line from <b>line</b>, depending on the value of <b>server</b>. Return 0
5573 * if the line is well-formed, and -1 if it isn't.
5575 * If <b>validate_only</b> is 0, the line is well-formed, and the transport is
5576 * needed by some bridge:
5577 * - If it's an external proxy line, add the transport described in the line to
5578 * our internal transport list.
5579 * - If it's a managed proxy line, launch the managed proxy.
5582 STATIC int
5583 parse_transport_line(const or_options_t *options,
5584 const char *line, int validate_only,
5585 int server)
5588 smartlist_t *items = NULL;
5589 int r;
5590 const char *transports = NULL;
5591 smartlist_t *transport_list = NULL;
5592 char *type = NULL;
5593 char *addrport = NULL;
5594 tor_addr_t addr;
5595 uint16_t port = 0;
5596 int socks_ver = PROXY_NONE;
5598 /* managed proxy options */
5599 int is_managed = 0;
5600 char **proxy_argv = NULL;
5601 char **tmp = NULL;
5602 int proxy_argc, i;
5603 int is_useless_proxy = 1;
5605 int line_length;
5607 /* Split the line into space-separated tokens */
5608 items = smartlist_new();
5609 smartlist_split_string(items, line, NULL,
5610 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5611 line_length = smartlist_len(items);
5613 if (line_length < 3) {
5614 log_warn(LD_CONFIG,
5615 "Too few arguments on %sTransportPlugin line.",
5616 server ? "Server" : "Client");
5617 goto err;
5620 /* Get the first line element, split it to commas into
5621 transport_list (in case it's multiple transports) and validate
5622 the transport names. */
5623 transports = smartlist_get(items, 0);
5624 transport_list = smartlist_new();
5625 smartlist_split_string(transport_list, transports, ",",
5626 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
5627 SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
5628 /* validate transport names */
5629 if (!string_is_C_identifier(transport_name)) {
5630 log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
5631 transport_name);
5632 goto err;
5635 /* see if we actually need the transports provided by this proxy */
5636 if (!validate_only && transport_is_needed(transport_name))
5637 is_useless_proxy = 0;
5638 } SMARTLIST_FOREACH_END(transport_name);
5640 type = smartlist_get(items, 1);
5641 if (!strcmp(type, "exec")) {
5642 is_managed = 1;
5643 } else if (server && !strcmp(type, "proxy")) {
5644 /* 'proxy' syntax only with ServerTransportPlugin */
5645 is_managed = 0;
5646 } else if (!server && !strcmp(type, "socks4")) {
5647 /* 'socks4' syntax only with ClientTransportPlugin */
5648 is_managed = 0;
5649 socks_ver = PROXY_SOCKS4;
5650 } else if (!server && !strcmp(type, "socks5")) {
5651 /* 'socks5' syntax only with ClientTransportPlugin */
5652 is_managed = 0;
5653 socks_ver = PROXY_SOCKS5;
5654 } else {
5655 log_warn(LD_CONFIG,
5656 "Strange %sTransportPlugin type '%s'",
5657 server ? "Server" : "Client", type);
5658 goto err;
5661 if (is_managed && options->Sandbox) {
5662 log_warn(LD_CONFIG,
5663 "Managed proxies are not compatible with Sandbox mode."
5664 "(%sTransportPlugin line was %s)",
5665 server ? "Server" : "Client", escaped(line));
5666 goto err;
5669 if (is_managed) {
5670 /* managed */
5672 if (!server && !validate_only && is_useless_proxy) {
5673 log_info(LD_GENERAL,
5674 "Pluggable transport proxy (%s) does not provide "
5675 "any needed transports and will not be launched.",
5676 line);
5680 * If we are not just validating, use the rest of the line as the
5681 * argv of the proxy to be launched. Also, make sure that we are
5682 * only launching proxies that contribute useful transports.
5685 if (!validate_only && (server || !is_useless_proxy)) {
5686 proxy_argc = line_length - 2;
5687 tor_assert(proxy_argc > 0);
5688 proxy_argv = tor_calloc((proxy_argc + 1), sizeof(char *));
5689 tmp = proxy_argv;
5691 for (i = 0; i < proxy_argc; i++) {
5692 /* store arguments */
5693 *tmp++ = smartlist_get(items, 2);
5694 smartlist_del_keeporder(items, 2);
5696 *tmp = NULL; /* terminated with NULL, just like execve() likes it */
5698 /* kickstart the thing */
5699 if (server) {
5700 pt_kickstart_server_proxy(transport_list, proxy_argv);
5701 } else {
5702 pt_kickstart_client_proxy(transport_list, proxy_argv);
5705 } else {
5706 /* external */
5708 /* ClientTransportPlugins connecting through a proxy is managed only. */
5709 if (!server && (options->Socks4Proxy || options->Socks5Proxy ||
5710 options->HTTPSProxy)) {
5711 log_warn(LD_CONFIG, "You have configured an external proxy with another "
5712 "proxy type. (Socks4Proxy|Socks5Proxy|HTTPSProxy)");
5713 goto err;
5716 if (smartlist_len(transport_list) != 1) {
5717 log_warn(LD_CONFIG,
5718 "You can't have an external proxy with more than "
5719 "one transport.");
5720 goto err;
5723 addrport = smartlist_get(items, 2);
5725 if (tor_addr_port_lookup(addrport, &addr, &port) < 0) {
5726 log_warn(LD_CONFIG,
5727 "Error parsing transport address '%s'", addrport);
5728 goto err;
5731 if (!port) {
5732 log_warn(LD_CONFIG,
5733 "Transport address '%s' has no port.", addrport);
5734 goto err;
5737 if (!validate_only) {
5738 log_info(LD_DIR, "%s '%s' at %s.",
5739 server ? "Server transport" : "Transport",
5740 transports, fmt_addrport(&addr, port));
5742 if (!server) {
5743 transport_add_from_config(&addr, port,
5744 smartlist_get(transport_list, 0),
5745 socks_ver);
5750 r = 0;
5751 goto done;
5753 err:
5754 r = -1;
5756 done:
5757 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5758 smartlist_free(items);
5759 if (transport_list) {
5760 SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
5761 smartlist_free(transport_list);
5764 return r;
5767 /** Given a ServerTransportListenAddr <b>line</b>, return its
5768 * <address:port> string. Return NULL if the line was not
5769 * well-formed.
5771 * If <b>transport</b> is set, return NULL if the line is not
5772 * referring to <b>transport</b>.
5774 * The returned string is allocated on the heap and it's the
5775 * responsibility of the caller to free it. */
5776 static char *
5777 get_bindaddr_from_transport_listen_line(const char *line,const char *transport)
5779 smartlist_t *items = NULL;
5780 const char *parsed_transport = NULL;
5781 char *addrport = NULL;
5782 tor_addr_t addr;
5783 uint16_t port = 0;
5785 items = smartlist_new();
5786 smartlist_split_string(items, line, NULL,
5787 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5789 if (smartlist_len(items) < 2) {
5790 log_warn(LD_CONFIG,"Too few arguments on ServerTransportListenAddr line.");
5791 goto err;
5794 parsed_transport = smartlist_get(items, 0);
5795 addrport = tor_strdup(smartlist_get(items, 1));
5797 /* If 'transport' is given, check if it matches the one on the line */
5798 if (transport && strcmp(transport, parsed_transport))
5799 goto err;
5801 /* Validate addrport */
5802 if (tor_addr_port_parse(LOG_WARN, addrport, &addr, &port, -1)<0) {
5803 log_warn(LD_CONFIG, "Error parsing ServerTransportListenAddr "
5804 "address '%s'", addrport);
5805 goto err;
5808 goto done;
5810 err:
5811 tor_free(addrport);
5812 addrport = NULL;
5814 done:
5815 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5816 smartlist_free(items);
5818 return addrport;
5821 /** Given a ServerTransportOptions <b>line</b>, return a smartlist
5822 * with the options. Return NULL if the line was not well-formed.
5824 * If <b>transport</b> is set, return NULL if the line is not
5825 * referring to <b>transport</b>.
5827 * The returned smartlist and its strings are allocated on the heap
5828 * and it's the responsibility of the caller to free it. */
5829 smartlist_t *
5830 get_options_from_transport_options_line(const char *line,const char *transport)
5832 smartlist_t *items = smartlist_new();
5833 smartlist_t *options = smartlist_new();
5834 const char *parsed_transport = NULL;
5836 smartlist_split_string(items, line, NULL,
5837 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5839 if (smartlist_len(items) < 2) {
5840 log_warn(LD_CONFIG,"Too few arguments on ServerTransportOptions line.");
5841 goto err;
5844 parsed_transport = smartlist_get(items, 0);
5845 /* If 'transport' is given, check if it matches the one on the line */
5846 if (transport && strcmp(transport, parsed_transport))
5847 goto err;
5849 SMARTLIST_FOREACH_BEGIN(items, const char *, option) {
5850 if (option_sl_idx == 0) /* skip the transport field (first field)*/
5851 continue;
5853 /* validate that it's a k=v value */
5854 if (!string_is_key_value(LOG_WARN, option)) {
5855 log_warn(LD_CONFIG, "%s is not a k=v value.", escaped(option));
5856 goto err;
5859 /* add it to the options smartlist */
5860 smartlist_add(options, tor_strdup(option));
5861 log_debug(LD_CONFIG, "Added %s to the list of options", escaped(option));
5862 } SMARTLIST_FOREACH_END(option);
5864 goto done;
5866 err:
5867 SMARTLIST_FOREACH(options, char*, s, tor_free(s));
5868 smartlist_free(options);
5869 options = NULL;
5871 done:
5872 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5873 smartlist_free(items);
5875 return options;
5878 /** Given the name of a pluggable transport in <b>transport</b>, check
5879 * the configuration file to see if the user has explicitly asked for
5880 * it to listen on a specific port. Return a <address:port> string if
5881 * so, otherwise NULL. */
5882 char *
5883 get_transport_bindaddr_from_config(const char *transport)
5885 config_line_t *cl;
5886 const or_options_t *options = get_options();
5888 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
5889 char *bindaddr =
5890 get_bindaddr_from_transport_listen_line(cl->value, transport);
5891 if (bindaddr)
5892 return bindaddr;
5895 return NULL;
5898 /** Given the name of a pluggable transport in <b>transport</b>, check
5899 * the configuration file to see if the user has asked us to pass any
5900 * parameters to the pluggable transport. Return a smartlist
5901 * containing the parameters, otherwise NULL. */
5902 smartlist_t *
5903 get_options_for_server_transport(const char *transport)
5905 config_line_t *cl;
5906 const or_options_t *options = get_options();
5908 for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
5909 smartlist_t *options_sl =
5910 get_options_from_transport_options_line(cl->value, transport);
5911 if (options_sl)
5912 return options_sl;
5915 return NULL;
5918 /** Read the contents of a DirAuthority line from <b>line</b>. If
5919 * <b>validate_only</b> is 0, and the line is well-formed, and it
5920 * shares any bits with <b>required_type</b> or <b>required_type</b>
5921 * is NO_DIRINFO (zero), then add the dirserver described in the line
5922 * (minus whatever bits it's missing) as a valid authority.
5923 * Return 0 on success or filtering out by type,
5924 * or -1 if the line isn't well-formed or if we can't add it. */
5925 STATIC int
5926 parse_dir_authority_line(const char *line, dirinfo_type_t required_type,
5927 int validate_only)
5929 smartlist_t *items = NULL;
5930 int r;
5931 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
5932 tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
5933 uint16_t dir_port = 0, or_port = 0;
5934 char digest[DIGEST_LEN];
5935 char v3_digest[DIGEST_LEN];
5936 dirinfo_type_t type = 0;
5937 double weight = 1.0;
5939 items = smartlist_new();
5940 smartlist_split_string(items, line, NULL,
5941 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5942 if (smartlist_len(items) < 1) {
5943 log_warn(LD_CONFIG, "No arguments on DirAuthority line.");
5944 goto err;
5947 if (is_legal_nickname(smartlist_get(items, 0))) {
5948 nickname = smartlist_get(items, 0);
5949 smartlist_del_keeporder(items, 0);
5952 while (smartlist_len(items)) {
5953 char *flag = smartlist_get(items, 0);
5954 if (TOR_ISDIGIT(flag[0]))
5955 break;
5956 if (!strcasecmp(flag, "hs") ||
5957 !strcasecmp(flag, "no-hs")) {
5958 log_warn(LD_CONFIG, "The DirAuthority options 'hs' and 'no-hs' are "
5959 "obsolete; you don't need them any more.");
5960 } else if (!strcasecmp(flag, "bridge")) {
5961 type |= BRIDGE_DIRINFO;
5962 } else if (!strcasecmp(flag, "no-v2")) {
5963 /* obsolete, but may still be contained in DirAuthority lines generated
5964 by various tools */;
5965 } else if (!strcasecmpstart(flag, "orport=")) {
5966 int ok;
5967 char *portstring = flag + strlen("orport=");
5968 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
5969 if (!ok)
5970 log_warn(LD_CONFIG, "Invalid orport '%s' on DirAuthority line.",
5971 portstring);
5972 } else if (!strcmpstart(flag, "weight=")) {
5973 int ok;
5974 const char *wstring = flag + strlen("weight=");
5975 weight = tor_parse_double(wstring, 0, (double)UINT64_MAX, &ok, NULL);
5976 if (!ok) {
5977 log_warn(LD_CONFIG, "Invalid weight '%s' on DirAuthority line.",flag);
5978 weight=1.0;
5980 } else if (!strcasecmpstart(flag, "v3ident=")) {
5981 char *idstr = flag + strlen("v3ident=");
5982 if (strlen(idstr) != HEX_DIGEST_LEN ||
5983 base16_decode(v3_digest, DIGEST_LEN,
5984 idstr, HEX_DIGEST_LEN) != DIGEST_LEN) {
5985 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirAuthority line",
5986 flag);
5987 } else {
5988 type |= V3_DIRINFO|EXTRAINFO_DIRINFO|MICRODESC_DIRINFO;
5990 } else if (!strcasecmpstart(flag, "ipv6=")) {
5991 if (ipv6_addrport_ptr) {
5992 log_warn(LD_CONFIG, "Redundant ipv6 addr/port on DirAuthority line");
5993 } else {
5994 if (tor_addr_port_parse(LOG_WARN, flag+strlen("ipv6="),
5995 &ipv6_addrport.addr, &ipv6_addrport.port,
5996 -1) < 0
5997 || tor_addr_family(&ipv6_addrport.addr) != AF_INET6) {
5998 log_warn(LD_CONFIG, "Bad ipv6 addr/port %s on DirAuthority line",
5999 escaped(flag));
6000 goto err;
6002 ipv6_addrport_ptr = &ipv6_addrport;
6004 } else {
6005 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirAuthority line",
6006 flag);
6008 tor_free(flag);
6009 smartlist_del_keeporder(items, 0);
6012 if (smartlist_len(items) < 2) {
6013 log_warn(LD_CONFIG, "Too few arguments to DirAuthority line.");
6014 goto err;
6016 addrport = smartlist_get(items, 0);
6017 smartlist_del_keeporder(items, 0);
6018 if (addr_port_lookup(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
6019 log_warn(LD_CONFIG, "Error parsing DirAuthority address '%s'", addrport);
6020 goto err;
6022 if (!dir_port) {
6023 log_warn(LD_CONFIG, "Missing port in DirAuthority address '%s'",addrport);
6024 goto err;
6027 fingerprint = smartlist_join_strings(items, "", 0, NULL);
6028 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
6029 log_warn(LD_CONFIG, "Key digest '%s' for DirAuthority is wrong length %d.",
6030 fingerprint, (int)strlen(fingerprint));
6031 goto err;
6033 if (base16_decode(digest, DIGEST_LEN,
6034 fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
6035 log_warn(LD_CONFIG, "Unable to decode DirAuthority key digest.");
6036 goto err;
6039 if (!validate_only && (!required_type || required_type & type)) {
6040 dir_server_t *ds;
6041 if (required_type)
6042 type &= required_type; /* pare down what we think of them as an
6043 * authority for. */
6044 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
6045 address, (int)dir_port, (char*)smartlist_get(items,0));
6046 if (!(ds = trusted_dir_server_new(nickname, address, dir_port, or_port,
6047 ipv6_addrport_ptr,
6048 digest, v3_digest, type, weight)))
6049 goto err;
6050 dir_server_add(ds);
6053 r = 0;
6054 goto done;
6056 err:
6057 r = -1;
6059 done:
6060 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
6061 smartlist_free(items);
6062 tor_free(addrport);
6063 tor_free(address);
6064 tor_free(nickname);
6065 tor_free(fingerprint);
6066 return r;
6069 /** Read the contents of a FallbackDir line from <b>line</b>. If
6070 * <b>validate_only</b> is 0, and the line is well-formed, then add the
6071 * dirserver described in the line as a fallback directory. Return 0 on
6072 * success, or -1 if the line isn't well-formed or if we can't add it. */
6074 parse_dir_fallback_line(const char *line,
6075 int validate_only)
6077 int r = -1;
6078 smartlist_t *items = smartlist_new(), *positional = smartlist_new();
6079 int orport = -1;
6080 uint16_t dirport;
6081 tor_addr_t addr;
6082 int ok;
6083 char id[DIGEST_LEN];
6084 char *address=NULL;
6085 tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
6086 double weight=1.0;
6088 memset(id, 0, sizeof(id));
6089 smartlist_split_string(items, line, NULL,
6090 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6091 SMARTLIST_FOREACH_BEGIN(items, const char *, cp) {
6092 const char *eq = strchr(cp, '=');
6093 ok = 1;
6094 if (! eq) {
6095 smartlist_add(positional, (char*)cp);
6096 continue;
6098 if (!strcmpstart(cp, "orport=")) {
6099 orport = (int)tor_parse_long(cp+strlen("orport="), 10,
6100 1, 65535, &ok, NULL);
6101 } else if (!strcmpstart(cp, "id=")) {
6102 ok = base16_decode(id, DIGEST_LEN, cp+strlen("id="),
6103 strlen(cp)-strlen("id=")) == DIGEST_LEN;
6104 } else if (!strcasecmpstart(cp, "ipv6=")) {
6105 if (ipv6_addrport_ptr) {
6106 log_warn(LD_CONFIG, "Redundant ipv6 addr/port on FallbackDir line");
6107 } else {
6108 if (tor_addr_port_parse(LOG_WARN, cp+strlen("ipv6="),
6109 &ipv6_addrport.addr, &ipv6_addrport.port,
6110 -1) < 0
6111 || tor_addr_family(&ipv6_addrport.addr) != AF_INET6) {
6112 log_warn(LD_CONFIG, "Bad ipv6 addr/port %s on FallbackDir line",
6113 escaped(cp));
6114 goto end;
6116 ipv6_addrport_ptr = &ipv6_addrport;
6118 } else if (!strcmpstart(cp, "weight=")) {
6119 int num_ok;
6120 const char *wstring = cp + strlen("weight=");
6121 weight = tor_parse_double(wstring, 0, (double)UINT64_MAX, &num_ok, NULL);
6122 if (!num_ok) {
6123 log_warn(LD_CONFIG, "Invalid weight '%s' on FallbackDir line.", cp);
6124 weight=1.0;
6128 if (!ok) {
6129 log_warn(LD_CONFIG, "Bad FallbackDir option %s", escaped(cp));
6130 goto end;
6132 } SMARTLIST_FOREACH_END(cp);
6134 if (smartlist_len(positional) != 1) {
6135 log_warn(LD_CONFIG, "Couldn't parse FallbackDir line %s", escaped(line));
6136 goto end;
6139 if (tor_digest_is_zero(id)) {
6140 log_warn(LD_CONFIG, "Missing identity on FallbackDir line");
6141 goto end;
6144 if (orport <= 0) {
6145 log_warn(LD_CONFIG, "Missing orport on FallbackDir line");
6146 goto end;
6149 if (tor_addr_port_split(LOG_INFO, smartlist_get(positional, 0),
6150 &address, &dirport) < 0 ||
6151 tor_addr_parse(&addr, address)<0) {
6152 log_warn(LD_CONFIG, "Couldn't parse address:port %s on FallbackDir line",
6153 (const char*)smartlist_get(positional, 0));
6154 goto end;
6157 if (!validate_only) {
6158 dir_server_t *ds;
6159 ds = fallback_dir_server_new(&addr, dirport, orport, ipv6_addrport_ptr,
6160 id, weight);
6161 if (!ds) {
6162 log_warn(LD_CONFIG, "Couldn't create FallbackDir %s", escaped(line));
6163 goto end;
6165 dir_server_add(ds);
6168 r = 0;
6170 end:
6171 SMARTLIST_FOREACH(items, char *, cp, tor_free(cp));
6172 smartlist_free(items);
6173 smartlist_free(positional);
6174 tor_free(address);
6175 return r;
6178 /** Allocate and return a new port_cfg_t with reasonable defaults. */
6179 STATIC port_cfg_t *
6180 port_cfg_new(size_t namelen)
6182 tor_assert(namelen <= SIZE_T_CEILING - sizeof(port_cfg_t) - 1);
6183 port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t) + namelen + 1);
6184 cfg->entry_cfg.ipv4_traffic = 1;
6185 cfg->entry_cfg.cache_ipv4_answers = 1;
6186 cfg->entry_cfg.prefer_ipv6_virtaddr = 1;
6187 return cfg;
6190 /** Free all storage held in <b>port</b> */
6191 STATIC void
6192 port_cfg_free(port_cfg_t *port)
6194 tor_free(port);
6197 /** Warn for every port in <b>ports</b> of type <b>listener_type</b> that is
6198 * on a publicly routable address. */
6199 static void
6200 warn_nonlocal_client_ports(const smartlist_t *ports, const char *portname,
6201 int listener_type)
6203 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
6204 if (port->type != listener_type)
6205 continue;
6206 if (port->is_unix_addr) {
6207 /* Unix sockets aren't accessible over a network. */
6208 } else if (!tor_addr_is_internal(&port->addr, 1)) {
6209 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
6210 "Other people on the Internet might find your computer and "
6211 "use it as an open proxy. Please don't allow this unless you "
6212 "have a good reason.",
6213 fmt_addrport(&port->addr, port->port), portname);
6214 } else if (!tor_addr_is_loopback(&port->addr)) {
6215 log_notice(LD_CONFIG, "You configured a non-loopback address '%s' "
6216 "for %sPort. This allows everybody on your local network to "
6217 "use your machine as a proxy. Make sure this is what you "
6218 "wanted.",
6219 fmt_addrport(&port->addr, port->port), portname);
6221 } SMARTLIST_FOREACH_END(port);
6224 /** Warn for every Extended ORPort port in <b>ports</b> that is on a
6225 * publicly routable address. */
6226 static void
6227 warn_nonlocal_ext_orports(const smartlist_t *ports, const char *portname)
6229 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
6230 if (port->type != CONN_TYPE_EXT_OR_LISTENER)
6231 continue;
6232 if (port->is_unix_addr)
6233 continue;
6234 /* XXX maybe warn even if address is RFC1918? */
6235 if (!tor_addr_is_internal(&port->addr, 1)) {
6236 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
6237 "This is not advised; this address is supposed to only be "
6238 "exposed on localhost so that your pluggable transport "
6239 "proxies can connect to it.",
6240 fmt_addrport(&port->addr, port->port), portname);
6242 } SMARTLIST_FOREACH_END(port);
6245 /** Given a list of port_cfg_t in <b>ports</b>, warn if any controller port
6246 * there is listening on any non-loopback address. If <b>forbid_nonlocal</b>
6247 * is true, then emit a stronger warning and remove the port from the list.
6249 static void
6250 warn_nonlocal_controller_ports(smartlist_t *ports, unsigned forbid_nonlocal)
6252 int warned = 0;
6253 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
6254 if (port->type != CONN_TYPE_CONTROL_LISTENER)
6255 continue;
6256 if (port->is_unix_addr)
6257 continue;
6258 if (!tor_addr_is_loopback(&port->addr)) {
6259 if (forbid_nonlocal) {
6260 if (!warned)
6261 log_warn(LD_CONFIG,
6262 "You have a ControlPort set to accept "
6263 "unauthenticated connections from a non-local address. "
6264 "This means that programs not running on your computer "
6265 "can reconfigure your Tor, without even having to guess a "
6266 "password. That's so bad that I'm closing your ControlPort "
6267 "for you. If you need to control your Tor remotely, try "
6268 "enabling authentication and using a tool like stunnel or "
6269 "ssh to encrypt remote access.");
6270 warned = 1;
6271 port_cfg_free(port);
6272 SMARTLIST_DEL_CURRENT(ports, port);
6273 } else {
6274 log_warn(LD_CONFIG, "You have a ControlPort set to accept "
6275 "connections from a non-local address. This means that "
6276 "programs not running on your computer can reconfigure your "
6277 "Tor. That's pretty bad, since the controller "
6278 "protocol isn't encrypted! Maybe you should just listen on "
6279 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
6280 "remote connections to your control port.");
6281 return; /* No point in checking the rest */
6284 } SMARTLIST_FOREACH_END(port);
6287 #ifdef HAVE_SYS_UN_H
6289 /** Parse the given <b>addrport</b> and set <b>path_out</b> if a Unix socket
6290 * path is found. Return 0 on success. On error, a negative value is
6291 * returned, -ENOENT if no Unix statement found, -EINVAL if the socket path
6292 * is empty and -ENOSYS if AF_UNIX is not supported (see function in the
6293 * #else statement below). */
6296 config_parse_unix_port(const char *addrport, char **path_out)
6298 tor_assert(path_out);
6299 tor_assert(addrport);
6301 if (strcmpstart(addrport, unix_socket_prefix)) {
6302 /* Not a Unix socket path. */
6303 return -ENOENT;
6306 if (strlen(addrport + strlen(unix_socket_prefix)) == 0) {
6307 /* Empty socket path, not very usable. */
6308 return -EINVAL;
6311 *path_out = tor_strdup(addrport + strlen(unix_socket_prefix));
6312 return 0;
6315 #else /* defined(HAVE_SYS_UN_H) */
6318 config_parse_unix_port(const char *addrport, char **path_out)
6320 tor_assert(path_out);
6321 tor_assert(addrport);
6323 if (strcmpstart(addrport, unix_socket_prefix)) {
6324 /* Not a Unix socket path. */
6325 return -ENOENT;
6328 log_warn(LD_CONFIG,
6329 "Port configuration %s is for an AF_UNIX socket, but we have no"
6330 "support available on this platform",
6331 escaped(addrport));
6332 return -ENOSYS;
6334 #endif /* defined(HAVE_SYS_UN_H) */
6336 static void
6337 warn_client_dns_cache(const char *option, int disabling)
6339 if (disabling)
6340 return;
6342 warn_deprecated_option(option,
6343 "Client-side DNS cacheing enables a wide variety of route-"
6344 "capture attacks. If a single bad exit node lies to you about "
6345 "an IP address, cacheing that address would make you visit "
6346 "an address of the attacker's choice every time you connected "
6347 "to your destination.");
6351 * Parse port configuration for a single port type.
6353 * Read entries of the "FooPort" type from the list <b>ports</b>, and
6354 * entries of the "FooListenAddress" type from the list
6355 * <b>listenaddrs</b>. Two syntaxes are supported: a legacy syntax
6356 * where FooPort is at most a single entry containing a port number and
6357 * where FooListenAddress has any number of address:port combinations;
6358 * and a new syntax where there are no FooListenAddress entries and
6359 * where FooPort can have any number of entries of the format
6360 * "[Address:][Port] IsolationOptions".
6362 * In log messages, describe the port type as <b>portname</b>.
6364 * If no address is specified, default to <b>defaultaddr</b>. If no
6365 * FooPort is given, default to defaultport (if 0, there is no default).
6367 * If CL_PORT_NO_STREAM_OPTIONS is set in <b>flags</b>, do not allow stream
6368 * isolation options in the FooPort entries.
6370 * If CL_PORT_WARN_NONLOCAL is set in <b>flags</b>, warn if any of the
6371 * ports are not on a local address. If CL_PORT_FORBID_NONLOCAL is set,
6372 * this is a control port with no password set: don't even allow it.
6374 * Unless CL_PORT_ALLOW_EXTRA_LISTENADDR is set in <b>flags</b>, warn
6375 * if FooListenAddress is set but FooPort is 0.
6377 * If CL_PORT_SERVER_OPTIONS is set in <b>flags</b>, do not allow stream
6378 * isolation options in the FooPort entries; instead allow the
6379 * server-port option set.
6381 * If CL_PORT_TAKES_HOSTNAMES is set in <b>flags</b>, allow the options
6382 * {No,}IPv{4,6}Traffic.
6384 * On success, if <b>out</b> is given, add a new port_cfg_t entry to
6385 * <b>out</b> for every port that the client should listen on. Return 0
6386 * on success, -1 on failure.
6388 STATIC int
6389 parse_port_config(smartlist_t *out,
6390 const config_line_t *ports,
6391 const config_line_t *listenaddrs,
6392 const char *portname,
6393 int listener_type,
6394 const char *defaultaddr,
6395 int defaultport,
6396 const unsigned flags)
6398 smartlist_t *elts;
6399 int retval = -1;
6400 const unsigned is_control = (listener_type == CONN_TYPE_CONTROL_LISTENER);
6401 const unsigned is_ext_orport = (listener_type == CONN_TYPE_EXT_OR_LISTENER);
6402 const unsigned allow_no_stream_options = flags & CL_PORT_NO_STREAM_OPTIONS;
6403 const unsigned use_server_options = flags & CL_PORT_SERVER_OPTIONS;
6404 const unsigned warn_nonlocal = flags & CL_PORT_WARN_NONLOCAL;
6405 const unsigned forbid_nonlocal = flags & CL_PORT_FORBID_NONLOCAL;
6406 const unsigned default_to_group_writable =
6407 flags & CL_PORT_DFLT_GROUP_WRITABLE;
6408 const unsigned allow_spurious_listenaddr =
6409 flags & CL_PORT_ALLOW_EXTRA_LISTENADDR;
6410 const unsigned takes_hostnames = flags & CL_PORT_TAKES_HOSTNAMES;
6411 const unsigned is_unix_socket = flags & CL_PORT_IS_UNIXSOCKET;
6412 int got_zero_port=0, got_nonzero_port=0;
6413 char *unix_socket_path = NULL;
6415 /* FooListenAddress is deprecated; let's make it work like it used to work,
6416 * though. */
6417 if (listenaddrs) {
6418 int mainport = defaultport;
6420 if (ports && ports->next) {
6421 log_warn(LD_CONFIG, "%sListenAddress can't be used when there are "
6422 "multiple %sPort lines", portname, portname);
6423 return -1;
6424 } else if (ports) {
6425 if (!strcmp(ports->value, "auto")) {
6426 mainport = CFG_AUTO_PORT;
6427 } else {
6428 int ok;
6429 mainport = (int)tor_parse_long(ports->value, 10, 0, 65535, &ok, NULL);
6430 if (!ok) {
6431 log_warn(LD_CONFIG, "%sListenAddress can only be used with a single "
6432 "%sPort with value \"auto\" or 1-65535 and no options set.",
6433 portname, portname);
6434 return -1;
6439 if (mainport == 0) {
6440 if (allow_spurious_listenaddr)
6441 return 1; /*DOCDOC*/
6442 log_warn(LD_CONFIG, "%sPort must be defined if %sListenAddress is used",
6443 portname, portname);
6444 return -1;
6447 if (use_server_options && out) {
6448 /* Add a no_listen port. */
6449 port_cfg_t *cfg = port_cfg_new(0);
6450 cfg->type = listener_type;
6451 cfg->port = mainport;
6452 tor_addr_make_unspec(&cfg->addr); /* Server ports default to 0.0.0.0 */
6453 cfg->server_cfg.no_listen = 1;
6454 cfg->server_cfg.bind_ipv4_only = 1;
6455 cfg->entry_cfg.ipv4_traffic = 1;
6456 cfg->entry_cfg.prefer_ipv6_virtaddr = 1;
6457 smartlist_add(out, cfg);
6460 for (; listenaddrs; listenaddrs = listenaddrs->next) {
6461 tor_addr_t addr;
6462 uint16_t port = 0;
6463 if (tor_addr_port_lookup(listenaddrs->value, &addr, &port) < 0) {
6464 log_warn(LD_CONFIG, "Unable to parse %sListenAddress '%s'",
6465 portname, listenaddrs->value);
6466 return -1;
6468 if (out) {
6469 port_cfg_t *cfg = port_cfg_new(0);
6470 cfg->type = listener_type;
6471 cfg->port = port ? port : mainport;
6472 tor_addr_copy(&cfg->addr, &addr);
6473 cfg->entry_cfg.session_group = SESSION_GROUP_UNSET;
6474 cfg->entry_cfg.isolation_flags = ISO_DEFAULT;
6475 cfg->server_cfg.no_advertise = 1;
6476 smartlist_add(out, cfg);
6480 if (warn_nonlocal && out) {
6481 if (is_control)
6482 warn_nonlocal_controller_ports(out, forbid_nonlocal);
6483 else if (is_ext_orport)
6484 warn_nonlocal_ext_orports(out, portname);
6485 else
6486 warn_nonlocal_client_ports(out, portname, listener_type);
6488 return 0;
6489 } /* end if (listenaddrs) */
6491 /* No ListenAddress lines. If there's no FooPort, then maybe make a default
6492 * one. */
6493 if (! ports) {
6494 if (defaultport && defaultaddr && out) {
6495 port_cfg_t *cfg = port_cfg_new(is_unix_socket ? strlen(defaultaddr) : 0);
6496 cfg->type = listener_type;
6497 if (is_unix_socket) {
6498 tor_addr_make_unspec(&cfg->addr);
6499 memcpy(cfg->unix_addr, defaultaddr, strlen(defaultaddr) + 1);
6500 cfg->is_unix_addr = 1;
6501 } else {
6502 cfg->port = defaultport;
6503 tor_addr_parse(&cfg->addr, defaultaddr);
6505 cfg->entry_cfg.session_group = SESSION_GROUP_UNSET;
6506 cfg->entry_cfg.isolation_flags = ISO_DEFAULT;
6507 smartlist_add(out, cfg);
6509 return 0;
6512 /* At last we can actually parse the FooPort lines. The syntax is:
6513 * [Addr:](Port|auto) [Options].*/
6514 elts = smartlist_new();
6516 for (; ports; ports = ports->next) {
6517 tor_addr_t addr;
6518 int port, ret;
6519 int sessiongroup = SESSION_GROUP_UNSET;
6520 unsigned isolation = ISO_DEFAULT;
6521 int prefer_no_auth = 0;
6522 int socks_iso_keep_alive = 0;
6524 char *addrport;
6525 uint16_t ptmp=0;
6526 int ok;
6527 int no_listen = 0, no_advertise = 0, all_addrs = 0,
6528 bind_ipv4_only = 0, bind_ipv6_only = 0,
6529 ipv4_traffic = 1, ipv6_traffic = 0, prefer_ipv6 = 0,
6530 cache_ipv4 = 1, use_cached_ipv4 = 0,
6531 cache_ipv6 = 0, use_cached_ipv6 = 0,
6532 prefer_ipv6_automap = 1, world_writable = 0, group_writable = 0,
6533 relax_dirmode_check = 0,
6534 has_used_unix_socket_only_option = 0;
6536 smartlist_split_string(elts, ports->value, NULL,
6537 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
6538 if (smartlist_len(elts) == 0) {
6539 log_warn(LD_CONFIG, "Invalid %sPort line with no value", portname);
6540 goto err;
6543 /* Now parse the addr/port value */
6544 addrport = smartlist_get(elts, 0);
6546 /* Let's start to check if it's a Unix socket path. */
6547 ret = config_parse_unix_port(addrport, &unix_socket_path);
6548 if (ret < 0 && ret != -ENOENT) {
6549 if (ret == -EINVAL) {
6550 log_warn(LD_CONFIG, "Empty Unix socket path.");
6552 goto err;
6555 if (unix_socket_path &&
6556 ! conn_listener_type_supports_af_unix(listener_type)) {
6557 log_warn(LD_CONFIG, "%sPort does not support unix sockets", portname);
6558 goto err;
6561 if (unix_socket_path) {
6562 port = 1;
6563 } else if (is_unix_socket) {
6564 unix_socket_path = tor_strdup(addrport);
6565 if (!strcmp(addrport, "0"))
6566 port = 0;
6567 else
6568 port = 1;
6569 } else if (!strcmp(addrport, "auto")) {
6570 port = CFG_AUTO_PORT;
6571 int af = tor_addr_parse(&addr, defaultaddr);
6572 tor_assert(af >= 0);
6573 } else if (!strcasecmpend(addrport, ":auto")) {
6574 char *addrtmp = tor_strndup(addrport, strlen(addrport)-5);
6575 port = CFG_AUTO_PORT;
6576 if (tor_addr_port_lookup(addrtmp, &addr, &ptmp)<0 || ptmp) {
6577 log_warn(LD_CONFIG, "Invalid address '%s' for %sPort",
6578 escaped(addrport), portname);
6579 tor_free(addrtmp);
6580 goto err;
6582 tor_free(addrtmp);
6583 } else {
6584 /* Try parsing integer port before address, because, who knows?
6585 "9050" might be a valid address. */
6586 port = (int) tor_parse_long(addrport, 10, 0, 65535, &ok, NULL);
6587 if (ok) {
6588 int af = tor_addr_parse(&addr, defaultaddr);
6589 tor_assert(af >= 0);
6590 } else if (tor_addr_port_lookup(addrport, &addr, &ptmp) == 0) {
6591 if (ptmp == 0) {
6592 log_warn(LD_CONFIG, "%sPort line has address but no port", portname);
6593 goto err;
6595 port = ptmp;
6596 } else {
6597 log_warn(LD_CONFIG, "Couldn't parse address %s for %sPort",
6598 escaped(addrport), portname);
6599 goto err;
6603 if (unix_socket_path && default_to_group_writable)
6604 group_writable = 1;
6606 /* Now parse the rest of the options, if any. */
6607 if (use_server_options) {
6608 /* This is a server port; parse advertising options */
6609 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
6610 if (elt_sl_idx == 0)
6611 continue; /* Skip addr:port */
6613 if (!strcasecmp(elt, "NoAdvertise")) {
6614 no_advertise = 1;
6615 } else if (!strcasecmp(elt, "NoListen")) {
6616 no_listen = 1;
6617 #if 0
6618 /* not implemented yet. */
6619 } else if (!strcasecmp(elt, "AllAddrs")) {
6621 all_addrs = 1;
6622 #endif
6623 } else if (!strcasecmp(elt, "IPv4Only")) {
6624 bind_ipv4_only = 1;
6625 } else if (!strcasecmp(elt, "IPv6Only")) {
6626 bind_ipv6_only = 1;
6627 } else {
6628 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6629 portname, escaped(elt));
6631 } SMARTLIST_FOREACH_END(elt);
6633 if (no_advertise && no_listen) {
6634 log_warn(LD_CONFIG, "Tried to set both NoListen and NoAdvertise "
6635 "on %sPort line '%s'",
6636 portname, escaped(ports->value));
6637 goto err;
6639 if (bind_ipv4_only && bind_ipv6_only) {
6640 log_warn(LD_CONFIG, "Tried to set both IPv4Only and IPv6Only "
6641 "on %sPort line '%s'",
6642 portname, escaped(ports->value));
6643 goto err;
6645 if (bind_ipv4_only && tor_addr_family(&addr) == AF_INET6) {
6646 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv6",
6647 portname);
6648 goto err;
6650 if (bind_ipv6_only && tor_addr_family(&addr) == AF_INET) {
6651 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv4",
6652 portname);
6653 goto err;
6655 } else {
6656 /* This is a client port; parse isolation options */
6657 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
6658 int no = 0, isoflag = 0;
6659 const char *elt_orig = elt;
6660 if (elt_sl_idx == 0)
6661 continue; /* Skip addr:port */
6663 if (!strcasecmpstart(elt, "SessionGroup=")) {
6664 int group = (int)tor_parse_long(elt+strlen("SessionGroup="),
6665 10, 0, INT_MAX, &ok, NULL);
6666 if (!ok || !allow_no_stream_options) {
6667 log_warn(LD_CONFIG, "Invalid %sPort option '%s'",
6668 portname, escaped(elt));
6669 goto err;
6671 if (sessiongroup >= 0) {
6672 log_warn(LD_CONFIG, "Multiple SessionGroup options on %sPort",
6673 portname);
6674 goto err;
6676 sessiongroup = group;
6677 continue;
6680 if (!strcasecmpstart(elt, "No")) {
6681 no = 1;
6682 elt += 2;
6685 if (!strcasecmp(elt, "GroupWritable")) {
6686 group_writable = !no;
6687 has_used_unix_socket_only_option = 1;
6688 continue;
6689 } else if (!strcasecmp(elt, "WorldWritable")) {
6690 world_writable = !no;
6691 has_used_unix_socket_only_option = 1;
6692 continue;
6693 } else if (!strcasecmp(elt, "RelaxDirModeCheck")) {
6694 relax_dirmode_check = !no;
6695 has_used_unix_socket_only_option = 1;
6696 continue;
6699 if (allow_no_stream_options) {
6700 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6701 portname, escaped(elt));
6702 continue;
6705 if (takes_hostnames) {
6706 if (!strcasecmp(elt, "IPv4Traffic")) {
6707 ipv4_traffic = ! no;
6708 continue;
6709 } else if (!strcasecmp(elt, "IPv6Traffic")) {
6710 ipv6_traffic = ! no;
6711 continue;
6712 } else if (!strcasecmp(elt, "PreferIPv6")) {
6713 prefer_ipv6 = ! no;
6714 continue;
6717 if (!strcasecmp(elt, "CacheIPv4DNS")) {
6718 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6719 cache_ipv4 = ! no;
6720 continue;
6721 } else if (!strcasecmp(elt, "CacheIPv6DNS")) {
6722 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6723 cache_ipv6 = ! no;
6724 continue;
6725 } else if (!strcasecmp(elt, "CacheDNS")) {
6726 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6727 cache_ipv4 = cache_ipv6 = ! no;
6728 continue;
6729 } else if (!strcasecmp(elt, "UseIPv4Cache")) {
6730 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6731 use_cached_ipv4 = ! no;
6732 continue;
6733 } else if (!strcasecmp(elt, "UseIPv6Cache")) {
6734 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6735 use_cached_ipv6 = ! no;
6736 continue;
6737 } else if (!strcasecmp(elt, "UseDNSCache")) {
6738 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6739 use_cached_ipv4 = use_cached_ipv6 = ! no;
6740 continue;
6741 } else if (!strcasecmp(elt, "PreferIPv6Automap")) {
6742 prefer_ipv6_automap = ! no;
6743 continue;
6744 } else if (!strcasecmp(elt, "PreferSOCKSNoAuth")) {
6745 prefer_no_auth = ! no;
6746 continue;
6747 } else if (!strcasecmp(elt, "KeepAliveIsolateSOCKSAuth")) {
6748 socks_iso_keep_alive = ! no;
6749 continue;
6752 if (!strcasecmpend(elt, "s"))
6753 elt[strlen(elt)-1] = '\0'; /* kill plurals. */
6755 if (!strcasecmp(elt, "IsolateDestPort")) {
6756 isoflag = ISO_DESTPORT;
6757 } else if (!strcasecmp(elt, "IsolateDestAddr")) {
6758 isoflag = ISO_DESTADDR;
6759 } else if (!strcasecmp(elt, "IsolateSOCKSAuth")) {
6760 isoflag = ISO_SOCKSAUTH;
6761 } else if (!strcasecmp(elt, "IsolateClientProtocol")) {
6762 isoflag = ISO_CLIENTPROTO;
6763 } else if (!strcasecmp(elt, "IsolateClientAddr")) {
6764 isoflag = ISO_CLIENTADDR;
6765 } else {
6766 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6767 portname, escaped(elt_orig));
6770 if (no) {
6771 isolation &= ~isoflag;
6772 } else {
6773 isolation |= isoflag;
6775 } SMARTLIST_FOREACH_END(elt);
6778 if (port)
6779 got_nonzero_port = 1;
6780 else
6781 got_zero_port = 1;
6783 if (ipv4_traffic == 0 && ipv6_traffic == 0) {
6784 log_warn(LD_CONFIG, "You have a %sPort entry with both IPv4 and "
6785 "IPv6 disabled; that won't work.", portname);
6786 goto err;
6789 if ( has_used_unix_socket_only_option && ! unix_socket_path) {
6790 log_warn(LD_CONFIG, "You have a %sPort entry with GroupWritable, "
6791 "WorldWritable, or RelaxDirModeCheck, but it is not a "
6792 "unix socket.", portname);
6793 goto err;
6796 if (!(isolation & ISO_SOCKSAUTH) && socks_iso_keep_alive) {
6797 log_warn(LD_CONFIG, "You have a %sPort entry with both "
6798 "NoIsolateSOCKSAuth and KeepAliveIsolateSOCKSAuth set.",
6799 portname);
6800 goto err;
6803 if (out && port) {
6804 size_t namelen = unix_socket_path ? strlen(unix_socket_path) : 0;
6805 port_cfg_t *cfg = port_cfg_new(namelen);
6806 if (unix_socket_path) {
6807 tor_addr_make_unspec(&cfg->addr);
6808 memcpy(cfg->unix_addr, unix_socket_path, namelen + 1);
6809 cfg->is_unix_addr = 1;
6810 tor_free(unix_socket_path);
6811 } else {
6812 tor_addr_copy(&cfg->addr, &addr);
6813 cfg->port = port;
6815 cfg->type = listener_type;
6816 cfg->is_world_writable = world_writable;
6817 cfg->is_group_writable = group_writable;
6818 cfg->relax_dirmode_check = relax_dirmode_check;
6819 cfg->entry_cfg.isolation_flags = isolation;
6820 cfg->entry_cfg.session_group = sessiongroup;
6821 cfg->server_cfg.no_advertise = no_advertise;
6822 cfg->server_cfg.no_listen = no_listen;
6823 cfg->server_cfg.all_addrs = all_addrs;
6824 cfg->server_cfg.bind_ipv4_only = bind_ipv4_only;
6825 cfg->server_cfg.bind_ipv6_only = bind_ipv6_only;
6826 cfg->entry_cfg.ipv4_traffic = ipv4_traffic;
6827 cfg->entry_cfg.ipv6_traffic = ipv6_traffic;
6828 cfg->entry_cfg.prefer_ipv6 = prefer_ipv6;
6829 cfg->entry_cfg.cache_ipv4_answers = cache_ipv4;
6830 cfg->entry_cfg.cache_ipv6_answers = cache_ipv6;
6831 cfg->entry_cfg.use_cached_ipv4_answers = use_cached_ipv4;
6832 cfg->entry_cfg.use_cached_ipv6_answers = use_cached_ipv6;
6833 cfg->entry_cfg.prefer_ipv6_virtaddr = prefer_ipv6_automap;
6834 cfg->entry_cfg.socks_prefer_no_auth = prefer_no_auth;
6835 if (! (isolation & ISO_SOCKSAUTH))
6836 cfg->entry_cfg.socks_prefer_no_auth = 1;
6837 cfg->entry_cfg.socks_iso_keep_alive = socks_iso_keep_alive;
6839 smartlist_add(out, cfg);
6841 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
6842 smartlist_clear(elts);
6845 if (warn_nonlocal && out) {
6846 if (is_control)
6847 warn_nonlocal_controller_ports(out, forbid_nonlocal);
6848 else if (is_ext_orport)
6849 warn_nonlocal_ext_orports(out, portname);
6850 else
6851 warn_nonlocal_client_ports(out, portname, listener_type);
6854 if (got_zero_port && got_nonzero_port) {
6855 log_warn(LD_CONFIG, "You specified a nonzero %sPort along with '%sPort 0' "
6856 "in the same configuration. Did you mean to disable %sPort or "
6857 "not?", portname, portname, portname);
6858 goto err;
6861 retval = 0;
6862 err:
6863 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
6864 smartlist_free(elts);
6865 tor_free(unix_socket_path);
6866 return retval;
6869 /** Return the number of ports which are actually going to listen with type
6870 * <b>listenertype</b>. Do not count no_listen ports. Only count unix
6871 * sockets if count_sockets is true. */
6872 static int
6873 count_real_listeners(const smartlist_t *ports, int listenertype,
6874 int count_sockets)
6876 int n = 0;
6877 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
6878 if (port->server_cfg.no_listen)
6879 continue;
6880 if (!count_sockets && port->is_unix_addr)
6881 continue;
6882 if (port->type != listenertype)
6883 continue;
6884 ++n;
6885 } SMARTLIST_FOREACH_END(port);
6886 return n;
6889 /** Parse all ports from <b>options</b>. On success, set *<b>n_ports_out</b>
6890 * to the number of ports that are listed, update the *Port_set values in
6891 * <b>options</b>, and return 0. On failure, set *<b>msg</b> to a
6892 * description of the problem and return -1.
6894 * If <b>validate_only</b> is false, set configured_client_ports to the
6895 * new list of ports parsed from <b>options</b>.
6897 static int
6898 parse_ports(or_options_t *options, int validate_only,
6899 char **msg, int *n_ports_out,
6900 int *world_writable_control_socket)
6902 smartlist_t *ports;
6903 int retval = -1;
6905 ports = smartlist_new();
6907 *n_ports_out = 0;
6909 const unsigned gw_flag = options->SocksSocketsGroupWritable ?
6910 CL_PORT_DFLT_GROUP_WRITABLE : 0;
6911 if (parse_port_config(ports,
6912 options->SocksPort_lines, options->SocksListenAddress,
6913 "Socks", CONN_TYPE_AP_LISTENER,
6914 "127.0.0.1", 9050,
6915 CL_PORT_WARN_NONLOCAL|CL_PORT_ALLOW_EXTRA_LISTENADDR|
6916 CL_PORT_TAKES_HOSTNAMES|gw_flag) < 0) {
6917 *msg = tor_strdup("Invalid SocksPort/SocksListenAddress configuration");
6918 goto err;
6920 if (parse_port_config(ports,
6921 options->DNSPort_lines, options->DNSListenAddress,
6922 "DNS", CONN_TYPE_AP_DNS_LISTENER,
6923 "127.0.0.1", 0,
6924 CL_PORT_WARN_NONLOCAL|CL_PORT_TAKES_HOSTNAMES) < 0) {
6925 *msg = tor_strdup("Invalid DNSPort/DNSListenAddress configuration");
6926 goto err;
6928 if (parse_port_config(ports,
6929 options->TransPort_lines, options->TransListenAddress,
6930 "Trans", CONN_TYPE_AP_TRANS_LISTENER,
6931 "127.0.0.1", 0,
6932 CL_PORT_WARN_NONLOCAL) < 0) {
6933 *msg = tor_strdup("Invalid TransPort/TransListenAddress configuration");
6934 goto err;
6936 if (parse_port_config(ports,
6937 options->NATDPort_lines, options->NATDListenAddress,
6938 "NATD", CONN_TYPE_AP_NATD_LISTENER,
6939 "127.0.0.1", 0,
6940 CL_PORT_WARN_NONLOCAL) < 0) {
6941 *msg = tor_strdup("Invalid NatdPort/NatdListenAddress configuration");
6942 goto err;
6945 unsigned control_port_flags = CL_PORT_NO_STREAM_OPTIONS |
6946 CL_PORT_WARN_NONLOCAL;
6947 const int any_passwords = (options->HashedControlPassword ||
6948 options->HashedControlSessionPassword ||
6949 options->CookieAuthentication);
6950 if (! any_passwords)
6951 control_port_flags |= CL_PORT_FORBID_NONLOCAL;
6952 if (options->ControlSocketsGroupWritable)
6953 control_port_flags |= CL_PORT_DFLT_GROUP_WRITABLE;
6955 if (parse_port_config(ports,
6956 options->ControlPort_lines,
6957 options->ControlListenAddress,
6958 "Control", CONN_TYPE_CONTROL_LISTENER,
6959 "127.0.0.1", 0,
6960 control_port_flags) < 0) {
6961 *msg = tor_strdup("Invalid ControlPort/ControlListenAddress "
6962 "configuration");
6963 goto err;
6966 if (parse_port_config(ports, options->ControlSocket, NULL,
6967 "ControlSocket",
6968 CONN_TYPE_CONTROL_LISTENER, NULL, 0,
6969 control_port_flags | CL_PORT_IS_UNIXSOCKET) < 0) {
6970 *msg = tor_strdup("Invalid ControlSocket configuration");
6971 goto err;
6974 if (! options->ClientOnly) {
6975 if (parse_port_config(ports,
6976 options->ORPort_lines, options->ORListenAddress,
6977 "OR", CONN_TYPE_OR_LISTENER,
6978 "0.0.0.0", 0,
6979 CL_PORT_SERVER_OPTIONS) < 0) {
6980 *msg = tor_strdup("Invalid ORPort/ORListenAddress configuration");
6981 goto err;
6983 if (parse_port_config(ports,
6984 options->ExtORPort_lines, NULL,
6985 "ExtOR", CONN_TYPE_EXT_OR_LISTENER,
6986 "127.0.0.1", 0,
6987 CL_PORT_SERVER_OPTIONS|CL_PORT_WARN_NONLOCAL) < 0) {
6988 *msg = tor_strdup("Invalid ExtORPort configuration");
6989 goto err;
6991 if (parse_port_config(ports,
6992 options->DirPort_lines, options->DirListenAddress,
6993 "Dir", CONN_TYPE_DIR_LISTENER,
6994 "0.0.0.0", 0,
6995 CL_PORT_SERVER_OPTIONS) < 0) {
6996 *msg = tor_strdup("Invalid DirPort/DirListenAddress configuration");
6997 goto err;
7001 int n_low_ports = 0;
7002 if (check_server_ports(ports, options, &n_low_ports) < 0) {
7003 *msg = tor_strdup("Misconfigured server ports");
7004 goto err;
7006 if (have_low_ports < 0)
7007 have_low_ports = (n_low_ports > 0);
7009 *n_ports_out = smartlist_len(ports);
7011 retval = 0;
7013 /* Update the *Port_set options. The !! here is to force a boolean out of
7014 an integer. */
7015 options->ORPort_set =
7016 !! count_real_listeners(ports, CONN_TYPE_OR_LISTENER, 0);
7017 options->SocksPort_set =
7018 !! count_real_listeners(ports, CONN_TYPE_AP_LISTENER, 1);
7019 options->TransPort_set =
7020 !! count_real_listeners(ports, CONN_TYPE_AP_TRANS_LISTENER, 1);
7021 options->NATDPort_set =
7022 !! count_real_listeners(ports, CONN_TYPE_AP_NATD_LISTENER, 1);
7023 /* Use options->ControlSocket to test if a control socket is set */
7024 options->ControlPort_set =
7025 !! count_real_listeners(ports, CONN_TYPE_CONTROL_LISTENER, 0);
7026 options->DirPort_set =
7027 !! count_real_listeners(ports, CONN_TYPE_DIR_LISTENER, 0);
7028 options->DNSPort_set =
7029 !! count_real_listeners(ports, CONN_TYPE_AP_DNS_LISTENER, 1);
7030 options->ExtORPort_set =
7031 !! count_real_listeners(ports, CONN_TYPE_EXT_OR_LISTENER, 0);
7033 if (world_writable_control_socket) {
7034 SMARTLIST_FOREACH(ports, port_cfg_t *, p,
7035 if (p->type == CONN_TYPE_CONTROL_LISTENER &&
7036 p->is_unix_addr &&
7037 p->is_world_writable) {
7038 *world_writable_control_socket = 1;
7039 break;
7043 if (!validate_only) {
7044 if (configured_ports) {
7045 SMARTLIST_FOREACH(configured_ports,
7046 port_cfg_t *, p, port_cfg_free(p));
7047 smartlist_free(configured_ports);
7049 configured_ports = ports;
7050 ports = NULL; /* prevent free below. */
7053 err:
7054 if (ports) {
7055 SMARTLIST_FOREACH(ports, port_cfg_t *, p, port_cfg_free(p));
7056 smartlist_free(ports);
7058 return retval;
7061 /* Does port bind to IPv4? */
7062 static int
7063 port_binds_ipv4(const port_cfg_t *port)
7065 return tor_addr_family(&port->addr) == AF_INET ||
7066 (tor_addr_family(&port->addr) == AF_UNSPEC
7067 && !port->server_cfg.bind_ipv6_only);
7070 /* Does port bind to IPv6? */
7071 static int
7072 port_binds_ipv6(const port_cfg_t *port)
7074 return tor_addr_family(&port->addr) == AF_INET6 ||
7075 (tor_addr_family(&port->addr) == AF_UNSPEC
7076 && !port->server_cfg.bind_ipv4_only);
7079 /** Given a list of <b>port_cfg_t</b> in <b>ports</b>, check them for internal
7080 * consistency and warn as appropriate. Set *<b>n_low_ports_out</b> to the
7081 * number of sub-1024 ports we will be binding. */
7082 static int
7083 check_server_ports(const smartlist_t *ports,
7084 const or_options_t *options,
7085 int *n_low_ports_out)
7087 int n_orport_advertised = 0;
7088 int n_orport_advertised_ipv4 = 0;
7089 int n_orport_listeners = 0;
7090 int n_dirport_advertised = 0;
7091 int n_dirport_listeners = 0;
7092 int n_low_port = 0;
7093 int r = 0;
7095 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
7096 if (port->type == CONN_TYPE_DIR_LISTENER) {
7097 if (! port->server_cfg.no_advertise)
7098 ++n_dirport_advertised;
7099 if (! port->server_cfg.no_listen)
7100 ++n_dirport_listeners;
7101 } else if (port->type == CONN_TYPE_OR_LISTENER) {
7102 if (! port->server_cfg.no_advertise) {
7103 ++n_orport_advertised;
7104 if (port_binds_ipv4(port))
7105 ++n_orport_advertised_ipv4;
7107 if (! port->server_cfg.no_listen)
7108 ++n_orport_listeners;
7109 } else {
7110 continue;
7112 #ifndef _WIN32
7113 if (!port->server_cfg.no_listen && port->port < 1024)
7114 ++n_low_port;
7115 #endif
7116 } SMARTLIST_FOREACH_END(port);
7118 if (n_orport_advertised && !n_orport_listeners) {
7119 log_warn(LD_CONFIG, "We are advertising an ORPort, but not actually "
7120 "listening on one.");
7121 r = -1;
7123 if (n_orport_listeners && !n_orport_advertised) {
7124 log_warn(LD_CONFIG, "We are listening on an ORPort, but not advertising "
7125 "any ORPorts. This will keep us from building a %s "
7126 "descriptor, and make us impossible to use.",
7127 options->BridgeRelay ? "bridge" : "router");
7128 r = -1;
7130 if (n_dirport_advertised && !n_dirport_listeners) {
7131 log_warn(LD_CONFIG, "We are advertising a DirPort, but not actually "
7132 "listening on one.");
7133 r = -1;
7135 if (n_dirport_advertised > 1) {
7136 log_warn(LD_CONFIG, "Can't advertise more than one DirPort.");
7137 r = -1;
7139 if (n_orport_advertised && !n_orport_advertised_ipv4 &&
7140 !options->BridgeRelay) {
7141 log_warn(LD_CONFIG, "Configured non-bridge only to listen on an IPv6 "
7142 "address.");
7143 r = -1;
7146 if (n_low_port && options->AccountingMax &&
7147 (!have_capability_support() || options->KeepBindCapabilities == 0)) {
7148 const char *extra = "";
7149 if (options->KeepBindCapabilities == 0 && have_capability_support())
7150 extra = ", and you have disabled KeepBindCapabilities.";
7151 log_warn(LD_CONFIG,
7152 "You have set AccountingMax to use hibernation. You have also "
7153 "chosen a low DirPort or OrPort%s."
7154 "This combination can make Tor stop "
7155 "working when it tries to re-attach the port after a period of "
7156 "hibernation. Please choose a different port or turn off "
7157 "hibernation unless you know this combination will work on your "
7158 "platform.", extra);
7161 if (n_low_ports_out)
7162 *n_low_ports_out = n_low_port;
7164 return r;
7167 /** Return a list of port_cfg_t for client ports parsed from the
7168 * options. */
7169 MOCK_IMPL(const smartlist_t *,
7170 get_configured_ports,(void))
7172 if (!configured_ports)
7173 configured_ports = smartlist_new();
7174 return configured_ports;
7177 /** Return an address:port string representation of the address
7178 * where the first <b>listener_type</b> listener waits for
7179 * connections. Return NULL if we couldn't find a listener. The
7180 * string is allocated on the heap and it's the responsibility of the
7181 * caller to free it after use.
7183 * This function is meant to be used by the pluggable transport proxy
7184 * spawning code, please make sure that it fits your purposes before
7185 * using it. */
7186 char *
7187 get_first_listener_addrport_string(int listener_type)
7189 static const char *ipv4_localhost = "127.0.0.1";
7190 static const char *ipv6_localhost = "[::1]";
7191 const char *address;
7192 uint16_t port;
7193 char *string = NULL;
7195 if (!configured_ports)
7196 return NULL;
7198 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
7199 if (cfg->server_cfg.no_listen)
7200 continue;
7202 if (cfg->type == listener_type &&
7203 tor_addr_family(&cfg->addr) != AF_UNSPEC) {
7205 /* We found the first listener of the type we are interested in! */
7207 /* If a listener is listening on INADDR_ANY, assume that it's
7208 also listening on 127.0.0.1, and point the transport proxy
7209 there: */
7210 if (tor_addr_is_null(&cfg->addr))
7211 address = tor_addr_is_v4(&cfg->addr) ? ipv4_localhost : ipv6_localhost;
7212 else
7213 address = fmt_and_decorate_addr(&cfg->addr);
7215 /* If a listener is configured with port 'auto', we are forced
7216 to iterate all listener connections and find out in which
7217 port it ended up listening: */
7218 if (cfg->port == CFG_AUTO_PORT) {
7219 port = router_get_active_listener_port_by_type_af(listener_type,
7220 tor_addr_family(&cfg->addr));
7221 if (!port)
7222 return NULL;
7223 } else {
7224 port = cfg->port;
7227 tor_asprintf(&string, "%s:%u", address, port);
7229 return string;
7232 } SMARTLIST_FOREACH_END(cfg);
7234 return NULL;
7237 /** Return the first advertised port of type <b>listener_type</b> in
7238 * <b>address_family</b>. Returns 0 when no port is found, and when passed
7239 * AF_UNSPEC. */
7241 get_first_advertised_port_by_type_af(int listener_type, int address_family)
7243 if (address_family == AF_UNSPEC)
7244 return 0;
7246 const smartlist_t *conf_ports = get_configured_ports();
7247 SMARTLIST_FOREACH_BEGIN(conf_ports, const port_cfg_t *, cfg) {
7248 if (cfg->type == listener_type &&
7249 !cfg->server_cfg.no_advertise) {
7250 if ((address_family == AF_INET && port_binds_ipv4(cfg)) ||
7251 (address_family == AF_INET6 && port_binds_ipv6(cfg))) {
7252 return cfg->port;
7255 } SMARTLIST_FOREACH_END(cfg);
7256 return 0;
7259 /** Return the first advertised address of type <b>listener_type</b> in
7260 * <b>address_family</b>. Returns NULL if there is no advertised address,
7261 * and when passed AF_UNSPEC. */
7262 const tor_addr_t *
7263 get_first_advertised_addr_by_type_af(int listener_type, int address_family)
7265 if (address_family == AF_UNSPEC)
7266 return NULL;
7267 if (!configured_ports)
7268 return NULL;
7269 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
7270 if (cfg->type == listener_type &&
7271 !cfg->server_cfg.no_advertise) {
7272 if ((address_family == AF_INET && port_binds_ipv4(cfg)) ||
7273 (address_family == AF_INET6 && port_binds_ipv6(cfg))) {
7274 return &cfg->addr;
7277 } SMARTLIST_FOREACH_END(cfg);
7278 return NULL;
7281 /** Return 1 if a port exists of type <b>listener_type</b> on <b>addr</b> and
7282 * <b>port</b>. If <b>check_wildcard</b> is true, INADDR[6]_ANY and AF_UNSPEC
7283 * addresses match any address of the appropriate family; and port -1 matches
7284 * any port.
7285 * To match auto ports, pass CFG_PORT_AUTO. (Does not match on the actual
7286 * automatically chosen listener ports.) */
7288 port_exists_by_type_addr_port(int listener_type, const tor_addr_t *addr,
7289 int port, int check_wildcard)
7291 if (!configured_ports || !addr)
7292 return 0;
7293 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
7294 if (cfg->type == listener_type) {
7295 if (cfg->port == port || (check_wildcard && port == -1)) {
7296 /* Exact match */
7297 if (tor_addr_eq(&cfg->addr, addr)) {
7298 return 1;
7300 /* Skip wildcard matches if we're not doing them */
7301 if (!check_wildcard) {
7302 continue;
7304 /* Wildcard matches IPv4 */
7305 const int cfg_v4 = port_binds_ipv4(cfg);
7306 const int cfg_any_v4 = tor_addr_is_null(&cfg->addr) && cfg_v4;
7307 const int addr_v4 = tor_addr_family(addr) == AF_INET ||
7308 tor_addr_family(addr) == AF_UNSPEC;
7309 const int addr_any_v4 = tor_addr_is_null(&cfg->addr) && addr_v4;
7310 if ((cfg_any_v4 && addr_v4) || (cfg_v4 && addr_any_v4)) {
7311 return 1;
7313 /* Wildcard matches IPv6 */
7314 const int cfg_v6 = port_binds_ipv6(cfg);
7315 const int cfg_any_v6 = tor_addr_is_null(&cfg->addr) && cfg_v6;
7316 const int addr_v6 = tor_addr_family(addr) == AF_INET6 ||
7317 tor_addr_family(addr) == AF_UNSPEC;
7318 const int addr_any_v6 = tor_addr_is_null(&cfg->addr) && addr_v6;
7319 if ((cfg_any_v6 && addr_v6) || (cfg_v6 && addr_any_v6)) {
7320 return 1;
7324 } SMARTLIST_FOREACH_END(cfg);
7325 return 0;
7328 /* Like port_exists_by_type_addr_port, but accepts a host-order IPv4 address
7329 * instead. */
7331 port_exists_by_type_addr32h_port(int listener_type, uint32_t addr_ipv4h,
7332 int port, int check_wildcard)
7334 tor_addr_t ipv4;
7335 tor_addr_from_ipv4h(&ipv4, addr_ipv4h);
7336 return port_exists_by_type_addr_port(listener_type, &ipv4, port,
7337 check_wildcard);
7340 /** Adjust the value of options->DataDirectory, or fill it in if it's
7341 * absent. Return 0 on success, -1 on failure. */
7342 static int
7343 normalize_data_directory(or_options_t *options)
7345 #ifdef _WIN32
7346 char *p;
7347 if (options->DataDirectory)
7348 return 0; /* all set */
7349 p = tor_malloc(MAX_PATH);
7350 strlcpy(p,get_windows_conf_root(),MAX_PATH);
7351 options->DataDirectory = p;
7352 return 0;
7353 #else
7354 const char *d = options->DataDirectory;
7355 if (!d)
7356 d = "~/.tor";
7358 if (strncmp(d,"~/",2) == 0) {
7359 char *fn = expand_filename(d);
7360 if (!fn) {
7361 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
7362 return -1;
7364 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
7365 /* If our homedir is /, we probably don't want to use it. */
7366 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
7367 * want. */
7368 log_warn(LD_CONFIG,
7369 "Default DataDirectory is \"~/.tor\". This expands to "
7370 "\"%s\", which is probably not what you want. Using "
7371 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
7372 tor_free(fn);
7373 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
7375 tor_free(options->DataDirectory);
7376 options->DataDirectory = fn;
7378 return 0;
7379 #endif
7382 /** Check and normalize the value of options->DataDirectory; return 0 if it
7383 * is sane, -1 otherwise. */
7384 static int
7385 validate_data_directory(or_options_t *options)
7387 if (normalize_data_directory(options) < 0)
7388 return -1;
7389 tor_assert(options->DataDirectory);
7390 if (strlen(options->DataDirectory) > (512-128)) {
7391 log_warn(LD_CONFIG, "DataDirectory is too long.");
7392 return -1;
7394 return 0;
7397 /** This string must remain the same forevermore. It is how we
7398 * recognize that the torrc file doesn't need to be backed up. */
7399 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
7400 "if you edit it, comments will not be preserved"
7401 /** This string can change; it tries to give the reader an idea
7402 * that editing this file by hand is not a good plan. */
7403 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
7404 "to torrc.orig.1 or similar, and Tor will ignore it"
7406 /** Save a configuration file for the configuration in <b>options</b>
7407 * into the file <b>fname</b>. If the file already exists, and
7408 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
7409 * replace it. Return 0 on success, -1 on failure. */
7410 static int
7411 write_configuration_file(const char *fname, const or_options_t *options)
7413 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
7414 int rename_old = 0, r;
7416 if (!fname)
7417 return -1;
7419 switch (file_status(fname)) {
7420 /* create backups of old config files, even if they're empty */
7421 case FN_FILE:
7422 case FN_EMPTY:
7423 old_val = read_file_to_str(fname, 0, NULL);
7424 if (!old_val || strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
7425 rename_old = 1;
7427 tor_free(old_val);
7428 break;
7429 case FN_NOENT:
7430 break;
7431 case FN_ERROR:
7432 case FN_DIR:
7433 default:
7434 log_warn(LD_CONFIG,
7435 "Config file \"%s\" is not a file? Failing.", fname);
7436 return -1;
7439 if (!(new_conf = options_dump(options, OPTIONS_DUMP_MINIMAL))) {
7440 log_warn(LD_BUG, "Couldn't get configuration string");
7441 goto err;
7444 tor_asprintf(&new_val, "%s\n%s\n\n%s",
7445 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
7447 if (rename_old) {
7448 int i = 1;
7449 char *fn_tmp = NULL;
7450 while (1) {
7451 tor_asprintf(&fn_tmp, "%s.orig.%d", fname, i);
7452 if (file_status(fn_tmp) == FN_NOENT)
7453 break;
7454 tor_free(fn_tmp);
7455 ++i;
7457 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
7458 if (tor_rename(fname, fn_tmp) < 0) {//XXXX sandbox doesn't allow
7459 log_warn(LD_FS,
7460 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
7461 fname, fn_tmp, strerror(errno));
7462 tor_free(fn_tmp);
7463 goto err;
7465 tor_free(fn_tmp);
7468 if (write_str_to_file(fname, new_val, 0) < 0)
7469 goto err;
7471 r = 0;
7472 goto done;
7473 err:
7474 r = -1;
7475 done:
7476 tor_free(new_val);
7477 tor_free(new_conf);
7478 return r;
7482 * Save the current configuration file value to disk. Return 0 on
7483 * success, -1 on failure.
7486 options_save_current(void)
7488 /* This fails if we can't write to our configuration file.
7490 * If we try falling back to datadirectory or something, we have a better
7491 * chance of saving the configuration, but a better chance of doing
7492 * something the user never expected. */
7493 return write_configuration_file(get_torrc_fname(0), get_options());
7496 /** Return the number of cpus configured in <b>options</b>. If we are
7497 * told to auto-detect the number of cpus, return the auto-detected number. */
7499 get_num_cpus(const or_options_t *options)
7501 if (options->NumCPUs == 0) {
7502 int n = compute_num_cpus();
7503 return (n >= 1) ? n : 1;
7504 } else {
7505 return options->NumCPUs;
7510 * Initialize the libevent library.
7512 static void
7513 init_libevent(const or_options_t *options)
7515 tor_libevent_cfg cfg;
7517 tor_assert(options);
7519 configure_libevent_logging();
7520 /* If the kernel complains that some method (say, epoll) doesn't
7521 * exist, we don't care about it, since libevent will cope.
7523 suppress_libevent_log_msg("Function not implemented");
7525 memset(&cfg, 0, sizeof(cfg));
7526 cfg.num_cpus = get_num_cpus(options);
7527 cfg.msec_per_tick = options->TokenBucketRefillInterval;
7529 tor_libevent_initialize(&cfg);
7531 suppress_libevent_log_msg(NULL);
7534 /** Return a newly allocated string holding a filename relative to the data
7535 * directory. If <b>sub1</b> is present, it is the first path component after
7536 * the data directory. If <b>sub2</b> is also present, it is the second path
7537 * component after the data directory. If <b>suffix</b> is present, it
7538 * is appended to the filename.
7540 * Examples:
7541 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
7542 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
7543 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
7544 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
7546 * Note: Consider using the get_datadir_fname* macros in or.h.
7548 MOCK_IMPL(char *,
7549 options_get_datadir_fname2_suffix,(const or_options_t *options,
7550 const char *sub1, const char *sub2,
7551 const char *suffix))
7553 char *fname = NULL;
7554 size_t len;
7555 tor_assert(options);
7556 tor_assert(options->DataDirectory);
7557 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
7558 len = strlen(options->DataDirectory);
7559 if (sub1) {
7560 len += strlen(sub1)+1;
7561 if (sub2)
7562 len += strlen(sub2)+1;
7564 if (suffix)
7565 len += strlen(suffix);
7566 len++;
7567 fname = tor_malloc(len);
7568 if (sub1) {
7569 if (sub2) {
7570 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
7571 options->DataDirectory, sub1, sub2);
7572 } else {
7573 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
7574 options->DataDirectory, sub1);
7576 } else {
7577 strlcpy(fname, options->DataDirectory, len);
7579 if (suffix)
7580 strlcat(fname, suffix, len);
7581 return fname;
7584 /** Check wether the data directory has a private subdirectory
7585 * <b>subdir</b>. If not, try to create it. Return 0 on success,
7586 * -1 otherwise. */
7588 check_or_create_data_subdir(const char *subdir)
7590 char *statsdir = get_datadir_fname(subdir);
7591 int return_val = 0;
7593 if (check_private_dir(statsdir, CPD_CREATE, get_options()->User) < 0) {
7594 log_warn(LD_HIST, "Unable to create %s/ directory!", subdir);
7595 return_val = -1;
7597 tor_free(statsdir);
7598 return return_val;
7601 /** Create a file named <b>fname</b> with contents <b>str</b> in the
7602 * subdirectory <b>subdir</b> of the data directory. <b>descr</b>
7603 * should be a short description of the file's content and will be
7604 * used for the warning message, if it's present and the write process
7605 * fails. Return 0 on success, -1 otherwise.*/
7607 write_to_data_subdir(const char* subdir, const char* fname,
7608 const char* str, const char* descr)
7610 char *filename = get_datadir_fname2(subdir, fname);
7611 int return_val = 0;
7613 if (write_str_to_file(filename, str, 0) < 0) {
7614 log_warn(LD_HIST, "Unable to write %s to disk!", descr ? descr : fname);
7615 return_val = -1;
7617 tor_free(filename);
7618 return return_val;
7621 /** Given a file name check to see whether the file exists but has not been
7622 * modified for a very long time. If so, remove it. */
7623 void
7624 remove_file_if_very_old(const char *fname, time_t now)
7626 #define VERY_OLD_FILE_AGE (28*24*60*60)
7627 struct stat st;
7629 log_debug(LD_FS, "stat()ing %s", fname);
7630 if (stat(sandbox_intern_string(fname), &st)==0 &&
7631 st.st_mtime < now-VERY_OLD_FILE_AGE) {
7632 char buf[ISO_TIME_LEN+1];
7633 format_local_iso_time(buf, st.st_mtime);
7634 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
7635 "Removing it.", fname, buf);
7636 if (unlink(fname) != 0) {
7637 log_warn(LD_FS, "Failed to unlink %s: %s",
7638 fname, strerror(errno));
7643 /** Return a smartlist of ports that must be forwarded by
7644 * tor-fw-helper. The smartlist contains the ports in a string format
7645 * that is understandable by tor-fw-helper. */
7646 smartlist_t *
7647 get_list_of_ports_to_forward(void)
7649 smartlist_t *ports_to_forward = smartlist_new();
7650 int port = 0;
7652 /** XXX TODO tor-fw-helper does not support forwarding ports to
7653 other hosts than the local one. If the user is binding to a
7654 different IP address, tor-fw-helper won't work. */
7655 port = router_get_advertised_or_port(get_options()); /* Get ORPort */
7656 if (port)
7657 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
7659 port = router_get_advertised_dir_port(get_options(), 0); /* Get DirPort */
7660 if (port)
7661 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
7663 /* Get ports of transport proxies */
7665 smartlist_t *transport_ports = get_transport_proxy_ports();
7666 if (transport_ports) {
7667 smartlist_add_all(ports_to_forward, transport_ports);
7668 smartlist_free(transport_ports);
7672 if (!smartlist_len(ports_to_forward)) {
7673 smartlist_free(ports_to_forward);
7674 ports_to_forward = NULL;
7677 return ports_to_forward;
7680 /** Helper to implement GETINFO functions about configuration variables (not
7681 * their values). Given a "config/names" question, set *<b>answer</b> to a
7682 * new string describing the supported configuration variables and their
7683 * types. */
7685 getinfo_helper_config(control_connection_t *conn,
7686 const char *question, char **answer,
7687 const char **errmsg)
7689 (void) conn;
7690 (void) errmsg;
7691 if (!strcmp(question, "config/names")) {
7692 smartlist_t *sl = smartlist_new();
7693 int i;
7694 for (i = 0; option_vars_[i].name; ++i) {
7695 const config_var_t *var = &option_vars_[i];
7696 const char *type;
7697 /* don't tell controller about triple-underscore options */
7698 if (!strncmp(option_vars_[i].name, "___", 3))
7699 continue;
7700 switch (var->type) {
7701 case CONFIG_TYPE_STRING: type = "String"; break;
7702 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
7703 case CONFIG_TYPE_UINT: type = "Integer"; break;
7704 case CONFIG_TYPE_INT: type = "SignedInteger"; break;
7705 case CONFIG_TYPE_PORT: type = "Port"; break;
7706 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
7707 case CONFIG_TYPE_MSEC_INTERVAL: type = "TimeMsecInterval"; break;
7708 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
7709 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
7710 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
7711 case CONFIG_TYPE_AUTOBOOL: type = "Boolean+Auto"; break;
7712 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
7713 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
7714 case CONFIG_TYPE_CSV: type = "CommaList"; break;
7715 case CONFIG_TYPE_CSV_INTERVAL: type = "TimeIntervalCommaList"; break;
7716 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
7717 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
7718 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
7719 default:
7720 case CONFIG_TYPE_OBSOLETE:
7721 type = NULL; break;
7723 if (!type)
7724 continue;
7725 smartlist_add_asprintf(sl, "%s %s\n",var->name,type);
7727 *answer = smartlist_join_strings(sl, "", 0, NULL);
7728 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
7729 smartlist_free(sl);
7730 } else if (!strcmp(question, "config/defaults")) {
7731 smartlist_t *sl = smartlist_new();
7732 int dirauth_lines_seen = 0, fallback_lines_seen = 0;
7733 for (int i = 0; option_vars_[i].name; ++i) {
7734 const config_var_t *var = &option_vars_[i];
7735 if (var->initvalue != NULL) {
7736 if (strcmp(option_vars_[i].name, "DirAuthority") == 0) {
7738 * Count dirauth lines we have a default for; we'll use the
7739 * count later to decide whether to add the defaults manually
7741 ++dirauth_lines_seen;
7743 if (strcmp(option_vars_[i].name, "FallbackDir") == 0) {
7745 * Similarly count fallback lines, so that we can decided later
7746 * to add the defaults manually.
7748 ++fallback_lines_seen;
7750 char *val = esc_for_log(var->initvalue);
7751 smartlist_add_asprintf(sl, "%s %s\n",var->name,val);
7752 tor_free(val);
7756 if (dirauth_lines_seen == 0) {
7758 * We didn't see any directory authorities with default values,
7759 * so add the list of default authorities manually.
7763 * default_authorities is defined earlier in this file and
7764 * is a const char ** NULL-terminated array of dirauth config
7765 * lines.
7767 for (const char **i = default_authorities; *i != NULL; ++i) {
7768 char *val = esc_for_log(*i);
7769 smartlist_add_asprintf(sl, "DirAuthority %s\n", val);
7770 tor_free(val);
7774 if (fallback_lines_seen == 0 &&
7775 get_options()->UseDefaultFallbackDirs == 1) {
7777 * We didn't see any explicitly configured fallback mirrors,
7778 * so add the defaults to the list manually.
7780 * default_fallbacks is included earlier in this file and
7781 * is a const char ** NULL-terminated array of fallback config lines.
7783 const char **i;
7785 for (i = default_fallbacks; *i != NULL; ++i) {
7786 char *val = esc_for_log(*i);
7787 smartlist_add_asprintf(sl, "FallbackDir %s\n", val);
7788 tor_free(val);
7792 *answer = smartlist_join_strings(sl, "", 0, NULL);
7793 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
7794 smartlist_free(sl);
7796 return 0;
7799 /** Parse outbound bind address option lines. If <b>validate_only</b>
7800 * is not 0 update OutboundBindAddressIPv4_ and
7801 * OutboundBindAddressIPv6_ in <b>options</b>. On failure, set
7802 * <b>msg</b> (if provided) to a newly allocated string containing a
7803 * description of the problem and return -1. */
7804 static int
7805 parse_outbound_addresses(or_options_t *options, int validate_only, char **msg)
7807 const config_line_t *lines = options->OutboundBindAddress;
7808 int found_v4 = 0, found_v6 = 0;
7810 if (!validate_only) {
7811 memset(&options->OutboundBindAddressIPv4_, 0,
7812 sizeof(options->OutboundBindAddressIPv4_));
7813 memset(&options->OutboundBindAddressIPv6_, 0,
7814 sizeof(options->OutboundBindAddressIPv6_));
7816 while (lines) {
7817 tor_addr_t addr, *dst_addr = NULL;
7818 int af = tor_addr_parse(&addr, lines->value);
7819 switch (af) {
7820 case AF_INET:
7821 if (found_v4) {
7822 if (msg)
7823 tor_asprintf(msg, "Multiple IPv4 outbound bind addresses "
7824 "configured: %s", lines->value);
7825 return -1;
7827 found_v4 = 1;
7828 dst_addr = &options->OutboundBindAddressIPv4_;
7829 break;
7830 case AF_INET6:
7831 if (found_v6) {
7832 if (msg)
7833 tor_asprintf(msg, "Multiple IPv6 outbound bind addresses "
7834 "configured: %s", lines->value);
7835 return -1;
7837 found_v6 = 1;
7838 dst_addr = &options->OutboundBindAddressIPv6_;
7839 break;
7840 default:
7841 if (msg)
7842 tor_asprintf(msg, "Outbound bind address '%s' didn't parse.",
7843 lines->value);
7844 return -1;
7846 if (!validate_only)
7847 tor_addr_copy(dst_addr, &addr);
7848 lines = lines->next;
7850 return 0;
7853 /** Load one of the geoip files, <a>family</a> determining which
7854 * one. <a>default_fname</a> is used if on Windows and
7855 * <a>fname</a> equals "<default>". */
7856 static void
7857 config_load_geoip_file_(sa_family_t family,
7858 const char *fname,
7859 const char *default_fname)
7861 #ifdef _WIN32
7862 char *free_fname = NULL; /* Used to hold any temporary-allocated value */
7863 /* XXXX Don't use this "<default>" junk; make our filename options
7864 * understand prefixes somehow. -NM */
7865 if (!strcmp(fname, "<default>")) {
7866 const char *conf_root = get_windows_conf_root();
7867 tor_asprintf(&free_fname, "%s\\%s", conf_root, default_fname);
7868 fname = free_fname;
7870 geoip_load_file(family, fname);
7871 tor_free(free_fname);
7872 #else
7873 (void)default_fname;
7874 geoip_load_file(family, fname);
7875 #endif
7878 /** Load geoip files for IPv4 and IPv6 if <a>options</a> and
7879 * <a>old_options</a> indicate we should. */
7880 static void
7881 config_maybe_load_geoip_files_(const or_options_t *options,
7882 const or_options_t *old_options)
7884 /* XXXX Reload GeoIPFile on SIGHUP. -NM */
7886 if (options->GeoIPFile &&
7887 ((!old_options || !opt_streq(old_options->GeoIPFile,
7888 options->GeoIPFile))
7889 || !geoip_is_loaded(AF_INET)))
7890 config_load_geoip_file_(AF_INET, options->GeoIPFile, "geoip");
7891 if (options->GeoIPv6File &&
7892 ((!old_options || !opt_streq(old_options->GeoIPv6File,
7893 options->GeoIPv6File))
7894 || !geoip_is_loaded(AF_INET6)))
7895 config_load_geoip_file_(AF_INET6, options->GeoIPv6File, "geoip6");
7898 /** Initialize cookie authentication (used so far by the ControlPort
7899 * and Extended ORPort).
7901 * Allocate memory and create a cookie (of length <b>cookie_len</b>)
7902 * in <b>cookie_out</b>.
7903 * Then write it down to <b>fname</b> and prepend it with <b>header</b>.
7905 * If <b>group_readable</b> is set, set <b>fname</b> to be readable
7906 * by the default GID.
7908 * If the whole procedure was successful, set
7909 * <b>cookie_is_set_out</b> to True. */
7911 init_cookie_authentication(const char *fname, const char *header,
7912 int cookie_len, int group_readable,
7913 uint8_t **cookie_out, int *cookie_is_set_out)
7915 char cookie_file_str_len = strlen(header) + cookie_len;
7916 char *cookie_file_str = tor_malloc(cookie_file_str_len);
7917 int retval = -1;
7919 /* We don't want to generate a new cookie every time we call
7920 * options_act(). One should be enough. */
7921 if (*cookie_is_set_out) {
7922 retval = 0; /* we are all set */
7923 goto done;
7926 /* If we've already set the cookie, free it before re-setting
7927 it. This can happen if we previously generated a cookie, but
7928 couldn't write it to a disk. */
7929 if (*cookie_out)
7930 tor_free(*cookie_out);
7932 /* Generate the cookie */
7933 *cookie_out = tor_malloc(cookie_len);
7934 crypto_rand((char *)*cookie_out, cookie_len);
7936 /* Create the string that should be written on the file. */
7937 memcpy(cookie_file_str, header, strlen(header));
7938 memcpy(cookie_file_str+strlen(header), *cookie_out, cookie_len);
7939 if (write_bytes_to_file(fname, cookie_file_str, cookie_file_str_len, 1)) {
7940 log_warn(LD_FS,"Error writing auth cookie to %s.", escaped(fname));
7941 goto done;
7944 #ifndef _WIN32
7945 if (group_readable) {
7946 if (chmod(fname, 0640)) {
7947 log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
7950 #else
7951 (void) group_readable;
7952 #endif
7954 /* Success! */
7955 log_info(LD_GENERAL, "Generated auth cookie file in '%s'.", escaped(fname));
7956 *cookie_is_set_out = 1;
7957 retval = 0;
7959 done:
7960 memwipe(cookie_file_str, 0, cookie_file_str_len);
7961 tor_free(cookie_file_str);
7962 return retval;