Replace OnionService* with HiddenService* in option names
[tor.git] / src / or / config.c
blob949c8a973f5765e2ab8f8018e855c850aaf7d937
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 /** Read the contents of a Bridge line from <b>line</b>. Return 0
5455 * if the line is well-formed, and -1 if it isn't. If
5456 * <b>validate_only</b> is 0, and the line is well-formed, then add
5457 * the bridge described in the line to our internal bridge list.
5459 * Bridge line format:
5460 * Bridge [transport] IP:PORT [id-fingerprint] [k=v] [k=v] ...
5462 /* private */ bridge_line_t *
5463 parse_bridge_line(const char *line)
5465 smartlist_t *items = NULL;
5466 char *addrport=NULL, *fingerprint=NULL;
5467 char *field=NULL;
5468 bridge_line_t *bridge_line = tor_malloc_zero(sizeof(bridge_line_t));
5470 items = smartlist_new();
5471 smartlist_split_string(items, line, NULL,
5472 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5473 if (smartlist_len(items) < 1) {
5474 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
5475 goto err;
5478 /* first field is either a transport name or addrport */
5479 field = smartlist_get(items, 0);
5480 smartlist_del_keeporder(items, 0);
5482 if (string_is_C_identifier(field)) {
5483 /* It's a transport name. */
5484 bridge_line->transport_name = field;
5485 if (smartlist_len(items) < 1) {
5486 log_warn(LD_CONFIG, "Too few items to Bridge line.");
5487 goto err;
5489 addrport = smartlist_get(items, 0); /* Next field is addrport then. */
5490 smartlist_del_keeporder(items, 0);
5491 } else {
5492 addrport = field;
5495 if (tor_addr_port_parse(LOG_INFO, addrport,
5496 &bridge_line->addr, &bridge_line->port, 443)<0) {
5497 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
5498 goto err;
5501 /* If transports are enabled, next field could be a fingerprint or a
5502 socks argument. If transports are disabled, next field must be
5503 a fingerprint. */
5504 if (smartlist_len(items)) {
5505 if (bridge_line->transport_name) { /* transports enabled: */
5506 field = smartlist_get(items, 0);
5507 smartlist_del_keeporder(items, 0);
5509 /* If it's a key=value pair, then it's a SOCKS argument for the
5510 transport proxy... */
5511 if (string_is_key_value(LOG_DEBUG, field)) {
5512 bridge_line->socks_args = smartlist_new();
5513 smartlist_add(bridge_line->socks_args, field);
5514 } else { /* ...otherwise, it's the bridge fingerprint. */
5515 fingerprint = field;
5518 } else { /* transports disabled: */
5519 fingerprint = smartlist_join_strings(items, "", 0, NULL);
5523 /* Handle fingerprint, if it was provided. */
5524 if (fingerprint) {
5525 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
5526 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
5527 goto err;
5529 if (base16_decode(bridge_line->digest, DIGEST_LEN,
5530 fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
5531 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
5532 goto err;
5536 /* If we are using transports, any remaining items in the smartlist
5537 should be k=v values. */
5538 if (bridge_line->transport_name && smartlist_len(items)) {
5539 if (!bridge_line->socks_args)
5540 bridge_line->socks_args = smartlist_new();
5542 /* append remaining items of 'items' to 'socks_args' */
5543 smartlist_add_all(bridge_line->socks_args, items);
5544 smartlist_clear(items);
5546 tor_assert(smartlist_len(bridge_line->socks_args) > 0);
5549 if (bridge_line->socks_args) {
5550 if (validate_transport_socks_arguments(bridge_line->socks_args) < 0)
5551 goto err;
5554 goto done;
5556 err:
5557 bridge_line_free(bridge_line);
5558 bridge_line = NULL;
5560 done:
5561 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5562 smartlist_free(items);
5563 tor_free(addrport);
5564 tor_free(fingerprint);
5566 return bridge_line;
5569 /** Read the contents of a ClientTransportPlugin or ServerTransportPlugin
5570 * line from <b>line</b>, depending on the value of <b>server</b>. Return 0
5571 * if the line is well-formed, and -1 if it isn't.
5573 * If <b>validate_only</b> is 0, the line is well-formed, and the transport is
5574 * needed by some bridge:
5575 * - If it's an external proxy line, add the transport described in the line to
5576 * our internal transport list.
5577 * - If it's a managed proxy line, launch the managed proxy.
5580 STATIC int
5581 parse_transport_line(const or_options_t *options,
5582 const char *line, int validate_only,
5583 int server)
5586 smartlist_t *items = NULL;
5587 int r;
5588 const char *transports = NULL;
5589 smartlist_t *transport_list = NULL;
5590 char *type = NULL;
5591 char *addrport = NULL;
5592 tor_addr_t addr;
5593 uint16_t port = 0;
5594 int socks_ver = PROXY_NONE;
5596 /* managed proxy options */
5597 int is_managed = 0;
5598 char **proxy_argv = NULL;
5599 char **tmp = NULL;
5600 int proxy_argc, i;
5601 int is_useless_proxy = 1;
5603 int line_length;
5605 /* Split the line into space-separated tokens */
5606 items = smartlist_new();
5607 smartlist_split_string(items, line, NULL,
5608 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5609 line_length = smartlist_len(items);
5611 if (line_length < 3) {
5612 log_warn(LD_CONFIG,
5613 "Too few arguments on %sTransportPlugin line.",
5614 server ? "Server" : "Client");
5615 goto err;
5618 /* Get the first line element, split it to commas into
5619 transport_list (in case it's multiple transports) and validate
5620 the transport names. */
5621 transports = smartlist_get(items, 0);
5622 transport_list = smartlist_new();
5623 smartlist_split_string(transport_list, transports, ",",
5624 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
5625 SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
5626 /* validate transport names */
5627 if (!string_is_C_identifier(transport_name)) {
5628 log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
5629 transport_name);
5630 goto err;
5633 /* see if we actually need the transports provided by this proxy */
5634 if (!validate_only && transport_is_needed(transport_name))
5635 is_useless_proxy = 0;
5636 } SMARTLIST_FOREACH_END(transport_name);
5638 type = smartlist_get(items, 1);
5639 if (!strcmp(type, "exec")) {
5640 is_managed = 1;
5641 } else if (server && !strcmp(type, "proxy")) {
5642 /* 'proxy' syntax only with ServerTransportPlugin */
5643 is_managed = 0;
5644 } else if (!server && !strcmp(type, "socks4")) {
5645 /* 'socks4' syntax only with ClientTransportPlugin */
5646 is_managed = 0;
5647 socks_ver = PROXY_SOCKS4;
5648 } else if (!server && !strcmp(type, "socks5")) {
5649 /* 'socks5' syntax only with ClientTransportPlugin */
5650 is_managed = 0;
5651 socks_ver = PROXY_SOCKS5;
5652 } else {
5653 log_warn(LD_CONFIG,
5654 "Strange %sTransportPlugin type '%s'",
5655 server ? "Server" : "Client", type);
5656 goto err;
5659 if (is_managed && options->Sandbox) {
5660 log_warn(LD_CONFIG,
5661 "Managed proxies are not compatible with Sandbox mode."
5662 "(%sTransportPlugin line was %s)",
5663 server ? "Server" : "Client", escaped(line));
5664 goto err;
5667 if (is_managed) {
5668 /* managed */
5670 if (!server && !validate_only && is_useless_proxy) {
5671 log_info(LD_GENERAL,
5672 "Pluggable transport proxy (%s) does not provide "
5673 "any needed transports and will not be launched.",
5674 line);
5678 * If we are not just validating, use the rest of the line as the
5679 * argv of the proxy to be launched. Also, make sure that we are
5680 * only launching proxies that contribute useful transports.
5683 if (!validate_only && (server || !is_useless_proxy)) {
5684 proxy_argc = line_length - 2;
5685 tor_assert(proxy_argc > 0);
5686 proxy_argv = tor_calloc((proxy_argc + 1), sizeof(char *));
5687 tmp = proxy_argv;
5689 for (i = 0; i < proxy_argc; i++) {
5690 /* store arguments */
5691 *tmp++ = smartlist_get(items, 2);
5692 smartlist_del_keeporder(items, 2);
5694 *tmp = NULL; /* terminated with NULL, just like execve() likes it */
5696 /* kickstart the thing */
5697 if (server) {
5698 pt_kickstart_server_proxy(transport_list, proxy_argv);
5699 } else {
5700 pt_kickstart_client_proxy(transport_list, proxy_argv);
5703 } else {
5704 /* external */
5706 /* ClientTransportPlugins connecting through a proxy is managed only. */
5707 if (!server && (options->Socks4Proxy || options->Socks5Proxy ||
5708 options->HTTPSProxy)) {
5709 log_warn(LD_CONFIG, "You have configured an external proxy with another "
5710 "proxy type. (Socks4Proxy|Socks5Proxy|HTTPSProxy)");
5711 goto err;
5714 if (smartlist_len(transport_list) != 1) {
5715 log_warn(LD_CONFIG,
5716 "You can't have an external proxy with more than "
5717 "one transport.");
5718 goto err;
5721 addrport = smartlist_get(items, 2);
5723 if (tor_addr_port_lookup(addrport, &addr, &port) < 0) {
5724 log_warn(LD_CONFIG,
5725 "Error parsing transport address '%s'", addrport);
5726 goto err;
5729 if (!port) {
5730 log_warn(LD_CONFIG,
5731 "Transport address '%s' has no port.", addrport);
5732 goto err;
5735 if (!validate_only) {
5736 log_info(LD_DIR, "%s '%s' at %s.",
5737 server ? "Server transport" : "Transport",
5738 transports, fmt_addrport(&addr, port));
5740 if (!server) {
5741 transport_add_from_config(&addr, port,
5742 smartlist_get(transport_list, 0),
5743 socks_ver);
5748 r = 0;
5749 goto done;
5751 err:
5752 r = -1;
5754 done:
5755 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5756 smartlist_free(items);
5757 if (transport_list) {
5758 SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
5759 smartlist_free(transport_list);
5762 return r;
5765 /** Given a ServerTransportListenAddr <b>line</b>, return its
5766 * <address:port> string. Return NULL if the line was not
5767 * well-formed.
5769 * If <b>transport</b> is set, return NULL if the line is not
5770 * referring to <b>transport</b>.
5772 * The returned string is allocated on the heap and it's the
5773 * responsibility of the caller to free it. */
5774 static char *
5775 get_bindaddr_from_transport_listen_line(const char *line,const char *transport)
5777 smartlist_t *items = NULL;
5778 const char *parsed_transport = NULL;
5779 char *addrport = NULL;
5780 tor_addr_t addr;
5781 uint16_t port = 0;
5783 items = smartlist_new();
5784 smartlist_split_string(items, line, NULL,
5785 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5787 if (smartlist_len(items) < 2) {
5788 log_warn(LD_CONFIG,"Too few arguments on ServerTransportListenAddr line.");
5789 goto err;
5792 parsed_transport = smartlist_get(items, 0);
5793 addrport = tor_strdup(smartlist_get(items, 1));
5795 /* If 'transport' is given, check if it matches the one on the line */
5796 if (transport && strcmp(transport, parsed_transport))
5797 goto err;
5799 /* Validate addrport */
5800 if (tor_addr_port_parse(LOG_WARN, addrport, &addr, &port, -1)<0) {
5801 log_warn(LD_CONFIG, "Error parsing ServerTransportListenAddr "
5802 "address '%s'", addrport);
5803 goto err;
5806 goto done;
5808 err:
5809 tor_free(addrport);
5810 addrport = NULL;
5812 done:
5813 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5814 smartlist_free(items);
5816 return addrport;
5819 /** Given a ServerTransportOptions <b>line</b>, return a smartlist
5820 * with the options. Return NULL if the line was not well-formed.
5822 * If <b>transport</b> is set, return NULL if the line is not
5823 * referring to <b>transport</b>.
5825 * The returned smartlist and its strings are allocated on the heap
5826 * and it's the responsibility of the caller to free it. */
5827 smartlist_t *
5828 get_options_from_transport_options_line(const char *line,const char *transport)
5830 smartlist_t *items = smartlist_new();
5831 smartlist_t *options = smartlist_new();
5832 const char *parsed_transport = NULL;
5834 smartlist_split_string(items, line, NULL,
5835 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5837 if (smartlist_len(items) < 2) {
5838 log_warn(LD_CONFIG,"Too few arguments on ServerTransportOptions line.");
5839 goto err;
5842 parsed_transport = smartlist_get(items, 0);
5843 /* If 'transport' is given, check if it matches the one on the line */
5844 if (transport && strcmp(transport, parsed_transport))
5845 goto err;
5847 SMARTLIST_FOREACH_BEGIN(items, const char *, option) {
5848 if (option_sl_idx == 0) /* skip the transport field (first field)*/
5849 continue;
5851 /* validate that it's a k=v value */
5852 if (!string_is_key_value(LOG_WARN, option)) {
5853 log_warn(LD_CONFIG, "%s is not a k=v value.", escaped(option));
5854 goto err;
5857 /* add it to the options smartlist */
5858 smartlist_add(options, tor_strdup(option));
5859 log_debug(LD_CONFIG, "Added %s to the list of options", escaped(option));
5860 } SMARTLIST_FOREACH_END(option);
5862 goto done;
5864 err:
5865 SMARTLIST_FOREACH(options, char*, s, tor_free(s));
5866 smartlist_free(options);
5867 options = NULL;
5869 done:
5870 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5871 smartlist_free(items);
5873 return options;
5876 /** Given the name of a pluggable transport in <b>transport</b>, check
5877 * the configuration file to see if the user has explicitly asked for
5878 * it to listen on a specific port. Return a <address:port> string if
5879 * so, otherwise NULL. */
5880 char *
5881 get_transport_bindaddr_from_config(const char *transport)
5883 config_line_t *cl;
5884 const or_options_t *options = get_options();
5886 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
5887 char *bindaddr =
5888 get_bindaddr_from_transport_listen_line(cl->value, transport);
5889 if (bindaddr)
5890 return bindaddr;
5893 return NULL;
5896 /** Given the name of a pluggable transport in <b>transport</b>, check
5897 * the configuration file to see if the user has asked us to pass any
5898 * parameters to the pluggable transport. Return a smartlist
5899 * containing the parameters, otherwise NULL. */
5900 smartlist_t *
5901 get_options_for_server_transport(const char *transport)
5903 config_line_t *cl;
5904 const or_options_t *options = get_options();
5906 for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
5907 smartlist_t *options_sl =
5908 get_options_from_transport_options_line(cl->value, transport);
5909 if (options_sl)
5910 return options_sl;
5913 return NULL;
5916 /** Read the contents of a DirAuthority line from <b>line</b>. If
5917 * <b>validate_only</b> is 0, and the line is well-formed, and it
5918 * shares any bits with <b>required_type</b> or <b>required_type</b>
5919 * is NO_DIRINFO (zero), then add the dirserver described in the line
5920 * (minus whatever bits it's missing) as a valid authority.
5921 * Return 0 on success or filtering out by type,
5922 * or -1 if the line isn't well-formed or if we can't add it. */
5923 STATIC int
5924 parse_dir_authority_line(const char *line, dirinfo_type_t required_type,
5925 int validate_only)
5927 smartlist_t *items = NULL;
5928 int r;
5929 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
5930 tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
5931 uint16_t dir_port = 0, or_port = 0;
5932 char digest[DIGEST_LEN];
5933 char v3_digest[DIGEST_LEN];
5934 dirinfo_type_t type = 0;
5935 double weight = 1.0;
5937 items = smartlist_new();
5938 smartlist_split_string(items, line, NULL,
5939 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5940 if (smartlist_len(items) < 1) {
5941 log_warn(LD_CONFIG, "No arguments on DirAuthority line.");
5942 goto err;
5945 if (is_legal_nickname(smartlist_get(items, 0))) {
5946 nickname = smartlist_get(items, 0);
5947 smartlist_del_keeporder(items, 0);
5950 while (smartlist_len(items)) {
5951 char *flag = smartlist_get(items, 0);
5952 if (TOR_ISDIGIT(flag[0]))
5953 break;
5954 if (!strcasecmp(flag, "hs") ||
5955 !strcasecmp(flag, "no-hs")) {
5956 log_warn(LD_CONFIG, "The DirAuthority options 'hs' and 'no-hs' are "
5957 "obsolete; you don't need them any more.");
5958 } else if (!strcasecmp(flag, "bridge")) {
5959 type |= BRIDGE_DIRINFO;
5960 } else if (!strcasecmp(flag, "no-v2")) {
5961 /* obsolete, but may still be contained in DirAuthority lines generated
5962 by various tools */;
5963 } else if (!strcasecmpstart(flag, "orport=")) {
5964 int ok;
5965 char *portstring = flag + strlen("orport=");
5966 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
5967 if (!ok)
5968 log_warn(LD_CONFIG, "Invalid orport '%s' on DirAuthority line.",
5969 portstring);
5970 } else if (!strcmpstart(flag, "weight=")) {
5971 int ok;
5972 const char *wstring = flag + strlen("weight=");
5973 weight = tor_parse_double(wstring, 0, (double)UINT64_MAX, &ok, NULL);
5974 if (!ok) {
5975 log_warn(LD_CONFIG, "Invalid weight '%s' on DirAuthority line.",flag);
5976 weight=1.0;
5978 } else if (!strcasecmpstart(flag, "v3ident=")) {
5979 char *idstr = flag + strlen("v3ident=");
5980 if (strlen(idstr) != HEX_DIGEST_LEN ||
5981 base16_decode(v3_digest, DIGEST_LEN,
5982 idstr, HEX_DIGEST_LEN) != DIGEST_LEN) {
5983 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirAuthority line",
5984 flag);
5985 } else {
5986 type |= V3_DIRINFO|EXTRAINFO_DIRINFO|MICRODESC_DIRINFO;
5988 } else if (!strcasecmpstart(flag, "ipv6=")) {
5989 if (ipv6_addrport_ptr) {
5990 log_warn(LD_CONFIG, "Redundant ipv6 addr/port on DirAuthority line");
5991 } else {
5992 if (tor_addr_port_parse(LOG_WARN, flag+strlen("ipv6="),
5993 &ipv6_addrport.addr, &ipv6_addrport.port,
5994 -1) < 0
5995 || tor_addr_family(&ipv6_addrport.addr) != AF_INET6) {
5996 log_warn(LD_CONFIG, "Bad ipv6 addr/port %s on DirAuthority line",
5997 escaped(flag));
5998 goto err;
6000 ipv6_addrport_ptr = &ipv6_addrport;
6002 } else {
6003 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirAuthority line",
6004 flag);
6006 tor_free(flag);
6007 smartlist_del_keeporder(items, 0);
6010 if (smartlist_len(items) < 2) {
6011 log_warn(LD_CONFIG, "Too few arguments to DirAuthority line.");
6012 goto err;
6014 addrport = smartlist_get(items, 0);
6015 smartlist_del_keeporder(items, 0);
6016 if (addr_port_lookup(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
6017 log_warn(LD_CONFIG, "Error parsing DirAuthority address '%s'", addrport);
6018 goto err;
6020 if (!dir_port) {
6021 log_warn(LD_CONFIG, "Missing port in DirAuthority address '%s'",addrport);
6022 goto err;
6025 fingerprint = smartlist_join_strings(items, "", 0, NULL);
6026 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
6027 log_warn(LD_CONFIG, "Key digest '%s' for DirAuthority is wrong length %d.",
6028 fingerprint, (int)strlen(fingerprint));
6029 goto err;
6031 if (base16_decode(digest, DIGEST_LEN,
6032 fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
6033 log_warn(LD_CONFIG, "Unable to decode DirAuthority key digest.");
6034 goto err;
6037 if (!validate_only && (!required_type || required_type & type)) {
6038 dir_server_t *ds;
6039 if (required_type)
6040 type &= required_type; /* pare down what we think of them as an
6041 * authority for. */
6042 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
6043 address, (int)dir_port, (char*)smartlist_get(items,0));
6044 if (!(ds = trusted_dir_server_new(nickname, address, dir_port, or_port,
6045 ipv6_addrport_ptr,
6046 digest, v3_digest, type, weight)))
6047 goto err;
6048 dir_server_add(ds);
6051 r = 0;
6052 goto done;
6054 err:
6055 r = -1;
6057 done:
6058 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
6059 smartlist_free(items);
6060 tor_free(addrport);
6061 tor_free(address);
6062 tor_free(nickname);
6063 tor_free(fingerprint);
6064 return r;
6067 /** Read the contents of a FallbackDir line from <b>line</b>. If
6068 * <b>validate_only</b> is 0, and the line is well-formed, then add the
6069 * dirserver described in the line as a fallback directory. Return 0 on
6070 * success, or -1 if the line isn't well-formed or if we can't add it. */
6072 parse_dir_fallback_line(const char *line,
6073 int validate_only)
6075 int r = -1;
6076 smartlist_t *items = smartlist_new(), *positional = smartlist_new();
6077 int orport = -1;
6078 uint16_t dirport;
6079 tor_addr_t addr;
6080 int ok;
6081 char id[DIGEST_LEN];
6082 char *address=NULL;
6083 tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
6084 double weight=1.0;
6086 memset(id, 0, sizeof(id));
6087 smartlist_split_string(items, line, NULL,
6088 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6089 SMARTLIST_FOREACH_BEGIN(items, const char *, cp) {
6090 const char *eq = strchr(cp, '=');
6091 ok = 1;
6092 if (! eq) {
6093 smartlist_add(positional, (char*)cp);
6094 continue;
6096 if (!strcmpstart(cp, "orport=")) {
6097 orport = (int)tor_parse_long(cp+strlen("orport="), 10,
6098 1, 65535, &ok, NULL);
6099 } else if (!strcmpstart(cp, "id=")) {
6100 ok = base16_decode(id, DIGEST_LEN, cp+strlen("id="),
6101 strlen(cp)-strlen("id=")) == DIGEST_LEN;
6102 } else if (!strcasecmpstart(cp, "ipv6=")) {
6103 if (ipv6_addrport_ptr) {
6104 log_warn(LD_CONFIG, "Redundant ipv6 addr/port on FallbackDir line");
6105 } else {
6106 if (tor_addr_port_parse(LOG_WARN, cp+strlen("ipv6="),
6107 &ipv6_addrport.addr, &ipv6_addrport.port,
6108 -1) < 0
6109 || tor_addr_family(&ipv6_addrport.addr) != AF_INET6) {
6110 log_warn(LD_CONFIG, "Bad ipv6 addr/port %s on FallbackDir line",
6111 escaped(cp));
6112 goto end;
6114 ipv6_addrport_ptr = &ipv6_addrport;
6116 } else if (!strcmpstart(cp, "weight=")) {
6117 int num_ok;
6118 const char *wstring = cp + strlen("weight=");
6119 weight = tor_parse_double(wstring, 0, (double)UINT64_MAX, &num_ok, NULL);
6120 if (!num_ok) {
6121 log_warn(LD_CONFIG, "Invalid weight '%s' on FallbackDir line.", cp);
6122 weight=1.0;
6126 if (!ok) {
6127 log_warn(LD_CONFIG, "Bad FallbackDir option %s", escaped(cp));
6128 goto end;
6130 } SMARTLIST_FOREACH_END(cp);
6132 if (smartlist_len(positional) != 1) {
6133 log_warn(LD_CONFIG, "Couldn't parse FallbackDir line %s", escaped(line));
6134 goto end;
6137 if (tor_digest_is_zero(id)) {
6138 log_warn(LD_CONFIG, "Missing identity on FallbackDir line");
6139 goto end;
6142 if (orport <= 0) {
6143 log_warn(LD_CONFIG, "Missing orport on FallbackDir line");
6144 goto end;
6147 if (tor_addr_port_split(LOG_INFO, smartlist_get(positional, 0),
6148 &address, &dirport) < 0 ||
6149 tor_addr_parse(&addr, address)<0) {
6150 log_warn(LD_CONFIG, "Couldn't parse address:port %s on FallbackDir line",
6151 (const char*)smartlist_get(positional, 0));
6152 goto end;
6155 if (!validate_only) {
6156 dir_server_t *ds;
6157 ds = fallback_dir_server_new(&addr, dirport, orport, ipv6_addrport_ptr,
6158 id, weight);
6159 if (!ds) {
6160 log_warn(LD_CONFIG, "Couldn't create FallbackDir %s", escaped(line));
6161 goto end;
6163 dir_server_add(ds);
6166 r = 0;
6168 end:
6169 SMARTLIST_FOREACH(items, char *, cp, tor_free(cp));
6170 smartlist_free(items);
6171 smartlist_free(positional);
6172 tor_free(address);
6173 return r;
6176 /** Allocate and return a new port_cfg_t with reasonable defaults. */
6177 STATIC port_cfg_t *
6178 port_cfg_new(size_t namelen)
6180 tor_assert(namelen <= SIZE_T_CEILING - sizeof(port_cfg_t) - 1);
6181 port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t) + namelen + 1);
6182 cfg->entry_cfg.ipv4_traffic = 1;
6183 cfg->entry_cfg.cache_ipv4_answers = 1;
6184 cfg->entry_cfg.prefer_ipv6_virtaddr = 1;
6185 return cfg;
6188 /** Free all storage held in <b>port</b> */
6189 STATIC void
6190 port_cfg_free(port_cfg_t *port)
6192 tor_free(port);
6195 /** Warn for every port in <b>ports</b> of type <b>listener_type</b> that is
6196 * on a publicly routable address. */
6197 static void
6198 warn_nonlocal_client_ports(const smartlist_t *ports, const char *portname,
6199 int listener_type)
6201 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
6202 if (port->type != listener_type)
6203 continue;
6204 if (port->is_unix_addr) {
6205 /* Unix sockets aren't accessible over a network. */
6206 } else if (!tor_addr_is_internal(&port->addr, 1)) {
6207 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
6208 "Other people on the Internet might find your computer and "
6209 "use it as an open proxy. Please don't allow this unless you "
6210 "have a good reason.",
6211 fmt_addrport(&port->addr, port->port), portname);
6212 } else if (!tor_addr_is_loopback(&port->addr)) {
6213 log_notice(LD_CONFIG, "You configured a non-loopback address '%s' "
6214 "for %sPort. This allows everybody on your local network to "
6215 "use your machine as a proxy. Make sure this is what you "
6216 "wanted.",
6217 fmt_addrport(&port->addr, port->port), portname);
6219 } SMARTLIST_FOREACH_END(port);
6222 /** Warn for every Extended ORPort port in <b>ports</b> that is on a
6223 * publicly routable address. */
6224 static void
6225 warn_nonlocal_ext_orports(const smartlist_t *ports, const char *portname)
6227 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
6228 if (port->type != CONN_TYPE_EXT_OR_LISTENER)
6229 continue;
6230 if (port->is_unix_addr)
6231 continue;
6232 /* XXX maybe warn even if address is RFC1918? */
6233 if (!tor_addr_is_internal(&port->addr, 1)) {
6234 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
6235 "This is not advised; this address is supposed to only be "
6236 "exposed on localhost so that your pluggable transport "
6237 "proxies can connect to it.",
6238 fmt_addrport(&port->addr, port->port), portname);
6240 } SMARTLIST_FOREACH_END(port);
6243 /** Given a list of port_cfg_t in <b>ports</b>, warn if any controller port
6244 * there is listening on any non-loopback address. If <b>forbid_nonlocal</b>
6245 * is true, then emit a stronger warning and remove the port from the list.
6247 static void
6248 warn_nonlocal_controller_ports(smartlist_t *ports, unsigned forbid_nonlocal)
6250 int warned = 0;
6251 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
6252 if (port->type != CONN_TYPE_CONTROL_LISTENER)
6253 continue;
6254 if (port->is_unix_addr)
6255 continue;
6256 if (!tor_addr_is_loopback(&port->addr)) {
6257 if (forbid_nonlocal) {
6258 if (!warned)
6259 log_warn(LD_CONFIG,
6260 "You have a ControlPort set to accept "
6261 "unauthenticated connections from a non-local address. "
6262 "This means that programs not running on your computer "
6263 "can reconfigure your Tor, without even having to guess a "
6264 "password. That's so bad that I'm closing your ControlPort "
6265 "for you. If you need to control your Tor remotely, try "
6266 "enabling authentication and using a tool like stunnel or "
6267 "ssh to encrypt remote access.");
6268 warned = 1;
6269 port_cfg_free(port);
6270 SMARTLIST_DEL_CURRENT(ports, port);
6271 } else {
6272 log_warn(LD_CONFIG, "You have a ControlPort set to accept "
6273 "connections from a non-local address. This means that "
6274 "programs not running on your computer can reconfigure your "
6275 "Tor. That's pretty bad, since the controller "
6276 "protocol isn't encrypted! Maybe you should just listen on "
6277 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
6278 "remote connections to your control port.");
6279 return; /* No point in checking the rest */
6282 } SMARTLIST_FOREACH_END(port);
6285 #ifdef HAVE_SYS_UN_H
6287 /** Parse the given <b>addrport</b> and set <b>path_out</b> if a Unix socket
6288 * path is found. Return 0 on success. On error, a negative value is
6289 * returned, -ENOENT if no Unix statement found, -EINVAL if the socket path
6290 * is empty and -ENOSYS if AF_UNIX is not supported (see function in the
6291 * #else statement below). */
6294 config_parse_unix_port(const char *addrport, char **path_out)
6296 tor_assert(path_out);
6297 tor_assert(addrport);
6299 if (strcmpstart(addrport, unix_socket_prefix)) {
6300 /* Not a Unix socket path. */
6301 return -ENOENT;
6304 if (strlen(addrport + strlen(unix_socket_prefix)) == 0) {
6305 /* Empty socket path, not very usable. */
6306 return -EINVAL;
6309 *path_out = tor_strdup(addrport + strlen(unix_socket_prefix));
6310 return 0;
6313 #else /* defined(HAVE_SYS_UN_H) */
6316 config_parse_unix_port(const char *addrport, char **path_out)
6318 tor_assert(path_out);
6319 tor_assert(addrport);
6321 if (strcmpstart(addrport, unix_socket_prefix)) {
6322 /* Not a Unix socket path. */
6323 return -ENOENT;
6326 log_warn(LD_CONFIG,
6327 "Port configuration %s is for an AF_UNIX socket, but we have no"
6328 "support available on this platform",
6329 escaped(addrport));
6330 return -ENOSYS;
6332 #endif /* defined(HAVE_SYS_UN_H) */
6334 static void
6335 warn_client_dns_cache(const char *option, int disabling)
6337 if (disabling)
6338 return;
6340 warn_deprecated_option(option,
6341 "Client-side DNS cacheing enables a wide variety of route-"
6342 "capture attacks. If a single bad exit node lies to you about "
6343 "an IP address, cacheing that address would make you visit "
6344 "an address of the attacker's choice every time you connected "
6345 "to your destination.");
6349 * Parse port configuration for a single port type.
6351 * Read entries of the "FooPort" type from the list <b>ports</b>, and
6352 * entries of the "FooListenAddress" type from the list
6353 * <b>listenaddrs</b>. Two syntaxes are supported: a legacy syntax
6354 * where FooPort is at most a single entry containing a port number and
6355 * where FooListenAddress has any number of address:port combinations;
6356 * and a new syntax where there are no FooListenAddress entries and
6357 * where FooPort can have any number of entries of the format
6358 * "[Address:][Port] IsolationOptions".
6360 * In log messages, describe the port type as <b>portname</b>.
6362 * If no address is specified, default to <b>defaultaddr</b>. If no
6363 * FooPort is given, default to defaultport (if 0, there is no default).
6365 * If CL_PORT_NO_STREAM_OPTIONS is set in <b>flags</b>, do not allow stream
6366 * isolation options in the FooPort entries.
6368 * If CL_PORT_WARN_NONLOCAL is set in <b>flags</b>, warn if any of the
6369 * ports are not on a local address. If CL_PORT_FORBID_NONLOCAL is set,
6370 * this is a control port with no password set: don't even allow it.
6372 * Unless CL_PORT_ALLOW_EXTRA_LISTENADDR is set in <b>flags</b>, warn
6373 * if FooListenAddress is set but FooPort is 0.
6375 * If CL_PORT_SERVER_OPTIONS is set in <b>flags</b>, do not allow stream
6376 * isolation options in the FooPort entries; instead allow the
6377 * server-port option set.
6379 * If CL_PORT_TAKES_HOSTNAMES is set in <b>flags</b>, allow the options
6380 * {No,}IPv{4,6}Traffic.
6382 * On success, if <b>out</b> is given, add a new port_cfg_t entry to
6383 * <b>out</b> for every port that the client should listen on. Return 0
6384 * on success, -1 on failure.
6386 STATIC int
6387 parse_port_config(smartlist_t *out,
6388 const config_line_t *ports,
6389 const config_line_t *listenaddrs,
6390 const char *portname,
6391 int listener_type,
6392 const char *defaultaddr,
6393 int defaultport,
6394 const unsigned flags)
6396 smartlist_t *elts;
6397 int retval = -1;
6398 const unsigned is_control = (listener_type == CONN_TYPE_CONTROL_LISTENER);
6399 const unsigned is_ext_orport = (listener_type == CONN_TYPE_EXT_OR_LISTENER);
6400 const unsigned allow_no_stream_options = flags & CL_PORT_NO_STREAM_OPTIONS;
6401 const unsigned use_server_options = flags & CL_PORT_SERVER_OPTIONS;
6402 const unsigned warn_nonlocal = flags & CL_PORT_WARN_NONLOCAL;
6403 const unsigned forbid_nonlocal = flags & CL_PORT_FORBID_NONLOCAL;
6404 const unsigned default_to_group_writable =
6405 flags & CL_PORT_DFLT_GROUP_WRITABLE;
6406 const unsigned allow_spurious_listenaddr =
6407 flags & CL_PORT_ALLOW_EXTRA_LISTENADDR;
6408 const unsigned takes_hostnames = flags & CL_PORT_TAKES_HOSTNAMES;
6409 const unsigned is_unix_socket = flags & CL_PORT_IS_UNIXSOCKET;
6410 int got_zero_port=0, got_nonzero_port=0;
6411 char *unix_socket_path = NULL;
6413 /* FooListenAddress is deprecated; let's make it work like it used to work,
6414 * though. */
6415 if (listenaddrs) {
6416 int mainport = defaultport;
6418 if (ports && ports->next) {
6419 log_warn(LD_CONFIG, "%sListenAddress can't be used when there are "
6420 "multiple %sPort lines", portname, portname);
6421 return -1;
6422 } else if (ports) {
6423 if (!strcmp(ports->value, "auto")) {
6424 mainport = CFG_AUTO_PORT;
6425 } else {
6426 int ok;
6427 mainport = (int)tor_parse_long(ports->value, 10, 0, 65535, &ok, NULL);
6428 if (!ok) {
6429 log_warn(LD_CONFIG, "%sListenAddress can only be used with a single "
6430 "%sPort with value \"auto\" or 1-65535 and no options set.",
6431 portname, portname);
6432 return -1;
6437 if (mainport == 0) {
6438 if (allow_spurious_listenaddr)
6439 return 1; /*DOCDOC*/
6440 log_warn(LD_CONFIG, "%sPort must be defined if %sListenAddress is used",
6441 portname, portname);
6442 return -1;
6445 if (use_server_options && out) {
6446 /* Add a no_listen port. */
6447 port_cfg_t *cfg = port_cfg_new(0);
6448 cfg->type = listener_type;
6449 cfg->port = mainport;
6450 tor_addr_make_unspec(&cfg->addr); /* Server ports default to 0.0.0.0 */
6451 cfg->server_cfg.no_listen = 1;
6452 cfg->server_cfg.bind_ipv4_only = 1;
6453 cfg->entry_cfg.ipv4_traffic = 1;
6454 cfg->entry_cfg.prefer_ipv6_virtaddr = 1;
6455 smartlist_add(out, cfg);
6458 for (; listenaddrs; listenaddrs = listenaddrs->next) {
6459 tor_addr_t addr;
6460 uint16_t port = 0;
6461 if (tor_addr_port_lookup(listenaddrs->value, &addr, &port) < 0) {
6462 log_warn(LD_CONFIG, "Unable to parse %sListenAddress '%s'",
6463 portname, listenaddrs->value);
6464 return -1;
6466 if (out) {
6467 port_cfg_t *cfg = port_cfg_new(0);
6468 cfg->type = listener_type;
6469 cfg->port = port ? port : mainport;
6470 tor_addr_copy(&cfg->addr, &addr);
6471 cfg->entry_cfg.session_group = SESSION_GROUP_UNSET;
6472 cfg->entry_cfg.isolation_flags = ISO_DEFAULT;
6473 cfg->server_cfg.no_advertise = 1;
6474 smartlist_add(out, cfg);
6478 if (warn_nonlocal && out) {
6479 if (is_control)
6480 warn_nonlocal_controller_ports(out, forbid_nonlocal);
6481 else if (is_ext_orport)
6482 warn_nonlocal_ext_orports(out, portname);
6483 else
6484 warn_nonlocal_client_ports(out, portname, listener_type);
6486 return 0;
6487 } /* end if (listenaddrs) */
6489 /* No ListenAddress lines. If there's no FooPort, then maybe make a default
6490 * one. */
6491 if (! ports) {
6492 if (defaultport && defaultaddr && out) {
6493 port_cfg_t *cfg = port_cfg_new(is_unix_socket ? strlen(defaultaddr) : 0);
6494 cfg->type = listener_type;
6495 if (is_unix_socket) {
6496 tor_addr_make_unspec(&cfg->addr);
6497 memcpy(cfg->unix_addr, defaultaddr, strlen(defaultaddr) + 1);
6498 cfg->is_unix_addr = 1;
6499 } else {
6500 cfg->port = defaultport;
6501 tor_addr_parse(&cfg->addr, defaultaddr);
6503 cfg->entry_cfg.session_group = SESSION_GROUP_UNSET;
6504 cfg->entry_cfg.isolation_flags = ISO_DEFAULT;
6505 smartlist_add(out, cfg);
6507 return 0;
6510 /* At last we can actually parse the FooPort lines. The syntax is:
6511 * [Addr:](Port|auto) [Options].*/
6512 elts = smartlist_new();
6514 for (; ports; ports = ports->next) {
6515 tor_addr_t addr;
6516 int port, ret;
6517 int sessiongroup = SESSION_GROUP_UNSET;
6518 unsigned isolation = ISO_DEFAULT;
6519 int prefer_no_auth = 0;
6520 int socks_iso_keep_alive = 0;
6522 char *addrport;
6523 uint16_t ptmp=0;
6524 int ok;
6525 int no_listen = 0, no_advertise = 0, all_addrs = 0,
6526 bind_ipv4_only = 0, bind_ipv6_only = 0,
6527 ipv4_traffic = 1, ipv6_traffic = 0, prefer_ipv6 = 0,
6528 cache_ipv4 = 1, use_cached_ipv4 = 0,
6529 cache_ipv6 = 0, use_cached_ipv6 = 0,
6530 prefer_ipv6_automap = 1, world_writable = 0, group_writable = 0,
6531 relax_dirmode_check = 0,
6532 has_used_unix_socket_only_option = 0;
6534 smartlist_split_string(elts, ports->value, NULL,
6535 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
6536 if (smartlist_len(elts) == 0) {
6537 log_warn(LD_CONFIG, "Invalid %sPort line with no value", portname);
6538 goto err;
6541 /* Now parse the addr/port value */
6542 addrport = smartlist_get(elts, 0);
6544 /* Let's start to check if it's a Unix socket path. */
6545 ret = config_parse_unix_port(addrport, &unix_socket_path);
6546 if (ret < 0 && ret != -ENOENT) {
6547 if (ret == -EINVAL) {
6548 log_warn(LD_CONFIG, "Empty Unix socket path.");
6550 goto err;
6553 if (unix_socket_path &&
6554 ! conn_listener_type_supports_af_unix(listener_type)) {
6555 log_warn(LD_CONFIG, "%sPort does not support unix sockets", portname);
6556 goto err;
6559 if (unix_socket_path) {
6560 port = 1;
6561 } else if (is_unix_socket) {
6562 unix_socket_path = tor_strdup(addrport);
6563 if (!strcmp(addrport, "0"))
6564 port = 0;
6565 else
6566 port = 1;
6567 } else if (!strcmp(addrport, "auto")) {
6568 port = CFG_AUTO_PORT;
6569 int af = tor_addr_parse(&addr, defaultaddr);
6570 tor_assert(af >= 0);
6571 } else if (!strcasecmpend(addrport, ":auto")) {
6572 char *addrtmp = tor_strndup(addrport, strlen(addrport)-5);
6573 port = CFG_AUTO_PORT;
6574 if (tor_addr_port_lookup(addrtmp, &addr, &ptmp)<0 || ptmp) {
6575 log_warn(LD_CONFIG, "Invalid address '%s' for %sPort",
6576 escaped(addrport), portname);
6577 tor_free(addrtmp);
6578 goto err;
6580 tor_free(addrtmp);
6581 } else {
6582 /* Try parsing integer port before address, because, who knows?
6583 "9050" might be a valid address. */
6584 port = (int) tor_parse_long(addrport, 10, 0, 65535, &ok, NULL);
6585 if (ok) {
6586 int af = tor_addr_parse(&addr, defaultaddr);
6587 tor_assert(af >= 0);
6588 } else if (tor_addr_port_lookup(addrport, &addr, &ptmp) == 0) {
6589 if (ptmp == 0) {
6590 log_warn(LD_CONFIG, "%sPort line has address but no port", portname);
6591 goto err;
6593 port = ptmp;
6594 } else {
6595 log_warn(LD_CONFIG, "Couldn't parse address %s for %sPort",
6596 escaped(addrport), portname);
6597 goto err;
6601 if (unix_socket_path && default_to_group_writable)
6602 group_writable = 1;
6604 /* Now parse the rest of the options, if any. */
6605 if (use_server_options) {
6606 /* This is a server port; parse advertising options */
6607 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
6608 if (elt_sl_idx == 0)
6609 continue; /* Skip addr:port */
6611 if (!strcasecmp(elt, "NoAdvertise")) {
6612 no_advertise = 1;
6613 } else if (!strcasecmp(elt, "NoListen")) {
6614 no_listen = 1;
6615 #if 0
6616 /* not implemented yet. */
6617 } else if (!strcasecmp(elt, "AllAddrs")) {
6619 all_addrs = 1;
6620 #endif
6621 } else if (!strcasecmp(elt, "IPv4Only")) {
6622 bind_ipv4_only = 1;
6623 } else if (!strcasecmp(elt, "IPv6Only")) {
6624 bind_ipv6_only = 1;
6625 } else {
6626 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6627 portname, escaped(elt));
6629 } SMARTLIST_FOREACH_END(elt);
6631 if (no_advertise && no_listen) {
6632 log_warn(LD_CONFIG, "Tried to set both NoListen and NoAdvertise "
6633 "on %sPort line '%s'",
6634 portname, escaped(ports->value));
6635 goto err;
6637 if (bind_ipv4_only && bind_ipv6_only) {
6638 log_warn(LD_CONFIG, "Tried to set both IPv4Only and IPv6Only "
6639 "on %sPort line '%s'",
6640 portname, escaped(ports->value));
6641 goto err;
6643 if (bind_ipv4_only && tor_addr_family(&addr) == AF_INET6) {
6644 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv6",
6645 portname);
6646 goto err;
6648 if (bind_ipv6_only && tor_addr_family(&addr) == AF_INET) {
6649 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv4",
6650 portname);
6651 goto err;
6653 } else {
6654 /* This is a client port; parse isolation options */
6655 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
6656 int no = 0, isoflag = 0;
6657 const char *elt_orig = elt;
6658 if (elt_sl_idx == 0)
6659 continue; /* Skip addr:port */
6661 if (!strcasecmpstart(elt, "SessionGroup=")) {
6662 int group = (int)tor_parse_long(elt+strlen("SessionGroup="),
6663 10, 0, INT_MAX, &ok, NULL);
6664 if (!ok || !allow_no_stream_options) {
6665 log_warn(LD_CONFIG, "Invalid %sPort option '%s'",
6666 portname, escaped(elt));
6667 goto err;
6669 if (sessiongroup >= 0) {
6670 log_warn(LD_CONFIG, "Multiple SessionGroup options on %sPort",
6671 portname);
6672 goto err;
6674 sessiongroup = group;
6675 continue;
6678 if (!strcasecmpstart(elt, "No")) {
6679 no = 1;
6680 elt += 2;
6683 if (!strcasecmp(elt, "GroupWritable")) {
6684 group_writable = !no;
6685 has_used_unix_socket_only_option = 1;
6686 continue;
6687 } else if (!strcasecmp(elt, "WorldWritable")) {
6688 world_writable = !no;
6689 has_used_unix_socket_only_option = 1;
6690 continue;
6691 } else if (!strcasecmp(elt, "RelaxDirModeCheck")) {
6692 relax_dirmode_check = !no;
6693 has_used_unix_socket_only_option = 1;
6694 continue;
6697 if (allow_no_stream_options) {
6698 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6699 portname, escaped(elt));
6700 continue;
6703 if (takes_hostnames) {
6704 if (!strcasecmp(elt, "IPv4Traffic")) {
6705 ipv4_traffic = ! no;
6706 continue;
6707 } else if (!strcasecmp(elt, "IPv6Traffic")) {
6708 ipv6_traffic = ! no;
6709 continue;
6710 } else if (!strcasecmp(elt, "PreferIPv6")) {
6711 prefer_ipv6 = ! no;
6712 continue;
6715 if (!strcasecmp(elt, "CacheIPv4DNS")) {
6716 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6717 cache_ipv4 = ! no;
6718 continue;
6719 } else if (!strcasecmp(elt, "CacheIPv6DNS")) {
6720 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6721 cache_ipv6 = ! no;
6722 continue;
6723 } else if (!strcasecmp(elt, "CacheDNS")) {
6724 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6725 cache_ipv4 = cache_ipv6 = ! no;
6726 continue;
6727 } else if (!strcasecmp(elt, "UseIPv4Cache")) {
6728 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6729 use_cached_ipv4 = ! no;
6730 continue;
6731 } else if (!strcasecmp(elt, "UseIPv6Cache")) {
6732 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6733 use_cached_ipv6 = ! no;
6734 continue;
6735 } else if (!strcasecmp(elt, "UseDNSCache")) {
6736 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6737 use_cached_ipv4 = use_cached_ipv6 = ! no;
6738 continue;
6739 } else if (!strcasecmp(elt, "PreferIPv6Automap")) {
6740 prefer_ipv6_automap = ! no;
6741 continue;
6742 } else if (!strcasecmp(elt, "PreferSOCKSNoAuth")) {
6743 prefer_no_auth = ! no;
6744 continue;
6745 } else if (!strcasecmp(elt, "KeepAliveIsolateSOCKSAuth")) {
6746 socks_iso_keep_alive = ! no;
6747 continue;
6750 if (!strcasecmpend(elt, "s"))
6751 elt[strlen(elt)-1] = '\0'; /* kill plurals. */
6753 if (!strcasecmp(elt, "IsolateDestPort")) {
6754 isoflag = ISO_DESTPORT;
6755 } else if (!strcasecmp(elt, "IsolateDestAddr")) {
6756 isoflag = ISO_DESTADDR;
6757 } else if (!strcasecmp(elt, "IsolateSOCKSAuth")) {
6758 isoflag = ISO_SOCKSAUTH;
6759 } else if (!strcasecmp(elt, "IsolateClientProtocol")) {
6760 isoflag = ISO_CLIENTPROTO;
6761 } else if (!strcasecmp(elt, "IsolateClientAddr")) {
6762 isoflag = ISO_CLIENTADDR;
6763 } else {
6764 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6765 portname, escaped(elt_orig));
6768 if (no) {
6769 isolation &= ~isoflag;
6770 } else {
6771 isolation |= isoflag;
6773 } SMARTLIST_FOREACH_END(elt);
6776 if (port)
6777 got_nonzero_port = 1;
6778 else
6779 got_zero_port = 1;
6781 if (ipv4_traffic == 0 && ipv6_traffic == 0) {
6782 log_warn(LD_CONFIG, "You have a %sPort entry with both IPv4 and "
6783 "IPv6 disabled; that won't work.", portname);
6784 goto err;
6787 if ( has_used_unix_socket_only_option && ! unix_socket_path) {
6788 log_warn(LD_CONFIG, "You have a %sPort entry with GroupWritable, "
6789 "WorldWritable, or RelaxDirModeCheck, but it is not a "
6790 "unix socket.", portname);
6791 goto err;
6794 if (!(isolation & ISO_SOCKSAUTH) && socks_iso_keep_alive) {
6795 log_warn(LD_CONFIG, "You have a %sPort entry with both "
6796 "NoIsolateSOCKSAuth and KeepAliveIsolateSOCKSAuth set.",
6797 portname);
6798 goto err;
6801 if (out && port) {
6802 size_t namelen = unix_socket_path ? strlen(unix_socket_path) : 0;
6803 port_cfg_t *cfg = port_cfg_new(namelen);
6804 if (unix_socket_path) {
6805 tor_addr_make_unspec(&cfg->addr);
6806 memcpy(cfg->unix_addr, unix_socket_path, namelen + 1);
6807 cfg->is_unix_addr = 1;
6808 tor_free(unix_socket_path);
6809 } else {
6810 tor_addr_copy(&cfg->addr, &addr);
6811 cfg->port = port;
6813 cfg->type = listener_type;
6814 cfg->is_world_writable = world_writable;
6815 cfg->is_group_writable = group_writable;
6816 cfg->relax_dirmode_check = relax_dirmode_check;
6817 cfg->entry_cfg.isolation_flags = isolation;
6818 cfg->entry_cfg.session_group = sessiongroup;
6819 cfg->server_cfg.no_advertise = no_advertise;
6820 cfg->server_cfg.no_listen = no_listen;
6821 cfg->server_cfg.all_addrs = all_addrs;
6822 cfg->server_cfg.bind_ipv4_only = bind_ipv4_only;
6823 cfg->server_cfg.bind_ipv6_only = bind_ipv6_only;
6824 cfg->entry_cfg.ipv4_traffic = ipv4_traffic;
6825 cfg->entry_cfg.ipv6_traffic = ipv6_traffic;
6826 cfg->entry_cfg.prefer_ipv6 = prefer_ipv6;
6827 cfg->entry_cfg.cache_ipv4_answers = cache_ipv4;
6828 cfg->entry_cfg.cache_ipv6_answers = cache_ipv6;
6829 cfg->entry_cfg.use_cached_ipv4_answers = use_cached_ipv4;
6830 cfg->entry_cfg.use_cached_ipv6_answers = use_cached_ipv6;
6831 cfg->entry_cfg.prefer_ipv6_virtaddr = prefer_ipv6_automap;
6832 cfg->entry_cfg.socks_prefer_no_auth = prefer_no_auth;
6833 if (! (isolation & ISO_SOCKSAUTH))
6834 cfg->entry_cfg.socks_prefer_no_auth = 1;
6835 cfg->entry_cfg.socks_iso_keep_alive = socks_iso_keep_alive;
6837 smartlist_add(out, cfg);
6839 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
6840 smartlist_clear(elts);
6843 if (warn_nonlocal && out) {
6844 if (is_control)
6845 warn_nonlocal_controller_ports(out, forbid_nonlocal);
6846 else if (is_ext_orport)
6847 warn_nonlocal_ext_orports(out, portname);
6848 else
6849 warn_nonlocal_client_ports(out, portname, listener_type);
6852 if (got_zero_port && got_nonzero_port) {
6853 log_warn(LD_CONFIG, "You specified a nonzero %sPort along with '%sPort 0' "
6854 "in the same configuration. Did you mean to disable %sPort or "
6855 "not?", portname, portname, portname);
6856 goto err;
6859 retval = 0;
6860 err:
6861 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
6862 smartlist_free(elts);
6863 tor_free(unix_socket_path);
6864 return retval;
6867 /** Return the number of ports which are actually going to listen with type
6868 * <b>listenertype</b>. Do not count no_listen ports. Only count unix
6869 * sockets if count_sockets is true. */
6870 static int
6871 count_real_listeners(const smartlist_t *ports, int listenertype,
6872 int count_sockets)
6874 int n = 0;
6875 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
6876 if (port->server_cfg.no_listen)
6877 continue;
6878 if (!count_sockets && port->is_unix_addr)
6879 continue;
6880 if (port->type != listenertype)
6881 continue;
6882 ++n;
6883 } SMARTLIST_FOREACH_END(port);
6884 return n;
6887 /** Parse all ports from <b>options</b>. On success, set *<b>n_ports_out</b>
6888 * to the number of ports that are listed, update the *Port_set values in
6889 * <b>options</b>, and return 0. On failure, set *<b>msg</b> to a
6890 * description of the problem and return -1.
6892 * If <b>validate_only</b> is false, set configured_client_ports to the
6893 * new list of ports parsed from <b>options</b>.
6895 static int
6896 parse_ports(or_options_t *options, int validate_only,
6897 char **msg, int *n_ports_out,
6898 int *world_writable_control_socket)
6900 smartlist_t *ports;
6901 int retval = -1;
6903 ports = smartlist_new();
6905 *n_ports_out = 0;
6907 const unsigned gw_flag = options->SocksSocketsGroupWritable ?
6908 CL_PORT_DFLT_GROUP_WRITABLE : 0;
6909 if (parse_port_config(ports,
6910 options->SocksPort_lines, options->SocksListenAddress,
6911 "Socks", CONN_TYPE_AP_LISTENER,
6912 "127.0.0.1", 9050,
6913 CL_PORT_WARN_NONLOCAL|CL_PORT_ALLOW_EXTRA_LISTENADDR|
6914 CL_PORT_TAKES_HOSTNAMES|gw_flag) < 0) {
6915 *msg = tor_strdup("Invalid SocksPort/SocksListenAddress configuration");
6916 goto err;
6918 if (parse_port_config(ports,
6919 options->DNSPort_lines, options->DNSListenAddress,
6920 "DNS", CONN_TYPE_AP_DNS_LISTENER,
6921 "127.0.0.1", 0,
6922 CL_PORT_WARN_NONLOCAL|CL_PORT_TAKES_HOSTNAMES) < 0) {
6923 *msg = tor_strdup("Invalid DNSPort/DNSListenAddress configuration");
6924 goto err;
6926 if (parse_port_config(ports,
6927 options->TransPort_lines, options->TransListenAddress,
6928 "Trans", CONN_TYPE_AP_TRANS_LISTENER,
6929 "127.0.0.1", 0,
6930 CL_PORT_WARN_NONLOCAL) < 0) {
6931 *msg = tor_strdup("Invalid TransPort/TransListenAddress configuration");
6932 goto err;
6934 if (parse_port_config(ports,
6935 options->NATDPort_lines, options->NATDListenAddress,
6936 "NATD", CONN_TYPE_AP_NATD_LISTENER,
6937 "127.0.0.1", 0,
6938 CL_PORT_WARN_NONLOCAL) < 0) {
6939 *msg = tor_strdup("Invalid NatdPort/NatdListenAddress configuration");
6940 goto err;
6943 unsigned control_port_flags = CL_PORT_NO_STREAM_OPTIONS |
6944 CL_PORT_WARN_NONLOCAL;
6945 const int any_passwords = (options->HashedControlPassword ||
6946 options->HashedControlSessionPassword ||
6947 options->CookieAuthentication);
6948 if (! any_passwords)
6949 control_port_flags |= CL_PORT_FORBID_NONLOCAL;
6950 if (options->ControlSocketsGroupWritable)
6951 control_port_flags |= CL_PORT_DFLT_GROUP_WRITABLE;
6953 if (parse_port_config(ports,
6954 options->ControlPort_lines,
6955 options->ControlListenAddress,
6956 "Control", CONN_TYPE_CONTROL_LISTENER,
6957 "127.0.0.1", 0,
6958 control_port_flags) < 0) {
6959 *msg = tor_strdup("Invalid ControlPort/ControlListenAddress "
6960 "configuration");
6961 goto err;
6964 if (parse_port_config(ports, options->ControlSocket, NULL,
6965 "ControlSocket",
6966 CONN_TYPE_CONTROL_LISTENER, NULL, 0,
6967 control_port_flags | CL_PORT_IS_UNIXSOCKET) < 0) {
6968 *msg = tor_strdup("Invalid ControlSocket configuration");
6969 goto err;
6972 if (! options->ClientOnly) {
6973 if (parse_port_config(ports,
6974 options->ORPort_lines, options->ORListenAddress,
6975 "OR", CONN_TYPE_OR_LISTENER,
6976 "0.0.0.0", 0,
6977 CL_PORT_SERVER_OPTIONS) < 0) {
6978 *msg = tor_strdup("Invalid ORPort/ORListenAddress configuration");
6979 goto err;
6981 if (parse_port_config(ports,
6982 options->ExtORPort_lines, NULL,
6983 "ExtOR", CONN_TYPE_EXT_OR_LISTENER,
6984 "127.0.0.1", 0,
6985 CL_PORT_SERVER_OPTIONS|CL_PORT_WARN_NONLOCAL) < 0) {
6986 *msg = tor_strdup("Invalid ExtORPort configuration");
6987 goto err;
6989 if (parse_port_config(ports,
6990 options->DirPort_lines, options->DirListenAddress,
6991 "Dir", CONN_TYPE_DIR_LISTENER,
6992 "0.0.0.0", 0,
6993 CL_PORT_SERVER_OPTIONS) < 0) {
6994 *msg = tor_strdup("Invalid DirPort/DirListenAddress configuration");
6995 goto err;
6999 int n_low_ports = 0;
7000 if (check_server_ports(ports, options, &n_low_ports) < 0) {
7001 *msg = tor_strdup("Misconfigured server ports");
7002 goto err;
7004 if (have_low_ports < 0)
7005 have_low_ports = (n_low_ports > 0);
7007 *n_ports_out = smartlist_len(ports);
7009 retval = 0;
7011 /* Update the *Port_set options. The !! here is to force a boolean out of
7012 an integer. */
7013 options->ORPort_set =
7014 !! count_real_listeners(ports, CONN_TYPE_OR_LISTENER, 0);
7015 options->SocksPort_set =
7016 !! count_real_listeners(ports, CONN_TYPE_AP_LISTENER, 1);
7017 options->TransPort_set =
7018 !! count_real_listeners(ports, CONN_TYPE_AP_TRANS_LISTENER, 1);
7019 options->NATDPort_set =
7020 !! count_real_listeners(ports, CONN_TYPE_AP_NATD_LISTENER, 1);
7021 /* Use options->ControlSocket to test if a control socket is set */
7022 options->ControlPort_set =
7023 !! count_real_listeners(ports, CONN_TYPE_CONTROL_LISTENER, 0);
7024 options->DirPort_set =
7025 !! count_real_listeners(ports, CONN_TYPE_DIR_LISTENER, 0);
7026 options->DNSPort_set =
7027 !! count_real_listeners(ports, CONN_TYPE_AP_DNS_LISTENER, 1);
7028 options->ExtORPort_set =
7029 !! count_real_listeners(ports, CONN_TYPE_EXT_OR_LISTENER, 0);
7031 if (world_writable_control_socket) {
7032 SMARTLIST_FOREACH(ports, port_cfg_t *, p,
7033 if (p->type == CONN_TYPE_CONTROL_LISTENER &&
7034 p->is_unix_addr &&
7035 p->is_world_writable) {
7036 *world_writable_control_socket = 1;
7037 break;
7041 if (!validate_only) {
7042 if (configured_ports) {
7043 SMARTLIST_FOREACH(configured_ports,
7044 port_cfg_t *, p, port_cfg_free(p));
7045 smartlist_free(configured_ports);
7047 configured_ports = ports;
7048 ports = NULL; /* prevent free below. */
7051 err:
7052 if (ports) {
7053 SMARTLIST_FOREACH(ports, port_cfg_t *, p, port_cfg_free(p));
7054 smartlist_free(ports);
7056 return retval;
7059 /* Does port bind to IPv4? */
7060 static int
7061 port_binds_ipv4(const port_cfg_t *port)
7063 return tor_addr_family(&port->addr) == AF_INET ||
7064 (tor_addr_family(&port->addr) == AF_UNSPEC
7065 && !port->server_cfg.bind_ipv6_only);
7068 /* Does port bind to IPv6? */
7069 static int
7070 port_binds_ipv6(const port_cfg_t *port)
7072 return tor_addr_family(&port->addr) == AF_INET6 ||
7073 (tor_addr_family(&port->addr) == AF_UNSPEC
7074 && !port->server_cfg.bind_ipv4_only);
7077 /** Given a list of <b>port_cfg_t</b> in <b>ports</b>, check them for internal
7078 * consistency and warn as appropriate. Set *<b>n_low_ports_out</b> to the
7079 * number of sub-1024 ports we will be binding. */
7080 static int
7081 check_server_ports(const smartlist_t *ports,
7082 const or_options_t *options,
7083 int *n_low_ports_out)
7085 int n_orport_advertised = 0;
7086 int n_orport_advertised_ipv4 = 0;
7087 int n_orport_listeners = 0;
7088 int n_dirport_advertised = 0;
7089 int n_dirport_listeners = 0;
7090 int n_low_port = 0;
7091 int r = 0;
7093 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
7094 if (port->type == CONN_TYPE_DIR_LISTENER) {
7095 if (! port->server_cfg.no_advertise)
7096 ++n_dirport_advertised;
7097 if (! port->server_cfg.no_listen)
7098 ++n_dirport_listeners;
7099 } else if (port->type == CONN_TYPE_OR_LISTENER) {
7100 if (! port->server_cfg.no_advertise) {
7101 ++n_orport_advertised;
7102 if (port_binds_ipv4(port))
7103 ++n_orport_advertised_ipv4;
7105 if (! port->server_cfg.no_listen)
7106 ++n_orport_listeners;
7107 } else {
7108 continue;
7110 #ifndef _WIN32
7111 if (!port->server_cfg.no_listen && port->port < 1024)
7112 ++n_low_port;
7113 #endif
7114 } SMARTLIST_FOREACH_END(port);
7116 if (n_orport_advertised && !n_orport_listeners) {
7117 log_warn(LD_CONFIG, "We are advertising an ORPort, but not actually "
7118 "listening on one.");
7119 r = -1;
7121 if (n_orport_listeners && !n_orport_advertised) {
7122 log_warn(LD_CONFIG, "We are listening on an ORPort, but not advertising "
7123 "any ORPorts. This will keep us from building a %s "
7124 "descriptor, and make us impossible to use.",
7125 options->BridgeRelay ? "bridge" : "router");
7126 r = -1;
7128 if (n_dirport_advertised && !n_dirport_listeners) {
7129 log_warn(LD_CONFIG, "We are advertising a DirPort, but not actually "
7130 "listening on one.");
7131 r = -1;
7133 if (n_dirport_advertised > 1) {
7134 log_warn(LD_CONFIG, "Can't advertise more than one DirPort.");
7135 r = -1;
7137 if (n_orport_advertised && !n_orport_advertised_ipv4 &&
7138 !options->BridgeRelay) {
7139 log_warn(LD_CONFIG, "Configured non-bridge only to listen on an IPv6 "
7140 "address.");
7141 r = -1;
7144 if (n_low_port && options->AccountingMax &&
7145 (!have_capability_support() || options->KeepBindCapabilities == 0)) {
7146 const char *extra = "";
7147 if (options->KeepBindCapabilities == 0 && have_capability_support())
7148 extra = ", and you have disabled KeepBindCapabilities.";
7149 log_warn(LD_CONFIG,
7150 "You have set AccountingMax to use hibernation. You have also "
7151 "chosen a low DirPort or OrPort%s."
7152 "This combination can make Tor stop "
7153 "working when it tries to re-attach the port after a period of "
7154 "hibernation. Please choose a different port or turn off "
7155 "hibernation unless you know this combination will work on your "
7156 "platform.", extra);
7159 if (n_low_ports_out)
7160 *n_low_ports_out = n_low_port;
7162 return r;
7165 /** Return a list of port_cfg_t for client ports parsed from the
7166 * options. */
7167 MOCK_IMPL(const smartlist_t *,
7168 get_configured_ports,(void))
7170 if (!configured_ports)
7171 configured_ports = smartlist_new();
7172 return configured_ports;
7175 /** Return an address:port string representation of the address
7176 * where the first <b>listener_type</b> listener waits for
7177 * connections. Return NULL if we couldn't find a listener. The
7178 * string is allocated on the heap and it's the responsibility of the
7179 * caller to free it after use.
7181 * This function is meant to be used by the pluggable transport proxy
7182 * spawning code, please make sure that it fits your purposes before
7183 * using it. */
7184 char *
7185 get_first_listener_addrport_string(int listener_type)
7187 static const char *ipv4_localhost = "127.0.0.1";
7188 static const char *ipv6_localhost = "[::1]";
7189 const char *address;
7190 uint16_t port;
7191 char *string = NULL;
7193 if (!configured_ports)
7194 return NULL;
7196 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
7197 if (cfg->server_cfg.no_listen)
7198 continue;
7200 if (cfg->type == listener_type &&
7201 tor_addr_family(&cfg->addr) != AF_UNSPEC) {
7203 /* We found the first listener of the type we are interested in! */
7205 /* If a listener is listening on INADDR_ANY, assume that it's
7206 also listening on 127.0.0.1, and point the transport proxy
7207 there: */
7208 if (tor_addr_is_null(&cfg->addr))
7209 address = tor_addr_is_v4(&cfg->addr) ? ipv4_localhost : ipv6_localhost;
7210 else
7211 address = fmt_and_decorate_addr(&cfg->addr);
7213 /* If a listener is configured with port 'auto', we are forced
7214 to iterate all listener connections and find out in which
7215 port it ended up listening: */
7216 if (cfg->port == CFG_AUTO_PORT) {
7217 port = router_get_active_listener_port_by_type_af(listener_type,
7218 tor_addr_family(&cfg->addr));
7219 if (!port)
7220 return NULL;
7221 } else {
7222 port = cfg->port;
7225 tor_asprintf(&string, "%s:%u", address, port);
7227 return string;
7230 } SMARTLIST_FOREACH_END(cfg);
7232 return NULL;
7235 /** Return the first advertised port of type <b>listener_type</b> in
7236 * <b>address_family</b>. Returns 0 when no port is found, and when passed
7237 * AF_UNSPEC. */
7239 get_first_advertised_port_by_type_af(int listener_type, int address_family)
7241 if (address_family == AF_UNSPEC)
7242 return 0;
7244 const smartlist_t *conf_ports = get_configured_ports();
7245 SMARTLIST_FOREACH_BEGIN(conf_ports, const port_cfg_t *, cfg) {
7246 if (cfg->type == listener_type &&
7247 !cfg->server_cfg.no_advertise) {
7248 if ((address_family == AF_INET && port_binds_ipv4(cfg)) ||
7249 (address_family == AF_INET6 && port_binds_ipv6(cfg))) {
7250 return cfg->port;
7253 } SMARTLIST_FOREACH_END(cfg);
7254 return 0;
7257 /** Return the first advertised address of type <b>listener_type</b> in
7258 * <b>address_family</b>. Returns NULL if there is no advertised address,
7259 * and when passed AF_UNSPEC. */
7260 const tor_addr_t *
7261 get_first_advertised_addr_by_type_af(int listener_type, int address_family)
7263 if (address_family == AF_UNSPEC)
7264 return NULL;
7265 if (!configured_ports)
7266 return NULL;
7267 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
7268 if (cfg->type == listener_type &&
7269 !cfg->server_cfg.no_advertise) {
7270 if ((address_family == AF_INET && port_binds_ipv4(cfg)) ||
7271 (address_family == AF_INET6 && port_binds_ipv6(cfg))) {
7272 return &cfg->addr;
7275 } SMARTLIST_FOREACH_END(cfg);
7276 return NULL;
7279 /** Return 1 if a port exists of type <b>listener_type</b> on <b>addr</b> and
7280 * <b>port</b>. If <b>check_wildcard</b> is true, INADDR[6]_ANY and AF_UNSPEC
7281 * addresses match any address of the appropriate family; and port -1 matches
7282 * any port.
7283 * To match auto ports, pass CFG_PORT_AUTO. (Does not match on the actual
7284 * automatically chosen listener ports.) */
7286 port_exists_by_type_addr_port(int listener_type, const tor_addr_t *addr,
7287 int port, int check_wildcard)
7289 if (!configured_ports || !addr)
7290 return 0;
7291 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
7292 if (cfg->type == listener_type) {
7293 if (cfg->port == port || (check_wildcard && port == -1)) {
7294 /* Exact match */
7295 if (tor_addr_eq(&cfg->addr, addr)) {
7296 return 1;
7298 /* Skip wildcard matches if we're not doing them */
7299 if (!check_wildcard) {
7300 continue;
7302 /* Wildcard matches IPv4 */
7303 const int cfg_v4 = port_binds_ipv4(cfg);
7304 const int cfg_any_v4 = tor_addr_is_null(&cfg->addr) && cfg_v4;
7305 const int addr_v4 = tor_addr_family(addr) == AF_INET ||
7306 tor_addr_family(addr) == AF_UNSPEC;
7307 const int addr_any_v4 = tor_addr_is_null(&cfg->addr) && addr_v4;
7308 if ((cfg_any_v4 && addr_v4) || (cfg_v4 && addr_any_v4)) {
7309 return 1;
7311 /* Wildcard matches IPv6 */
7312 const int cfg_v6 = port_binds_ipv6(cfg);
7313 const int cfg_any_v6 = tor_addr_is_null(&cfg->addr) && cfg_v6;
7314 const int addr_v6 = tor_addr_family(addr) == AF_INET6 ||
7315 tor_addr_family(addr) == AF_UNSPEC;
7316 const int addr_any_v6 = tor_addr_is_null(&cfg->addr) && addr_v6;
7317 if ((cfg_any_v6 && addr_v6) || (cfg_v6 && addr_any_v6)) {
7318 return 1;
7322 } SMARTLIST_FOREACH_END(cfg);
7323 return 0;
7326 /* Like port_exists_by_type_addr_port, but accepts a host-order IPv4 address
7327 * instead. */
7329 port_exists_by_type_addr32h_port(int listener_type, uint32_t addr_ipv4h,
7330 int port, int check_wildcard)
7332 tor_addr_t ipv4;
7333 tor_addr_from_ipv4h(&ipv4, addr_ipv4h);
7334 return port_exists_by_type_addr_port(listener_type, &ipv4, port,
7335 check_wildcard);
7338 /** Adjust the value of options->DataDirectory, or fill it in if it's
7339 * absent. Return 0 on success, -1 on failure. */
7340 static int
7341 normalize_data_directory(or_options_t *options)
7343 #ifdef _WIN32
7344 char *p;
7345 if (options->DataDirectory)
7346 return 0; /* all set */
7347 p = tor_malloc(MAX_PATH);
7348 strlcpy(p,get_windows_conf_root(),MAX_PATH);
7349 options->DataDirectory = p;
7350 return 0;
7351 #else
7352 const char *d = options->DataDirectory;
7353 if (!d)
7354 d = "~/.tor";
7356 if (strncmp(d,"~/",2) == 0) {
7357 char *fn = expand_filename(d);
7358 if (!fn) {
7359 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
7360 return -1;
7362 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
7363 /* If our homedir is /, we probably don't want to use it. */
7364 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
7365 * want. */
7366 log_warn(LD_CONFIG,
7367 "Default DataDirectory is \"~/.tor\". This expands to "
7368 "\"%s\", which is probably not what you want. Using "
7369 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
7370 tor_free(fn);
7371 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
7373 tor_free(options->DataDirectory);
7374 options->DataDirectory = fn;
7376 return 0;
7377 #endif
7380 /** Check and normalize the value of options->DataDirectory; return 0 if it
7381 * is sane, -1 otherwise. */
7382 static int
7383 validate_data_directory(or_options_t *options)
7385 if (normalize_data_directory(options) < 0)
7386 return -1;
7387 tor_assert(options->DataDirectory);
7388 if (strlen(options->DataDirectory) > (512-128)) {
7389 log_warn(LD_CONFIG, "DataDirectory is too long.");
7390 return -1;
7392 return 0;
7395 /** This string must remain the same forevermore. It is how we
7396 * recognize that the torrc file doesn't need to be backed up. */
7397 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
7398 "if you edit it, comments will not be preserved"
7399 /** This string can change; it tries to give the reader an idea
7400 * that editing this file by hand is not a good plan. */
7401 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
7402 "to torrc.orig.1 or similar, and Tor will ignore it"
7404 /** Save a configuration file for the configuration in <b>options</b>
7405 * into the file <b>fname</b>. If the file already exists, and
7406 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
7407 * replace it. Return 0 on success, -1 on failure. */
7408 static int
7409 write_configuration_file(const char *fname, const or_options_t *options)
7411 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
7412 int rename_old = 0, r;
7414 if (!fname)
7415 return -1;
7417 switch (file_status(fname)) {
7418 /* create backups of old config files, even if they're empty */
7419 case FN_FILE:
7420 case FN_EMPTY:
7421 old_val = read_file_to_str(fname, 0, NULL);
7422 if (!old_val || strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
7423 rename_old = 1;
7425 tor_free(old_val);
7426 break;
7427 case FN_NOENT:
7428 break;
7429 case FN_ERROR:
7430 case FN_DIR:
7431 default:
7432 log_warn(LD_CONFIG,
7433 "Config file \"%s\" is not a file? Failing.", fname);
7434 return -1;
7437 if (!(new_conf = options_dump(options, OPTIONS_DUMP_MINIMAL))) {
7438 log_warn(LD_BUG, "Couldn't get configuration string");
7439 goto err;
7442 tor_asprintf(&new_val, "%s\n%s\n\n%s",
7443 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
7445 if (rename_old) {
7446 int i = 1;
7447 char *fn_tmp = NULL;
7448 while (1) {
7449 tor_asprintf(&fn_tmp, "%s.orig.%d", fname, i);
7450 if (file_status(fn_tmp) == FN_NOENT)
7451 break;
7452 tor_free(fn_tmp);
7453 ++i;
7455 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
7456 if (tor_rename(fname, fn_tmp) < 0) {//XXXX sandbox doesn't allow
7457 log_warn(LD_FS,
7458 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
7459 fname, fn_tmp, strerror(errno));
7460 tor_free(fn_tmp);
7461 goto err;
7463 tor_free(fn_tmp);
7466 if (write_str_to_file(fname, new_val, 0) < 0)
7467 goto err;
7469 r = 0;
7470 goto done;
7471 err:
7472 r = -1;
7473 done:
7474 tor_free(new_val);
7475 tor_free(new_conf);
7476 return r;
7480 * Save the current configuration file value to disk. Return 0 on
7481 * success, -1 on failure.
7484 options_save_current(void)
7486 /* This fails if we can't write to our configuration file.
7488 * If we try falling back to datadirectory or something, we have a better
7489 * chance of saving the configuration, but a better chance of doing
7490 * something the user never expected. */
7491 return write_configuration_file(get_torrc_fname(0), get_options());
7494 /** Return the number of cpus configured in <b>options</b>. If we are
7495 * told to auto-detect the number of cpus, return the auto-detected number. */
7497 get_num_cpus(const or_options_t *options)
7499 if (options->NumCPUs == 0) {
7500 int n = compute_num_cpus();
7501 return (n >= 1) ? n : 1;
7502 } else {
7503 return options->NumCPUs;
7508 * Initialize the libevent library.
7510 static void
7511 init_libevent(const or_options_t *options)
7513 tor_libevent_cfg cfg;
7515 tor_assert(options);
7517 configure_libevent_logging();
7518 /* If the kernel complains that some method (say, epoll) doesn't
7519 * exist, we don't care about it, since libevent will cope.
7521 suppress_libevent_log_msg("Function not implemented");
7523 memset(&cfg, 0, sizeof(cfg));
7524 cfg.num_cpus = get_num_cpus(options);
7525 cfg.msec_per_tick = options->TokenBucketRefillInterval;
7527 tor_libevent_initialize(&cfg);
7529 suppress_libevent_log_msg(NULL);
7532 /** Return a newly allocated string holding a filename relative to the data
7533 * directory. If <b>sub1</b> is present, it is the first path component after
7534 * the data directory. If <b>sub2</b> is also present, it is the second path
7535 * component after the data directory. If <b>suffix</b> is present, it
7536 * is appended to the filename.
7538 * Examples:
7539 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
7540 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
7541 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
7542 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
7544 * Note: Consider using the get_datadir_fname* macros in or.h.
7546 MOCK_IMPL(char *,
7547 options_get_datadir_fname2_suffix,(const or_options_t *options,
7548 const char *sub1, const char *sub2,
7549 const char *suffix))
7551 char *fname = NULL;
7552 size_t len;
7553 tor_assert(options);
7554 tor_assert(options->DataDirectory);
7555 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
7556 len = strlen(options->DataDirectory);
7557 if (sub1) {
7558 len += strlen(sub1)+1;
7559 if (sub2)
7560 len += strlen(sub2)+1;
7562 if (suffix)
7563 len += strlen(suffix);
7564 len++;
7565 fname = tor_malloc(len);
7566 if (sub1) {
7567 if (sub2) {
7568 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
7569 options->DataDirectory, sub1, sub2);
7570 } else {
7571 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
7572 options->DataDirectory, sub1);
7574 } else {
7575 strlcpy(fname, options->DataDirectory, len);
7577 if (suffix)
7578 strlcat(fname, suffix, len);
7579 return fname;
7582 /** Check wether the data directory has a private subdirectory
7583 * <b>subdir</b>. If not, try to create it. Return 0 on success,
7584 * -1 otherwise. */
7586 check_or_create_data_subdir(const char *subdir)
7588 char *statsdir = get_datadir_fname(subdir);
7589 int return_val = 0;
7591 if (check_private_dir(statsdir, CPD_CREATE, get_options()->User) < 0) {
7592 log_warn(LD_HIST, "Unable to create %s/ directory!", subdir);
7593 return_val = -1;
7595 tor_free(statsdir);
7596 return return_val;
7599 /** Create a file named <b>fname</b> with contents <b>str</b> in the
7600 * subdirectory <b>subdir</b> of the data directory. <b>descr</b>
7601 * should be a short description of the file's content and will be
7602 * used for the warning message, if it's present and the write process
7603 * fails. Return 0 on success, -1 otherwise.*/
7605 write_to_data_subdir(const char* subdir, const char* fname,
7606 const char* str, const char* descr)
7608 char *filename = get_datadir_fname2(subdir, fname);
7609 int return_val = 0;
7611 if (write_str_to_file(filename, str, 0) < 0) {
7612 log_warn(LD_HIST, "Unable to write %s to disk!", descr ? descr : fname);
7613 return_val = -1;
7615 tor_free(filename);
7616 return return_val;
7619 /** Given a file name check to see whether the file exists but has not been
7620 * modified for a very long time. If so, remove it. */
7621 void
7622 remove_file_if_very_old(const char *fname, time_t now)
7624 #define VERY_OLD_FILE_AGE (28*24*60*60)
7625 struct stat st;
7627 log_debug(LD_FS, "stat()ing %s", fname);
7628 if (stat(sandbox_intern_string(fname), &st)==0 &&
7629 st.st_mtime < now-VERY_OLD_FILE_AGE) {
7630 char buf[ISO_TIME_LEN+1];
7631 format_local_iso_time(buf, st.st_mtime);
7632 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
7633 "Removing it.", fname, buf);
7634 if (unlink(fname) != 0) {
7635 log_warn(LD_FS, "Failed to unlink %s: %s",
7636 fname, strerror(errno));
7641 /** Return a smartlist of ports that must be forwarded by
7642 * tor-fw-helper. The smartlist contains the ports in a string format
7643 * that is understandable by tor-fw-helper. */
7644 smartlist_t *
7645 get_list_of_ports_to_forward(void)
7647 smartlist_t *ports_to_forward = smartlist_new();
7648 int port = 0;
7650 /** XXX TODO tor-fw-helper does not support forwarding ports to
7651 other hosts than the local one. If the user is binding to a
7652 different IP address, tor-fw-helper won't work. */
7653 port = router_get_advertised_or_port(get_options()); /* Get ORPort */
7654 if (port)
7655 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
7657 port = router_get_advertised_dir_port(get_options(), 0); /* Get DirPort */
7658 if (port)
7659 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
7661 /* Get ports of transport proxies */
7663 smartlist_t *transport_ports = get_transport_proxy_ports();
7664 if (transport_ports) {
7665 smartlist_add_all(ports_to_forward, transport_ports);
7666 smartlist_free(transport_ports);
7670 if (!smartlist_len(ports_to_forward)) {
7671 smartlist_free(ports_to_forward);
7672 ports_to_forward = NULL;
7675 return ports_to_forward;
7678 /** Helper to implement GETINFO functions about configuration variables (not
7679 * their values). Given a "config/names" question, set *<b>answer</b> to a
7680 * new string describing the supported configuration variables and their
7681 * types. */
7683 getinfo_helper_config(control_connection_t *conn,
7684 const char *question, char **answer,
7685 const char **errmsg)
7687 (void) conn;
7688 (void) errmsg;
7689 if (!strcmp(question, "config/names")) {
7690 smartlist_t *sl = smartlist_new();
7691 int i;
7692 for (i = 0; option_vars_[i].name; ++i) {
7693 const config_var_t *var = &option_vars_[i];
7694 const char *type;
7695 /* don't tell controller about triple-underscore options */
7696 if (!strncmp(option_vars_[i].name, "___", 3))
7697 continue;
7698 switch (var->type) {
7699 case CONFIG_TYPE_STRING: type = "String"; break;
7700 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
7701 case CONFIG_TYPE_UINT: type = "Integer"; break;
7702 case CONFIG_TYPE_INT: type = "SignedInteger"; break;
7703 case CONFIG_TYPE_PORT: type = "Port"; break;
7704 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
7705 case CONFIG_TYPE_MSEC_INTERVAL: type = "TimeMsecInterval"; break;
7706 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
7707 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
7708 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
7709 case CONFIG_TYPE_AUTOBOOL: type = "Boolean+Auto"; break;
7710 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
7711 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
7712 case CONFIG_TYPE_CSV: type = "CommaList"; break;
7713 case CONFIG_TYPE_CSV_INTERVAL: type = "TimeIntervalCommaList"; break;
7714 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
7715 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
7716 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
7717 default:
7718 case CONFIG_TYPE_OBSOLETE:
7719 type = NULL; break;
7721 if (!type)
7722 continue;
7723 smartlist_add_asprintf(sl, "%s %s\n",var->name,type);
7725 *answer = smartlist_join_strings(sl, "", 0, NULL);
7726 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
7727 smartlist_free(sl);
7728 } else if (!strcmp(question, "config/defaults")) {
7729 smartlist_t *sl = smartlist_new();
7730 int dirauth_lines_seen = 0, fallback_lines_seen = 0;
7731 for (int i = 0; option_vars_[i].name; ++i) {
7732 const config_var_t *var = &option_vars_[i];
7733 if (var->initvalue != NULL) {
7734 if (strcmp(option_vars_[i].name, "DirAuthority") == 0) {
7736 * Count dirauth lines we have a default for; we'll use the
7737 * count later to decide whether to add the defaults manually
7739 ++dirauth_lines_seen;
7741 if (strcmp(option_vars_[i].name, "FallbackDir") == 0) {
7743 * Similarly count fallback lines, so that we can decided later
7744 * to add the defaults manually.
7746 ++fallback_lines_seen;
7748 char *val = esc_for_log(var->initvalue);
7749 smartlist_add_asprintf(sl, "%s %s\n",var->name,val);
7750 tor_free(val);
7754 if (dirauth_lines_seen == 0) {
7756 * We didn't see any directory authorities with default values,
7757 * so add the list of default authorities manually.
7761 * default_authorities is defined earlier in this file and
7762 * is a const char ** NULL-terminated array of dirauth config
7763 * lines.
7765 for (const char **i = default_authorities; *i != NULL; ++i) {
7766 char *val = esc_for_log(*i);
7767 smartlist_add_asprintf(sl, "DirAuthority %s\n", val);
7768 tor_free(val);
7772 if (fallback_lines_seen == 0 &&
7773 get_options()->UseDefaultFallbackDirs == 1) {
7775 * We didn't see any explicitly configured fallback mirrors,
7776 * so add the defaults to the list manually.
7778 * default_fallbacks is included earlier in this file and
7779 * is a const char ** NULL-terminated array of fallback config lines.
7781 const char **i;
7783 for (i = default_fallbacks; *i != NULL; ++i) {
7784 char *val = esc_for_log(*i);
7785 smartlist_add_asprintf(sl, "FallbackDir %s\n", val);
7786 tor_free(val);
7790 *answer = smartlist_join_strings(sl, "", 0, NULL);
7791 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
7792 smartlist_free(sl);
7794 return 0;
7797 /** Parse outbound bind address option lines. If <b>validate_only</b>
7798 * is not 0 update OutboundBindAddressIPv4_ and
7799 * OutboundBindAddressIPv6_ in <b>options</b>. On failure, set
7800 * <b>msg</b> (if provided) to a newly allocated string containing a
7801 * description of the problem and return -1. */
7802 static int
7803 parse_outbound_addresses(or_options_t *options, int validate_only, char **msg)
7805 const config_line_t *lines = options->OutboundBindAddress;
7806 int found_v4 = 0, found_v6 = 0;
7808 if (!validate_only) {
7809 memset(&options->OutboundBindAddressIPv4_, 0,
7810 sizeof(options->OutboundBindAddressIPv4_));
7811 memset(&options->OutboundBindAddressIPv6_, 0,
7812 sizeof(options->OutboundBindAddressIPv6_));
7814 while (lines) {
7815 tor_addr_t addr, *dst_addr = NULL;
7816 int af = tor_addr_parse(&addr, lines->value);
7817 switch (af) {
7818 case AF_INET:
7819 if (found_v4) {
7820 if (msg)
7821 tor_asprintf(msg, "Multiple IPv4 outbound bind addresses "
7822 "configured: %s", lines->value);
7823 return -1;
7825 found_v4 = 1;
7826 dst_addr = &options->OutboundBindAddressIPv4_;
7827 break;
7828 case AF_INET6:
7829 if (found_v6) {
7830 if (msg)
7831 tor_asprintf(msg, "Multiple IPv6 outbound bind addresses "
7832 "configured: %s", lines->value);
7833 return -1;
7835 found_v6 = 1;
7836 dst_addr = &options->OutboundBindAddressIPv6_;
7837 break;
7838 default:
7839 if (msg)
7840 tor_asprintf(msg, "Outbound bind address '%s' didn't parse.",
7841 lines->value);
7842 return -1;
7844 if (!validate_only)
7845 tor_addr_copy(dst_addr, &addr);
7846 lines = lines->next;
7848 return 0;
7851 /** Load one of the geoip files, <a>family</a> determining which
7852 * one. <a>default_fname</a> is used if on Windows and
7853 * <a>fname</a> equals "<default>". */
7854 static void
7855 config_load_geoip_file_(sa_family_t family,
7856 const char *fname,
7857 const char *default_fname)
7859 #ifdef _WIN32
7860 char *free_fname = NULL; /* Used to hold any temporary-allocated value */
7861 /* XXXX Don't use this "<default>" junk; make our filename options
7862 * understand prefixes somehow. -NM */
7863 if (!strcmp(fname, "<default>")) {
7864 const char *conf_root = get_windows_conf_root();
7865 tor_asprintf(&free_fname, "%s\\%s", conf_root, default_fname);
7866 fname = free_fname;
7868 geoip_load_file(family, fname);
7869 tor_free(free_fname);
7870 #else
7871 (void)default_fname;
7872 geoip_load_file(family, fname);
7873 #endif
7876 /** Load geoip files for IPv4 and IPv6 if <a>options</a> and
7877 * <a>old_options</a> indicate we should. */
7878 static void
7879 config_maybe_load_geoip_files_(const or_options_t *options,
7880 const or_options_t *old_options)
7882 /* XXXX Reload GeoIPFile on SIGHUP. -NM */
7884 if (options->GeoIPFile &&
7885 ((!old_options || !opt_streq(old_options->GeoIPFile,
7886 options->GeoIPFile))
7887 || !geoip_is_loaded(AF_INET)))
7888 config_load_geoip_file_(AF_INET, options->GeoIPFile, "geoip");
7889 if (options->GeoIPv6File &&
7890 ((!old_options || !opt_streq(old_options->GeoIPv6File,
7891 options->GeoIPv6File))
7892 || !geoip_is_loaded(AF_INET6)))
7893 config_load_geoip_file_(AF_INET6, options->GeoIPv6File, "geoip6");
7896 /** Initialize cookie authentication (used so far by the ControlPort
7897 * and Extended ORPort).
7899 * Allocate memory and create a cookie (of length <b>cookie_len</b>)
7900 * in <b>cookie_out</b>.
7901 * Then write it down to <b>fname</b> and prepend it with <b>header</b>.
7903 * If <b>group_readable</b> is set, set <b>fname</b> to be readable
7904 * by the default GID.
7906 * If the whole procedure was successful, set
7907 * <b>cookie_is_set_out</b> to True. */
7909 init_cookie_authentication(const char *fname, const char *header,
7910 int cookie_len, int group_readable,
7911 uint8_t **cookie_out, int *cookie_is_set_out)
7913 char cookie_file_str_len = strlen(header) + cookie_len;
7914 char *cookie_file_str = tor_malloc(cookie_file_str_len);
7915 int retval = -1;
7917 /* We don't want to generate a new cookie every time we call
7918 * options_act(). One should be enough. */
7919 if (*cookie_is_set_out) {
7920 retval = 0; /* we are all set */
7921 goto done;
7924 /* If we've already set the cookie, free it before re-setting
7925 it. This can happen if we previously generated a cookie, but
7926 couldn't write it to a disk. */
7927 if (*cookie_out)
7928 tor_free(*cookie_out);
7930 /* Generate the cookie */
7931 *cookie_out = tor_malloc(cookie_len);
7932 crypto_rand((char *)*cookie_out, cookie_len);
7934 /* Create the string that should be written on the file. */
7935 memcpy(cookie_file_str, header, strlen(header));
7936 memcpy(cookie_file_str+strlen(header), *cookie_out, cookie_len);
7937 if (write_bytes_to_file(fname, cookie_file_str, cookie_file_str_len, 1)) {
7938 log_warn(LD_FS,"Error writing auth cookie to %s.", escaped(fname));
7939 goto done;
7942 #ifndef _WIN32
7943 if (group_readable) {
7944 if (chmod(fname, 0640)) {
7945 log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
7948 #else
7949 (void) group_readable;
7950 #endif
7952 /* Success! */
7953 log_info(LD_GENERAL, "Generated auth cookie file in '%s'.", escaped(fname));
7954 *cookie_is_set_out = 1;
7955 retval = 0;
7957 done:
7958 memwipe(cookie_file_str, 0, cookie_file_str_len);
7959 tor_free(cookie_file_str);
7960 return retval;