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