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 */
9 * \brief Code to parse and interpret configuration files.
12 #define CONFIG_PRIVATE
15 #include "addressmap.h"
17 #include "circuitbuild.h"
18 #include "circuitlist.h"
19 #include "circuitmux.h"
20 #include "circuitmux_ewma.h"
21 #include "circuitstats.h"
23 #include "connection.h"
24 #include "connection_edge.h"
25 #include "connection_or.h"
27 #include "confparse.h"
28 #include "cpuworker.h"
32 #include "entrynodes.h"
34 #include "hibernate.h"
36 #include "networkstatus.h"
40 #include "rendclient.h"
41 #include "rendservice.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"
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
66 #include <systemd/sd-daemon.h>
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
),
81 PLURAL(Tor2webRendezvousPoint
),
83 PLURAL(LongLivedPort
),
84 PLURAL(HiddenServiceNode
),
85 PLURAL(HiddenServiceExcludeNode
),
88 PLURAL(RecommendedPackage
),
89 PLURAL(RendExcludeNode
),
90 PLURAL(StrictEntryNode
),
91 PLURAL(StrictExitNode
),
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},
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), \
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
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"),
271 V(GeoIPFile
, FILENAME
, "<default>"),
272 V(GeoIPv6File
, FILENAME
, "<default>"),
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"),
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
,
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, "
481 V(TestingServerConsensusDownloadSchedule
, CSV_INTERVAL
, "0, 0, 60, "
482 "300, 600, 1800, 1800, 1800, 1800, "
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
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, "
569 V(TestingClientDownloadSchedule
, CSV_INTERVAL
, "0, 0, 5, 10, 15, 20, "
571 V(TestingServerConsensusDownloadSchedule
, CSV_INTERVAL
, "0, 0, 5, 10, "
573 V(TestingClientConsensusDownloadSchedule
, CSV_INTERVAL
, "0, 0, 5, 10, "
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
}
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 "
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 "
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 "
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. */
634 static char *get_windows_conf_root(void);
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,
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
,
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
,
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
),
679 STRUCT_OFFSET(or_options_t
, magic_
),
681 option_deprecation_notes_
,
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
*,
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
)
741 smartlist_t
*elements
;
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) {
749 global_options
= old_options
;
752 if (options_act(old_options
) < 0) { /* acting on the options failed. die. */
754 "Acting on config options left us in a broken state. Dying.");
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
) {
768 if (!config_is_same(&options_format
, new_val
, old_options
, var_name
)) {
769 line
= config_get_assigned_option(&options_format
, new_val
,
774 for (; line
; line
= next
) {
776 smartlist_add(elements
, line
->key
);
777 smartlist_add(elements
, line
->value
);
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
);
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. */
809 if (the_tor_version
== NULL
) {
810 if (strlen(tor_git_revision
)) {
811 tor_asprintf(&the_tor_version
, "%s (git-%s)", get_short_version(),
814 the_tor_version
= tor_strdup(get_short_version());
817 return the_tor_version
;
820 /** Return the current Tor version, without any git tag. */
822 get_short_version(void)
825 if (the_short_tor_version
== NULL
) {
827 tor_asprintf(&the_short_tor_version
, "%s (%s)", VERSION
, TOR_BUILD_TAG
);
829 the_short_tor_version
= tor_strdup(VERSION
);
832 return the_short_tor_version
;
835 /** Release additional memory allocated in options
838 or_options_free(or_options_t
*options
)
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.
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,
890 * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
893 safe_str_client(const char *address
)
896 if (get_options()->SafeLogging_
== SAFELOG_SCRUB_ALL
)
902 /** Make <b>address</b> -- a piece of information of unspecified sensitivity
903 * -- safe to log according to the settings in options->SafeLogging, and
906 * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
910 safe_str(const char *address
)
913 if (get_options()->SafeLogging_
!= SAFELOG_SCRUB_NONE
)
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
923 escaped_safe_str_client(const char *address
)
925 if (get_options()->SafeLogging_
== SAFELOG_SCRUB_ALL
)
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
935 escaped_safe_str(const char *address
)
937 if (get_options()->SafeLogging_
!= SAFELOG_SCRUB_NONE
)
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",
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",
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",
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"
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. */
992 add_default_trusted_dir_authorities(dirinfo_type_t type
)
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
1006 add_default_fallback_dir_servers
,(void))
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.
1022 validate_dir_servers(or_options_t
*options
, or_options_t
*old_options
)
1026 if (options
->DirAuthorities
&&
1027 (options
->AlternateDirAuthority
|| options
->AlternateBridgeAuthority
)) {
1029 "You cannot set both DirAuthority and Alternate*Authority.");
1033 /* do we want to complain to the user about being partitionable? */
1034 if ((options
->DirAuthorities
&&
1036 !config_lines_eq(options
->DirAuthorities
,
1037 old_options
->DirAuthorities
))) ||
1038 (options
->AlternateDirAuthority
&&
1040 !config_lines_eq(options
->AlternateDirAuthority
,
1041 old_options
->AlternateDirAuthority
)))) {
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)
1057 for (cl
= options
->AlternateBridgeAuthority
; cl
; cl
= cl
->next
)
1058 if (parse_dir_authority_line(cl
->value
, NO_DIRINFO
, 1)<0)
1060 for (cl
= options
->AlternateDirAuthority
; cl
; cl
= cl
->next
)
1061 if (parse_dir_authority_line(cl
->value
, NO_DIRINFO
, 1)<0)
1063 for (cl
= options
->FallbackDir
; cl
; cl
= cl
->next
)
1064 if (parse_dir_fallback_line(cl
->value
, 1)<0)
1069 /** Look at all the config options and assign new dir authorities
1073 consider_adding_dir_servers(const or_options_t
*options
,
1074 const or_options_t
*old_options
)
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)
1125 for (cl
= options
->AlternateBridgeAuthority
; cl
; cl
= cl
->next
)
1126 if (parse_dir_authority_line(cl
->value
, NO_DIRINFO
, 0)<0)
1128 for (cl
= options
->AlternateDirAuthority
; cl
; cl
= cl
->next
)
1129 if (parse_dir_authority_line(cl
->value
, NO_DIRINFO
, 0)<0)
1131 for (cl
= options
->FallbackDir
; cl
; cl
= cl
->next
)
1132 if (parse_dir_fallback_line(cl
->value
, 0)<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.
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;
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
1162 if (running_tor
&& options
->RunAsDaemon
) {
1163 /* No need to roll back, since you can't change the value. */
1168 /* Our PID may have changed, inform supervisor */
1169 sd_notifyf(0, "MAINPID=%ld\n", (long int)getpid());
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.");
1179 if (options
->ControlSocketsGroupWritable
&& !options
->ControlSocket
) {
1180 *msg
= tor_strdup("Setting ControlSocketGroupWritable without setting"
1181 "a ControlSocket makes no sense.");
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.");
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. */
1220 /* Adjust the port configuration so we can launch listeners. */
1221 if (parse_ports(options
, 0, msg
, &n_ports
, NULL
)) {
1223 *msg
= tor_strdup("Unexpected problem parsing port config");
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.");
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 "
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.");
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 "
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.");
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
,
1298 "Couldn't access/create private data directory \"%s\"",
1299 options
->DataDirectory
);
1302 /* No need to roll back, since you can't change the value. */
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
));
1315 /* Bail out at this point if we're not going to be a client or server:
1316 * we don't run Tor itself. */
1320 mark_logs_temp(); /* Close current logs once new logs are open. */
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.");
1327 logs_initialized
= 1;
1332 log_severity_list_t
*severity
=
1333 tor_malloc_zero(sizeof(log_severity_list_t
));
1335 add_callback_log(severity
, control_event_logmsg
);
1336 control_adjust_event_log_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
) {
1349 if (!old_options
|| old_options
->SafeLogging_
!= options
->SafeLogging_
)
1352 if (get_min_log_level() >= LOG_INFO
) {
1354 if (get_min_log_level() != old_min_log_level
)
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";
1363 badness
= "you're logging more than \"notice\"";
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
);
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
1390 * Somewhat arbitrarily, set socks_in_reserve to 5% of ConnLimit_, but
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);
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
);
1433 smartlist_free(new_listeners
);
1434 smartlist_free(replaced_listeners
);
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
)
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 "
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 "
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. */
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. */
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. */
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
);
1501 if (!opt_streq(old_options
->TLSECGroup
, new_options
->TLSECGroup
))
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.
1517 options_act(const or_options_t
*old_options
)
1520 or_options_t
*options
= get_options_mutable();
1521 int running_tor
= options
->command
== CMD_RUN_TOR
;
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
&&
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 "
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)
1561 if (consider_adding_dir_servers(options
, old_options
) < 0)
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 "
1577 /* LCOV_EXCL_STOP */
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.");
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
) {
1603 for (cl
= options
->Bridges
; cl
; cl
= cl
->next
) {
1604 bridge_line_t
*bridge_line
= parse_bridge_line(cl
->value
);
1607 "Previously validated Bridge line could not be added!");
1610 bridge_add_from_config(bridge_line
);
1612 sweep_bridge_list();
1615 if (running_tor
&& rend_config_services(options
, 0)<0) {
1617 "Previously validated hidden services line could not be added!");
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!");
1628 if (! or_state_loaded() && running_tor
) {
1629 if (or_state_load())
1631 rep_hist_load_mtbf_data(time(NULL
));
1634 /* If we have an ExtORPort, initialize its auth cookie. */
1636 init_ext_or_cookie_authentication(!!options
->ExtORPort_lines
) < 0) {
1637 log_warn(LD_CONFIG
,"Error creating Extended ORPort cookie file.");
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) {
1648 "Previously validated ClientTransportPlugin line "
1649 "could not be added!");
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) {
1659 "Previously validated ServerTransportPlugin line "
1660 "could not be added!");
1666 sweep_transport_list();
1669 /* Start the PT proxy configuration. By doing this configuration
1670 here, we also figure out which proxies need to be restarted and
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. */
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");
1695 } else if (old_options
&&
1696 options_transition_requires_fresh_tls_context(old_options
,
1698 if (router_initialize_tls_context() < 0) {
1699 log_warn(LD_BUG
,"Error initializing TLS context.");
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.");
1722 if (init_control_cookie_authentication(options
->CookieAuthentication
) < 0) {
1723 log_warn(LD_CONFIG
,"Error creating control cookie authentication file.");
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
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.");
1741 if (rend_service_poison_new_single_onion_dirs(NULL
) < 0) {
1742 log_warn(LD_GENERAL
,"Failed to mark new hidden services as Single "
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");
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");
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 "
1790 options
->BridgePassword_AuthDigest_
= tor_malloc(DIGEST256_LEN
);
1791 crypto_digest256(options
->BridgePassword_AuthDigest_
,
1792 http_authenticator
, strlen(http_authenticator
),
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
);
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;
1810 changed
= routerset_add_unknown_ccs(&options
->ExcludeNodes
, is_auto
);
1811 changed
+= routerset_add_unknown_ccs(&options
->ExcludeExitNodes
, is_auto
);
1814 routerset_add_unknown_ccs(&options
->ExcludeExitNodesUnion_
, is_auto
);
1817 /* Check for transitions that need action. */
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
) {
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;
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
)) {
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
;
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" : "");
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
)) {
1898 ip_address_changed(0);
1899 if (have_completed_a_circuit() || !any_predicted_circuits(time(NULL
)))
1900 inform_testing_reachability();
1902 cpuworkers_rotate_keyinfo();
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
);
1941 if ((!old_options
|| !old_options
->DirReqStatistics
) &&
1942 options
->DirReqStatistics
) {
1943 if (geoip_is_loaded(AF_INET
)) {
1944 geoip_dirreq_stats_init(now
);
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
);
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
);
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
);
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
&&
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.
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. */
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
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
) {
2056 "DirPortFrontPage file '%s' not found. Continuing anyway.",
2057 options
->DirPortFrontPage
);
2065 TAKES_NO_ARGUMENT
= 0,
2066 ARGUMENT_NECESSARY
= 1,
2067 ARGUMENT_OPTIONAL
= 2
2070 static const struct {
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
},
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>
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
;
2121 unsigned command
= CONFIG_LINE_NORMAL
;
2122 takes_argument_t want_arg
= ARGUMENT_NECESSARY
;
2126 for (j
= 0; CMDLINE_ONLY_OPTIONS
[j
].name
!= NULL
; ++j
) {
2127 if (!strcmp(argv
[i
], CMDLINE_ONLY_OPTIONS
[j
].name
)) {
2129 want_arg
= CMDLINE_ONLY_OPTIONS
[j
].takes_argument
;
2136 /* Each keyword may be prefixed with one or two dashes. */
2141 /* Figure out the command, if any. */
2144 command
= CONFIG_LINE_APPEND
;
2145 } else if (*s
== '/') {
2147 command
= CONFIG_LINE_CLEAR
;
2148 /* A 'clear' command has no argument. */
2152 const int is_last
= (i
== argc
-1);
2154 if (want_arg
== ARGUMENT_NECESSARY
&& is_last
) {
2155 if (ignore_errors
) {
2156 arg
= tor_strdup("");
2158 log_warn(LD_CONFIG
,"Command-line option '%s' with no value. Failing.",
2160 config_free_lines(front
);
2161 config_free_lines(front_cmdline
);
2164 } else if (want_arg
== ARGUMENT_OPTIONAL
&& is_last
) {
2165 arg
= tor_strdup("");
2167 arg
= (want_arg
!= TAKES_NO_ARGUMENT
) ? tor_strdup(argv
[i
+1]) :
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));
2175 param
->command
= command
;
2177 log_debug(LD_CONFIG
, "command line: parsed keyword '%s', value '%s'",
2178 param
->key
, param
->value
);
2181 *new_cmdline
= param
;
2182 new_cmdline
= &((*new_cmdline
)->next
);
2185 new = &((*new)->next
);
2188 i
+= want_arg
? 2 : 1;
2190 *cmdline_result
= front_cmdline
;
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. */
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.
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
2230 options_trial_assign(config_line_t
*list
, unsigned flags
, char **msg
)
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
);
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. */
2261 /** Print a usage message for tor. */
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. */
2276 list_torrc_options(void)
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
)
2284 printf("%s\n", var
->name
);
2288 /** Print all deprecated but non-obsolete torrc options. */
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. */
2303 get_last_resolved_addr(void)
2305 return last_resolved_addr
;
2308 /** Reset last_resolved_addr from outside this file. */
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,
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.)
2364 resolve_my_address(int warn_severity
, const or_options_t
*options
,
2366 const char **method_out
, char **hostname_out
)
2369 uint32_t addr
; /* host order */
2371 const char *method_used
;
2372 const char *hostname_used
;
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
;
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");
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 */
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
);
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.");
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
));
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
));
2460 addr
= ntohl(in
.s_addr
); /* set addr so that addr_string is not
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
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
);
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
);
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
);
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
;
2513 method_used
= "GETHOSTNAME";
2514 hostname_used
= hostname
;
2519 *method_out
= method_used
;
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
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. */
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
);
2558 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2559 * on a private network.
2562 is_local_addr
, (const tor_addr_t
*addr
))
2564 if (tor_addr_is_internal(addr
, 0))
2566 /* Check whether ip is on the same /24 as we are. */
2567 if (get_options()->EnforceDistinctSubnets
== 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
))
2586 /** Return a new empty or_options_t. Used for testing. */
2590 return config_new(&options_format
);
2593 /** Set <b>options</b> to hold reasonable defaults for most options.
2594 * Each option defaults to zero. */
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.
2606 options_dump(const or_options_t
*options
, int how_to_dump
)
2608 const or_options_t
*use_defaults
;
2610 switch (how_to_dump
) {
2611 case OPTIONS_DUMP_MINIMAL
:
2612 use_defaults
= global_default_options
;
2615 case OPTIONS_DUMP_DEFAULTS
:
2616 use_defaults
= NULL
;
2619 case OPTIONS_DUMP_ALL
:
2620 use_defaults
= NULL
;
2624 log_warn(LD_BUG
, "Bogus value for how_to_dump==%d", how_to_dump
);
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. */
2635 validate_ports_csv(smartlist_t
*sl
, const char *name
, char **msg
)
2643 SMARTLIST_FOREACH(sl
, const char *, cp
,
2646 if (i
< 1 || i
> 65535) {
2647 tor_asprintf(msg
, "Port '%s' out of range in %s", cp
, name
);
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.
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) */
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
);
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".
2679 * Return 0 on success or -1 if not a recognized authority type (in which
2680 * case the value of PublishServerDescriptor_ is undefined). */
2682 compute_publishserverdescriptor(or_options_t
*options
)
2684 smartlist_t
*list
= options
->PublishServerDescriptor
;
2685 dirinfo_type_t
*auth
= &options
->PublishServerDescriptor_
;
2687 if (!list
) /* empty list, answer is none */
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
;
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"))
2707 "PublishServerDescriptor hidserv is invalid. See "
2708 "PublishHidServDescriptors.");
2709 else if (!strcasecmp(string
, "") || !strcmp(string
, "0"))
2713 } SMARTLIST_FOREACH_END(string
);
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
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.
2751 #define RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT (10)
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
,
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
2767 #define COMPLAIN(args, ...) \
2768 STMT_BEGIN log_warn(LD_CONFIG, args, ##__VA_ARGS__); STMT_END
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.
2778 warn_if_option_path_is_relative(const char *option
,
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
);
2789 /** Scan <b>options</b> for occurances of relative file/directory
2790 * path and log a warning whenever it is found.
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. */
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 "
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 "
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 "
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"
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>.
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.
2917 options_validate(or_options_t
*old_options
, or_options_t
*options
,
2918 or_options_t
*default_options
, int from_setconf
, char **msg
)
2922 const char *uname
= get_uname();
2924 int world_writable_control_socket
=0;
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)
2951 if (parse_outbound_addresses(options
, 1, msg
) < 0)
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
);
2962 if (!is_legal_nickname(options
->Nickname
)) {
2964 "Nickname '%s', nicknames must be between 1 and 19 characters "
2965 "inclusive, and must contain only the characters [a-zA-Z0-9].",
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 */
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
)
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
)
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.");
3021 options
->TransProxyType_parsed
= TPT_PF_DIVERT
;
3023 } else if (!strcasecmp(options
->TransProxyType
, "tproxy")) {
3024 #if !defined(__linux__)
3025 REJECT("TPROXY is a Linux-specific feature.");
3027 options
->TransProxyType_parsed
= TPT_TPROXY
;
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.");
3035 options
->TransProxyType_parsed
= TPT_IPFW
;
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.");
3048 if (options
->TransPort_set
)
3049 REJECT("TransPort and TransListenAddress are disabled "
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");
3068 } else if (options
->SchedulerHighWaterMark__
<=
3069 options
->SchedulerLowWaterMark__
||
3070 options
->SchedulerHighWaterMark__
> UINT32_MAX
) {
3071 log_warn(LD_GENERAL
, "Bad SchedulerHighWaterMark option");
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
);
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) {
3162 "ConnLimit must be greater than 0, but was set to %d",
3163 options
->ConnLimit
);
3167 if (options
->PathsNeededToBuildCircuits
>= 0.0) {
3168 if (options
->PathsNeededToBuildCircuits
< 0.25) {
3169 log_warn(LD_CONFIG
, "PathsNeededToBuildCircuits is too low. Increasing "
3171 options
->PathsNeededToBuildCircuits
= 0.25;
3172 } else if (options
->PathsNeededToBuildCircuits
> 0.95) {
3173 log_warn(LD_CONFIG
, "PathsNeededToBuildCircuits is too high. Decreasing "
3175 options
->PathsNeededToBuildCircuits
= 0.95;
3179 if (options
->MaxClientCircuitsPending
<= 0 ||
3180 options
->MaxClientCircuitsPending
> MAX_MAX_CLIENT_CIRCUITS_PENDING
) {
3182 "MaxClientCircuitsPending must be between 1 and %d, but "
3183 "was set to %d", MAX_MAX_CLIENT_CIRCUITS_PENDING
,
3184 options
->MaxClientCircuitsPending
);
3188 if (validate_ports_csv(options
->FirewallPorts
, "FirewallPorts", msg
) < 0)
3191 if (validate_ports_csv(options
->LongLivedPorts
, "LongLivedPorts", msg
) < 0)
3194 if (validate_ports_csv(options
->RejectPlaintextPorts
,
3195 "RejectPlaintextPorts", msg
) < 0)
3198 if (validate_ports_csv(options
->WarnPlaintextPorts
,
3199 "WarnPlaintextPorts", msg
) < 0)
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
3212 SMARTLIST_FOREACH(options
->FirewallPorts
, const char *, portno
,
3214 int p
= atoi(portno
);
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\"",
3224 options
->ReachableAddresses
= new_line
;
3225 SMARTLIST_FOREACH(instead
, char *, cp
, tor_free(cp
));
3226 smartlist_free(instead
);
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
;
3258 /* We need to end with a reject *:*, not an implicit accept *:* */
3260 linep
= &((*linep
)->next
);
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 *:*");
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
;
3331 "Unrecognized value '%s' in AllowInvalidNodes", cp
);
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
;
3346 "Unrecognized value '%s' in SafeLogging",
3347 escaped(options
->SafeLogging
));
3351 if (compute_publishserverdescriptor(options
) < 0) {
3352 tor_asprintf(msg
, "Unrecognized value in PublishServerDescriptor");
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 "
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.",
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)
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;
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
)) {
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
)) {
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.");
3453 /* OnionServiceSingleHopMode: one hop between the onion service server and
3454 * intro and rendezvous points */
3455 if (options
->OnionServiceSingleHopMode
) {
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
) {
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 "
3486 if (options
->PathBiasNoticeRate
> 1.0) {
3488 "PathBiasNoticeRate is too high. "
3489 "It must be between 0 and 1.0");
3492 if (options
->PathBiasWarnRate
> 1.0) {
3494 "PathBiasWarnRate is too high. "
3495 "It must be between 0 and 1.0");
3498 if (options
->PathBiasExtremeRate
> 1.0) {
3500 "PathBiasExtremeRate is too high. "
3501 "It must be between 0 and 1.0");
3504 if (options
->PathBiasNoticeUseRate
> 1.0) {
3506 "PathBiasNoticeUseRate is too high. "
3507 "It must be between 0 and 1.0");
3510 if (options
->PathBiasExtremeUseRate
> 1.0) {
3512 "PathBiasExtremeUseRate is too high. "
3513 "It must be between 0 and 1.0");
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 "
3551 if (ensure_bandwidth_cap(&options
->BandwidthRate
,
3552 "BandwidthRate", msg
) < 0)
3554 if (ensure_bandwidth_cap(&options
->BandwidthBurst
,
3555 "BandwidthBurst", msg
) < 0)
3557 if (ensure_bandwidth_cap(&options
->MaxAdvertisedBandwidth
,
3558 "MaxAdvertisedBandwidth", msg
) < 0)
3560 if (ensure_bandwidth_cap(&options
->RelayBandwidthRate
,
3561 "RelayBandwidthRate", msg
) < 0)
3563 if (ensure_bandwidth_cap(&options
->RelayBandwidthBurst
,
3564 "RelayBandwidthBurst", msg
) < 0)
3566 if (ensure_bandwidth_cap(&options
->PerConnBWRate
,
3567 "PerConnBWRate", msg
) < 0)
3569 if (ensure_bandwidth_cap(&options
->PerConnBWBurst
,
3570 "PerConnBWBurst", msg
) < 0)
3572 if (ensure_bandwidth_cap(&options
->AuthDirFastGuarantee
,
3573 "AuthDirFastGuarantee", msg
) < 0)
3575 if (ensure_bandwidth_cap(&options
->AuthDirGuardBWGuarantee
,
3576 "AuthDirGuardBWGuarantee", msg
) < 0)
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
) {
3592 "BandwidthRate is set to %d bytes/second. "
3593 "For %sservers, it must be at least %u.",
3594 (int)options
->BandwidthRate
, optbridge
,
3597 } else if (options
->MaxAdvertisedBandwidth
<
3598 required_min_bw
/2) {
3600 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3601 "For %sservers, it must be at least %u.",
3602 (int)options
->MaxAdvertisedBandwidth
, optbridge
,
3606 if (options
->RelayBandwidthRate
&&
3607 options
->RelayBandwidthRate
< required_min_bw
) {
3609 "RelayBandwidthRate is set to %d bytes/second. "
3610 "For %sservers, it must be at least %u.",
3611 (int)options
->RelayBandwidthRate
, optbridge
,
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
;
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 "
3667 if (options
->BridgeRelay
&& !options
->DirCache
) {
3668 REJECT("We're a bridge but DirCache is disabled. BridgeRelay requires "
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
) {
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
);
3762 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3764 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
3769 if (options
->HashedControlSessionPassword
) {
3770 smartlist_t
*sl
= decode_hashed_passwords(
3771 options
->HashedControlSessionPassword
);
3773 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3775 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
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
);
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
))
3816 for (cl
= options
->NodeFamilies
; cl
; cl
= cl
->next
) {
3817 routerset_t
*rs
= routerset_new();
3818 if (routerset_parse(rs
, cl
->value
, cl
->key
)) {
3825 if (validate_addr_policies(options
, msg
) < 0)
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 "
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
);
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
);
3872 REJECT("ServerTransportListenAddr did not parse. See logs for details.");
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
);
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) {
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
);
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");
3928 COMPLAIN("V3AuthVoteDelay plus V3AuthDistDelay is more than half "
3929 "V3AuthVotingInterval. This may lead to "
3930 "consensus instability, particularly if clocks drift.");
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.");
3946 COMPLAIN("V3AuthVoteDelay is very low. "
3947 "This may lead to failure to vote for a consensus.");
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.");
3959 COMPLAIN("V3AuthDistDelay is very low. "
3960 "This may lead to missing votes in a consensus.");
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.");
3975 COMPLAIN("V3AuthVotingInterval is very low. "
3976 "This may lead to failure to synchronise for a consensus.");
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
,
3998 if (parse_virtual_addr_network(options
->VirtualAddrNetworkIPv6
,
3999 AF_INET6
, 1, msg
)<0)
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 "
4018 #define CHECK_DEFAULT(arg) \
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 " \
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 "
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 "
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 "
4124 } else if (options
->ClientBootstrapConsensusMaxDownloadTries
> 800) {
4125 COMPLAIN("ClientBootstrapConsensusMaxDownloadTries is insanely "
4129 if (options
->ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries
4131 REJECT("ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries must "
4132 "be greater than 2."
4135 options
->ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries
4137 COMPLAIN("ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries is "
4141 if (options
->ClientBootstrapConsensusMaxInProgressTries
< 1) {
4142 REJECT("ClientBootstrapConsensusMaxInProgressTries must be greater "
4144 } else if (options
->ClientBootstrapConsensusMaxInProgressTries
4146 COMPLAIN("ClientBootstrapConsensusMaxInProgressTries is insanely "
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 "
4174 if (options
->TestingEnableCellStatsEvent
&&
4175 !options
->TestingTorNetwork
&& !options
->UsingTestNetworkDefaults_
) {
4176 REJECT("TestingEnableCellStatsEvent may only be changed in testing "
4180 if (options
->TestingEnableTbEmptyEvent
&&
4181 !options
->TestingTorNetwork
&& !options
->UsingTestNetworkDefaults_
) {
4182 REJECT("TestingEnableTbEmptyEvent may only be changed in testing "
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.");
4210 if (options
->BridgeRelay
== 1 && ! options
->ORPort_set
)
4211 REJECT("BridgeRelay is 1, ORPort is not set. This is an invalid "
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. */
4224 compute_real_max_mem_in_queues(const uint64_t val
, int log_guess
)
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)
4234 #define MAX_DEFAULT_MAXMEM (2*ONE_GIGABYTE)
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;
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
;
4246 /* (presumably) 32-bit system. Let's hope for 1 GB. */
4247 result
= ONE_GIGABYTE
;
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
4257 result
= MAX_DEFAULT_MAXMEM
;
4258 } else if (avail
< ONE_GIGABYTE
/ 4) {
4259 result
= ONE_GIGABYTE
/ 4;
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
));
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;
4277 /* The value was fine all along */
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. */
4291 have_enough_mem_for_dircache(const or_options_t
*options
, size_t total_mem
,
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.");
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.");
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 "
4324 return *msg
== NULL
? 0 : -1;
4328 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
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. */
4338 options_transition_allowed(const or_options_t
*old
,
4339 const or_options_t
*new_val
,
4345 if (!opt_streq(old
->PidFile
, new_val
->PidFile
)) {
4346 *msg
= tor_strdup("PidFile is not allowed to change.");
4350 if (old
->RunAsDaemon
!= new_val
->RunAsDaemon
) {
4351 *msg
= tor_strdup("While Tor is running, changing RunAsDaemon "
4356 if (old
->Sandbox
!= new_val
->Sandbox
) {
4357 *msg
= tor_strdup("While Tor is running, changing Sandbox "
4362 if (strcmp(old
->DataDirectory
,new_val
->DataDirectory
)!=0) {
4364 "While Tor is running, changing DataDirectory "
4365 "(\"%s\"->\"%s\") is not allowed.",
4366 old
->DataDirectory
, new_val
->DataDirectory
);
4370 if (!opt_streq(old
->User
, new_val
->User
)) {
4371 *msg
= tor_strdup("While Tor is running, changing User is not allowed.");
4375 if (old
->KeepBindCapabilities
!= new_val
->KeepBindCapabilities
) {
4376 *msg
= tor_strdup("While Tor is running, changing KeepBindCapabilities is "
4381 if (!opt_streq(old
->SyslogIdentityTag
, new_val
->SyslogIdentityTag
)) {
4382 *msg
= tor_strdup("While Tor is running, changing "
4383 "SyslogIdentityTag is not allowed.");
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.");
4395 if (old
->TestingTorNetwork
!= new_val
->TestingTorNetwork
) {
4396 *msg
= tor_strdup("While Tor is running, changing TestingTorNetwork "
4401 if (old
->DisableAllSwap
!= new_val
->DisableAllSwap
) {
4402 *msg
= tor_strdup("While Tor is running, changing DisableAllSwap "
4407 if (old
->TokenBucketRefillInterval
!= new_val
->TokenBucketRefillInterval
) {
4408 *msg
= tor_strdup("While Tor is running, changing TokenBucketRefill"
4409 "Interval is not allowed");
4413 if (old
->OnionServiceSingleHopMode
!= new_val
->OnionServiceSingleHopMode
) {
4414 *msg
= tor_strdup("While Tor is running, changing "
4415 "OnionServiceSingleHopMode is not allowed.");
4419 if (old
->OnionServiceNonAnonymousMode
!=
4420 new_val
->OnionServiceNonAnonymousMode
) {
4421 *msg
= tor_strdup("While Tor is running, changing "
4422 "OnionServiceNonAnonymousMode is not allowed.");
4426 if (old
->DisableDebuggerAttachment
&&
4427 !new_val
->DisableDebuggerAttachment
) {
4428 *msg
= tor_strdup("While Tor is running, disabling "
4429 "DisableDebuggerAttachment is not allowed.");
4433 if (sandbox_is_active()) {
4434 #define SB_NOCHANGE_STR(opt) \
4436 if (! opt_streq(old->opt, new_val->opt)) { \
4437 *msg = tor_strdup("Can't change " #opt " while Sandbox is active"); \
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");
4455 if (old
->ConnLimit
!= new_val
->ConnLimit
) {
4456 *msg
= tor_strdup("Can't change ConnLimit while Sandbox is active");
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");
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. */
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
)
4487 /* Check whether log options match. */
4489 /* Nothing that changed matters. */
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. */
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
)
4536 /** Return the directory on windows where we expect to find our application
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};
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
4558 #define APPDATA_PATH CSIDL_APPDATA
4560 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL
, APPDATA_PATH
, &idl
))) {
4561 getcwd(path
,MAX_PATH
);
4564 "I couldn't find your application data folder: are you "
4565 "running an ancient version of Windows 95? Defaulting to \"%s\"",
4569 /* Convert the path from an "ID List" (whatever that is!) to a path. */
4570 result
= SHGetPathFromIDList(idl
, tpath
);
4572 wcstombs(path
,tpath
,sizeof(path
));
4573 path
[sizeof(path
)-1] = '\0';
4575 strlcpy(path
,tpath
,sizeof(path
));
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. */
4582 m
->lpVtbl
->Free(m
, idl
);
4583 m
->lpVtbl
->Release(m
);
4585 if (!SUCCEEDED(result
)) {
4588 strlcat(path
,"\\tor",MAX_PATH
);
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). */
4597 get_default_conf_file(int defaults_file
)
4599 #ifdef DISABLE_SYSTEM_TORRC
4600 (void) defaults_file
;
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
;
4609 static char path
[MAX_PATH
+1];
4610 tor_snprintf(path
, MAX_PATH
, "%s\\torrc",
4611 get_windows_conf_root());
4615 return defaults_file
? CONFDIR
"/torrc-defaults" : CONFDIR
"/torrc";
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.
4625 check_nickname_list(char **lst
, const char *name
, char **msg
)
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
4643 // Try again but with a dollar symbol 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
4651 SMARTLIST_REPLACE_CURRENT(sl
, s
, prepended
);
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
);
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
);
4671 *lst
= newNicknames
;
4674 SMARTLIST_FOREACH(sl
, char *, s
, tor_free(s
));
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.
4692 find_torrc_filename(config_line_t
*cmd_arg
,
4694 int *using_default_fname
, int *ignore_missing_torrc
)
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";
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
)) {
4707 log_warn(LD_CONFIG
, "Duplicate %s options on command line.",
4711 fname
= expand_filename(p_index
->value
);
4715 absfname
= make_path_absolute(fname
);
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
);
4735 if (!defaults_file
) {
4736 fn
= expand_filename("~/.torrc");
4739 file_status_t hmst
= file_status(fn
);
4740 if (hmst
== FN_FILE
|| hmst
== FN_EMPTY
|| dflt
== NULL
) {
4744 fname
= tor_strdup(dflt
);
4747 fname
= dflt
? tor_strdup(dflt
) : NULL
;
4750 fname
= dflt
? tor_strdup(dflt
) : NULL
;
4757 /** Read the torrc from standard input and return it as a string.
4758 * Upon failure, return NULL.
4761 load_torrc_from_stdin(void)
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.
4776 load_torrc_from_disk(config_line_t
*cmd_arg
, int defaults_file
)
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
);
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
) {
4801 log_notice(LD_CONFIG
, "Configuration file \"%s\" not present, "
4802 "using reasonable defaults.", fname
);
4803 tor_free(fname
); /* sets fname to NULL */
4805 cf
= tor_strdup("");
4808 "Unable to open configuration file \"%s\".", fname
);
4812 log_notice(LD_CONFIG
, "Read configuration file \"%s\".", fname
);
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
;
4832 char *command_arg
= 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) {
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")) {
4854 if (config_line_find(cmdline_only_options
, "--list-torrc-options")) {
4855 /* For validating whether we've documented everything. */
4856 list_torrc_options();
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();
4865 if (config_line_find(cmdline_only_options
, "--version")) {
4866 printf("Tor version %s.\n",get_version());
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?
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("");
4907 cf_defaults
= load_torrc_from_disk(cmdline_only_options
, 1);
4909 const config_line_t
*f_line
= config_line_find(cmdline_only_options
,
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();
4918 cf
= load_torrc_from_disk(cmdline_only_options
, 0);
4922 if (config_line_find(cmdline_only_options
, "--allow-missing-torrc")) {
4923 cf
= tor_strdup("");
4930 retval
= options_init_from_string(cf_defaults
, cf
, command
, command_arg
,
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
;
4940 log_err(LD_CONFIG
, "--no-passphrase specified without --keygen!");
4945 if (config_line_find(cmdline_only_options
, "--newpass")) {
4946 if (command
== CMD_KEYGEN
) {
4947 get_options_mutable()->change_key_passphrase
= 1;
4949 log_err(LD_CONFIG
, "--newpass specified without --keygen!");
4955 const config_line_t
*fd_line
= config_line_find(cmdline_only_options
,
4958 if (get_options()->keygen_force_passphrase
== FORCE_PASSPHRASE_OFF
) {
4959 log_err(LD_CONFIG
, "--no-passphrase specified with --passphrase-fd!");
4961 } else if (command
!= CMD_KEYGEN
) {
4962 log_err(LD_CONFIG
, "--passphrase-fd specified without --keygen!");
4965 const char *v
= fd_line
->value
;
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
));
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
,
4983 if (command
!= CMD_KEYGEN
) {
4984 log_err(LD_CONFIG
, "--master-key without --keygen!");
4987 get_options_mutable()->master_key_fname
= tor_strdup(key_line
->value
);
4995 tor_free(cf_defaults
);
4997 log_warn(LD_CONFIG
,"%s", 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
5013 options_init_from_string(const char *cf_defaults
, const char *cf
,
5014 int command
, const char *command_arg
,
5017 or_options_t
*oldoptions
, *newoptions
, *newdefaultoptions
=NULL
;
5020 setopt_err_t err
= SETOPT_ERR_MISC
;
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
;
5036 /* get config lines, assign them */
5037 retval
= config_get_lines(body
, &cl
, 1);
5039 err
= SETOPT_ERR_PARSE
;
5042 retval
= config_assign(&options_format
, newoptions
, cl
,
5043 CAL_WARN_DEPRECATIONS
, msg
);
5044 config_free_lines(cl
);
5046 err
= SETOPT_ERR_PARSE
;
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
);
5061 err
= SETOPT_ERR_PARSE
;
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?",
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
;
5107 /* get config lines, assign them */
5108 retval
= config_get_lines(body
, &cl
, 1);
5110 err
= SETOPT_ERR_PARSE
;
5113 retval
= config_assign(&options_format
, newoptions
, cl
, 0, msg
);
5114 config_free_lines(cl
);
5116 err
= SETOPT_ERR_PARSE
;
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
);
5126 err
= SETOPT_ERR_PARSE
;
5131 /* Validate newoptions */
5132 if (options_validate(oldoptions
, newoptions
, newdefaultoptions
,
5134 err
= SETOPT_ERR_PARSE
; /*XXX make this a separate return value.*/
5138 if (options_transition_allowed(oldoptions
, newoptions
, msg
) < 0) {
5139 err
= SETOPT_ERR_TRANSITION
;
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
;
5153 or_options_free(newoptions
);
5154 or_options_free(newdefaultoptions
);
5156 char *old_msg
= *msg
;
5157 tor_asprintf(msg
, "Failed to parse/validate config: %s", old_msg
);
5163 /** Return the location for our configuration file. May return NULL.
5166 get_torrc_fname(int defaults_fname
)
5168 const char *fname
= defaults_fname
? torrc_defaults_fname
: torrc_fname
;
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>
5180 config_register_addressmaps(const or_options_t
*options
)
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.",
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
);
5206 if (addressmap_register_auto(from
, to
, 0, ADDRMAPSRC_TORRC
, &msg
) < 0) {
5207 log_warn(LD_CONFIG
,"MapAddress '%s' failed: %s. Ignoring.", opt
->value
,
5212 if (smartlist_len(elts
) > 2)
5213 log_warn(LD_CONFIG
,"Ignoring extra arguments to MapAddress.");
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
,
5228 addressmap_entry_source_t addrmap_source
,
5231 int from_wildcard
= 0, to_wildcard
= 0;
5233 *msg
= "whoops, forgot the error message";
5235 if (!strcmp(to
, "*") || !strcmp(from
, "*")) {
5236 *msg
= "can't remap from or to *";
5239 /* Detect asterisks in expressions of type: '*.example.com' */
5240 if (!strncmp(from
,"*.",2)) {
5244 if (!strncmp(to
,"*.",2)) {
5249 if (to_wildcard
&& !from_wildcard
) {
5250 *msg
= "can only use wildcard (i.e. '*.') if 'from' address "
5251 "uses wildcard also";
5255 if (address_is_invalid_destination(to
, 1)) {
5256 *msg
= "destination is invalid";
5260 addressmap_register(from
, tor_strdup(to
), expires
, addrmap_source
,
5261 from_wildcard
, to_wildcard
);
5267 * Initialize the logs based on the configuration file.
5270 options_init_logs(const or_options_t
*old_options
, or_options_t
*options
,
5280 options
->RunAsDaemon
;
5283 if (options
->LogTimeGranularity
<= 0) {
5284 log_warn(LD_CONFIG
, "Log time granularity '%d' has to be positive.",
5285 options
->LogTimeGranularity
);
5287 } else if (1000 % options
->LogTimeGranularity
!= 0 &&
5288 options
->LogTimeGranularity
% 1000 != 0) {
5289 int granularity
= options
->LogTimeGranularity
;
5290 if (granularity
< 40) {
5292 while (1000 % granularity
!= 0);
5293 } else if (granularity
< 1000) {
5294 granularity
= 1000 / granularity
;
5295 while (1000 % granularity
!= 0)
5297 granularity
= 1000 / granularity
;
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 "
5304 options
->LogTimeGranularity
, granularity
);
5306 set_log_time_granularity(granularity
);
5309 set_log_time_granularity(options
->LogTimeGranularity
);
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'",
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
) {
5339 "Can't log to %s with RunAsDaemon set; skipping stdout",
5340 err
?"stderr":"stdout");
5342 add_stream_log(severity
, err
?"<stderr>":"<stdout>",
5343 fileno(err
?stderr
:stdout
));
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
);
5355 log_warn(LD_CONFIG
, "Syslog is not supported on this system. Sorry.");
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
5366 int truncate_log
= 0;
5367 if (options
->TruncateLogFile
) {
5370 config_line_t
*opt2
;
5371 for (opt2
= old_options
->Logs
; opt2
; opt2
= opt2
->next
)
5372 if (!strcmp(opt
->value
, opt2
->value
)) {
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
));
5388 log_warn(LD_CONFIG
, "Bad syntax on file Log option 'Log %s'",
5390 ok
= 0; goto cleanup
;
5393 SMARTLIST_FOREACH(elts
, char*, cp
, tor_free(cp
));
5394 smartlist_clear(elts
);
5397 smartlist_free(elts
);
5399 if (ok
&& !validate_only
)
5400 logs_set_domain_logging(options
->LogMessageDomains
);
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. */
5409 validate_transport_socks_arguments(const smartlist_t
*args
)
5411 char *socks_string
= NULL
;
5412 size_t socks_string_len
;
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
);
5422 } SMARTLIST_FOREACH_END(s
);
5424 socks_string
= pt_stringify_socks_args(args
);
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
);
5441 /** Deallocate a bridge_line_t structure. */
5443 bridge_line_free(bridge_line_t
*bridge_line
)
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
;
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.");
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.");
5491 addrport
= smartlist_get(items
, 0); /* Next field is addrport then. */
5492 smartlist_del_keeporder(items
, 0);
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
);
5503 /* If transports are enabled, next field could be a fingerprint or a
5504 socks argument. If transports are disabled, next field must be
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. */
5527 if (strlen(fingerprint
) != HEX_DIGEST_LEN
) {
5528 log_warn(LD_CONFIG
, "Key digest for Bridge is wrong length.");
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.");
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)
5559 bridge_line_free(bridge_line
);
5563 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
5564 smartlist_free(items
);
5566 tor_free(fingerprint
);
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.
5583 parse_transport_line(const or_options_t
*options
,
5584 const char *line
, int validate_only
,
5588 smartlist_t
*items
= NULL
;
5590 const char *transports
= NULL
;
5591 smartlist_t
*transport_list
= NULL
;
5593 char *addrport
= NULL
;
5596 int socks_ver
= PROXY_NONE
;
5598 /* managed proxy options */
5600 char **proxy_argv
= NULL
;
5603 int is_useless_proxy
= 1;
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) {
5615 "Too few arguments on %sTransportPlugin line.",
5616 server
? "Server" : "Client");
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).",
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")) {
5643 } else if (server
&& !strcmp(type
, "proxy")) {
5644 /* 'proxy' syntax only with ServerTransportPlugin */
5646 } else if (!server
&& !strcmp(type
, "socks4")) {
5647 /* 'socks4' syntax only with ClientTransportPlugin */
5649 socks_ver
= PROXY_SOCKS4
;
5650 } else if (!server
&& !strcmp(type
, "socks5")) {
5651 /* 'socks5' syntax only with ClientTransportPlugin */
5653 socks_ver
= PROXY_SOCKS5
;
5656 "Strange %sTransportPlugin type '%s'",
5657 server
? "Server" : "Client", type
);
5661 if (is_managed
&& options
->Sandbox
) {
5663 "Managed proxies are not compatible with Sandbox mode."
5664 "(%sTransportPlugin line was %s)",
5665 server
? "Server" : "Client", escaped(line
));
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.",
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 *));
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 */
5700 pt_kickstart_server_proxy(transport_list
, proxy_argv
);
5702 pt_kickstart_client_proxy(transport_list
, proxy_argv
);
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)");
5716 if (smartlist_len(transport_list
) != 1) {
5718 "You can't have an external proxy with more than "
5723 addrport
= smartlist_get(items
, 2);
5725 if (tor_addr_port_lookup(addrport
, &addr
, &port
) < 0) {
5727 "Error parsing transport address '%s'", addrport
);
5733 "Transport address '%s' has no port.", addrport
);
5737 if (!validate_only
) {
5738 log_info(LD_DIR
, "%s '%s' at %s.",
5739 server
? "Server transport" : "Transport",
5740 transports
, fmt_addrport(&addr
, port
));
5743 transport_add_from_config(&addr
, port
,
5744 smartlist_get(transport_list
, 0),
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
);
5767 /** Given a ServerTransportListenAddr <b>line</b>, return its
5768 * <address:port> string. Return NULL if the line was not
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. */
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
;
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.");
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
))
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
);
5815 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
5816 smartlist_free(items
);
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. */
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.");
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
))
5849 SMARTLIST_FOREACH_BEGIN(items
, const char *, option
) {
5850 if (option_sl_idx
== 0) /* skip the transport field (first field)*/
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
));
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
);
5867 SMARTLIST_FOREACH(options
, char*, s
, tor_free(s
));
5868 smartlist_free(options
);
5872 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
5873 smartlist_free(items
);
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. */
5883 get_transport_bindaddr_from_config(const char *transport
)
5886 const or_options_t
*options
= get_options();
5888 for (cl
= options
->ServerTransportListenAddr
; cl
; cl
= cl
->next
) {
5890 get_bindaddr_from_transport_listen_line(cl
->value
, transport
);
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. */
5903 get_options_for_server_transport(const char *transport
)
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
);
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. */
5926 parse_dir_authority_line(const char *line
, dirinfo_type_t required_type
,
5929 smartlist_t
*items
= NULL
;
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.");
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]))
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=")) {
5967 char *portstring
= flag
+ strlen("orport=");
5968 or_port
= (uint16_t) tor_parse_long(portstring
, 10, 1, 65535, &ok
, NULL
);
5970 log_warn(LD_CONFIG
, "Invalid orport '%s' on DirAuthority line.",
5972 } else if (!strcmpstart(flag
, "weight=")) {
5974 const char *wstring
= flag
+ strlen("weight=");
5975 weight
= tor_parse_double(wstring
, 0, (double)UINT64_MAX
, &ok
, NULL
);
5977 log_warn(LD_CONFIG
, "Invalid weight '%s' on DirAuthority line.",flag
);
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",
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");
5994 if (tor_addr_port_parse(LOG_WARN
, flag
+strlen("ipv6="),
5995 &ipv6_addrport
.addr
, &ipv6_addrport
.port
,
5997 || tor_addr_family(&ipv6_addrport
.addr
) != AF_INET6
) {
5998 log_warn(LD_CONFIG
, "Bad ipv6 addr/port %s on DirAuthority line",
6002 ipv6_addrport_ptr
= &ipv6_addrport
;
6005 log_warn(LD_CONFIG
, "Unrecognized flag '%s' on DirAuthority line",
6009 smartlist_del_keeporder(items
, 0);
6012 if (smartlist_len(items
) < 2) {
6013 log_warn(LD_CONFIG
, "Too few arguments to DirAuthority line.");
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
);
6023 log_warn(LD_CONFIG
, "Missing port in DirAuthority address '%s'",addrport
);
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
));
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.");
6039 if (!validate_only
&& (!required_type
|| required_type
& type
)) {
6042 type
&= required_type
; /* pare down what we think of them as an
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
,
6048 digest
, v3_digest
, type
, weight
)))
6060 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
6061 smartlist_free(items
);
6065 tor_free(fingerprint
);
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
,
6078 smartlist_t
*items
= smartlist_new(), *positional
= smartlist_new();
6083 char id
[DIGEST_LEN
];
6085 tor_addr_port_t ipv6_addrport
, *ipv6_addrport_ptr
= NULL
;
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
, '=');
6095 smartlist_add(positional
, (char*)cp
);
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");
6108 if (tor_addr_port_parse(LOG_WARN
, cp
+strlen("ipv6="),
6109 &ipv6_addrport
.addr
, &ipv6_addrport
.port
,
6111 || tor_addr_family(&ipv6_addrport
.addr
) != AF_INET6
) {
6112 log_warn(LD_CONFIG
, "Bad ipv6 addr/port %s on FallbackDir line",
6116 ipv6_addrport_ptr
= &ipv6_addrport
;
6118 } else if (!strcmpstart(cp
, "weight=")) {
6120 const char *wstring
= cp
+ strlen("weight=");
6121 weight
= tor_parse_double(wstring
, 0, (double)UINT64_MAX
, &num_ok
, NULL
);
6123 log_warn(LD_CONFIG
, "Invalid weight '%s' on FallbackDir line.", cp
);
6129 log_warn(LD_CONFIG
, "Bad FallbackDir option %s", escaped(cp
));
6132 } SMARTLIST_FOREACH_END(cp
);
6134 if (smartlist_len(positional
) != 1) {
6135 log_warn(LD_CONFIG
, "Couldn't parse FallbackDir line %s", escaped(line
));
6139 if (tor_digest_is_zero(id
)) {
6140 log_warn(LD_CONFIG
, "Missing identity on FallbackDir line");
6145 log_warn(LD_CONFIG
, "Missing orport on FallbackDir line");
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));
6157 if (!validate_only
) {
6159 ds
= fallback_dir_server_new(&addr
, dirport
, orport
, ipv6_addrport_ptr
,
6162 log_warn(LD_CONFIG
, "Couldn't create FallbackDir %s", escaped(line
));
6171 SMARTLIST_FOREACH(items
, char *, cp
, tor_free(cp
));
6172 smartlist_free(items
);
6173 smartlist_free(positional
);
6178 /** Allocate and return a new port_cfg_t with reasonable defaults. */
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;
6190 /** Free all storage held in <b>port</b> */
6192 port_cfg_free(port_cfg_t
*port
)
6197 /** Warn for every port in <b>ports</b> of type <b>listener_type</b> that is
6198 * on a publicly routable address. */
6200 warn_nonlocal_client_ports(const smartlist_t
*ports
, const char *portname
,
6203 SMARTLIST_FOREACH_BEGIN(ports
, const port_cfg_t
*, port
) {
6204 if (port
->type
!= listener_type
)
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 "
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. */
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
)
6232 if (port
->is_unix_addr
)
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.
6250 warn_nonlocal_controller_ports(smartlist_t
*ports
, unsigned forbid_nonlocal
)
6253 SMARTLIST_FOREACH_BEGIN(ports
, port_cfg_t
*, port
) {
6254 if (port
->type
!= CONN_TYPE_CONTROL_LISTENER
)
6256 if (port
->is_unix_addr
)
6258 if (!tor_addr_is_loopback(&port
->addr
)) {
6259 if (forbid_nonlocal
) {
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.");
6271 port_cfg_free(port
);
6272 SMARTLIST_DEL_CURRENT(ports
, port
);
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. */
6306 if (strlen(addrport
+ strlen(unix_socket_prefix
)) == 0) {
6307 /* Empty socket path, not very usable. */
6311 *path_out
= tor_strdup(addrport
+ strlen(unix_socket_prefix
));
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. */
6329 "Port configuration %s is for an AF_UNIX socket, but we have no"
6330 "support available on this platform",
6334 #endif /* defined(HAVE_SYS_UN_H) */
6337 warn_client_dns_cache(const char *option
, int disabling
)
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.
6389 parse_port_config(smartlist_t
*out
,
6390 const config_line_t
*ports
,
6391 const config_line_t
*listenaddrs
,
6392 const char *portname
,
6394 const char *defaultaddr
,
6396 const unsigned flags
)
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,
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
);
6425 if (!strcmp(ports
->value
, "auto")) {
6426 mainport
= CFG_AUTO_PORT
;
6429 mainport
= (int)tor_parse_long(ports
->value
, 10, 0, 65535, &ok
, NULL
);
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
);
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
);
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
) {
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
);
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
) {
6482 warn_nonlocal_controller_ports(out
, forbid_nonlocal
);
6483 else if (is_ext_orport
)
6484 warn_nonlocal_ext_orports(out
, portname
);
6486 warn_nonlocal_client_ports(out
, portname
, listener_type
);
6489 } /* end if (listenaddrs) */
6491 /* No ListenAddress lines. If there's no FooPort, then maybe make a default
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;
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
);
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
) {
6519 int sessiongroup
= SESSION_GROUP_UNSET
;
6520 unsigned isolation
= ISO_DEFAULT
;
6521 int prefer_no_auth
= 0;
6522 int socks_iso_keep_alive
= 0;
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
);
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.");
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
);
6561 if (unix_socket_path
) {
6563 } else if (is_unix_socket
) {
6564 unix_socket_path
= tor_strdup(addrport
);
6565 if (!strcmp(addrport
, "0"))
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
);
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
);
6588 int af
= tor_addr_parse(&addr
, defaultaddr
);
6589 tor_assert(af
>= 0);
6590 } else if (tor_addr_port_lookup(addrport
, &addr
, &ptmp
) == 0) {
6592 log_warn(LD_CONFIG
, "%sPort line has address but no port", portname
);
6597 log_warn(LD_CONFIG
, "Couldn't parse address %s for %sPort",
6598 escaped(addrport
), portname
);
6603 if (unix_socket_path
&& default_to_group_writable
)
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")) {
6615 } else if (!strcasecmp(elt
, "NoListen")) {
6618 /* not implemented yet. */
6619 } else if (!strcasecmp(elt
, "AllAddrs")) {
6623 } else if (!strcasecmp(elt
, "IPv4Only")) {
6625 } else if (!strcasecmp(elt
, "IPv6Only")) {
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
));
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
));
6645 if (bind_ipv4_only
&& tor_addr_family(&addr
) == AF_INET6
) {
6646 log_warn(LD_CONFIG
, "Could not interpret %sPort address as IPv6",
6650 if (bind_ipv6_only
&& tor_addr_family(&addr
) == AF_INET
) {
6651 log_warn(LD_CONFIG
, "Could not interpret %sPort address as IPv4",
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
));
6671 if (sessiongroup
>= 0) {
6672 log_warn(LD_CONFIG
, "Multiple SessionGroup options on %sPort",
6676 sessiongroup
= group
;
6680 if (!strcasecmpstart(elt
, "No")) {
6685 if (!strcasecmp(elt
, "GroupWritable")) {
6686 group_writable
= !no
;
6687 has_used_unix_socket_only_option
= 1;
6689 } else if (!strcasecmp(elt
, "WorldWritable")) {
6690 world_writable
= !no
;
6691 has_used_unix_socket_only_option
= 1;
6693 } else if (!strcasecmp(elt
, "RelaxDirModeCheck")) {
6694 relax_dirmode_check
= !no
;
6695 has_used_unix_socket_only_option
= 1;
6699 if (allow_no_stream_options
) {
6700 log_warn(LD_CONFIG
, "Unrecognized %sPort option '%s'",
6701 portname
, escaped(elt
));
6705 if (takes_hostnames
) {
6706 if (!strcasecmp(elt
, "IPv4Traffic")) {
6707 ipv4_traffic
= ! no
;
6709 } else if (!strcasecmp(elt
, "IPv6Traffic")) {
6710 ipv6_traffic
= ! no
;
6712 } else if (!strcasecmp(elt
, "PreferIPv6")) {
6717 if (!strcasecmp(elt
, "CacheIPv4DNS")) {
6718 warn_client_dns_cache(elt
, no
); // since 0.2.9.2-alpha
6721 } else if (!strcasecmp(elt
, "CacheIPv6DNS")) {
6722 warn_client_dns_cache(elt
, no
); // since 0.2.9.2-alpha
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
;
6729 } else if (!strcasecmp(elt
, "UseIPv4Cache")) {
6730 warn_client_dns_cache(elt
, no
); // since 0.2.9.2-alpha
6731 use_cached_ipv4
= ! no
;
6733 } else if (!strcasecmp(elt
, "UseIPv6Cache")) {
6734 warn_client_dns_cache(elt
, no
); // since 0.2.9.2-alpha
6735 use_cached_ipv6
= ! no
;
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
;
6741 } else if (!strcasecmp(elt
, "PreferIPv6Automap")) {
6742 prefer_ipv6_automap
= ! no
;
6744 } else if (!strcasecmp(elt
, "PreferSOCKSNoAuth")) {
6745 prefer_no_auth
= ! no
;
6747 } else if (!strcasecmp(elt
, "KeepAliveIsolateSOCKSAuth")) {
6748 socks_iso_keep_alive
= ! no
;
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
;
6766 log_warn(LD_CONFIG
, "Unrecognized %sPort option '%s'",
6767 portname
, escaped(elt_orig
));
6771 isolation
&= ~isoflag
;
6773 isolation
|= isoflag
;
6775 } SMARTLIST_FOREACH_END(elt
);
6779 got_nonzero_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
);
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
);
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.",
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
);
6812 tor_addr_copy(&cfg
->addr
, &addr
);
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
) {
6847 warn_nonlocal_controller_ports(out
, forbid_nonlocal
);
6848 else if (is_ext_orport
)
6849 warn_nonlocal_ext_orports(out
, portname
);
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
);
6863 SMARTLIST_FOREACH(elts
, char *, cp
, tor_free(cp
));
6864 smartlist_free(elts
);
6865 tor_free(unix_socket_path
);
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. */
6873 count_real_listeners(const smartlist_t
*ports
, int listenertype
,
6877 SMARTLIST_FOREACH_BEGIN(ports
, port_cfg_t
*, port
) {
6878 if (port
->server_cfg
.no_listen
)
6880 if (!count_sockets
&& port
->is_unix_addr
)
6882 if (port
->type
!= listenertype
)
6885 } SMARTLIST_FOREACH_END(port
);
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>.
6898 parse_ports(or_options_t
*options
, int validate_only
,
6899 char **msg
, int *n_ports_out
,
6900 int *world_writable_control_socket
)
6905 ports
= smartlist_new();
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
,
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");
6920 if (parse_port_config(ports
,
6921 options
->DNSPort_lines
, options
->DNSListenAddress
,
6922 "DNS", CONN_TYPE_AP_DNS_LISTENER
,
6924 CL_PORT_WARN_NONLOCAL
|CL_PORT_TAKES_HOSTNAMES
) < 0) {
6925 *msg
= tor_strdup("Invalid DNSPort/DNSListenAddress configuration");
6928 if (parse_port_config(ports
,
6929 options
->TransPort_lines
, options
->TransListenAddress
,
6930 "Trans", CONN_TYPE_AP_TRANS_LISTENER
,
6932 CL_PORT_WARN_NONLOCAL
) < 0) {
6933 *msg
= tor_strdup("Invalid TransPort/TransListenAddress configuration");
6936 if (parse_port_config(ports
,
6937 options
->NATDPort_lines
, options
->NATDListenAddress
,
6938 "NATD", CONN_TYPE_AP_NATD_LISTENER
,
6940 CL_PORT_WARN_NONLOCAL
) < 0) {
6941 *msg
= tor_strdup("Invalid NatdPort/NatdListenAddress configuration");
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
,
6960 control_port_flags
) < 0) {
6961 *msg
= tor_strdup("Invalid ControlPort/ControlListenAddress "
6966 if (parse_port_config(ports
, options
->ControlSocket
, NULL
,
6968 CONN_TYPE_CONTROL_LISTENER
, NULL
, 0,
6969 control_port_flags
| CL_PORT_IS_UNIXSOCKET
) < 0) {
6970 *msg
= tor_strdup("Invalid ControlSocket configuration");
6974 if (! options
->ClientOnly
) {
6975 if (parse_port_config(ports
,
6976 options
->ORPort_lines
, options
->ORListenAddress
,
6977 "OR", CONN_TYPE_OR_LISTENER
,
6979 CL_PORT_SERVER_OPTIONS
) < 0) {
6980 *msg
= tor_strdup("Invalid ORPort/ORListenAddress configuration");
6983 if (parse_port_config(ports
,
6984 options
->ExtORPort_lines
, NULL
,
6985 "ExtOR", CONN_TYPE_EXT_OR_LISTENER
,
6987 CL_PORT_SERVER_OPTIONS
|CL_PORT_WARN_NONLOCAL
) < 0) {
6988 *msg
= tor_strdup("Invalid ExtORPort configuration");
6991 if (parse_port_config(ports
,
6992 options
->DirPort_lines
, options
->DirListenAddress
,
6993 "Dir", CONN_TYPE_DIR_LISTENER
,
6995 CL_PORT_SERVER_OPTIONS
) < 0) {
6996 *msg
= tor_strdup("Invalid DirPort/DirListenAddress configuration");
7001 int n_low_ports
= 0;
7002 if (check_server_ports(ports
, options
, &n_low_ports
) < 0) {
7003 *msg
= tor_strdup("Misconfigured server ports");
7006 if (have_low_ports
< 0)
7007 have_low_ports
= (n_low_ports
> 0);
7009 *n_ports_out
= smartlist_len(ports
);
7013 /* Update the *Port_set options. The !! here is to force a boolean out of
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
&&
7037 p
->is_world_writable
) {
7038 *world_writable_control_socket
= 1;
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. */
7055 SMARTLIST_FOREACH(ports
, port_cfg_t
*, p
, port_cfg_free(p
));
7056 smartlist_free(ports
);
7061 /* Does port bind to IPv4? */
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? */
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. */
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;
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
;
7113 if (!port
->server_cfg
.no_listen
&& port
->port
< 1024)
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.");
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");
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.");
7135 if (n_dirport_advertised
> 1) {
7136 log_warn(LD_CONFIG
, "Can't advertise more than one DirPort.");
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 "
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.";
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
;
7167 /** Return a list of port_cfg_t for client ports parsed from the
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
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
;
7193 char *string
= NULL
;
7195 if (!configured_ports
)
7198 SMARTLIST_FOREACH_BEGIN(configured_ports
, const port_cfg_t
*, cfg
) {
7199 if (cfg
->server_cfg
.no_listen
)
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
7210 if (tor_addr_is_null(&cfg
->addr
))
7211 address
= tor_addr_is_v4(&cfg
->addr
) ? ipv4_localhost
: ipv6_localhost
;
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
));
7227 tor_asprintf(&string
, "%s:%u", address
, port
);
7232 } SMARTLIST_FOREACH_END(cfg
);
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
7241 get_first_advertised_port_by_type_af(int listener_type
, int address_family
)
7243 if (address_family
== AF_UNSPEC
)
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
))) {
7255 } SMARTLIST_FOREACH_END(cfg
);
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. */
7263 get_first_advertised_addr_by_type_af(int listener_type
, int address_family
)
7265 if (address_family
== AF_UNSPEC
)
7267 if (!configured_ports
)
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
))) {
7277 } SMARTLIST_FOREACH_END(cfg
);
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
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
)
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)) {
7297 if (tor_addr_eq(&cfg
->addr
, addr
)) {
7300 /* Skip wildcard matches if we're not doing them */
7301 if (!check_wildcard
) {
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
)) {
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
)) {
7324 } SMARTLIST_FOREACH_END(cfg
);
7328 /* Like port_exists_by_type_addr_port, but accepts a host-order IPv4 address
7331 port_exists_by_type_addr32h_port(int listener_type
, uint32_t addr_ipv4h
,
7332 int port
, int check_wildcard
)
7335 tor_addr_from_ipv4h(&ipv4
, addr_ipv4h
);
7336 return port_exists_by_type_addr_port(listener_type
, &ipv4
, port
,
7340 /** Adjust the value of options->DataDirectory, or fill it in if it's
7341 * absent. Return 0 on success, -1 on failure. */
7343 normalize_data_directory(or_options_t
*options
)
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
;
7354 const char *d
= options
->DataDirectory
;
7358 if (strncmp(d
,"~/",2) == 0) {
7359 char *fn
= expand_filename(d
);
7361 log_warn(LD_CONFIG
,"Failed to expand filename \"%s\".", d
);
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
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);
7373 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor
");
7375 tor_free(options->DataDirectory);
7376 options->DataDirectory = fn;
7382 /** Check and normalize the value of options->DataDirectory; return 0 if it
7383 * is sane, -1 otherwise. */
7385 validate_data_directory(or_options_t *options)
7387 if (normalize_data_directory(options) < 0)
7389 tor_assert(options->DataDirectory);
7390 if (strlen(options->DataDirectory) > (512-128)) {
7391 log_warn(LD_CONFIG, "DataDirectory is too
long.");
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. */
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;
7419 switch (file_status(fname)) {
7420 /* create backups of old config files, even if they're empty */
7423 old_val = read_file_to_str(fname, 0, NULL);
7424 if (!old_val || strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
7435 "Config file \"%s\" is not a file? Failing.", fname);
7439 if (!(new_conf = options_dump(options, OPTIONS_DUMP_MINIMAL))) {
7440 log_warn(LD_BUG, "Couldn't get configuration string");
7444 tor_asprintf(&new_val, "%s\n%s\n\n%s",
7445 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
7449 char *fn_tmp = NULL;
7451 tor_asprintf(&fn_tmp, "%s.orig.%d", fname, i);
7452 if (file_status(fn_tmp) == FN_NOENT)
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
7460 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
7461 fname
, fn_tmp
, strerror(errno
));
7468 if (write_str_to_file(fname
, new_val
, 0) < 0)
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;
7505 return options
->NumCPUs
;
7510 * Initialize the libevent library.
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.
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.
7549 options_get_datadir_fname2_suffix
,(const or_options_t
*options
,
7550 const char *sub1
, const char *sub2
,
7551 const char *suffix
))
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
);
7560 len
+= strlen(sub1
)+1;
7562 len
+= strlen(sub2
)+1;
7565 len
+= strlen(suffix
);
7567 fname
= tor_malloc(len
);
7570 tor_snprintf(fname
, len
, "%s"PATH_SEPARATOR
"%s"PATH_SEPARATOR
"%s",
7571 options
->DataDirectory
, sub1
, sub2
);
7573 tor_snprintf(fname
, len
, "%s"PATH_SEPARATOR
"%s",
7574 options
->DataDirectory
, sub1
);
7577 strlcpy(fname
, options
->DataDirectory
, len
);
7580 strlcat(fname
, suffix
, len
);
7584 /** Check wether the data directory has a private subdirectory
7585 * <b>subdir</b>. If not, try to create it. Return 0 on success,
7588 check_or_create_data_subdir(const char *subdir
)
7590 char *statsdir
= get_datadir_fname(subdir
);
7593 if (check_private_dir(statsdir
, CPD_CREATE
, get_options()->User
) < 0) {
7594 log_warn(LD_HIST
, "Unable to create %s/ directory!", subdir
);
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
);
7613 if (write_str_to_file(filename
, str
, 0) < 0) {
7614 log_warn(LD_HIST
, "Unable to write %s to disk!", descr
? descr
: fname
);
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. */
7624 remove_file_if_very_old(const char *fname
, time_t now
)
7626 #define VERY_OLD_FILE_AGE (28*24*60*60)
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. */
7647 get_list_of_ports_to_forward(void)
7649 smartlist_t
*ports_to_forward
= smartlist_new();
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 */
7657 smartlist_add_asprintf(ports_to_forward
, "%d:%d", port
, port
);
7659 port
= router_get_advertised_dir_port(get_options(), 0); /* Get DirPort */
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
7685 getinfo_helper_config(control_connection_t
*conn
,
7686 const char *question
, char **answer
,
7687 const char **errmsg
)
7691 if (!strcmp(question
, "config/names")) {
7692 smartlist_t
*sl
= smartlist_new();
7694 for (i
= 0; option_vars_
[i
].name
; ++i
) {
7695 const config_var_t
*var
= &option_vars_
[i
];
7697 /* don't tell controller about triple-underscore options */
7698 if (!strncmp(option_vars_
[i
].name
, "___", 3))
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;
7720 case CONFIG_TYPE_OBSOLETE
:
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
));
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
);
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
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
);
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.
7785 for (i
= default_fallbacks
; *i
!= NULL
; ++i
) {
7786 char *val
= esc_for_log(*i
);
7787 smartlist_add_asprintf(sl
, "FallbackDir %s\n", val
);
7792 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
7793 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
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. */
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_
));
7817 tor_addr_t addr
, *dst_addr
= NULL
;
7818 int af
= tor_addr_parse(&addr
, lines
->value
);
7823 tor_asprintf(msg
, "Multiple IPv4 outbound bind addresses "
7824 "configured: %s", lines
->value
);
7828 dst_addr
= &options
->OutboundBindAddressIPv4_
;
7833 tor_asprintf(msg
, "Multiple IPv6 outbound bind addresses "
7834 "configured: %s", lines
->value
);
7838 dst_addr
= &options
->OutboundBindAddressIPv6_
;
7842 tor_asprintf(msg
, "Outbound bind address '%s' didn't parse.",
7847 tor_addr_copy(dst_addr
, &addr
);
7848 lines
= lines
->next
;
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>". */
7857 config_load_geoip_file_(sa_family_t family
,
7859 const char *default_fname
)
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
);
7870 geoip_load_file(family
, fname
);
7871 tor_free(free_fname
);
7873 (void)default_fname
;
7874 geoip_load_file(family
, fname
);
7878 /** Load geoip files for IPv4 and IPv6 if <a>options</a> and
7879 * <a>old_options</a> indicate we should. */
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
);
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 */
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. */
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
));
7945 if (group_readable
) {
7946 if (chmod(fname
, 0640)) {
7947 log_warn(LD_FS
,"Unable to make %s group-readable.", escaped(fname
));
7951 (void) group_readable
;
7955 log_info(LD_GENERAL
, "Generated auth cookie file in '%s'.", escaped(fname
));
7956 *cookie_is_set_out
= 1;
7960 memwipe(cookie_file_str
, 0, cookie_file_str_len
);
7961 tor_free(cookie_file_str
);