protover: Fix old tor hardcoded version check
[tor.git] / src / or / config.c
blob8568ea9d649ada4716dbf214a310742e7ec3053c
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:";
71 /* Prefix used to indicate a Unix socket with spaces in it, in a FooPort
72 * configuration. */
73 static const char unix_q_socket_prefix[] = "unix:\"";
75 /** A list of abbreviations and aliases to map command-line options, obsolete
76 * option names, or alternative option names, to their current values. */
77 static config_abbrev_t option_abbrevs_[] = {
78 PLURAL(AuthDirBadDirCC),
79 PLURAL(AuthDirBadExitCC),
80 PLURAL(AuthDirInvalidCC),
81 PLURAL(AuthDirRejectCC),
82 PLURAL(EntryNode),
83 PLURAL(ExcludeNode),
84 PLURAL(Tor2webRendezvousPoint),
85 PLURAL(FirewallPort),
86 PLURAL(LongLivedPort),
87 PLURAL(HiddenServiceNode),
88 PLURAL(HiddenServiceExcludeNode),
89 PLURAL(NumCPU),
90 PLURAL(RendNode),
91 PLURAL(RecommendedPackage),
92 PLURAL(RendExcludeNode),
93 PLURAL(StrictEntryNode),
94 PLURAL(StrictExitNode),
95 PLURAL(StrictNode),
96 { "l", "Log", 1, 0},
97 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
98 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
99 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
100 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
101 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
102 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
103 { "DirServer", "DirAuthority", 0, 0}, /* XXXX later, make this warn? */
104 { "MaxConn", "ConnLimit", 0, 1},
105 { "MaxMemInCellQueues", "MaxMemInQueues", 0, 0},
106 { "ORBindAddress", "ORListenAddress", 0, 0},
107 { "DirBindAddress", "DirListenAddress", 0, 0},
108 { "SocksBindAddress", "SocksListenAddress", 0, 0},
109 { "UseHelperNodes", "UseEntryGuards", 0, 0},
110 { "NumHelperNodes", "NumEntryGuards", 0, 0},
111 { "UseEntryNodes", "UseEntryGuards", 0, 0},
112 { "NumEntryNodes", "NumEntryGuards", 0, 0},
113 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
114 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
115 { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0},
116 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
117 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
118 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
119 { "VirtualAddrNetwork", "VirtualAddrNetworkIPv4", 0, 0},
120 { NULL, NULL, 0, 0},
123 /** An entry for config_vars: "The option <b>name</b> has type
124 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
125 * or_options_t.<b>member</b>"
127 #define VAR(name,conftype,member,initvalue) \
128 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
129 initvalue }
130 /** As VAR, but the option name and member name are the same. */
131 #define V(member,conftype,initvalue) \
132 VAR(#member, conftype, member, initvalue)
133 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
134 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
136 #define VPORT(member,conftype,initvalue) \
137 VAR(#member, conftype, member ## _lines, initvalue)
139 /** Array of configuration options. Until we disallow nonstandard
140 * abbreviations, order is significant, since the first matching option will
141 * be chosen first.
143 static config_var_t option_vars_[] = {
144 V(AccountingMax, MEMUNIT, "0 bytes"),
145 VAR("AccountingRule", STRING, AccountingRule_option, "max"),
146 V(AccountingStart, STRING, NULL),
147 V(Address, STRING, NULL),
148 V(AllowDotExit, BOOL, "0"),
149 V(AllowInvalidNodes, CSV, "middle,rendezvous"),
150 V(AllowNonRFC953Hostnames, BOOL, "0"),
151 V(AllowSingleHopCircuits, BOOL, "0"),
152 V(AllowSingleHopExits, BOOL, "0"),
153 V(AlternateBridgeAuthority, LINELIST, NULL),
154 V(AlternateDirAuthority, LINELIST, NULL),
155 OBSOLETE("AlternateHSAuthority"),
156 V(AssumeReachable, BOOL, "0"),
157 OBSOLETE("AuthDirBadDir"),
158 OBSOLETE("AuthDirBadDirCCs"),
159 V(AuthDirBadExit, LINELIST, NULL),
160 V(AuthDirBadExitCCs, CSV, ""),
161 V(AuthDirInvalid, LINELIST, NULL),
162 V(AuthDirInvalidCCs, CSV, ""),
163 V(AuthDirFastGuarantee, MEMUNIT, "100 KB"),
164 V(AuthDirGuardBWGuarantee, MEMUNIT, "2 MB"),
165 V(AuthDirPinKeys, BOOL, "0"),
166 V(AuthDirReject, LINELIST, NULL),
167 V(AuthDirRejectCCs, CSV, ""),
168 OBSOLETE("AuthDirRejectUnlisted"),
169 OBSOLETE("AuthDirListBadDirs"),
170 V(AuthDirListBadExits, BOOL, "0"),
171 V(AuthDirMaxServersPerAddr, UINT, "2"),
172 V(AuthDirMaxServersPerAuthAddr,UINT, "5"),
173 V(AuthDirHasIPv6Connectivity, BOOL, "0"),
174 VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
175 V(AutomapHostsOnResolve, BOOL, "0"),
176 V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
177 V(AvoidDiskWrites, BOOL, "0"),
178 V(BandwidthBurst, MEMUNIT, "1 GB"),
179 V(BandwidthRate, MEMUNIT, "1 GB"),
180 V(BridgeAuthoritativeDir, BOOL, "0"),
181 VAR("Bridge", LINELIST, Bridges, NULL),
182 V(BridgePassword, STRING, NULL),
183 V(BridgeRecordUsageByCountry, BOOL, "1"),
184 V(BridgeRelay, BOOL, "0"),
185 V(CellStatistics, BOOL, "0"),
186 V(LearnCircuitBuildTimeout, BOOL, "1"),
187 V(CircuitBuildTimeout, INTERVAL, "0"),
188 V(CircuitIdleTimeout, INTERVAL, "1 hour"),
189 V(CircuitStreamTimeout, INTERVAL, "0"),
190 V(CircuitPriorityHalflife, DOUBLE, "-100.0"), /*negative:'Use default'*/
191 V(ClientDNSRejectInternalAddresses, BOOL,"1"),
192 V(ClientOnly, BOOL, "0"),
193 V(ClientPreferIPv6ORPort, AUTOBOOL, "auto"),
194 V(ClientPreferIPv6DirPort, AUTOBOOL, "auto"),
195 V(ClientRejectInternalAddresses, BOOL, "1"),
196 V(ClientTransportPlugin, LINELIST, NULL),
197 V(ClientUseIPv6, BOOL, "0"),
198 V(ClientUseIPv4, BOOL, "1"),
199 V(ConsensusParams, STRING, NULL),
200 V(ConnLimit, UINT, "1000"),
201 V(ConnDirectionStatistics, BOOL, "0"),
202 V(ConstrainedSockets, BOOL, "0"),
203 V(ConstrainedSockSize, MEMUNIT, "8192"),
204 V(ContactInfo, STRING, NULL),
205 V(ControlListenAddress, LINELIST, NULL),
206 VPORT(ControlPort, LINELIST, NULL),
207 V(ControlPortFileGroupReadable,BOOL, "0"),
208 V(ControlPortWriteToFile, FILENAME, NULL),
209 V(ControlSocket, LINELIST, NULL),
210 V(ControlSocketsGroupWritable, BOOL, "0"),
211 V(SocksSocketsGroupWritable, BOOL, "0"),
212 V(CookieAuthentication, BOOL, "0"),
213 V(CookieAuthFileGroupReadable, BOOL, "0"),
214 V(CookieAuthFile, STRING, NULL),
215 V(CountPrivateBandwidth, BOOL, "0"),
216 V(DataDirectory, FILENAME, NULL),
217 V(DataDirectoryGroupReadable, BOOL, "0"),
218 V(DisableOOSCheck, BOOL, "1"),
219 V(DisableNetwork, BOOL, "0"),
220 V(DirAllowPrivateAddresses, BOOL, "0"),
221 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
222 V(DirListenAddress, LINELIST, NULL),
223 V(DirPolicy, LINELIST, NULL),
224 VPORT(DirPort, LINELIST, NULL),
225 V(DirPortFrontPage, FILENAME, NULL),
226 VAR("DirReqStatistics", BOOL, DirReqStatistics_option, "1"),
227 VAR("DirAuthority", LINELIST, DirAuthorities, NULL),
228 V(DirCache, BOOL, "1"),
229 V(DirAuthorityFallbackRate, DOUBLE, "1.0"),
230 V(DisableAllSwap, BOOL, "0"),
231 V(DisableDebuggerAttachment, BOOL, "1"),
232 OBSOLETE("DisableIOCP"),
233 OBSOLETE("DisableV2DirectoryInfo_"),
234 OBSOLETE("DynamicDHGroups"),
235 VPORT(DNSPort, LINELIST, NULL),
236 V(DNSListenAddress, LINELIST, NULL),
237 V(DownloadExtraInfo, BOOL, "0"),
238 V(TestingEnableConnBwEvent, BOOL, "0"),
239 V(TestingEnableCellStatsEvent, BOOL, "0"),
240 V(TestingEnableTbEmptyEvent, BOOL, "0"),
241 V(EnforceDistinctSubnets, BOOL, "1"),
242 V(EntryNodes, ROUTERSET, NULL),
243 V(EntryStatistics, BOOL, "0"),
244 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
245 V(ExcludeNodes, ROUTERSET, NULL),
246 V(ExcludeExitNodes, ROUTERSET, NULL),
247 V(ExcludeSingleHopRelays, BOOL, "1"),
248 V(ExitNodes, ROUTERSET, NULL),
249 V(ExitPolicy, LINELIST, NULL),
250 V(ExitPolicyRejectPrivate, BOOL, "1"),
251 V(ExitPolicyRejectLocalInterfaces, BOOL, "0"),
252 V(ExitPortStatistics, BOOL, "0"),
253 V(ExtendAllowPrivateAddresses, BOOL, "0"),
254 V(ExitRelay, AUTOBOOL, "auto"),
255 VPORT(ExtORPort, LINELIST, NULL),
256 V(ExtORPortCookieAuthFile, STRING, NULL),
257 V(ExtORPortCookieAuthFileGroupReadable, BOOL, "0"),
258 V(ExtraInfoStatistics, BOOL, "1"),
259 V(FallbackDir, LINELIST, NULL),
260 V(UseDefaultFallbackDirs, BOOL, "1"),
262 OBSOLETE("FallbackNetworkstatusFile"),
263 V(FascistFirewall, BOOL, "0"),
264 V(FirewallPorts, CSV, ""),
265 V(FastFirstHopPK, AUTOBOOL, "auto"),
266 V(FetchDirInfoEarly, BOOL, "0"),
267 V(FetchDirInfoExtraEarly, BOOL, "0"),
268 V(FetchServerDescriptors, BOOL, "1"),
269 V(FetchHidServDescriptors, BOOL, "1"),
270 V(FetchUselessDescriptors, BOOL, "0"),
271 OBSOLETE("FetchV2Networkstatus"),
272 V(GeoIPExcludeUnknown, AUTOBOOL, "auto"),
273 #ifdef _WIN32
274 V(GeoIPFile, FILENAME, "<default>"),
275 V(GeoIPv6File, FILENAME, "<default>"),
276 #else
277 V(GeoIPFile, FILENAME,
278 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
279 V(GeoIPv6File, FILENAME,
280 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip6"),
281 #endif
282 OBSOLETE("Group"),
283 V(GuardLifetime, INTERVAL, "0 minutes"),
284 V(HardwareAccel, BOOL, "0"),
285 V(HeartbeatPeriod, INTERVAL, "6 hours"),
286 V(AccelName, STRING, NULL),
287 V(AccelDir, FILENAME, NULL),
288 V(HashedControlPassword, LINELIST, NULL),
289 OBSOLETE("HidServDirectoryV2"),
290 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
291 VAR("HiddenServiceDirGroupReadable", LINELIST_S, RendConfigLines, NULL),
292 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
293 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
294 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
295 VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
296 VAR("HiddenServiceAllowUnknownPorts",LINELIST_S, RendConfigLines, NULL),
297 VAR("HiddenServiceMaxStreams",LINELIST_S, RendConfigLines, NULL),
298 VAR("HiddenServiceMaxStreamsCloseCircuit",LINELIST_S, RendConfigLines, NULL),
299 VAR("HiddenServiceNumIntroductionPoints", LINELIST_S, RendConfigLines, NULL),
300 V(HiddenServiceStatistics, BOOL, "1"),
301 V(HidServAuth, LINELIST, NULL),
302 V(CloseHSClientCircuitsImmediatelyOnTimeout, BOOL, "0"),
303 V(CloseHSServiceRendCircuitsImmediatelyOnTimeout, BOOL, "0"),
304 V(HiddenServiceSingleHopMode, BOOL, "0"),
305 V(HiddenServiceNonAnonymousMode,BOOL, "0"),
306 V(HTTPProxy, STRING, NULL),
307 V(HTTPProxyAuthenticator, STRING, NULL),
308 V(HTTPSProxy, STRING, NULL),
309 V(HTTPSProxyAuthenticator, STRING, NULL),
310 V(IPv6Exit, BOOL, "0"),
311 VAR("ServerTransportPlugin", LINELIST, ServerTransportPlugin, NULL),
312 V(ServerTransportListenAddr, LINELIST, NULL),
313 V(ServerTransportOptions, LINELIST, NULL),
314 V(SigningKeyLifetime, INTERVAL, "30 days"),
315 V(Socks4Proxy, STRING, NULL),
316 V(Socks5Proxy, STRING, NULL),
317 V(Socks5ProxyUsername, STRING, NULL),
318 V(Socks5ProxyPassword, STRING, NULL),
319 V(KeepalivePeriod, INTERVAL, "5 minutes"),
320 V(KeepBindCapabilities, AUTOBOOL, "auto"),
321 VAR("Log", LINELIST, Logs, NULL),
322 V(LogMessageDomains, BOOL, "0"),
323 V(LogTimeGranularity, MSEC_INTERVAL, "1 second"),
324 V(TruncateLogFile, BOOL, "0"),
325 V(SyslogIdentityTag, STRING, NULL),
326 V(LongLivedPorts, CSV,
327 "21,22,706,1863,5050,5190,5222,5223,6523,6667,6697,8300"),
328 VAR("MapAddress", LINELIST, AddressMap, NULL),
329 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
330 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
331 V(MaxClientCircuitsPending, UINT, "32"),
332 VAR("MaxMemInQueues", MEMUNIT, MaxMemInQueues_raw, "0"),
333 OBSOLETE("MaxOnionsPending"),
334 V(MaxOnionQueueDelay, MSEC_INTERVAL, "1750 msec"),
335 V(MaxUnparseableDescSizeToLog, MEMUNIT, "10 MB"),
336 V(MinMeasuredBWsForAuthToIgnoreAdvertised, INT, "500"),
337 V(MyFamily, STRING, NULL),
338 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
339 OBSOLETE("NamingAuthoritativeDirectory"),
340 V(NATDListenAddress, LINELIST, NULL),
341 VPORT(NATDPort, LINELIST, NULL),
342 V(Nickname, STRING, NULL),
343 V(PredictedPortsRelevanceTime, INTERVAL, "1 hour"),
344 V(WarnUnsafeSocks, BOOL, "1"),
345 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
346 V(NumCPUs, UINT, "0"),
347 V(NumDirectoryGuards, UINT, "0"),
348 V(NumEntryGuards, UINT, "0"),
349 V(OfflineMasterKey, BOOL, "0"),
350 V(ORListenAddress, LINELIST, NULL),
351 VPORT(ORPort, LINELIST, NULL),
352 V(OutboundBindAddress, LINELIST, NULL),
354 OBSOLETE("PathBiasDisableRate"),
355 V(PathBiasCircThreshold, INT, "-1"),
356 V(PathBiasNoticeRate, DOUBLE, "-1"),
357 V(PathBiasWarnRate, DOUBLE, "-1"),
358 V(PathBiasExtremeRate, DOUBLE, "-1"),
359 V(PathBiasScaleThreshold, INT, "-1"),
360 OBSOLETE("PathBiasScaleFactor"),
361 OBSOLETE("PathBiasMultFactor"),
362 V(PathBiasDropGuards, AUTOBOOL, "0"),
363 OBSOLETE("PathBiasUseCloseCounts"),
365 V(PathBiasUseThreshold, INT, "-1"),
366 V(PathBiasNoticeUseRate, DOUBLE, "-1"),
367 V(PathBiasExtremeUseRate, DOUBLE, "-1"),
368 V(PathBiasScaleUseThreshold, INT, "-1"),
370 V(PathsNeededToBuildCircuits, DOUBLE, "-1"),
371 V(PerConnBWBurst, MEMUNIT, "0"),
372 V(PerConnBWRate, MEMUNIT, "0"),
373 V(PidFile, STRING, NULL),
374 V(TestingTorNetwork, BOOL, "0"),
375 V(TestingMinExitFlagThreshold, MEMUNIT, "0"),
376 V(TestingMinFastFlagThreshold, MEMUNIT, "0"),
378 V(TestingLinkCertLifetime, INTERVAL, "2 days"),
379 V(TestingAuthKeyLifetime, INTERVAL, "2 days"),
380 V(TestingLinkKeySlop, INTERVAL, "3 hours"),
381 V(TestingAuthKeySlop, INTERVAL, "3 hours"),
382 V(TestingSigningKeySlop, INTERVAL, "1 day"),
384 V(OptimisticData, AUTOBOOL, "auto"),
385 V(PortForwarding, BOOL, "0"),
386 V(PortForwardingHelper, FILENAME, "tor-fw-helper"),
387 OBSOLETE("PreferTunneledDirConns"),
388 V(ProtocolWarnings, BOOL, "0"),
389 V(PublishServerDescriptor, CSV, "1"),
390 V(PublishHidServDescriptors, BOOL, "1"),
391 V(ReachableAddresses, LINELIST, NULL),
392 V(ReachableDirAddresses, LINELIST, NULL),
393 V(ReachableORAddresses, LINELIST, NULL),
394 V(RecommendedVersions, LINELIST, NULL),
395 V(RecommendedClientVersions, LINELIST, NULL),
396 V(RecommendedServerVersions, LINELIST, NULL),
397 V(RecommendedPackages, LINELIST, NULL),
398 V(RefuseUnknownExits, AUTOBOOL, "auto"),
399 V(RejectPlaintextPorts, CSV, ""),
400 V(RelayBandwidthBurst, MEMUNIT, "0"),
401 V(RelayBandwidthRate, MEMUNIT, "0"),
402 V(RendPostPeriod, INTERVAL, "1 hour"),
403 V(RephistTrackTime, INTERVAL, "24 hours"),
404 V(RunAsDaemon, BOOL, "0"),
405 OBSOLETE("RunTesting"), // currently unused
406 V(Sandbox, BOOL, "0"),
407 V(SafeLogging, STRING, "1"),
408 V(SafeSocks, BOOL, "0"),
409 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
410 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
411 V(ServerDNSDetectHijacking, BOOL, "1"),
412 V(ServerDNSRandomizeCase, BOOL, "1"),
413 V(ServerDNSResolvConfFile, STRING, NULL),
414 V(ServerDNSSearchDomains, BOOL, "0"),
415 V(ServerDNSTestAddresses, CSV,
416 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
417 V(SchedulerLowWaterMark__, MEMUNIT, "100 MB"),
418 V(SchedulerHighWaterMark__, MEMUNIT, "101 MB"),
419 V(SchedulerMaxFlushCells__, UINT, "1000"),
420 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
421 V(SocksListenAddress, LINELIST, NULL),
422 V(SocksPolicy, LINELIST, NULL),
423 VPORT(SocksPort, LINELIST, NULL),
424 V(SocksTimeout, INTERVAL, "2 minutes"),
425 V(SSLKeyLifetime, INTERVAL, "0"),
426 OBSOLETE("StrictEntryNodes"),
427 OBSOLETE("StrictExitNodes"),
428 V(StrictNodes, BOOL, "0"),
429 OBSOLETE("Support022HiddenServices"),
430 V(TestSocks, BOOL, "0"),
431 V(TokenBucketRefillInterval, MSEC_INTERVAL, "100 msec"),
432 V(Tor2webMode, BOOL, "0"),
433 V(Tor2webRendezvousPoints, ROUTERSET, NULL),
434 V(TLSECGroup, STRING, NULL),
435 V(TrackHostExits, CSV, NULL),
436 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
437 V(TransListenAddress, LINELIST, NULL),
438 VPORT(TransPort, LINELIST, NULL),
439 V(TransProxyType, STRING, "default"),
440 OBSOLETE("TunnelDirConns"),
441 V(UpdateBridgesFromAuthority, BOOL, "0"),
442 V(UseBridges, BOOL, "0"),
443 VAR("UseEntryGuards", BOOL, UseEntryGuards_option, "1"),
444 V(UseEntryGuardsAsDirGuards, BOOL, "1"),
445 V(UseGuardFraction, AUTOBOOL, "auto"),
446 V(UseMicrodescriptors, AUTOBOOL, "auto"),
447 OBSOLETE("UseNTorHandshake"),
448 V(User, STRING, NULL),
449 OBSOLETE("UserspaceIOCPBuffers"),
450 V(AuthDirSharedRandomness, BOOL, "1"),
451 OBSOLETE("V1AuthoritativeDirectory"),
452 OBSOLETE("V2AuthoritativeDirectory"),
453 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
454 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
455 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
456 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
457 V(TestingV3AuthVotingStartOffset, INTERVAL, "0"),
458 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
459 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
460 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
461 V(V3AuthNIntervalsValid, UINT, "3"),
462 V(V3AuthUseLegacyKey, BOOL, "0"),
463 V(V3BandwidthsFile, FILENAME, NULL),
464 V(GuardfractionFile, FILENAME, NULL),
465 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
466 OBSOLETE("VoteOnHidServDirectoriesV2"),
467 V(VirtualAddrNetworkIPv4, STRING, "127.192.0.0/10"),
468 V(VirtualAddrNetworkIPv6, STRING, "[FE80::]/10"),
469 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
470 OBSOLETE("UseFilteringSSLBufferevents"),
471 OBSOLETE("__UseFilteringSSLBufferevents"),
472 VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
473 VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
474 VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
475 VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
476 VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
477 NULL),
478 VAR("__OwningControllerProcess",STRING,OwningControllerProcess, NULL),
479 V(MinUptimeHidServDirectoryV2, INTERVAL, "96 hours"),
480 V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 60, 60, 120, "
481 "300, 900, 2147483647"),
482 V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 60, 300, 600, "
483 "2147483647"),
484 V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
485 "300, 600, 1800, 1800, 1800, 1800, "
486 "1800, 3600, 7200"),
487 V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
488 "300, 600, 1800, 3600, 3600, 3600, "
489 "10800, 21600, 43200"),
490 /* With the ClientBootstrapConsensus*Download* below:
491 * Clients with only authorities will try:
492 * - 3 authorities over 10 seconds, then wait 60 minutes.
493 * Clients with authorities and fallbacks will try:
494 * - 2 authorities and 4 fallbacks over 21 seconds, then wait 60 minutes.
495 * Clients will also retry when an application request arrives.
496 * After a number of failed reqests, clients retry every 3 days + 1 hour.
498 * Clients used to try 2 authorities over 10 seconds, then wait for
499 * 60 minutes or an application request.
501 * When clients have authorities and fallbacks available, they use these
502 * schedules: (we stagger the times to avoid thundering herds) */
503 V(ClientBootstrapConsensusAuthorityDownloadSchedule, CSV_INTERVAL,
504 "6, 11, 3600, 10800, 25200, 54000, 111600, 262800" /* 3 days + 1 hour */),
505 V(ClientBootstrapConsensusFallbackDownloadSchedule, CSV_INTERVAL,
506 "0, 1, 4, 11, 3600, 10800, 25200, 54000, 111600, 262800"),
507 /* When clients only have authorities available, they use this schedule: */
508 V(ClientBootstrapConsensusAuthorityOnlyDownloadSchedule, CSV_INTERVAL,
509 "0, 3, 7, 3600, 10800, 25200, 54000, 111600, 262800"),
510 /* We don't want to overwhelm slow networks (or mirrors whose replies are
511 * blocked), but we also don't want to fail if only some mirrors are
512 * blackholed. Clients will try 3 directories simultaneously.
513 * (Relays never use simultaneous connections.) */
514 V(ClientBootstrapConsensusMaxInProgressTries, UINT, "3"),
515 V(TestingBridgeDownloadSchedule, CSV_INTERVAL, "1200, 900, 900, 3600"),
516 V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "10 minutes"),
517 V(TestingDirConnectionMaxStall, INTERVAL, "5 minutes"),
518 V(TestingConsensusMaxDownloadTries, UINT, "8"),
519 /* Since we try connections rapidly and simultaneously, we can afford
520 * to give up earlier. (This protects against overloading directories.) */
521 V(ClientBootstrapConsensusMaxDownloadTries, UINT, "7"),
522 /* We want to give up much earlier if we're only using authorities. */
523 V(ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries, UINT, "4"),
524 V(TestingDescriptorMaxDownloadTries, UINT, "8"),
525 V(TestingMicrodescMaxDownloadTries, UINT, "8"),
526 V(TestingCertMaxDownloadTries, UINT, "8"),
527 V(TestingDirAuthVoteExit, ROUTERSET, NULL),
528 V(TestingDirAuthVoteExitIsStrict, BOOL, "0"),
529 V(TestingDirAuthVoteGuard, ROUTERSET, NULL),
530 V(TestingDirAuthVoteGuardIsStrict, BOOL, "0"),
531 V(TestingDirAuthVoteHSDir, ROUTERSET, NULL),
532 V(TestingDirAuthVoteHSDirIsStrict, BOOL, "0"),
533 VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "0"),
535 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
538 /** Override default values with these if the user sets the TestingTorNetwork
539 * option. */
540 static const config_var_t testing_tor_network_defaults[] = {
541 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
542 V(DirAllowPrivateAddresses, BOOL, "1"),
543 V(EnforceDistinctSubnets, BOOL, "0"),
544 V(AssumeReachable, BOOL, "1"),
545 V(AuthDirMaxServersPerAddr, UINT, "0"),
546 V(AuthDirMaxServersPerAuthAddr,UINT, "0"),
547 V(ClientBootstrapConsensusAuthorityDownloadSchedule, CSV_INTERVAL,
548 "0, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
549 V(ClientBootstrapConsensusFallbackDownloadSchedule, CSV_INTERVAL,
550 "0, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
551 V(ClientBootstrapConsensusAuthorityOnlyDownloadSchedule, CSV_INTERVAL,
552 "0, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
553 V(ClientBootstrapConsensusMaxDownloadTries, UINT, "80"),
554 V(ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries, UINT, "80"),
555 V(ClientDNSRejectInternalAddresses, BOOL,"0"), // deprecated in 0.2.9.2-alpha
556 V(ClientRejectInternalAddresses, BOOL, "0"),
557 V(CountPrivateBandwidth, BOOL, "1"),
558 V(ExitPolicyRejectPrivate, BOOL, "0"),
559 V(ExtendAllowPrivateAddresses, BOOL, "1"),
560 V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
561 V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
562 V(V3AuthDistDelay, INTERVAL, "20 seconds"),
563 V(TestingV3AuthInitialVotingInterval, INTERVAL, "150 seconds"),
564 V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
565 V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
566 V(TestingV3AuthVotingStartOffset, INTERVAL, "0"),
567 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
568 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
569 V(MinUptimeHidServDirectoryV2, INTERVAL, "0 minutes"),
570 V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 5, 10, 15, "
571 "20, 30, 60"),
572 V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, 15, 20, "
573 "30, 60"),
574 V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
575 "15, 20, 30, 60"),
576 V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
577 "15, 20, 30, 60"),
578 V(TestingBridgeDownloadSchedule, CSV_INTERVAL, "60, 30, 30, 60"),
579 V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "5 seconds"),
580 V(TestingDirConnectionMaxStall, INTERVAL, "30 seconds"),
581 V(TestingConsensusMaxDownloadTries, UINT, "80"),
582 V(TestingDescriptorMaxDownloadTries, UINT, "80"),
583 V(TestingMicrodescMaxDownloadTries, UINT, "80"),
584 V(TestingCertMaxDownloadTries, UINT, "80"),
585 V(TestingEnableConnBwEvent, BOOL, "1"),
586 V(TestingEnableCellStatsEvent, BOOL, "1"),
587 V(TestingEnableTbEmptyEvent, BOOL, "1"),
588 VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "1"),
589 V(RendPostPeriod, INTERVAL, "2 minutes"),
591 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
594 #undef VAR
595 #undef V
596 #undef OBSOLETE
598 static const config_deprecation_t option_deprecation_notes_[] = {
599 /* Deprecated since 0.2.9.2-alpha... */
600 { "AllowDotExit", "Unrestricted use of the .exit notation can be used for "
601 "a wide variety of application-level attacks." },
602 { "AllowInvalidNodes", "There is no reason to enable this option; at best "
603 "it will make you easier to track." },
604 { "AllowSingleHopCircuits", "Almost no relays actually allow single-hop "
605 "exits, making this option pointless." },
606 { "AllowSingleHopExits", "Turning this on will make your relay easier "
607 "to abuse." },
608 { "ClientDNSRejectInternalAddresses", "Turning this on makes your client "
609 "easier to fingerprint, and may open you to esoteric attacks." },
610 { "ExcludeSingleHopRelays", "Turning it on makes your client easier to "
611 "fingerprint." },
612 { "FastFirstHopPK", "Changing this option does not make your client more "
613 "secure, but does make it easier to fingerprint." },
614 { "CloseHSClientCircuitsImmediatelyOnTimeout", "This option makes your "
615 "client easier to fingerprint." },
616 { "CloseHSServiceRendCircuitsImmediatelyOnTimeout", "This option makes "
617 "your hidden services easier to fingerprint." },
618 { "WarnUnsafeSocks", "Changing this option makes it easier for you "
619 "to accidentally lose your anonymity by leaking DNS information" },
620 { "TLSECGroup", "The default is a nice secure choice; the other option "
621 "is less secure." },
622 { "ControlListenAddress", "Use ControlPort instead." },
623 { "DirListenAddress", "Use DirPort instead, possibly with the "
624 "NoAdvertise sub-option" },
625 { "DNSListenAddress", "Use DNSPort instead." },
626 { "SocksListenAddress", "Use SocksPort instead." },
627 { "TransListenAddress", "Use TransPort instead." },
628 { "NATDListenAddress", "Use NATDPort instead." },
629 { "ORListenAddress", "Use ORPort instead, possibly with the "
630 "NoAdvertise sub-option" },
631 /* End of options deprecated since 0.2.9.2-alpha. */
633 { NULL, NULL }
636 #ifdef _WIN32
637 static char *get_windows_conf_root(void);
638 #endif
639 static int options_act_reversible(const or_options_t *old_options, char **msg);
640 static int options_transition_allowed(const or_options_t *old,
641 const or_options_t *new,
642 char **msg);
643 static int options_transition_affects_workers(
644 const or_options_t *old_options, const or_options_t *new_options);
645 static int options_transition_affects_descriptor(
646 const or_options_t *old_options, const or_options_t *new_options);
647 static int check_nickname_list(char **lst, const char *name, char **msg);
648 static char *get_bindaddr_from_transport_listen_line(const char *line,
649 const char *transport);
650 static int parse_ports(or_options_t *options, int validate_only,
651 char **msg_out, int *n_ports_out,
652 int *world_writable_control_socket);
653 static int check_server_ports(const smartlist_t *ports,
654 const or_options_t *options,
655 int *num_low_ports_out);
657 static int validate_data_directory(or_options_t *options);
658 static int write_configuration_file(const char *fname,
659 const or_options_t *options);
660 static int options_init_logs(const or_options_t *old_options,
661 or_options_t *options, int validate_only);
663 static void init_libevent(const or_options_t *options);
664 static int opt_streq(const char *s1, const char *s2);
665 static int parse_outbound_addresses(or_options_t *options, int validate_only,
666 char **msg);
667 static void config_maybe_load_geoip_files_(const or_options_t *options,
668 const or_options_t *old_options);
669 static int options_validate_cb(void *old_options, void *options,
670 void *default_options,
671 int from_setconf, char **msg);
672 static uint64_t compute_real_max_mem_in_queues(const uint64_t val,
673 int log_guess);
675 /** Magic value for or_options_t. */
676 #define OR_OPTIONS_MAGIC 9090909
678 /** Configuration format for or_options_t. */
679 STATIC config_format_t options_format = {
680 sizeof(or_options_t),
681 OR_OPTIONS_MAGIC,
682 STRUCT_OFFSET(or_options_t, magic_),
683 option_abbrevs_,
684 option_deprecation_notes_,
685 option_vars_,
686 options_validate_cb,
687 NULL
691 * Functions to read and write the global options pointer.
694 /** Command-line and config-file options. */
695 static or_options_t *global_options = NULL;
696 /** The fallback options_t object; this is where we look for options not
697 * in torrc before we fall back to Tor's defaults. */
698 static or_options_t *global_default_options = NULL;
699 /** Name of most recently read torrc file. */
700 static char *torrc_fname = NULL;
701 /** Name of the most recently read torrc-defaults file.*/
702 static char *torrc_defaults_fname;
703 /** Configuration options set by command line. */
704 static config_line_t *global_cmdline_options = NULL;
705 /** Non-configuration options set by the command line */
706 static config_line_t *global_cmdline_only_options = NULL;
707 /** Boolean: Have we parsed the command line? */
708 static int have_parsed_cmdline = 0;
709 /** Contents of most recently read DirPortFrontPage file. */
710 static char *global_dirfrontpagecontents = NULL;
711 /** List of port_cfg_t for all configured ports. */
712 static smartlist_t *configured_ports = NULL;
714 /** Return the contents of our frontpage string, or NULL if not configured. */
715 MOCK_IMPL(const char*,
716 get_dirportfrontpage, (void))
718 return global_dirfrontpagecontents;
721 /** Returns the currently configured options. */
722 MOCK_IMPL(or_options_t *,
723 get_options_mutable, (void))
725 tor_assert(global_options);
726 return global_options;
729 /** Returns the currently configured options */
730 MOCK_IMPL(const or_options_t *,
731 get_options,(void))
733 return get_options_mutable();
736 /** Change the current global options to contain <b>new_val</b> instead of
737 * their current value; take action based on the new value; free the old value
738 * as necessary. Returns 0 on success, -1 on failure.
741 set_options(or_options_t *new_val, char **msg)
743 int i;
744 smartlist_t *elements;
745 config_line_t *line;
746 or_options_t *old_options = global_options;
747 global_options = new_val;
748 /* Note that we pass the *old* options below, for comparison. It
749 * pulls the new options directly out of global_options. */
750 if (options_act_reversible(old_options, msg)<0) {
751 tor_assert(*msg);
752 global_options = old_options;
753 return -1;
755 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
756 log_err(LD_BUG,
757 "Acting on config options left us in a broken state. Dying.");
758 exit(1);
760 /* Issues a CONF_CHANGED event to notify controller of the change. If Tor is
761 * just starting up then the old_options will be undefined. */
762 if (old_options && old_options != global_options) {
763 elements = smartlist_new();
764 for (i=0; options_format.vars[i].name; ++i) {
765 const config_var_t *var = &options_format.vars[i];
766 const char *var_name = var->name;
767 if (var->type == CONFIG_TYPE_LINELIST_S ||
768 var->type == CONFIG_TYPE_OBSOLETE) {
769 continue;
771 if (!config_is_same(&options_format, new_val, old_options, var_name)) {
772 line = config_get_assigned_option(&options_format, new_val,
773 var_name, 1);
775 if (line) {
776 config_line_t *next;
777 for (; line; line = next) {
778 next = line->next;
779 smartlist_add(elements, line->key);
780 smartlist_add(elements, line->value);
781 tor_free(line);
783 } else {
784 smartlist_add(elements, tor_strdup(options_format.vars[i].name));
785 smartlist_add(elements, NULL);
789 control_event_conf_changed(elements);
790 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
791 smartlist_free(elements);
794 if (old_options != global_options)
795 or_options_free(old_options);
797 return 0;
800 extern const char tor_git_revision[]; /* from tor_main.c */
802 /** The version of this Tor process, as parsed. */
803 static char *the_tor_version = NULL;
804 /** A shorter version of this Tor process's version, for export in our router
805 * descriptor. (Does not include the git version, if any.) */
806 static char *the_short_tor_version = NULL;
808 /** Return the current Tor version. */
809 const char *
810 get_version(void)
812 if (the_tor_version == NULL) {
813 if (strlen(tor_git_revision)) {
814 tor_asprintf(&the_tor_version, "%s (git-%s)", get_short_version(),
815 tor_git_revision);
816 } else {
817 the_tor_version = tor_strdup(get_short_version());
820 return the_tor_version;
823 /** Return the current Tor version, without any git tag. */
824 const char *
825 get_short_version(void)
828 if (the_short_tor_version == NULL) {
829 #ifdef TOR_BUILD_TAG
830 tor_asprintf(&the_short_tor_version, "%s (%s)", VERSION, TOR_BUILD_TAG);
831 #else
832 the_short_tor_version = tor_strdup(VERSION);
833 #endif
835 return the_short_tor_version;
838 /** Release additional memory allocated in options
840 STATIC void
841 or_options_free(or_options_t *options)
843 if (!options)
844 return;
846 routerset_free(options->ExcludeExitNodesUnion_);
847 if (options->NodeFamilySets) {
848 SMARTLIST_FOREACH(options->NodeFamilySets, routerset_t *,
849 rs, routerset_free(rs));
850 smartlist_free(options->NodeFamilySets);
852 tor_free(options->BridgePassword_AuthDigest_);
853 tor_free(options->command_arg);
854 tor_free(options->master_key_fname);
855 config_free(&options_format, options);
858 /** Release all memory and resources held by global configuration structures.
860 void
861 config_free_all(void)
863 or_options_free(global_options);
864 global_options = NULL;
865 or_options_free(global_default_options);
866 global_default_options = NULL;
868 config_free_lines(global_cmdline_options);
869 global_cmdline_options = NULL;
871 config_free_lines(global_cmdline_only_options);
872 global_cmdline_only_options = NULL;
874 if (configured_ports) {
875 SMARTLIST_FOREACH(configured_ports,
876 port_cfg_t *, p, port_cfg_free(p));
877 smartlist_free(configured_ports);
878 configured_ports = NULL;
881 tor_free(torrc_fname);
882 tor_free(torrc_defaults_fname);
883 tor_free(global_dirfrontpagecontents);
885 tor_free(the_short_tor_version);
886 tor_free(the_tor_version);
889 /** Make <b>address</b> -- a piece of information related to our operation as
890 * a client -- safe to log according to the settings in options->SafeLogging,
891 * and return it.
893 * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
895 const char *
896 safe_str_client(const char *address)
898 tor_assert(address);
899 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
900 return "[scrubbed]";
901 else
902 return address;
905 /** Make <b>address</b> -- a piece of information of unspecified sensitivity
906 * -- safe to log according to the settings in options->SafeLogging, and
907 * return it.
909 * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
910 * otherwise.)
912 const char *
913 safe_str(const char *address)
915 tor_assert(address);
916 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
917 return "[scrubbed]";
918 else
919 return address;
922 /** Equivalent to escaped(safe_str_client(address)). See reentrancy note on
923 * escaped(): don't use this outside the main thread, or twice in the same
924 * log statement. */
925 const char *
926 escaped_safe_str_client(const char *address)
928 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
929 return "[scrubbed]";
930 else
931 return escaped(address);
934 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
935 * escaped(): don't use this outside the main thread, or twice in the same
936 * log statement. */
937 const char *
938 escaped_safe_str(const char *address)
940 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
941 return "[scrubbed]";
942 else
943 return escaped(address);
946 /** List of default directory authorities */
948 static const char *default_authorities[] = {
949 "moria1 orport=9101 "
950 "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
951 "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
952 "tor26 orport=443 "
953 "v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
954 "ipv6=[2001:858:2:2:aabb:0:563b:1526]:443 "
955 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
956 "dizum orport=443 "
957 "v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
958 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
959 "Bifroest orport=443 bridge "
960 "37.218.247.217:80 1D8F 3A91 C37C 5D1C 4C19 B1AD 1D0C FBE8 BF72 D8E1",
961 "gabelmoo orport=443 "
962 "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
963 "ipv6=[2001:638:a000:4140::ffff:189]:443 "
964 "131.188.40.189:80 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
965 "dannenberg orport=443 "
966 "v3ident=0232AF901C31A04EE9848595AF9BB7620D4C5B2E "
967 "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
968 "maatuska orport=80 "
969 "v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
970 "ipv6=[2001:67c:289c::9]:80 "
971 "171.25.193.9:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
972 "Faravahar orport=443 "
973 "v3ident=EFCBE720AB3A82B99F9E953CD5BF50F7EEFC7B97 "
974 "154.35.175.225:80 CF6D 0AAF B385 BE71 B8E1 11FC 5CFF 4B47 9237 33BC",
975 "longclaw orport=443 "
976 "v3ident=23D15D965BC35114467363C165C4F724B64B4F66 "
977 "ipv6=[2620:13:4000:8000:60:f3ff:fea1:7cff]:443 "
978 "199.254.238.52:80 74A9 1064 6BCE EFBC D2E8 74FC 1DC9 9743 0F96 8145",
979 NULL
982 /** List of fallback directory authorities. The list is generated by opt-in of
983 * relays that meet certain stability criteria.
985 static const char *default_fallbacks[] = {
986 #include "fallback_dirs.inc"
987 NULL
990 /** Add the default directory authorities directly into the trusted dir list,
991 * but only add them insofar as they share bits with <b>type</b>.
992 * Each authority's bits are restricted to the bits shared with <b>type</b>.
993 * If <b>type</b> is ALL_DIRINFO or NO_DIRINFO (zero), add all authorities. */
994 STATIC void
995 add_default_trusted_dir_authorities(dirinfo_type_t type)
997 int i;
998 for (i=0; default_authorities[i]; i++) {
999 if (parse_dir_authority_line(default_authorities[i], type, 0)<0) {
1000 log_err(LD_BUG, "Couldn't parse internal DirAuthority line %s",
1001 default_authorities[i]);
1006 /** Add the default fallback directory servers into the fallback directory
1007 * server list. */
1008 MOCK_IMPL(void,
1009 add_default_fallback_dir_servers,(void))
1011 int i;
1012 for (i=0; default_fallbacks[i]; i++) {
1013 if (parse_dir_fallback_line(default_fallbacks[i], 0)<0) {
1014 log_err(LD_BUG, "Couldn't parse internal FallbackDir line %s",
1015 default_fallbacks[i]);
1020 /** Look at all the config options for using alternate directory
1021 * authorities, and make sure none of them are broken. Also, warn the
1022 * user if we changed any dangerous ones.
1024 static int
1025 validate_dir_servers(or_options_t *options, or_options_t *old_options)
1027 config_line_t *cl;
1029 if (options->DirAuthorities &&
1030 (options->AlternateDirAuthority || options->AlternateBridgeAuthority)) {
1031 log_warn(LD_CONFIG,
1032 "You cannot set both DirAuthority and Alternate*Authority.");
1033 return -1;
1036 /* do we want to complain to the user about being partitionable? */
1037 if ((options->DirAuthorities &&
1038 (!old_options ||
1039 !config_lines_eq(options->DirAuthorities,
1040 old_options->DirAuthorities))) ||
1041 (options->AlternateDirAuthority &&
1042 (!old_options ||
1043 !config_lines_eq(options->AlternateDirAuthority,
1044 old_options->AlternateDirAuthority)))) {
1045 log_warn(LD_CONFIG,
1046 "You have used DirAuthority or AlternateDirAuthority to "
1047 "specify alternate directory authorities in "
1048 "your configuration. This is potentially dangerous: it can "
1049 "make you look different from all other Tor users, and hurt "
1050 "your anonymity. Even if you've specified the same "
1051 "authorities as Tor uses by default, the defaults could "
1052 "change in the future. Be sure you know what you're doing.");
1055 /* Now go through the four ways you can configure an alternate
1056 * set of directory authorities, and make sure none are broken. */
1057 for (cl = options->DirAuthorities; cl; cl = cl->next)
1058 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1059 return -1;
1060 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1061 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1062 return -1;
1063 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1064 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1065 return -1;
1066 for (cl = options->FallbackDir; cl; cl = cl->next)
1067 if (parse_dir_fallback_line(cl->value, 1)<0)
1068 return -1;
1069 return 0;
1072 /** Look at all the config options and assign new dir authorities
1073 * as appropriate.
1076 consider_adding_dir_servers(const or_options_t *options,
1077 const or_options_t *old_options)
1079 config_line_t *cl;
1080 int need_to_update =
1081 !smartlist_len(router_get_trusted_dir_servers()) ||
1082 !smartlist_len(router_get_fallback_dir_servers()) || !old_options ||
1083 !config_lines_eq(options->DirAuthorities, old_options->DirAuthorities) ||
1084 !config_lines_eq(options->FallbackDir, old_options->FallbackDir) ||
1085 (options->UseDefaultFallbackDirs != old_options->UseDefaultFallbackDirs) ||
1086 !config_lines_eq(options->AlternateBridgeAuthority,
1087 old_options->AlternateBridgeAuthority) ||
1088 !config_lines_eq(options->AlternateDirAuthority,
1089 old_options->AlternateDirAuthority);
1091 if (!need_to_update)
1092 return 0; /* all done */
1094 /* "You cannot set both DirAuthority and Alternate*Authority."
1095 * Checking that this restriction holds allows us to simplify
1096 * the unit tests. */
1097 tor_assert(!(options->DirAuthorities &&
1098 (options->AlternateDirAuthority
1099 || options->AlternateBridgeAuthority)));
1101 /* Start from a clean slate. */
1102 clear_dir_servers();
1104 if (!options->DirAuthorities) {
1105 /* then we may want some of the defaults */
1106 dirinfo_type_t type = NO_DIRINFO;
1107 if (!options->AlternateBridgeAuthority) {
1108 type |= BRIDGE_DIRINFO;
1110 if (!options->AlternateDirAuthority) {
1111 type |= V3_DIRINFO | EXTRAINFO_DIRINFO | MICRODESC_DIRINFO;
1112 /* Only add the default fallback directories when the DirAuthorities,
1113 * AlternateDirAuthority, and FallbackDir directory config options
1114 * are set to their defaults, and when UseDefaultFallbackDirs is 1. */
1115 if (!options->FallbackDir && options->UseDefaultFallbackDirs) {
1116 add_default_fallback_dir_servers();
1119 /* if type == NO_DIRINFO, we don't want to add any of the
1120 * default authorities, because we've replaced them all */
1121 if (type != NO_DIRINFO)
1122 add_default_trusted_dir_authorities(type);
1125 for (cl = options->DirAuthorities; cl; cl = cl->next)
1126 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1127 return -1;
1128 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1129 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1130 return -1;
1131 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1132 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1133 return -1;
1134 for (cl = options->FallbackDir; cl; cl = cl->next)
1135 if (parse_dir_fallback_line(cl->value, 0)<0)
1136 return -1;
1137 return 0;
1140 /* Helps determine flags to pass to switch_id. */
1141 static int have_low_ports = -1;
1143 /** Fetch the active option list, and take actions based on it. All of the
1144 * things we do should survive being done repeatedly. If present,
1145 * <b>old_options</b> contains the previous value of the options.
1147 * Return 0 if all goes well, return -1 if things went badly.
1149 static int
1150 options_act_reversible(const or_options_t *old_options, char **msg)
1152 smartlist_t *new_listeners = smartlist_new();
1153 smartlist_t *replaced_listeners = smartlist_new();
1154 static int libevent_initialized = 0;
1155 or_options_t *options = get_options_mutable();
1156 int running_tor = options->command == CMD_RUN_TOR;
1157 int set_conn_limit = 0;
1158 int r = -1;
1159 int logs_marked = 0, logs_initialized = 0;
1160 int old_min_log_level = get_min_log_level();
1162 /* Daemonize _first_, since we only want to open most of this stuff in
1163 * the subprocess. Libevent bases can't be reliably inherited across
1164 * processes. */
1165 if (running_tor && options->RunAsDaemon) {
1166 /* No need to roll back, since you can't change the value. */
1167 start_daemon();
1170 #ifdef HAVE_SYSTEMD
1171 /* Our PID may have changed, inform supervisor */
1172 sd_notifyf(0, "MAINPID=%ld\n", (long int)getpid());
1173 #endif
1175 #ifndef HAVE_SYS_UN_H
1176 if (options->ControlSocket || options->ControlSocketsGroupWritable) {
1177 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported "
1178 "on this OS/with this build.");
1179 goto rollback;
1181 #else
1182 if (options->ControlSocketsGroupWritable && !options->ControlSocket) {
1183 *msg = tor_strdup("Setting ControlSocketGroupWritable without setting"
1184 "a ControlSocket makes no sense.");
1185 goto rollback;
1187 #endif
1189 if (running_tor) {
1190 int n_ports=0;
1191 /* We need to set the connection limit before we can open the listeners. */
1192 if (! sandbox_is_active()) {
1193 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1194 &options->ConnLimit_) < 0) {
1195 *msg = tor_strdup("Problem with ConnLimit value. "
1196 "See logs for details.");
1197 goto rollback;
1199 set_conn_limit = 1;
1200 } else {
1201 tor_assert(old_options);
1202 options->ConnLimit_ = old_options->ConnLimit_;
1205 /* Set up libevent. (We need to do this before we can register the
1206 * listeners as listeners.) */
1207 if (running_tor && !libevent_initialized) {
1208 init_libevent(options);
1209 libevent_initialized = 1;
1211 /* This has to come up after libevent is initialized. */
1212 control_initialize_event_queue();
1215 * Initialize the scheduler - this has to come after
1216 * options_init_from_torrc() sets up libevent - why yes, that seems
1217 * completely sensible to hide the libevent setup in the option parsing
1218 * code! It also needs to happen before init_keys(), so it needs to
1219 * happen here too. How yucky. */
1220 scheduler_init();
1223 /* Adjust the port configuration so we can launch listeners. */
1224 if (parse_ports(options, 0, msg, &n_ports, NULL)) {
1225 if (!*msg)
1226 *msg = tor_strdup("Unexpected problem parsing port config");
1227 goto rollback;
1230 /* Set the hibernation state appropriately.*/
1231 consider_hibernation(time(NULL));
1233 /* Launch the listeners. (We do this before we setuid, so we can bind to
1234 * ports under 1024.) We don't want to rebind if we're hibernating. If
1235 * networking is disabled, this will close all but the control listeners,
1236 * but disable those. */
1237 if (!we_are_hibernating()) {
1238 if (retry_all_listeners(replaced_listeners, new_listeners,
1239 options->DisableNetwork) < 0) {
1240 *msg = tor_strdup("Failed to bind one of the listener ports.");
1241 goto rollback;
1244 if (options->DisableNetwork) {
1245 /* Aggressively close non-controller stuff, NOW */
1246 log_notice(LD_NET, "DisableNetwork is set. Tor will not make or accept "
1247 "non-control network connections. Shutting down all existing "
1248 "connections.");
1249 connection_mark_all_noncontrol_connections();
1250 /* We can't complete circuits until the network is re-enabled. */
1251 note_that_we_maybe_cant_complete_circuits();
1255 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1256 /* Open /dev/pf before dropping privileges. */
1257 if (options->TransPort_set &&
1258 options->TransProxyType_parsed == TPT_DEFAULT) {
1259 if (get_pf_socket() < 0) {
1260 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1261 goto rollback;
1264 #endif
1266 /* Attempt to lock all current and future memory with mlockall() only once */
1267 if (options->DisableAllSwap) {
1268 if (tor_mlockall() == -1) {
1269 *msg = tor_strdup("DisableAllSwap failure. Do you have proper "
1270 "permissions?");
1271 goto done;
1275 /* Setuid/setgid as appropriate */
1276 if (options->User) {
1277 tor_assert(have_low_ports != -1);
1278 unsigned switch_id_flags = 0;
1279 if (options->KeepBindCapabilities == 1) {
1280 switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
1281 switch_id_flags |= SWITCH_ID_WARN_IF_NO_CAPS;
1283 if (options->KeepBindCapabilities == -1 && have_low_ports) {
1284 switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
1286 if (switch_id(options->User, switch_id_flags) != 0) {
1287 /* No need to roll back, since you can't change the value. */
1288 *msg = tor_strdup("Problem with User value. See logs for details.");
1289 goto done;
1293 /* Ensure data directory is private; create if possible. */
1294 cpd_check_t cpd_opts = running_tor ? CPD_CREATE : CPD_CHECK;
1295 if (options->DataDirectoryGroupReadable)
1296 cpd_opts |= CPD_GROUP_READ;
1297 if (check_private_dir(options->DataDirectory,
1298 cpd_opts,
1299 options->User)<0) {
1300 tor_asprintf(msg,
1301 "Couldn't access/create private data directory \"%s\"",
1302 options->DataDirectory);
1304 goto done;
1305 /* No need to roll back, since you can't change the value. */
1308 #ifndef _WIN32
1309 if (options->DataDirectoryGroupReadable) {
1310 /* Only new dirs created get new opts, also enforce group read. */
1311 if (chmod(options->DataDirectory, 0750)) {
1312 log_warn(LD_FS,"Unable to make %s group-readable: %s",
1313 options->DataDirectory, strerror(errno));
1316 #endif
1318 /* Bail out at this point if we're not going to be a client or server:
1319 * we don't run Tor itself. */
1320 if (!running_tor)
1321 goto commit;
1323 mark_logs_temp(); /* Close current logs once new logs are open. */
1324 logs_marked = 1;
1325 /* Configure the tor_log(s) */
1326 if (options_init_logs(old_options, options, 0)<0) {
1327 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1328 goto rollback;
1330 logs_initialized = 1;
1332 commit:
1333 r = 0;
1334 if (logs_marked) {
1335 log_severity_list_t *severity =
1336 tor_malloc_zero(sizeof(log_severity_list_t));
1337 close_temp_logs();
1338 add_callback_log(severity, control_event_logmsg);
1339 control_adjust_event_log_severity();
1340 tor_free(severity);
1341 tor_log_update_sigsafe_err_fds();
1343 if (logs_initialized) {
1344 flush_log_messages_from_startup();
1348 const char *badness = NULL;
1349 int bad_safelog = 0, bad_severity = 0, new_badness = 0;
1350 if (options->SafeLogging_ != SAFELOG_SCRUB_ALL) {
1351 bad_safelog = 1;
1352 if (!old_options || old_options->SafeLogging_ != options->SafeLogging_)
1353 new_badness = 1;
1355 if (get_min_log_level() >= LOG_INFO) {
1356 bad_severity = 1;
1357 if (get_min_log_level() != old_min_log_level)
1358 new_badness = 1;
1360 if (bad_safelog && bad_severity)
1361 badness = "you disabled SafeLogging, and "
1362 "you're logging more than \"notice\"";
1363 else if (bad_safelog)
1364 badness = "you disabled SafeLogging";
1365 else
1366 badness = "you're logging more than \"notice\"";
1367 if (new_badness)
1368 log_warn(LD_GENERAL, "Your log may contain sensitive information - %s. "
1369 "Don't log unless it serves an important reason. "
1370 "Overwrite the log afterwards.", badness);
1373 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1375 int marked = conn->marked_for_close;
1376 log_notice(LD_NET, "Closing old %s on %s:%d",
1377 conn_type_to_string(conn->type), conn->address, conn->port);
1378 connection_close_immediate(conn);
1379 if (!marked) {
1380 connection_mark_for_close(conn);
1384 if (set_conn_limit) {
1386 * If we adjusted the conn limit, recompute the OOS threshold too
1388 * How many possible sockets to keep in reserve? If we have lots of
1389 * possible sockets, keep this below a limit and set ConnLimit_high_thresh
1390 * very close to ConnLimit_, but if ConnLimit_ is low, shrink it in
1391 * proportion.
1393 * Somewhat arbitrarily, set socks_in_reserve to 5% of ConnLimit_, but
1394 * cap it at 64.
1396 int socks_in_reserve = options->ConnLimit_ / 20;
1397 if (socks_in_reserve > 64) socks_in_reserve = 64;
1399 options->ConnLimit_high_thresh = options->ConnLimit_ - socks_in_reserve;
1400 options->ConnLimit_low_thresh = (options->ConnLimit_ / 4) * 3;
1401 log_info(LD_GENERAL,
1402 "Recomputed OOS thresholds: ConnLimit %d, ConnLimit_ %d, "
1403 "ConnLimit_high_thresh %d, ConnLimit_low_thresh %d",
1404 options->ConnLimit, options->ConnLimit_,
1405 options->ConnLimit_high_thresh,
1406 options->ConnLimit_low_thresh);
1408 /* Give the OOS handler a chance with the new thresholds */
1409 connection_check_oos(get_n_open_sockets(), 0);
1412 goto done;
1414 rollback:
1415 r = -1;
1416 tor_assert(*msg);
1418 if (logs_marked) {
1419 rollback_log_changes();
1420 control_adjust_event_log_severity();
1423 if (set_conn_limit && old_options)
1424 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1425 &options->ConnLimit_);
1427 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1429 log_notice(LD_NET, "Closing partially-constructed %s on %s:%d",
1430 conn_type_to_string(conn->type), conn->address, conn->port);
1431 connection_close_immediate(conn);
1432 connection_mark_for_close(conn);
1435 done:
1436 smartlist_free(new_listeners);
1437 smartlist_free(replaced_listeners);
1438 return r;
1441 /** If we need to have a GEOIP ip-to-country map to run with our configured
1442 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1444 options_need_geoip_info(const or_options_t *options, const char **reason_out)
1446 int bridge_usage =
1447 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1448 int routerset_usage =
1449 routerset_needs_geoip(options->EntryNodes) ||
1450 routerset_needs_geoip(options->ExitNodes) ||
1451 routerset_needs_geoip(options->ExcludeExitNodes) ||
1452 routerset_needs_geoip(options->ExcludeNodes) ||
1453 routerset_needs_geoip(options->Tor2webRendezvousPoints);
1455 if (routerset_usage && reason_out) {
1456 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1457 "countries, and we need GEOIP information to figure out which ones they "
1458 "are.";
1459 } else if (bridge_usage && reason_out) {
1460 *reason_out = "We've been configured to see which countries can access "
1461 "us as a bridge, and we need GEOIP information to tell which countries "
1462 "clients are in.";
1464 return bridge_usage || routerset_usage;
1467 /** Return the bandwidthrate that we are going to report to the authorities
1468 * based on the config options. */
1469 uint32_t
1470 get_effective_bwrate(const or_options_t *options)
1472 uint64_t bw = options->BandwidthRate;
1473 if (bw > options->MaxAdvertisedBandwidth)
1474 bw = options->MaxAdvertisedBandwidth;
1475 if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1476 bw = options->RelayBandwidthRate;
1477 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1478 return (uint32_t)bw;
1481 /** Return the bandwidthburst that we are going to report to the authorities
1482 * based on the config options. */
1483 uint32_t
1484 get_effective_bwburst(const or_options_t *options)
1486 uint64_t bw = options->BandwidthBurst;
1487 if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1488 bw = options->RelayBandwidthBurst;
1489 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1490 return (uint32_t)bw;
1493 /** Return True if any changes from <b>old_options</b> to
1494 * <b>new_options</b> needs us to refresh our TLS context. */
1495 static int
1496 options_transition_requires_fresh_tls_context(const or_options_t *old_options,
1497 const or_options_t *new_options)
1499 tor_assert(new_options);
1501 if (!old_options)
1502 return 0;
1504 if (!opt_streq(old_options->TLSECGroup, new_options->TLSECGroup))
1505 return 1;
1507 return 0;
1510 /** Fetch the active option list, and take actions based on it. All of the
1511 * things we do should survive being done repeatedly. If present,
1512 * <b>old_options</b> contains the previous value of the options.
1514 * Return 0 if all goes well, return -1 if it's time to die.
1516 * Note: We haven't moved all the "act on new configuration" logic
1517 * here yet. Some is still in do_hup() and other places.
1519 STATIC int
1520 options_act(const or_options_t *old_options)
1522 config_line_t *cl;
1523 or_options_t *options = get_options_mutable();
1524 int running_tor = options->command == CMD_RUN_TOR;
1525 char *msg=NULL;
1526 const int transition_affects_workers =
1527 old_options && options_transition_affects_workers(old_options, options);
1528 int old_ewma_enabled;
1530 /* disable ptrace and later, other basic debugging techniques */
1532 /* Remember if we already disabled debugger attachment */
1533 static int disabled_debugger_attach = 0;
1534 /* Remember if we already warned about being configured not to disable
1535 * debugger attachment */
1536 static int warned_debugger_attach = 0;
1537 /* Don't disable debugger attachment when we're running the unit tests. */
1538 if (options->DisableDebuggerAttachment && !disabled_debugger_attach &&
1539 running_tor) {
1540 int ok = tor_disable_debugger_attach();
1541 /* LCOV_EXCL_START the warned_debugger_attach is 0 can't reach inside. */
1542 if (warned_debugger_attach && ok == 1) {
1543 log_notice(LD_CONFIG, "Disabled attaching debuggers for unprivileged "
1544 "users.");
1546 /* LCOV_EXCL_STOP */
1547 disabled_debugger_attach = (ok == 1);
1548 } else if (!options->DisableDebuggerAttachment &&
1549 !warned_debugger_attach) {
1550 log_notice(LD_CONFIG, "Not disabling debugger attaching for "
1551 "unprivileged users.");
1552 warned_debugger_attach = 1;
1556 /* Write control ports to disk as appropriate */
1557 control_ports_write_to_file();
1559 if (running_tor && !have_lockfile()) {
1560 if (try_locking(options, 1) < 0)
1561 return -1;
1564 if (consider_adding_dir_servers(options, old_options) < 0)
1565 return -1;
1567 if (rend_non_anonymous_mode_enabled(options)) {
1568 log_warn(LD_GENERAL, "This copy of Tor was compiled or configured to run "
1569 "in a non-anonymous mode. It will provide NO ANONYMITY.");
1572 #ifdef ENABLE_TOR2WEB_MODE
1573 /* LCOV_EXCL_START */
1574 if (!options->Tor2webMode) {
1575 log_err(LD_CONFIG, "This copy of Tor was compiled to run in "
1576 "'tor2web mode'. It can only be run with the Tor2webMode torrc "
1577 "option enabled.");
1578 return -1;
1580 /* LCOV_EXCL_STOP */
1581 #else
1582 if (options->Tor2webMode) {
1583 log_err(LD_CONFIG, "This copy of Tor was not compiled to run in "
1584 "'tor2web mode'. It cannot be run with the Tor2webMode torrc "
1585 "option enabled. To enable Tor2webMode recompile with the "
1586 "--enable-tor2web-mode option.");
1587 return -1;
1589 #endif
1591 /* If we are a bridge with a pluggable transport proxy but no
1592 Extended ORPort, inform the user that they are missing out. */
1593 if (server_mode(options) && options->ServerTransportPlugin &&
1594 !options->ExtORPort_lines) {
1595 log_notice(LD_CONFIG, "We use pluggable transports but the Extended "
1596 "ORPort is disabled. Tor and your pluggable transports proxy "
1597 "communicate with each other via the Extended ORPort so it "
1598 "is suggested you enable it: it will also allow your Bridge "
1599 "to collect statistics about its clients that use pluggable "
1600 "transports. Please enable it using the ExtORPort torrc option "
1601 "(e.g. set 'ExtORPort auto').");
1604 if (options->Bridges) {
1605 mark_bridge_list();
1606 for (cl = options->Bridges; cl; cl = cl->next) {
1607 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
1608 if (!bridge_line) {
1609 log_warn(LD_BUG,
1610 "Previously validated Bridge line could not be added!");
1611 return -1;
1613 bridge_add_from_config(bridge_line);
1615 sweep_bridge_list();
1618 if (running_tor && rend_config_services(options, 0)<0) {
1619 log_warn(LD_BUG,
1620 "Previously validated hidden services line could not be added!");
1621 return -1;
1624 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1625 log_warn(LD_BUG, "Previously validated client authorization for "
1626 "hidden services could not be added!");
1627 return -1;
1630 /* Load state */
1631 if (! or_state_loaded() && running_tor) {
1632 if (or_state_load())
1633 return -1;
1634 rep_hist_load_mtbf_data(time(NULL));
1637 /* If we have an ExtORPort, initialize its auth cookie. */
1638 if (running_tor &&
1639 init_ext_or_cookie_authentication(!!options->ExtORPort_lines) < 0) {
1640 log_warn(LD_CONFIG,"Error creating Extended ORPort cookie file.");
1641 return -1;
1644 mark_transport_list();
1645 pt_prepare_proxy_list_for_config_read();
1646 if (!options->DisableNetwork) {
1647 if (options->ClientTransportPlugin) {
1648 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
1649 if (parse_transport_line(options, cl->value, 0, 0) < 0) {
1650 log_warn(LD_BUG,
1651 "Previously validated ClientTransportPlugin line "
1652 "could not be added!");
1653 return -1;
1658 if (options->ServerTransportPlugin && server_mode(options)) {
1659 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
1660 if (parse_transport_line(options, cl->value, 0, 1) < 0) {
1661 log_warn(LD_BUG,
1662 "Previously validated ServerTransportPlugin line "
1663 "could not be added!");
1664 return -1;
1669 sweep_transport_list();
1670 sweep_proxy_list();
1672 /* Start the PT proxy configuration. By doing this configuration
1673 here, we also figure out which proxies need to be restarted and
1674 which not. */
1675 if (pt_proxies_configuration_pending() && !net_is_disabled())
1676 pt_configure_remaining_proxies();
1678 /* Bail out at this point if we're not going to be a client or server:
1679 * we want to not fork, and to log stuff to stderr. */
1680 if (!running_tor)
1681 return 0;
1683 /* Finish backgrounding the process */
1684 if (options->RunAsDaemon) {
1685 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1686 finish_daemon(options->DataDirectory);
1689 /* We want to reinit keys as needed before we do much of anything else:
1690 keys are important, and other things can depend on them. */
1691 if (transition_affects_workers ||
1692 (options->V3AuthoritativeDir && (!old_options ||
1693 !old_options->V3AuthoritativeDir))) {
1694 if (init_keys() < 0) {
1695 log_warn(LD_BUG,"Error initializing keys; exiting");
1696 return -1;
1698 } else if (old_options &&
1699 options_transition_requires_fresh_tls_context(old_options,
1700 options)) {
1701 if (router_initialize_tls_context() < 0) {
1702 log_warn(LD_BUG,"Error initializing TLS context.");
1703 return -1;
1707 /* Write our PID to the PID file. If we do not have write permissions we
1708 * will log a warning */
1709 if (options->PidFile && !sandbox_is_active()) {
1710 write_pidfile(options->PidFile);
1713 /* Register addressmap directives */
1714 config_register_addressmaps(options);
1715 parse_virtual_addr_network(options->VirtualAddrNetworkIPv4, AF_INET,0,NULL);
1716 parse_virtual_addr_network(options->VirtualAddrNetworkIPv6, AF_INET6,0,NULL);
1718 /* Update address policies. */
1719 if (policies_parse_from_options(options) < 0) {
1720 /* This should be impossible, but let's be sure. */
1721 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1722 return -1;
1725 if (init_control_cookie_authentication(options->CookieAuthentication) < 0) {
1726 log_warn(LD_CONFIG,"Error creating control cookie authentication file.");
1727 return -1;
1730 monitor_owning_controller_process(options->OwningControllerProcess);
1732 /* reload keys as needed for rendezvous services. */
1733 if (rend_service_load_all_keys(NULL)<0) {
1734 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1735 return -1;
1738 /* Set up scheduler thresholds */
1739 scheduler_set_watermarks((uint32_t)options->SchedulerLowWaterMark__,
1740 (uint32_t)options->SchedulerHighWaterMark__,
1741 (options->SchedulerMaxFlushCells__ > 0) ?
1742 options->SchedulerMaxFlushCells__ : 1000);
1744 /* Set up accounting */
1745 if (accounting_parse_options(options, 0)<0) {
1746 log_warn(LD_CONFIG,"Error in accounting options");
1747 return -1;
1749 if (accounting_is_enabled(options))
1750 configure_accounting(time(NULL));
1752 old_ewma_enabled = cell_ewma_enabled();
1753 /* Change the cell EWMA settings */
1754 cell_ewma_set_scale_factor(options, networkstatus_get_latest_consensus());
1755 /* If we just enabled ewma, set the cmux policy on all active channels */
1756 if (cell_ewma_enabled() && !old_ewma_enabled) {
1757 channel_set_cmux_policy_everywhere(&ewma_policy);
1758 } else if (!cell_ewma_enabled() && old_ewma_enabled) {
1759 /* Turn it off everywhere */
1760 channel_set_cmux_policy_everywhere(NULL);
1763 /* Update the BridgePassword's hashed version as needed. We store this as a
1764 * digest so that we can do side-channel-proof comparisons on it.
1766 if (options->BridgePassword) {
1767 char *http_authenticator;
1768 http_authenticator = alloc_http_authenticator(options->BridgePassword);
1769 if (!http_authenticator) {
1770 log_warn(LD_BUG, "Unable to allocate HTTP authenticator. Not setting "
1771 "BridgePassword.");
1772 return -1;
1774 options->BridgePassword_AuthDigest_ = tor_malloc(DIGEST256_LEN);
1775 crypto_digest256(options->BridgePassword_AuthDigest_,
1776 http_authenticator, strlen(http_authenticator),
1777 DIGEST_SHA256);
1778 tor_free(http_authenticator);
1781 if (parse_outbound_addresses(options, 0, &msg) < 0) {
1782 log_warn(LD_BUG, "Failed parsing outbound bind addresses: %s", msg);
1783 tor_free(msg);
1784 return -1;
1787 config_maybe_load_geoip_files_(options, old_options);
1789 if (geoip_is_loaded(AF_INET) && options->GeoIPExcludeUnknown) {
1790 /* ExcludeUnknown is true or "auto" */
1791 const int is_auto = options->GeoIPExcludeUnknown == -1;
1792 int changed;
1794 changed = routerset_add_unknown_ccs(&options->ExcludeNodes, is_auto);
1795 changed += routerset_add_unknown_ccs(&options->ExcludeExitNodes, is_auto);
1797 if (changed)
1798 routerset_add_unknown_ccs(&options->ExcludeExitNodesUnion_, is_auto);
1801 /* Check for transitions that need action. */
1802 if (old_options) {
1803 int revise_trackexithosts = 0;
1804 int revise_automap_entries = 0;
1805 if ((options->UseEntryGuards && !old_options->UseEntryGuards) ||
1806 options->UseBridges != old_options->UseBridges ||
1807 (options->UseBridges &&
1808 !config_lines_eq(options->Bridges, old_options->Bridges)) ||
1809 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes) ||
1810 !routerset_equal(old_options->ExcludeExitNodes,
1811 options->ExcludeExitNodes) ||
1812 !routerset_equal(old_options->EntryNodes, options->EntryNodes) ||
1813 !routerset_equal(old_options->ExitNodes, options->ExitNodes) ||
1814 !routerset_equal(old_options->Tor2webRendezvousPoints,
1815 options->Tor2webRendezvousPoints) ||
1816 options->StrictNodes != old_options->StrictNodes) {
1817 log_info(LD_CIRC,
1818 "Changed to using entry guards or bridges, or changed "
1819 "preferred or excluded node lists. "
1820 "Abandoning previous circuits.");
1821 circuit_mark_all_unused_circs();
1822 circuit_mark_all_dirty_circs_as_unusable();
1823 revise_trackexithosts = 1;
1826 if (!smartlist_strings_eq(old_options->TrackHostExits,
1827 options->TrackHostExits))
1828 revise_trackexithosts = 1;
1830 if (revise_trackexithosts)
1831 addressmap_clear_excluded_trackexithosts(options);
1833 if (!options->AutomapHostsOnResolve &&
1834 old_options->AutomapHostsOnResolve) {
1835 revise_automap_entries = 1;
1836 } else {
1837 if (!smartlist_strings_eq(old_options->AutomapHostsSuffixes,
1838 options->AutomapHostsSuffixes))
1839 revise_automap_entries = 1;
1840 else if (!opt_streq(old_options->VirtualAddrNetworkIPv4,
1841 options->VirtualAddrNetworkIPv4) ||
1842 !opt_streq(old_options->VirtualAddrNetworkIPv6,
1843 options->VirtualAddrNetworkIPv6))
1844 revise_automap_entries = 1;
1847 if (revise_automap_entries)
1848 addressmap_clear_invalid_automaps(options);
1850 /* How long should we delay counting bridge stats after becoming a bridge?
1851 * We use this so we don't count people who used our bridge thinking it is
1852 * a relay. If you change this, don't forget to change the log message
1853 * below. It's 4 hours (the time it takes to stop being used by clients)
1854 * plus some extra time for clock skew. */
1855 #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
1857 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
1858 int was_relay = 0;
1859 if (options->BridgeRelay) {
1860 time_t int_start = time(NULL);
1861 if (config_lines_eq(old_options->ORPort_lines,options->ORPort_lines)) {
1862 int_start += RELAY_BRIDGE_STATS_DELAY;
1863 was_relay = 1;
1865 geoip_bridge_stats_init(int_start);
1866 log_info(LD_CONFIG, "We are acting as a bridge now. Starting new "
1867 "GeoIP stats interval%s.", was_relay ? " in 6 "
1868 "hours from now" : "");
1869 } else {
1870 geoip_bridge_stats_term();
1871 log_info(LD_GENERAL, "We are no longer acting as a bridge. "
1872 "Forgetting GeoIP stats.");
1876 if (transition_affects_workers) {
1877 log_info(LD_GENERAL,
1878 "Worker-related options changed. Rotating workers.");
1880 if (server_mode(options) && !server_mode(old_options)) {
1881 cpu_init();
1882 ip_address_changed(0);
1883 if (have_completed_a_circuit() || !any_predicted_circuits(time(NULL)))
1884 inform_testing_reachability();
1886 cpuworkers_rotate_keyinfo();
1887 if (dns_reset())
1888 return -1;
1889 } else {
1890 if (dns_reset())
1891 return -1;
1894 if (options->PerConnBWRate != old_options->PerConnBWRate ||
1895 options->PerConnBWBurst != old_options->PerConnBWBurst)
1896 connection_or_update_token_buckets(get_connection_array(), options);
1899 /* Only collect directory-request statistics on relays and bridges. */
1900 options->DirReqStatistics = options->DirReqStatistics_option &&
1901 server_mode(options);
1903 if (options->CellStatistics || options->DirReqStatistics ||
1904 options->EntryStatistics || options->ExitPortStatistics ||
1905 options->ConnDirectionStatistics ||
1906 options->HiddenServiceStatistics ||
1907 options->BridgeAuthoritativeDir) {
1908 time_t now = time(NULL);
1909 int print_notice = 0;
1911 /* Only collect other relay-only statistics on relays. */
1912 if (!public_server_mode(options)) {
1913 options->CellStatistics = 0;
1914 options->EntryStatistics = 0;
1915 options->ConnDirectionStatistics = 0;
1916 options->HiddenServiceStatistics = 0;
1917 options->ExitPortStatistics = 0;
1920 if ((!old_options || !old_options->CellStatistics) &&
1921 options->CellStatistics) {
1922 rep_hist_buffer_stats_init(now);
1923 print_notice = 1;
1925 if ((!old_options || !old_options->DirReqStatistics) &&
1926 options->DirReqStatistics) {
1927 if (geoip_is_loaded(AF_INET)) {
1928 geoip_dirreq_stats_init(now);
1929 print_notice = 1;
1930 } else {
1931 /* disable statistics collection since we have no geoip file */
1932 options->DirReqStatistics = 0;
1933 if (options->ORPort_set)
1934 log_notice(LD_CONFIG, "Configured to measure directory request "
1935 "statistics, but no GeoIP database found. "
1936 "Please specify a GeoIP database using the "
1937 "GeoIPFile option.");
1940 if ((!old_options || !old_options->EntryStatistics) &&
1941 options->EntryStatistics && !should_record_bridge_info(options)) {
1942 if (geoip_is_loaded(AF_INET) || geoip_is_loaded(AF_INET6)) {
1943 geoip_entry_stats_init(now);
1944 print_notice = 1;
1945 } else {
1946 options->EntryStatistics = 0;
1947 log_notice(LD_CONFIG, "Configured to measure entry node "
1948 "statistics, but no GeoIP database found. "
1949 "Please specify a GeoIP database using the "
1950 "GeoIPFile option.");
1953 if ((!old_options || !old_options->ExitPortStatistics) &&
1954 options->ExitPortStatistics) {
1955 rep_hist_exit_stats_init(now);
1956 print_notice = 1;
1958 if ((!old_options || !old_options->ConnDirectionStatistics) &&
1959 options->ConnDirectionStatistics) {
1960 rep_hist_conn_stats_init(now);
1962 if ((!old_options || !old_options->HiddenServiceStatistics) &&
1963 options->HiddenServiceStatistics) {
1964 log_info(LD_CONFIG, "Configured to measure hidden service statistics.");
1965 rep_hist_hs_stats_init(now);
1967 if ((!old_options || !old_options->BridgeAuthoritativeDir) &&
1968 options->BridgeAuthoritativeDir) {
1969 rep_hist_desc_stats_init(now);
1970 print_notice = 1;
1972 if (print_notice)
1973 log_notice(LD_CONFIG, "Configured to measure statistics. Look for "
1974 "the *-stats files that will first be written to the "
1975 "data directory in 24 hours from now.");
1978 /* If we used to have statistics enabled but we just disabled them,
1979 stop gathering them. */
1980 if (old_options && old_options->CellStatistics &&
1981 !options->CellStatistics)
1982 rep_hist_buffer_stats_term();
1983 if (old_options && old_options->DirReqStatistics &&
1984 !options->DirReqStatistics)
1985 geoip_dirreq_stats_term();
1986 if (old_options && old_options->EntryStatistics &&
1987 !options->EntryStatistics)
1988 geoip_entry_stats_term();
1989 if (old_options && old_options->HiddenServiceStatistics &&
1990 !options->HiddenServiceStatistics)
1991 rep_hist_hs_stats_term();
1992 if (old_options && old_options->ExitPortStatistics &&
1993 !options->ExitPortStatistics)
1994 rep_hist_exit_stats_term();
1995 if (old_options && old_options->ConnDirectionStatistics &&
1996 !options->ConnDirectionStatistics)
1997 rep_hist_conn_stats_term();
1998 if (old_options && old_options->BridgeAuthoritativeDir &&
1999 !options->BridgeAuthoritativeDir)
2000 rep_hist_desc_stats_term();
2002 /* Check if we need to parse and add the EntryNodes config option. */
2003 if (options->EntryNodes &&
2004 (!old_options ||
2005 !routerset_equal(old_options->EntryNodes,options->EntryNodes) ||
2006 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes)))
2007 entry_nodes_should_be_added();
2009 /* Since our options changed, we might need to regenerate and upload our
2010 * server descriptor.
2012 if (!old_options ||
2013 options_transition_affects_descriptor(old_options, options))
2014 mark_my_descriptor_dirty("config change");
2016 /* We may need to reschedule some directory stuff if our status changed. */
2017 if (old_options) {
2018 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
2019 dirvote_recalculate_timing(options, time(NULL));
2020 if (!bool_eq(directory_fetches_dir_info_early(options),
2021 directory_fetches_dir_info_early(old_options)) ||
2022 !bool_eq(directory_fetches_dir_info_later(options),
2023 directory_fetches_dir_info_later(old_options))) {
2024 /* Make sure update_router_have_minimum_dir_info() gets called. */
2025 router_dir_info_changed();
2026 /* We might need to download a new consensus status later or sooner than
2027 * we had expected. */
2028 update_consensus_networkstatus_fetch_time(time(NULL));
2032 /* Load the webpage we're going to serve every time someone asks for '/' on
2033 our DirPort. */
2034 tor_free(global_dirfrontpagecontents);
2035 if (options->DirPortFrontPage) {
2036 global_dirfrontpagecontents =
2037 read_file_to_str(options->DirPortFrontPage, 0, NULL);
2038 if (!global_dirfrontpagecontents) {
2039 log_warn(LD_CONFIG,
2040 "DirPortFrontPage file '%s' not found. Continuing anyway.",
2041 options->DirPortFrontPage);
2045 return 0;
2048 typedef enum {
2049 TAKES_NO_ARGUMENT = 0,
2050 ARGUMENT_NECESSARY = 1,
2051 ARGUMENT_OPTIONAL = 2
2052 } takes_argument_t;
2054 static const struct {
2055 const char *name;
2056 takes_argument_t takes_argument;
2057 } CMDLINE_ONLY_OPTIONS[] = {
2058 { "-f", ARGUMENT_NECESSARY },
2059 { "--allow-missing-torrc", TAKES_NO_ARGUMENT },
2060 { "--defaults-torrc", ARGUMENT_NECESSARY },
2061 { "--hash-password", ARGUMENT_NECESSARY },
2062 { "--dump-config", ARGUMENT_OPTIONAL },
2063 { "--list-fingerprint", TAKES_NO_ARGUMENT },
2064 { "--keygen", TAKES_NO_ARGUMENT },
2065 { "--newpass", TAKES_NO_ARGUMENT },
2066 { "--no-passphrase", TAKES_NO_ARGUMENT },
2067 { "--passphrase-fd", ARGUMENT_NECESSARY },
2068 { "--verify-config", TAKES_NO_ARGUMENT },
2069 { "--ignore-missing-torrc", TAKES_NO_ARGUMENT },
2070 { "--quiet", TAKES_NO_ARGUMENT },
2071 { "--hush", TAKES_NO_ARGUMENT },
2072 { "--version", TAKES_NO_ARGUMENT },
2073 { "--library-versions", TAKES_NO_ARGUMENT },
2074 { "-h", TAKES_NO_ARGUMENT },
2075 { "--help", TAKES_NO_ARGUMENT },
2076 { "--list-torrc-options", TAKES_NO_ARGUMENT },
2077 { "--list-deprecated-options",TAKES_NO_ARGUMENT },
2078 { "--nt-service", TAKES_NO_ARGUMENT },
2079 { "-nt-service", TAKES_NO_ARGUMENT },
2080 { NULL, 0 },
2083 /** Helper: Read a list of configuration options from the command line. If
2084 * successful, or if ignore_errors is set, put them in *<b>result</b>, put the
2085 * commandline-only options in *<b>cmdline_result</b>, and return 0;
2086 * otherwise, return -1 and leave *<b>result</b> and <b>cmdline_result</b>
2087 * alone. */
2089 config_parse_commandline(int argc, char **argv, int ignore_errors,
2090 config_line_t **result,
2091 config_line_t **cmdline_result)
2093 config_line_t *param = NULL;
2095 config_line_t *front = NULL;
2096 config_line_t **new = &front;
2098 config_line_t *front_cmdline = NULL;
2099 config_line_t **new_cmdline = &front_cmdline;
2101 char *s, *arg;
2102 int i = 1;
2104 while (i < argc) {
2105 unsigned command = CONFIG_LINE_NORMAL;
2106 takes_argument_t want_arg = ARGUMENT_NECESSARY;
2107 int is_cmdline = 0;
2108 int j;
2110 for (j = 0; CMDLINE_ONLY_OPTIONS[j].name != NULL; ++j) {
2111 if (!strcmp(argv[i], CMDLINE_ONLY_OPTIONS[j].name)) {
2112 is_cmdline = 1;
2113 want_arg = CMDLINE_ONLY_OPTIONS[j].takes_argument;
2114 break;
2118 s = argv[i];
2120 /* Each keyword may be prefixed with one or two dashes. */
2121 if (*s == '-')
2122 s++;
2123 if (*s == '-')
2124 s++;
2125 /* Figure out the command, if any. */
2126 if (*s == '+') {
2127 s++;
2128 command = CONFIG_LINE_APPEND;
2129 } else if (*s == '/') {
2130 s++;
2131 command = CONFIG_LINE_CLEAR;
2132 /* A 'clear' command has no argument. */
2133 want_arg = 0;
2136 const int is_last = (i == argc-1);
2138 if (want_arg == ARGUMENT_NECESSARY && is_last) {
2139 if (ignore_errors) {
2140 arg = tor_strdup("");
2141 } else {
2142 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
2143 argv[i]);
2144 config_free_lines(front);
2145 config_free_lines(front_cmdline);
2146 return -1;
2148 } else if (want_arg == ARGUMENT_OPTIONAL && is_last) {
2149 arg = tor_strdup("");
2150 } else {
2151 arg = (want_arg != TAKES_NO_ARGUMENT) ? tor_strdup(argv[i+1]) :
2152 tor_strdup("");
2155 param = tor_malloc_zero(sizeof(config_line_t));
2156 param->key = is_cmdline ? tor_strdup(argv[i]) :
2157 tor_strdup(config_expand_abbrev(&options_format, s, 1, 1));
2158 param->value = arg;
2159 param->command = command;
2160 param->next = NULL;
2161 log_debug(LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
2162 param->key, param->value);
2164 if (is_cmdline) {
2165 *new_cmdline = param;
2166 new_cmdline = &((*new_cmdline)->next);
2167 } else {
2168 *new = param;
2169 new = &((*new)->next);
2172 i += want_arg ? 2 : 1;
2174 *cmdline_result = front_cmdline;
2175 *result = front;
2176 return 0;
2179 /** Return true iff key is a valid configuration option. */
2181 option_is_recognized(const char *key)
2183 const config_var_t *var = config_find_option(&options_format, key);
2184 return (var != NULL);
2187 /** Return the canonical name of a configuration option, or NULL
2188 * if no such option exists. */
2189 const char *
2190 option_get_canonical_name(const char *key)
2192 const config_var_t *var = config_find_option(&options_format, key);
2193 return var ? var->name : NULL;
2196 /** Return a canonical list of the options assigned for key.
2198 config_line_t *
2199 option_get_assignment(const or_options_t *options, const char *key)
2201 return config_get_assigned_option(&options_format, options, key, 1);
2204 /** Try assigning <b>list</b> to the global options. You do this by duping
2205 * options, assigning list to the new one, then validating it. If it's
2206 * ok, then throw out the old one and stick with the new one. Else,
2207 * revert to old and return failure. Return SETOPT_OK on success, or
2208 * a setopt_err_t on failure.
2210 * If not success, point *<b>msg</b> to a newly allocated string describing
2211 * what went wrong.
2213 setopt_err_t
2214 options_trial_assign(config_line_t *list, unsigned flags, char **msg)
2216 int r;
2217 or_options_t *trial_options = config_dup(&options_format, get_options());
2219 if ((r=config_assign(&options_format, trial_options,
2220 list, flags, msg)) < 0) {
2221 or_options_free(trial_options);
2222 return r;
2225 if (options_validate(get_options_mutable(), trial_options,
2226 global_default_options, 1, msg) < 0) {
2227 or_options_free(trial_options);
2228 return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2231 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2232 or_options_free(trial_options);
2233 return SETOPT_ERR_TRANSITION;
2236 if (set_options(trial_options, msg)<0) {
2237 or_options_free(trial_options);
2238 return SETOPT_ERR_SETTING;
2241 /* we liked it. put it in place. */
2242 return SETOPT_OK;
2245 /** Print a usage message for tor. */
2246 static void
2247 print_usage(void)
2249 printf(
2250 "Copyright (c) 2001-2004, Roger Dingledine\n"
2251 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2252 "Copyright (c) 2007-2016, The Tor Project, Inc.\n\n"
2253 "tor -f <torrc> [args]\n"
2254 "See man page for options, or https://www.torproject.org/ for "
2255 "documentation.\n");
2258 /** Print all non-obsolete torrc options. */
2259 static void
2260 list_torrc_options(void)
2262 int i;
2263 for (i = 0; option_vars_[i].name; ++i) {
2264 const config_var_t *var = &option_vars_[i];
2265 if (var->type == CONFIG_TYPE_OBSOLETE ||
2266 var->type == CONFIG_TYPE_LINELIST_V)
2267 continue;
2268 printf("%s\n", var->name);
2272 /** Print all deprecated but non-obsolete torrc options. */
2273 static void
2274 list_deprecated_options(void)
2276 const config_deprecation_t *d;
2277 for (d = option_deprecation_notes_; d->name; ++d) {
2278 printf("%s\n", d->name);
2282 /** Last value actually set by resolve_my_address. */
2283 static uint32_t last_resolved_addr = 0;
2285 /** Accessor for last_resolved_addr from outside this file. */
2286 uint32_t
2287 get_last_resolved_addr(void)
2289 return last_resolved_addr;
2292 /** Reset last_resolved_addr from outside this file. */
2293 void
2294 reset_last_resolved_addr(void)
2296 last_resolved_addr = 0;
2299 /* Return true if <b>options</b> is using the default authorities, and false
2300 * if any authority-related option has been overridden. */
2302 using_default_dir_authorities(const or_options_t *options)
2304 return (!options->DirAuthorities && !options->AlternateDirAuthority);
2308 * Attempt getting our non-local (as judged by tor_addr_is_internal()
2309 * function) IP address using following techniques, listed in
2310 * order from best (most desirable, try first) to worst (least
2311 * desirable, try if everything else fails).
2313 * First, attempt using <b>options-\>Address</b> to get our
2314 * non-local IP address.
2316 * If <b>options-\>Address</b> represents a non-local IP address,
2317 * consider it ours.
2319 * If <b>options-\>Address</b> is a DNS name that resolves to
2320 * a non-local IP address, consider this IP address ours.
2322 * If <b>options-\>Address</b> is NULL, fall back to getting local
2323 * hostname and using it in above-described ways to try and
2324 * get our IP address.
2326 * In case local hostname cannot be resolved to a non-local IP
2327 * address, try getting an IP address of network interface
2328 * in hopes it will be non-local one.
2330 * Fail if one or more of the following is true:
2331 * - DNS name in <b>options-\>Address</b> cannot be resolved.
2332 * - <b>options-\>Address</b> is a local host address.
2333 * - Attempt to getting local hostname fails.
2334 * - Attempt to getting network interface address fails.
2336 * Return 0 if all is well, or -1 if we can't find a suitable
2337 * public IP address.
2339 * If we are returning 0:
2340 * - Put our public IP address (in host order) into *<b>addr_out</b>.
2341 * - If <b>method_out</b> is non-NULL, set *<b>method_out</b> to a static
2342 * string describing how we arrived at our answer.
2343 * - "CONFIGURED" - parsed from IP address string in
2344 * <b>options-\>Address</b>
2345 * - "RESOLVED" - resolved from DNS name in <b>options-\>Address</b>
2346 * - "GETHOSTNAME" - resolved from a local hostname.
2347 * - "INTERFACE" - retrieved from a network interface.
2348 * - If <b>hostname_out</b> is non-NULL, and we resolved a hostname to
2349 * get our address, set *<b>hostname_out</b> to a newly allocated string
2350 * holding that hostname. (If we didn't get our address by resolving a
2351 * hostname, set *<b>hostname_out</b> to NULL.)
2353 * XXXX ipv6
2356 resolve_my_address(int warn_severity, const or_options_t *options,
2357 uint32_t *addr_out,
2358 const char **method_out, char **hostname_out)
2360 struct in_addr in;
2361 uint32_t addr; /* host order */
2362 char hostname[256];
2363 const char *method_used;
2364 const char *hostname_used;
2365 int explicit_ip=1;
2366 int explicit_hostname=1;
2367 int from_interface=0;
2368 char *addr_string = NULL;
2369 const char *address = options->Address;
2370 int notice_severity = warn_severity <= LOG_NOTICE ?
2371 LOG_NOTICE : warn_severity;
2373 tor_addr_t myaddr;
2374 tor_assert(addr_out);
2377 * Step one: Fill in 'hostname' to be our best guess.
2380 if (address && *address) {
2381 strlcpy(hostname, address, sizeof(hostname));
2382 } else { /* then we need to guess our address */
2383 explicit_ip = 0; /* it's implicit */
2384 explicit_hostname = 0; /* it's implicit */
2386 if (tor_gethostname(hostname, sizeof(hostname)) < 0) {
2387 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2388 return -1;
2390 log_debug(LD_CONFIG, "Guessed local host name as '%s'", hostname);
2394 * Step two: Now that we know 'hostname', parse it or resolve it. If
2395 * it doesn't parse or resolve, look at the interface address. Set 'addr'
2396 * to be our (host-order) 32-bit answer.
2399 if (tor_inet_aton(hostname, &in) == 0) {
2400 /* then we have to resolve it */
2401 explicit_ip = 0;
2402 if (tor_lookup_hostname(hostname, &addr)) { /* failed to resolve */
2403 uint32_t interface_ip; /* host order */
2405 if (explicit_hostname) {
2406 log_fn(warn_severity, LD_CONFIG,
2407 "Could not resolve local Address '%s'. Failing.", hostname);
2408 return -1;
2410 log_fn(notice_severity, LD_CONFIG,
2411 "Could not resolve guessed local hostname '%s'. "
2412 "Trying something else.", hostname);
2413 if (get_interface_address(warn_severity, &interface_ip)) {
2414 log_fn(warn_severity, LD_CONFIG,
2415 "Could not get local interface IP address. Failing.");
2416 return -1;
2418 from_interface = 1;
2419 addr = interface_ip;
2420 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2421 "local interface. Using that.", fmt_addr32(addr));
2422 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2423 } else { /* resolved hostname into addr */
2424 tor_addr_from_ipv4h(&myaddr, addr);
2426 if (!explicit_hostname &&
2427 tor_addr_is_internal(&myaddr, 0)) {
2428 tor_addr_t interface_ip;
2430 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2431 "resolves to a private IP address (%s). Trying something "
2432 "else.", hostname, fmt_addr32(addr));
2434 if (get_interface_address6(warn_severity, AF_INET, &interface_ip)<0) {
2435 log_fn(warn_severity, LD_CONFIG,
2436 "Could not get local interface IP address. Too bad.");
2437 } else if (tor_addr_is_internal(&interface_ip, 0)) {
2438 log_fn(notice_severity, LD_CONFIG,
2439 "Interface IP address '%s' is a private address too. "
2440 "Ignoring.", fmt_addr(&interface_ip));
2441 } else {
2442 from_interface = 1;
2443 addr = tor_addr_to_ipv4h(&interface_ip);
2444 log_fn(notice_severity, LD_CONFIG,
2445 "Learned IP address '%s' for local interface."
2446 " Using that.", fmt_addr32(addr));
2447 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2451 } else {
2452 addr = ntohl(in.s_addr); /* set addr so that addr_string is not
2453 * illformed */
2457 * Step three: Check whether 'addr' is an internal IP address, and error
2458 * out if it is and we don't want that.
2461 tor_addr_from_ipv4h(&myaddr,addr);
2463 addr_string = tor_dup_ip(addr);
2464 if (tor_addr_is_internal(&myaddr, 0)) {
2465 /* make sure we're ok with publishing an internal IP */
2466 if (using_default_dir_authorities(options)) {
2467 /* if they are using the default authorities, disallow internal IPs
2468 * always. */
2469 log_fn(warn_severity, LD_CONFIG,
2470 "Address '%s' resolves to private IP address '%s'. "
2471 "Tor servers that use the default DirAuthorities must have "
2472 "public IP addresses.", hostname, addr_string);
2473 tor_free(addr_string);
2474 return -1;
2476 if (!explicit_ip) {
2477 /* even if they've set their own authorities, require an explicit IP if
2478 * they're using an internal address. */
2479 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2480 "IP address '%s'. Please set the Address config option to be "
2481 "the IP address you want to use.", hostname, addr_string);
2482 tor_free(addr_string);
2483 return -1;
2488 * Step four: We have a winner! 'addr' is our answer for sure, and
2489 * 'addr_string' is its string form. Fill out the various fields to
2490 * say how we decided it.
2493 log_debug(LD_CONFIG, "Resolved Address to '%s'.", addr_string);
2495 if (explicit_ip) {
2496 method_used = "CONFIGURED";
2497 hostname_used = NULL;
2498 } else if (explicit_hostname) {
2499 method_used = "RESOLVED";
2500 hostname_used = hostname;
2501 } else if (from_interface) {
2502 method_used = "INTERFACE";
2503 hostname_used = NULL;
2504 } else {
2505 method_used = "GETHOSTNAME";
2506 hostname_used = hostname;
2509 *addr_out = addr;
2510 if (method_out)
2511 *method_out = method_used;
2512 if (hostname_out)
2513 *hostname_out = hostname_used ? tor_strdup(hostname_used) : NULL;
2516 * Step five: Check if the answer has changed since last time (or if
2517 * there was no last time), and if so call various functions to keep
2518 * us up-to-date.
2521 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2522 /* Leave this as a notice, regardless of the requested severity,
2523 * at least until dynamic IP address support becomes bulletproof. */
2524 log_notice(LD_NET,
2525 "Your IP address seems to have changed to %s "
2526 "(METHOD=%s%s%s). Updating.",
2527 addr_string, method_used,
2528 hostname_used ? " HOSTNAME=" : "",
2529 hostname_used ? hostname_used : "");
2530 ip_address_changed(0);
2533 if (last_resolved_addr != *addr_out) {
2534 control_event_server_status(LOG_NOTICE,
2535 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s%s%s",
2536 addr_string, method_used,
2537 hostname_used ? " HOSTNAME=" : "",
2538 hostname_used ? hostname_used : "");
2540 last_resolved_addr = *addr_out;
2543 * And finally, clean up and return success.
2546 tor_free(addr_string);
2547 return 0;
2550 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2551 * on a private network.
2553 MOCK_IMPL(int,
2554 is_local_addr, (const tor_addr_t *addr))
2556 if (tor_addr_is_internal(addr, 0))
2557 return 1;
2558 /* Check whether ip is on the same /24 as we are. */
2559 if (get_options()->EnforceDistinctSubnets == 0)
2560 return 0;
2561 if (tor_addr_family(addr) == AF_INET) {
2562 uint32_t ip = tor_addr_to_ipv4h(addr);
2564 /* It's possible that this next check will hit before the first time
2565 * resolve_my_address actually succeeds. (For clients, it is likely that
2566 * resolve_my_address will never be called at all). In those cases,
2567 * last_resolved_addr will be 0, and so checking to see whether ip is on
2568 * the same /24 as last_resolved_addr will be the same as checking whether
2569 * it was on net 0, which is already done by tor_addr_is_internal.
2571 if ((last_resolved_addr & (uint32_t)0xffffff00ul)
2572 == (ip & (uint32_t)0xffffff00ul))
2573 return 1;
2575 return 0;
2578 /** Return a new empty or_options_t. Used for testing. */
2579 or_options_t *
2580 options_new(void)
2582 return config_new(&options_format);
2585 /** Set <b>options</b> to hold reasonable defaults for most options.
2586 * Each option defaults to zero. */
2587 void
2588 options_init(or_options_t *options)
2590 config_init(&options_format, options);
2593 /** Return a string containing a possible configuration file that would give
2594 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2595 * include options that are the same as Tor's defaults.
2597 char *
2598 options_dump(const or_options_t *options, int how_to_dump)
2600 const or_options_t *use_defaults;
2601 int minimal;
2602 switch (how_to_dump) {
2603 case OPTIONS_DUMP_MINIMAL:
2604 use_defaults = global_default_options;
2605 minimal = 1;
2606 break;
2607 case OPTIONS_DUMP_DEFAULTS:
2608 use_defaults = NULL;
2609 minimal = 1;
2610 break;
2611 case OPTIONS_DUMP_ALL:
2612 use_defaults = NULL;
2613 minimal = 0;
2614 break;
2615 default:
2616 log_warn(LD_BUG, "Bogus value for how_to_dump==%d", how_to_dump);
2617 return NULL;
2620 return config_dump(&options_format, use_defaults, options, minimal, 0);
2623 /** Return 0 if every element of sl is a string holding a decimal
2624 * representation of a port number, or if sl is NULL.
2625 * Otherwise set *msg and return -1. */
2626 static int
2627 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2629 int i;
2630 tor_assert(name);
2632 if (!sl)
2633 return 0;
2635 SMARTLIST_FOREACH(sl, const char *, cp,
2637 i = atoi(cp);
2638 if (i < 1 || i > 65535) {
2639 tor_asprintf(msg, "Port '%s' out of range in %s", cp, name);
2640 return -1;
2643 return 0;
2646 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2647 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2648 * Else return 0.
2650 static int
2651 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2653 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2654 /* This handles an understandable special case where somebody says "2gb"
2655 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2656 --*value;
2658 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2659 tor_asprintf(msg, "%s ("U64_FORMAT") must be at most %d",
2660 desc, U64_PRINTF_ARG(*value),
2661 ROUTER_MAX_DECLARED_BANDWIDTH);
2662 return -1;
2664 return 0;
2667 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2668 * and write it to <b>options</b>-\>PublishServerDescriptor_. Treat "1"
2669 * as "v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2670 * Treat "0" as "".
2671 * Return 0 on success or -1 if not a recognized authority type (in which
2672 * case the value of PublishServerDescriptor_ is undefined). */
2673 static int
2674 compute_publishserverdescriptor(or_options_t *options)
2676 smartlist_t *list = options->PublishServerDescriptor;
2677 dirinfo_type_t *auth = &options->PublishServerDescriptor_;
2678 *auth = NO_DIRINFO;
2679 if (!list) /* empty list, answer is none */
2680 return 0;
2681 SMARTLIST_FOREACH_BEGIN(list, const char *, string) {
2682 if (!strcasecmp(string, "v1"))
2683 log_warn(LD_CONFIG, "PublishServerDescriptor v1 has no effect, because "
2684 "there are no v1 directory authorities anymore.");
2685 else if (!strcmp(string, "1"))
2686 if (options->BridgeRelay)
2687 *auth |= BRIDGE_DIRINFO;
2688 else
2689 *auth |= V3_DIRINFO;
2690 else if (!strcasecmp(string, "v2"))
2691 log_warn(LD_CONFIG, "PublishServerDescriptor v2 has no effect, because "
2692 "there are no v2 directory authorities anymore.");
2693 else if (!strcasecmp(string, "v3"))
2694 *auth |= V3_DIRINFO;
2695 else if (!strcasecmp(string, "bridge"))
2696 *auth |= BRIDGE_DIRINFO;
2697 else if (!strcasecmp(string, "hidserv"))
2698 log_warn(LD_CONFIG,
2699 "PublishServerDescriptor hidserv is invalid. See "
2700 "PublishHidServDescriptors.");
2701 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2702 /* no authority */;
2703 else
2704 return -1;
2705 } SMARTLIST_FOREACH_END(string);
2706 return 0;
2709 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2710 * services can overload the directory system. */
2711 #define MIN_REND_POST_PERIOD (10*60)
2712 #define MIN_REND_POST_PERIOD_TESTING (5)
2714 /** Higest allowable value for PredictedPortsRelevanceTime; if this is
2715 * too high, our selection of exits will decrease for an extended
2716 * period of time to an uncomfortable level .*/
2717 #define MAX_PREDICTED_CIRCS_RELEVANCE (60*60)
2719 /** Highest allowable value for RendPostPeriod. */
2720 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2722 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2723 * will generate too many circuits and potentially overload the network. */
2724 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2726 /** Highest allowable value for MaxCircuitDirtiness: prevents time_t
2727 * overflows. */
2728 #define MAX_MAX_CIRCUIT_DIRTINESS (30*24*60*60)
2730 /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
2731 * will generate too many circuits and potentially overload the network. */
2732 #define MIN_CIRCUIT_STREAM_TIMEOUT 10
2734 /** Lowest allowable value for HeartbeatPeriod; if this is too low, we might
2735 * expose more information than we're comfortable with. */
2736 #define MIN_HEARTBEAT_PERIOD (30*60)
2738 /** Lowest recommended value for CircuitBuildTimeout; if it is set too low
2739 * and LearnCircuitBuildTimeout is off, the failure rate for circuit
2740 * construction may be very high. In that case, if it is set below this
2741 * threshold emit a warning.
2742 * */
2743 #define RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT (10)
2745 static int
2746 options_validate_cb(void *old_options, void *options, void *default_options,
2747 int from_setconf, char **msg)
2749 return options_validate(old_options, options, default_options,
2750 from_setconf, msg);
2753 #define REJECT(arg) \
2754 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2755 #if defined(__GNUC__) && __GNUC__ <= 3
2756 #define COMPLAIN(args...) \
2757 STMT_BEGIN log_warn(LD_CONFIG, args); STMT_END
2758 #else
2759 #define COMPLAIN(args, ...) \
2760 STMT_BEGIN log_warn(LD_CONFIG, args, ##__VA_ARGS__); STMT_END
2761 #endif
2763 /** Log a warning message iff <b>filepath</b> is not absolute.
2764 * Warning message must contain option name <b>option</b> and
2765 * an absolute path that <b>filepath</b> will resolve to.
2767 * In case <b>filepath</b> is absolute, do nothing.
2769 static void
2770 warn_if_option_path_is_relative(const char *option,
2771 char *filepath)
2773 if (filepath && path_is_relative(filepath)) {
2774 char *abs_path = make_path_absolute(filepath);
2775 COMPLAIN("Path for %s (%s) is relative and will resolve to %s."
2776 " Is this what you wanted?", option, filepath, abs_path);
2777 tor_free(abs_path);
2781 /** Scan <b>options</b> for occurances of relative file/directory
2782 * path and log a warning whenever it is found.
2784 static void
2785 warn_about_relative_paths(or_options_t *options)
2787 tor_assert(options);
2789 warn_if_option_path_is_relative("CookieAuthFile",
2790 options->CookieAuthFile);
2791 warn_if_option_path_is_relative("ExtORPortCookieAuthFile",
2792 options->ExtORPortCookieAuthFile);
2793 warn_if_option_path_is_relative("DirPortFrontPage",
2794 options->DirPortFrontPage);
2795 warn_if_option_path_is_relative("V3BandwidthsFile",
2796 options->V3BandwidthsFile);
2797 warn_if_option_path_is_relative("ControlPortWriteToFile",
2798 options->ControlPortWriteToFile);
2799 warn_if_option_path_is_relative("GeoIPFile",options->GeoIPFile);
2800 warn_if_option_path_is_relative("GeoIPv6File",options->GeoIPv6File);
2801 warn_if_option_path_is_relative("Log",options->DebugLogFile);
2802 warn_if_option_path_is_relative("AccelDir",options->AccelDir);
2803 warn_if_option_path_is_relative("DataDirectory",options->DataDirectory);
2804 warn_if_option_path_is_relative("PidFile",options->PidFile);
2806 for (config_line_t *hs_line = options->RendConfigLines; hs_line;
2807 hs_line = hs_line->next) {
2808 if (!strcasecmp(hs_line->key, "HiddenServiceDir"))
2809 warn_if_option_path_is_relative("HiddenServiceDir",hs_line->value);
2813 /* Validate options related to single onion services.
2814 * Modifies some options that are incompatible with single onion services.
2815 * On failure returns -1, and sets *msg to an error string.
2816 * Returns 0 on success. */
2817 STATIC int
2818 options_validate_single_onion(or_options_t *options, char **msg)
2820 /* The two single onion service options must have matching values. */
2821 if (options->HiddenServiceSingleHopMode &&
2822 !options->HiddenServiceNonAnonymousMode) {
2823 REJECT("HiddenServiceSingleHopMode does not provide any server anonymity. "
2824 "It must be used with HiddenServiceNonAnonymousMode set to 1.");
2826 if (options->HiddenServiceNonAnonymousMode &&
2827 !options->HiddenServiceSingleHopMode) {
2828 REJECT("HiddenServiceNonAnonymousMode does not provide any server "
2829 "anonymity. It must be used with HiddenServiceSingleHopMode set to "
2830 "1.");
2833 /* Now that we've checked that the two options are consistent, we can safely
2834 * call the rend_service_* functions that abstract these options. */
2836 /* If you run an anonymous client with an active Single Onion service, the
2837 * client loses anonymity. */
2838 const int client_port_set = (options->SocksPort_set ||
2839 options->TransPort_set ||
2840 options->NATDPort_set ||
2841 options->DNSPort_set);
2842 if (rend_service_non_anonymous_mode_enabled(options) && client_port_set &&
2843 !options->Tor2webMode) {
2844 REJECT("HiddenServiceNonAnonymousMode is incompatible with using Tor as "
2845 "an anonymous client. Please set Socks/Trans/NATD/DNSPort to 0, or "
2846 "HiddenServiceNonAnonymousMode to 0, or use the non-anonymous "
2847 "Tor2webMode.");
2850 /* If you run a hidden service in non-anonymous mode, the hidden service
2851 * loses anonymity, even if SOCKSPort / Tor2web mode isn't used. */
2852 if (!rend_service_non_anonymous_mode_enabled(options) &&
2853 options->RendConfigLines && options->Tor2webMode) {
2854 REJECT("Non-anonymous (Tor2web) mode is incompatible with using Tor as a "
2855 "hidden service. Please remove all HiddenServiceDir lines, or use "
2856 "a version of tor compiled without --enable-tor2web-mode, or use "
2857 " HiddenServiceNonAnonymousMode.");
2860 if (rend_service_allow_non_anonymous_connection(options)
2861 && options->UseEntryGuards) {
2862 /* Single Onion services only use entry guards when uploading descriptors,
2863 * all other connections are one-hop. Further, Single Onions causes the
2864 * hidden service code to do things which break the path bias
2865 * detector, and it's far easier to turn off entry guards (and
2866 * thus the path bias detector with it) than to figure out how to
2867 * make path bias compatible with single onions.
2869 log_notice(LD_CONFIG,
2870 "HiddenServiceSingleHopMode is enabled; disabling "
2871 "UseEntryGuards.");
2872 options->UseEntryGuards = 0;
2875 return 0;
2878 /** Return 0 if every setting in <b>options</b> is reasonable, is a
2879 * permissible transition from <b>old_options</b>, and none of the
2880 * testing-only settings differ from <b>default_options</b> unless in
2881 * testing mode. Else return -1. Should have no side effects, except for
2882 * normalizing the contents of <b>options</b>.
2884 * On error, tor_strdup an error explanation into *<b>msg</b>.
2886 * XXX
2887 * If <b>from_setconf</b>, we were called by the controller, and our
2888 * Log line should stay empty. If it's 0, then give us a default log
2889 * if there are no logs defined.
2891 STATIC int
2892 options_validate(or_options_t *old_options, or_options_t *options,
2893 or_options_t *default_options, int from_setconf, char **msg)
2895 int i;
2896 config_line_t *cl;
2897 const char *uname = get_uname();
2898 int n_ports=0;
2899 int world_writable_control_socket=0;
2901 tor_assert(msg);
2902 *msg = NULL;
2904 /* Set UseEntryGuards from the configured value, before we check it below.
2905 * We change UseEntryGuards whenn it's incompatible with other options,
2906 * but leave UseEntryGuards_option with the original value.
2907 * Always use the value of UseEntryGuards, not UseEntryGuards_option. */
2908 options->UseEntryGuards = options->UseEntryGuards_option;
2910 warn_about_relative_paths(options);
2912 if (server_mode(options) &&
2913 (!strcmpstart(uname, "Windows 95") ||
2914 !strcmpstart(uname, "Windows 98") ||
2915 !strcmpstart(uname, "Windows Me"))) {
2916 log_warn(LD_CONFIG, "Tor is running as a server, but you are "
2917 "running %s; this probably won't work. See "
2918 "https://www.torproject.org/docs/faq.html#BestOSForRelay "
2919 "for details.", uname);
2922 if (parse_ports(options, 1, msg, &n_ports,
2923 &world_writable_control_socket) < 0)
2924 return -1;
2926 if (parse_outbound_addresses(options, 1, msg) < 0)
2927 return -1;
2929 if (validate_data_directory(options)<0)
2930 REJECT("Invalid DataDirectory");
2932 if (options->Nickname == NULL) {
2933 if (server_mode(options)) {
2934 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
2936 } else {
2937 if (!is_legal_nickname(options->Nickname)) {
2938 tor_asprintf(msg,
2939 "Nickname '%s', nicknames must be between 1 and 19 characters "
2940 "inclusive, and must contain only the characters [a-zA-Z0-9].",
2941 options->Nickname);
2942 return -1;
2946 if (server_mode(options) && !options->ContactInfo)
2947 log_notice(LD_CONFIG, "Your ContactInfo config option is not set. "
2948 "Please consider setting it, so we can contact you if your server is "
2949 "misconfigured or something else goes wrong.");
2951 /* Special case on first boot if no Log options are given. */
2952 if (!options->Logs && !options->RunAsDaemon && !from_setconf) {
2953 if (quiet_level == 0)
2954 config_line_append(&options->Logs, "Log", "notice stdout");
2955 else if (quiet_level == 1)
2956 config_line_append(&options->Logs, "Log", "warn stdout");
2959 /* Validate the tor_log(s) */
2960 if (options_init_logs(old_options, options, 1)<0)
2961 REJECT("Failed to validate Log options. See logs for details.");
2963 if (authdir_mode(options)) {
2964 /* confirm that our address isn't broken, so we can complain now */
2965 uint32_t tmp;
2966 if (resolve_my_address(LOG_WARN, options, &tmp, NULL, NULL) < 0)
2967 REJECT("Failed to resolve/guess local address. See logs for details.");
2970 if (server_mode(options) && options->RendConfigLines)
2971 log_warn(LD_CONFIG,
2972 "Tor is currently configured as a relay and a hidden service. "
2973 "That's not very secure: you should probably run your hidden service "
2974 "in a separate Tor process, at least -- see "
2975 "https://trac.torproject.org/8742");
2977 /* XXXX require that the only port not be DirPort? */
2978 /* XXXX require that at least one port be listened-upon. */
2979 if (n_ports == 0 && !options->RendConfigLines)
2980 log_warn(LD_CONFIG,
2981 "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
2982 "undefined, and there aren't any hidden services configured. "
2983 "Tor will still run, but probably won't do anything.");
2985 options->TransProxyType_parsed = TPT_DEFAULT;
2986 #ifdef USE_TRANSPARENT
2987 if (options->TransProxyType) {
2988 if (!strcasecmp(options->TransProxyType, "default")) {
2989 options->TransProxyType_parsed = TPT_DEFAULT;
2990 } else if (!strcasecmp(options->TransProxyType, "pf-divert")) {
2991 #if !defined(__OpenBSD__) && !defined( DARWIN )
2992 /* Later versions of OS X have pf */
2993 REJECT("pf-divert is a OpenBSD-specific "
2994 "and OS X/Darwin-specific feature.");
2995 #else
2996 options->TransProxyType_parsed = TPT_PF_DIVERT;
2997 #endif
2998 } else if (!strcasecmp(options->TransProxyType, "tproxy")) {
2999 #if !defined(__linux__)
3000 REJECT("TPROXY is a Linux-specific feature.");
3001 #else
3002 options->TransProxyType_parsed = TPT_TPROXY;
3003 #endif
3004 } else if (!strcasecmp(options->TransProxyType, "ipfw")) {
3005 #ifndef KERNEL_MAY_SUPPORT_IPFW
3006 /* Earlier versions of OS X have ipfw */
3007 REJECT("ipfw is a FreeBSD-specific"
3008 "and OS X/Darwin-specific feature.");
3009 #else
3010 options->TransProxyType_parsed = TPT_IPFW;
3011 #endif
3012 } else {
3013 REJECT("Unrecognized value for TransProxyType");
3016 if (strcasecmp(options->TransProxyType, "default") &&
3017 !options->TransPort_set) {
3018 REJECT("Cannot use TransProxyType without any valid TransPort or "
3019 "TransListenAddress.");
3022 #else
3023 if (options->TransPort_set)
3024 REJECT("TransPort and TransListenAddress are disabled "
3025 "in this build.");
3026 #endif
3028 if (options->TokenBucketRefillInterval <= 0
3029 || options->TokenBucketRefillInterval > 1000) {
3030 REJECT("TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
3033 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3034 options->ExcludeExitNodesUnion_ = routerset_new();
3035 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeExitNodes);
3036 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeNodes);
3039 if (options->SchedulerLowWaterMark__ == 0 ||
3040 options->SchedulerLowWaterMark__ > UINT32_MAX) {
3041 log_warn(LD_GENERAL, "Bad SchedulerLowWaterMark__ option");
3042 return -1;
3043 } else if (options->SchedulerHighWaterMark__ <=
3044 options->SchedulerLowWaterMark__ ||
3045 options->SchedulerHighWaterMark__ > UINT32_MAX) {
3046 log_warn(LD_GENERAL, "Bad SchedulerHighWaterMark option");
3047 return -1;
3050 if (options->NodeFamilies) {
3051 options->NodeFamilySets = smartlist_new();
3052 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3053 routerset_t *rs = routerset_new();
3054 if (routerset_parse(rs, cl->value, cl->key) == 0) {
3055 smartlist_add(options->NodeFamilySets, rs);
3056 } else {
3057 routerset_free(rs);
3062 if (options->TLSECGroup && (strcasecmp(options->TLSECGroup, "P256") &&
3063 strcasecmp(options->TLSECGroup, "P224"))) {
3064 COMPLAIN("Unrecognized TLSECGroup: Falling back to the default.");
3065 tor_free(options->TLSECGroup);
3067 if (!evaluate_ecgroup_for_tls(options->TLSECGroup)) {
3068 REJECT("Unsupported TLSECGroup.");
3071 if (options->ExcludeNodes && options->StrictNodes) {
3072 COMPLAIN("You have asked to exclude certain relays from all positions "
3073 "in your circuits. Expect hidden services and other Tor "
3074 "features to be broken in unpredictable ways.");
3077 for (cl = options->RecommendedPackages; cl; cl = cl->next) {
3078 if (! validate_recommended_package_line(cl->value)) {
3079 log_warn(LD_CONFIG, "Invalid RecommendedPackage line %s will be ignored",
3080 escaped(cl->value));
3084 if (options->AuthoritativeDir) {
3085 if (!options->ContactInfo && !options->TestingTorNetwork)
3086 REJECT("Authoritative directory servers must set ContactInfo");
3087 if (!options->RecommendedClientVersions)
3088 options->RecommendedClientVersions =
3089 config_lines_dup(options->RecommendedVersions);
3090 if (!options->RecommendedServerVersions)
3091 options->RecommendedServerVersions =
3092 config_lines_dup(options->RecommendedVersions);
3093 if (options->VersioningAuthoritativeDir &&
3094 (!options->RecommendedClientVersions ||
3095 !options->RecommendedServerVersions))
3096 REJECT("Versioning authoritative dir servers must set "
3097 "Recommended*Versions.");
3098 if (options->UseEntryGuards) {
3099 log_info(LD_CONFIG, "Authoritative directory servers can't set "
3100 "UseEntryGuards. Disabling.");
3101 options->UseEntryGuards = 0;
3103 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
3104 log_info(LD_CONFIG, "Authoritative directories always try to download "
3105 "extra-info documents. Setting DownloadExtraInfo.");
3106 options->DownloadExtraInfo = 1;
3108 if (!(options->BridgeAuthoritativeDir ||
3109 options->V3AuthoritativeDir))
3110 REJECT("AuthoritativeDir is set, but none of "
3111 "(Bridge/V3)AuthoritativeDir is set.");
3112 /* If we have a v3bandwidthsfile and it's broken, complain on startup */
3113 if (options->V3BandwidthsFile && !old_options) {
3114 dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
3116 /* same for guardfraction file */
3117 if (options->GuardfractionFile && !old_options) {
3118 dirserv_read_guardfraction_file(options->GuardfractionFile, NULL);
3122 if (options->AuthoritativeDir && !options->DirPort_set)
3123 REJECT("Running as authoritative directory, but no DirPort set.");
3125 if (options->AuthoritativeDir && !options->ORPort_set)
3126 REJECT("Running as authoritative directory, but no ORPort set.");
3128 if (options->AuthoritativeDir && options->ClientOnly)
3129 REJECT("Running as authoritative directory, but ClientOnly also set.");
3131 if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
3132 REJECT("FetchDirInfoExtraEarly requires that you also set "
3133 "FetchDirInfoEarly");
3135 if (options->ConnLimit <= 0) {
3136 tor_asprintf(msg,
3137 "ConnLimit must be greater than 0, but was set to %d",
3138 options->ConnLimit);
3139 return -1;
3142 if (options->PathsNeededToBuildCircuits >= 0.0) {
3143 if (options->PathsNeededToBuildCircuits < 0.25) {
3144 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too low. Increasing "
3145 "to 0.25");
3146 options->PathsNeededToBuildCircuits = 0.25;
3147 } else if (options->PathsNeededToBuildCircuits > 0.95) {
3148 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too high. Decreasing "
3149 "to 0.95");
3150 options->PathsNeededToBuildCircuits = 0.95;
3154 if (options->MaxClientCircuitsPending <= 0 ||
3155 options->MaxClientCircuitsPending > MAX_MAX_CLIENT_CIRCUITS_PENDING) {
3156 tor_asprintf(msg,
3157 "MaxClientCircuitsPending must be between 1 and %d, but "
3158 "was set to %d", MAX_MAX_CLIENT_CIRCUITS_PENDING,
3159 options->MaxClientCircuitsPending);
3160 return -1;
3163 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3164 return -1;
3166 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3167 return -1;
3169 if (validate_ports_csv(options->RejectPlaintextPorts,
3170 "RejectPlaintextPorts", msg) < 0)
3171 return -1;
3173 if (validate_ports_csv(options->WarnPlaintextPorts,
3174 "WarnPlaintextPorts", msg) < 0)
3175 return -1;
3177 if (options->FascistFirewall && !options->ReachableAddresses) {
3178 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3179 /* We already have firewall ports set, so migrate them to
3180 * ReachableAddresses, which will set ReachableORAddresses and
3181 * ReachableDirAddresses if they aren't set explicitly. */
3182 smartlist_t *instead = smartlist_new();
3183 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3184 new_line->key = tor_strdup("ReachableAddresses");
3185 /* If we're configured with the old format, we need to prepend some
3186 * open ports. */
3187 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3189 int p = atoi(portno);
3190 if (p<0) continue;
3191 smartlist_add_asprintf(instead, "*:%d", p);
3193 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3194 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3195 log_notice(LD_CONFIG,
3196 "Converting FascistFirewall and FirewallPorts "
3197 "config options to new format: \"ReachableAddresses %s\"",
3198 new_line->value);
3199 options->ReachableAddresses = new_line;
3200 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3201 smartlist_free(instead);
3202 } else {
3203 /* We do not have FirewallPorts set, so add 80 to
3204 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3205 if (!options->ReachableDirAddresses) {
3206 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3207 new_line->key = tor_strdup("ReachableDirAddresses");
3208 new_line->value = tor_strdup("*:80");
3209 options->ReachableDirAddresses = new_line;
3210 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3211 "to new format: \"ReachableDirAddresses *:80\"");
3213 if (!options->ReachableORAddresses) {
3214 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3215 new_line->key = tor_strdup("ReachableORAddresses");
3216 new_line->value = tor_strdup("*:443");
3217 options->ReachableORAddresses = new_line;
3218 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3219 "to new format: \"ReachableORAddresses *:443\"");
3224 /* Terminate Reachable*Addresses with reject *
3226 for (i=0; i<3; i++) {
3227 config_line_t **linep =
3228 (i==0) ? &options->ReachableAddresses :
3229 (i==1) ? &options->ReachableORAddresses :
3230 &options->ReachableDirAddresses;
3231 if (!*linep)
3232 continue;
3233 /* We need to end with a reject *:*, not an implicit accept *:* */
3234 for (;;) {
3235 linep = &((*linep)->next);
3236 if (!*linep) {
3237 *linep = tor_malloc_zero(sizeof(config_line_t));
3238 (*linep)->key = tor_strdup(
3239 (i==0) ? "ReachableAddresses" :
3240 (i==1) ? "ReachableORAddresses" :
3241 "ReachableDirAddresses");
3242 (*linep)->value = tor_strdup("reject *:*");
3243 break;
3248 if ((options->ReachableAddresses ||
3249 options->ReachableORAddresses ||
3250 options->ReachableDirAddresses ||
3251 options->ClientUseIPv4 == 0) &&
3252 server_mode(options))
3253 REJECT("Servers must be able to freely connect to the rest "
3254 "of the Internet, so they must not set Reachable*Addresses "
3255 "or FascistFirewall or FirewallPorts or ClientUseIPv4 0.");
3257 /* We check if Reachable*Addresses blocks all addresses in
3258 * parse_reachable_addresses(). */
3260 #define WARN_PLEASE_USE_IPV6_LOG_MSG \
3261 "ClientPreferIPv6%sPort 1 is ignored unless tor is using IPv6. " \
3262 "Please set ClientUseIPv6 1, ClientUseIPv4 0, or configure bridges."
3264 if (!fascist_firewall_use_ipv6(options)
3265 && options->ClientPreferIPv6ORPort == 1)
3266 log_warn(LD_CONFIG, WARN_PLEASE_USE_IPV6_LOG_MSG, "OR");
3268 if (!fascist_firewall_use_ipv6(options)
3269 && options->ClientPreferIPv6DirPort == 1)
3270 log_warn(LD_CONFIG, WARN_PLEASE_USE_IPV6_LOG_MSG, "Dir");
3272 #undef WARN_PLEASE_USE_IPV6_LOG_MSG
3274 if (options->UseBridges &&
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 UseBridges.");
3279 /* If both of these are set, we'll end up with funny behavior where we
3280 * demand enough entrynodes be up and running else we won't build
3281 * circuits, yet we never actually use them. */
3282 if (options->UseBridges && options->EntryNodes)
3283 REJECT("You cannot set both UseBridges and EntryNodes.");
3285 options->MaxMemInQueues =
3286 compute_real_max_mem_in_queues(options->MaxMemInQueues_raw,
3287 server_mode(options));
3288 options->MaxMemInQueues_low_threshold = (options->MaxMemInQueues / 4) * 3;
3290 options->AllowInvalid_ = 0;
3292 if (options->AllowInvalidNodes) {
3293 SMARTLIST_FOREACH_BEGIN(options->AllowInvalidNodes, const char *, cp) {
3294 if (!strcasecmp(cp, "entry"))
3295 options->AllowInvalid_ |= ALLOW_INVALID_ENTRY;
3296 else if (!strcasecmp(cp, "exit"))
3297 options->AllowInvalid_ |= ALLOW_INVALID_EXIT;
3298 else if (!strcasecmp(cp, "middle"))
3299 options->AllowInvalid_ |= ALLOW_INVALID_MIDDLE;
3300 else if (!strcasecmp(cp, "introduction"))
3301 options->AllowInvalid_ |= ALLOW_INVALID_INTRODUCTION;
3302 else if (!strcasecmp(cp, "rendezvous"))
3303 options->AllowInvalid_ |= ALLOW_INVALID_RENDEZVOUS;
3304 else {
3305 tor_asprintf(msg,
3306 "Unrecognized value '%s' in AllowInvalidNodes", cp);
3307 return -1;
3309 } SMARTLIST_FOREACH_END(cp);
3312 if (!options->SafeLogging ||
3313 !strcasecmp(options->SafeLogging, "0")) {
3314 options->SafeLogging_ = SAFELOG_SCRUB_NONE;
3315 } else if (!strcasecmp(options->SafeLogging, "relay")) {
3316 options->SafeLogging_ = SAFELOG_SCRUB_RELAY;
3317 } else if (!strcasecmp(options->SafeLogging, "1")) {
3318 options->SafeLogging_ = SAFELOG_SCRUB_ALL;
3319 } else {
3320 tor_asprintf(msg,
3321 "Unrecognized value '%s' in SafeLogging",
3322 escaped(options->SafeLogging));
3323 return -1;
3326 if (compute_publishserverdescriptor(options) < 0) {
3327 tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
3328 return -1;
3331 if ((options->BridgeRelay
3332 || options->PublishServerDescriptor_ & BRIDGE_DIRINFO)
3333 && (options->PublishServerDescriptor_ & V3_DIRINFO)) {
3334 REJECT("Bridges are not supposed to publish router descriptors to the "
3335 "directory authorities. Please correct your "
3336 "PublishServerDescriptor line.");
3339 if (options->BridgeRelay && options->DirPort_set) {
3340 log_warn(LD_CONFIG, "Can't set a DirPort on a bridge relay; disabling "
3341 "DirPort");
3342 config_free_lines(options->DirPort_lines);
3343 options->DirPort_lines = NULL;
3344 options->DirPort_set = 0;
3347 if (options->MinUptimeHidServDirectoryV2 < 0) {
3348 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3349 "least 0 seconds. Changing to 0.");
3350 options->MinUptimeHidServDirectoryV2 = 0;
3353 const int min_rendpostperiod =
3354 options->TestingTorNetwork ?
3355 MIN_REND_POST_PERIOD_TESTING : MIN_REND_POST_PERIOD;
3356 if (options->RendPostPeriod < min_rendpostperiod) {
3357 log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
3358 "raising to %d seconds.", min_rendpostperiod);
3359 options->RendPostPeriod = min_rendpostperiod;;
3362 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3363 log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3364 MAX_DIR_PERIOD);
3365 options->RendPostPeriod = MAX_DIR_PERIOD;
3368 if (options->PredictedPortsRelevanceTime >
3369 MAX_PREDICTED_CIRCS_RELEVANCE) {
3370 log_warn(LD_CONFIG, "PredictedPortsRelevanceTime is too large; "
3371 "clipping to %ds.", MAX_PREDICTED_CIRCS_RELEVANCE);
3372 options->PredictedPortsRelevanceTime = MAX_PREDICTED_CIRCS_RELEVANCE;
3375 /* Check the Single Onion Service options */
3376 if (options_validate_single_onion(options, msg) < 0)
3377 return -1;
3379 #ifdef ENABLE_TOR2WEB_MODE
3380 if (options->Tor2webMode && options->UseEntryGuards) {
3381 /* tor2web mode clients do not (and should not) use entry guards
3382 * in any meaningful way. Further, tor2web mode causes the hidden
3383 * service client code to do things which break the path bias
3384 * detector, and it's far easier to turn off entry guards (and
3385 * thus the path bias detector with it) than to figure out how to
3386 * make a piece of code which cannot possibly help tor2web mode
3387 * users compatible with tor2web mode.
3389 log_notice(LD_CONFIG,
3390 "Tor2WebMode is enabled; disabling UseEntryGuards.");
3391 options->UseEntryGuards = 0;
3393 #endif
3395 if (options->Tor2webRendezvousPoints && !options->Tor2webMode) {
3396 REJECT("Tor2webRendezvousPoints cannot be set without Tor2webMode.");
3399 if (options->EntryNodes && !options->UseEntryGuards) {
3400 REJECT("If EntryNodes is set, UseEntryGuards must be enabled.");
3403 if (!(options->UseEntryGuards) &&
3404 (options->RendConfigLines != NULL) &&
3405 !rend_service_allow_non_anonymous_connection(options)) {
3406 log_warn(LD_CONFIG,
3407 "UseEntryGuards is disabled, but you have configured one or more "
3408 "hidden services on this Tor instance. Your hidden services "
3409 "will be very easy to locate using a well-known attack -- see "
3410 "http://freehaven.net/anonbib/#hs-attack06 for details.");
3413 if (options->EntryNodes &&
3414 routerset_is_list(options->EntryNodes) &&
3415 (routerset_len(options->EntryNodes) == 1) &&
3416 (options->RendConfigLines != NULL)) {
3417 tor_asprintf(msg,
3418 "You have one single EntryNodes and at least one hidden service "
3419 "configured. This is bad because it's very easy to locate your "
3420 "entry guard which can then lead to the deanonymization of your "
3421 "hidden service -- for more details, see "
3422 "https://trac.torproject.org/projects/tor/ticket/14917. "
3423 "For this reason, the use of one EntryNodes with an hidden "
3424 "service is prohibited until a better solution is found.");
3425 return -1;
3428 /* Single Onion Services: non-anonymous hidden services */
3429 if (rend_service_non_anonymous_mode_enabled(options)) {
3430 log_warn(LD_CONFIG,
3431 "HiddenServiceNonAnonymousMode is set. Every hidden service on "
3432 "this tor instance is NON-ANONYMOUS. If "
3433 "the HiddenServiceNonAnonymousMode option is changed, Tor will "
3434 "refuse to launch hidden services from the same directories, to "
3435 "protect your anonymity against config errors. This setting is "
3436 "for experimental use only.");
3439 if (!options->LearnCircuitBuildTimeout && options->CircuitBuildTimeout &&
3440 options->CircuitBuildTimeout < RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT) {
3441 log_warn(LD_CONFIG,
3442 "CircuitBuildTimeout is shorter (%d seconds) than the recommended "
3443 "minimum (%d seconds), and LearnCircuitBuildTimeout is disabled. "
3444 "If tor isn't working, raise this value or enable "
3445 "LearnCircuitBuildTimeout.",
3446 options->CircuitBuildTimeout,
3447 RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT );
3448 } else if (!options->LearnCircuitBuildTimeout &&
3449 !options->CircuitBuildTimeout) {
3450 int severity = LOG_NOTICE;
3451 /* Be a little quieter if we've deliberately disabled
3452 * LearnCircuitBuildTimeout. */
3453 if (circuit_build_times_disabled()) {
3454 severity = LOG_INFO;
3456 log_fn(severity, LD_CONFIG, "You disabled LearnCircuitBuildTimeout, but "
3457 "didn't specify a CircuitBuildTimeout. I'll pick a plausible "
3458 "default.");
3461 if (options->PathBiasNoticeRate > 1.0) {
3462 tor_asprintf(msg,
3463 "PathBiasNoticeRate is too high. "
3464 "It must be between 0 and 1.0");
3465 return -1;
3467 if (options->PathBiasWarnRate > 1.0) {
3468 tor_asprintf(msg,
3469 "PathBiasWarnRate is too high. "
3470 "It must be between 0 and 1.0");
3471 return -1;
3473 if (options->PathBiasExtremeRate > 1.0) {
3474 tor_asprintf(msg,
3475 "PathBiasExtremeRate is too high. "
3476 "It must be between 0 and 1.0");
3477 return -1;
3479 if (options->PathBiasNoticeUseRate > 1.0) {
3480 tor_asprintf(msg,
3481 "PathBiasNoticeUseRate is too high. "
3482 "It must be between 0 and 1.0");
3483 return -1;
3485 if (options->PathBiasExtremeUseRate > 1.0) {
3486 tor_asprintf(msg,
3487 "PathBiasExtremeUseRate is too high. "
3488 "It must be between 0 and 1.0");
3489 return -1;
3492 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3493 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3494 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3495 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3498 if (options->MaxCircuitDirtiness > MAX_MAX_CIRCUIT_DIRTINESS) {
3499 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too high; "
3500 "setting to %d days.", MAX_MAX_CIRCUIT_DIRTINESS/86400);
3501 options->MaxCircuitDirtiness = MAX_MAX_CIRCUIT_DIRTINESS;
3504 if (options->CircuitStreamTimeout &&
3505 options->CircuitStreamTimeout < MIN_CIRCUIT_STREAM_TIMEOUT) {
3506 log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
3507 "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
3508 options->CircuitStreamTimeout = MIN_CIRCUIT_STREAM_TIMEOUT;
3511 if (options->HeartbeatPeriod &&
3512 options->HeartbeatPeriod < MIN_HEARTBEAT_PERIOD) {
3513 log_warn(LD_CONFIG, "HeartbeatPeriod option is too short; "
3514 "raising to %d seconds.", MIN_HEARTBEAT_PERIOD);
3515 options->HeartbeatPeriod = MIN_HEARTBEAT_PERIOD;
3518 if (options->KeepalivePeriod < 1)
3519 REJECT("KeepalivePeriod option must be positive.");
3521 if (options->PortForwarding && options->Sandbox) {
3522 REJECT("PortForwarding is not compatible with Sandbox; at most one can "
3523 "be set");
3526 if (ensure_bandwidth_cap(&options->BandwidthRate,
3527 "BandwidthRate", msg) < 0)
3528 return -1;
3529 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3530 "BandwidthBurst", msg) < 0)
3531 return -1;
3532 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3533 "MaxAdvertisedBandwidth", msg) < 0)
3534 return -1;
3535 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3536 "RelayBandwidthRate", msg) < 0)
3537 return -1;
3538 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3539 "RelayBandwidthBurst", msg) < 0)
3540 return -1;
3541 if (ensure_bandwidth_cap(&options->PerConnBWRate,
3542 "PerConnBWRate", msg) < 0)
3543 return -1;
3544 if (ensure_bandwidth_cap(&options->PerConnBWBurst,
3545 "PerConnBWBurst", msg) < 0)
3546 return -1;
3547 if (ensure_bandwidth_cap(&options->AuthDirFastGuarantee,
3548 "AuthDirFastGuarantee", msg) < 0)
3549 return -1;
3550 if (ensure_bandwidth_cap(&options->AuthDirGuardBWGuarantee,
3551 "AuthDirGuardBWGuarantee", msg) < 0)
3552 return -1;
3554 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3555 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3556 if (options->RelayBandwidthBurst && !options->RelayBandwidthRate)
3557 options->RelayBandwidthRate = options->RelayBandwidthBurst;
3559 if (server_mode(options)) {
3560 const unsigned required_min_bw =
3561 public_server_mode(options) ?
3562 RELAY_REQUIRED_MIN_BANDWIDTH : BRIDGE_REQUIRED_MIN_BANDWIDTH;
3563 const char * const optbridge =
3564 public_server_mode(options) ? "" : "bridge ";
3565 if (options->BandwidthRate < required_min_bw) {
3566 tor_asprintf(msg,
3567 "BandwidthRate is set to %d bytes/second. "
3568 "For %sservers, it must be at least %u.",
3569 (int)options->BandwidthRate, optbridge,
3570 required_min_bw);
3571 return -1;
3572 } else if (options->MaxAdvertisedBandwidth <
3573 required_min_bw/2) {
3574 tor_asprintf(msg,
3575 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3576 "For %sservers, it must be at least %u.",
3577 (int)options->MaxAdvertisedBandwidth, optbridge,
3578 required_min_bw/2);
3579 return -1;
3581 if (options->RelayBandwidthRate &&
3582 options->RelayBandwidthRate < required_min_bw) {
3583 tor_asprintf(msg,
3584 "RelayBandwidthRate is set to %d bytes/second. "
3585 "For %sservers, it must be at least %u.",
3586 (int)options->RelayBandwidthRate, optbridge,
3587 required_min_bw);
3588 return -1;
3592 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3593 REJECT("RelayBandwidthBurst must be at least equal "
3594 "to RelayBandwidthRate.");
3596 if (options->BandwidthRate > options->BandwidthBurst)
3597 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3599 /* if they set relaybandwidth* really high but left bandwidth*
3600 * at the default, raise the defaults. */
3601 if (options->RelayBandwidthRate > options->BandwidthRate)
3602 options->BandwidthRate = options->RelayBandwidthRate;
3603 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3604 options->BandwidthBurst = options->RelayBandwidthBurst;
3606 if (accounting_parse_options(options, 1)<0)
3607 REJECT("Failed to parse accounting options. See logs for details.");
3609 if (options->AccountingMax) {
3610 if (options->RendConfigLines && server_mode(options)) {
3611 log_warn(LD_CONFIG, "Using accounting with a hidden service and an "
3612 "ORPort is risky: your hidden service(s) and your public "
3613 "address will all turn off at the same time, which may alert "
3614 "observers that they are being run by the same party.");
3615 } else if (config_count_key(options->RendConfigLines,
3616 "HiddenServiceDir") > 1) {
3617 log_warn(LD_CONFIG, "Using accounting with multiple hidden services is "
3618 "risky: they will all turn off at the same time, which may "
3619 "alert observers that they are being run by the same party.");
3623 options->AccountingRule = ACCT_MAX;
3624 if (options->AccountingRule_option) {
3625 if (!strcmp(options->AccountingRule_option, "sum"))
3626 options->AccountingRule = ACCT_SUM;
3627 else if (!strcmp(options->AccountingRule_option, "max"))
3628 options->AccountingRule = ACCT_MAX;
3629 else if (!strcmp(options->AccountingRule_option, "in"))
3630 options->AccountingRule = ACCT_IN;
3631 else if (!strcmp(options->AccountingRule_option, "out"))
3632 options->AccountingRule = ACCT_OUT;
3633 else
3634 REJECT("AccountingRule must be 'sum', 'max', 'in', or 'out'");
3637 if (options->DirPort_set && !options->DirCache) {
3638 REJECT("DirPort configured but DirCache disabled. DirPort requires "
3639 "DirCache.");
3642 if (options->BridgeRelay && !options->DirCache) {
3643 REJECT("We're a bridge but DirCache is disabled. BridgeRelay requires "
3644 "DirCache.");
3647 if (server_mode(options)) {
3648 char *dircache_msg = NULL;
3649 if (have_enough_mem_for_dircache(options, 0, &dircache_msg)) {
3650 log_warn(LD_CONFIG, "%s", dircache_msg);
3651 tor_free(dircache_msg);
3655 if (options->HTTPProxy) { /* parse it now */
3656 if (tor_addr_port_lookup(options->HTTPProxy,
3657 &options->HTTPProxyAddr, &options->HTTPProxyPort) < 0)
3658 REJECT("HTTPProxy failed to parse or resolve. Please fix.");
3659 if (options->HTTPProxyPort == 0) { /* give it a default */
3660 options->HTTPProxyPort = 80;
3664 if (options->HTTPProxyAuthenticator) {
3665 if (strlen(options->HTTPProxyAuthenticator) >= 512)
3666 REJECT("HTTPProxyAuthenticator is too long (>= 512 chars).");
3669 if (options->HTTPSProxy) { /* parse it now */
3670 if (tor_addr_port_lookup(options->HTTPSProxy,
3671 &options->HTTPSProxyAddr, &options->HTTPSProxyPort) <0)
3672 REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
3673 if (options->HTTPSProxyPort == 0) { /* give it a default */
3674 options->HTTPSProxyPort = 443;
3678 if (options->HTTPSProxyAuthenticator) {
3679 if (strlen(options->HTTPSProxyAuthenticator) >= 512)
3680 REJECT("HTTPSProxyAuthenticator is too long (>= 512 chars).");
3683 if (options->Socks4Proxy) { /* parse it now */
3684 if (tor_addr_port_lookup(options->Socks4Proxy,
3685 &options->Socks4ProxyAddr,
3686 &options->Socks4ProxyPort) <0)
3687 REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
3688 if (options->Socks4ProxyPort == 0) { /* give it a default */
3689 options->Socks4ProxyPort = 1080;
3693 if (options->Socks5Proxy) { /* parse it now */
3694 if (tor_addr_port_lookup(options->Socks5Proxy,
3695 &options->Socks5ProxyAddr,
3696 &options->Socks5ProxyPort) <0)
3697 REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
3698 if (options->Socks5ProxyPort == 0) { /* give it a default */
3699 options->Socks5ProxyPort = 1080;
3703 /* Check if more than one exclusive proxy type has been enabled. */
3704 if (!!options->Socks4Proxy + !!options->Socks5Proxy +
3705 !!options->HTTPSProxy > 1)
3706 REJECT("You have configured more than one proxy type. "
3707 "(Socks4Proxy|Socks5Proxy|HTTPSProxy)");
3709 /* Check if the proxies will give surprising behavior. */
3710 if (options->HTTPProxy && !(options->Socks4Proxy ||
3711 options->Socks5Proxy ||
3712 options->HTTPSProxy)) {
3713 log_warn(LD_CONFIG, "HTTPProxy configured, but no SOCKS proxy or "
3714 "HTTPS proxy configured. Watch out: this configuration will "
3715 "proxy unencrypted directory connections only.");
3718 if (options->Socks5ProxyUsername) {
3719 size_t len;
3721 len = strlen(options->Socks5ProxyUsername);
3722 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
3723 REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
3725 if (!options->Socks5ProxyPassword)
3726 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3728 len = strlen(options->Socks5ProxyPassword);
3729 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
3730 REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
3731 } else if (options->Socks5ProxyPassword)
3732 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3734 if (options->HashedControlPassword) {
3735 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3736 if (!sl) {
3737 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3738 } else {
3739 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3740 smartlist_free(sl);
3744 if (options->HashedControlSessionPassword) {
3745 smartlist_t *sl = decode_hashed_passwords(
3746 options->HashedControlSessionPassword);
3747 if (!sl) {
3748 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3749 } else {
3750 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3751 smartlist_free(sl);
3755 if (options->OwningControllerProcess) {
3756 const char *validate_pspec_msg = NULL;
3757 if (tor_validate_process_specifier(options->OwningControllerProcess,
3758 &validate_pspec_msg)) {
3759 tor_asprintf(msg, "Bad OwningControllerProcess: %s",
3760 validate_pspec_msg);
3761 return -1;
3765 if ((options->ControlPort_set || world_writable_control_socket) &&
3766 !options->HashedControlPassword &&
3767 !options->HashedControlSessionPassword &&
3768 !options->CookieAuthentication) {
3769 log_warn(LD_CONFIG, "Control%s is %s, but no authentication method "
3770 "has been configured. This means that any program on your "
3771 "computer can reconfigure your Tor. That's bad! You should "
3772 "upgrade your Tor controller as soon as possible.",
3773 options->ControlPort_set ? "Port" : "Socket",
3774 options->ControlPort_set ? "open" : "world writable");
3777 if (options->CookieAuthFileGroupReadable && !options->CookieAuthFile) {
3778 log_warn(LD_CONFIG, "CookieAuthFileGroupReadable is set, but will have "
3779 "no effect: you must specify an explicit CookieAuthFile to "
3780 "have it group-readable.");
3783 if (options->MyFamily && options->BridgeRelay) {
3784 log_warn(LD_CONFIG, "Listing a family for a bridge relay is not "
3785 "supported: it can reveal bridge fingerprints to censors. "
3786 "You should also make sure you aren't listing this bridge's "
3787 "fingerprint in any other MyFamily.");
3789 if (check_nickname_list(&options->MyFamily, "MyFamily", msg))
3790 return -1;
3791 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3792 routerset_t *rs = routerset_new();
3793 if (routerset_parse(rs, cl->value, cl->key)) {
3794 routerset_free(rs);
3795 return -1;
3797 routerset_free(rs);
3800 if (validate_addr_policies(options, msg) < 0)
3801 return -1;
3803 /* If FallbackDir is set, we don't UseDefaultFallbackDirs */
3804 if (options->UseDefaultFallbackDirs && options->FallbackDir) {
3805 log_info(LD_CONFIG, "You have set UseDefaultFallbackDirs 1 and "
3806 "FallbackDir(s). Ignoring UseDefaultFallbackDirs, and "
3807 "using the FallbackDir(s) you have set.");
3810 if (validate_dir_servers(options, old_options) < 0)
3811 REJECT("Directory authority/fallback line did not parse. See logs "
3812 "for details.");
3814 if (options->UseBridges && !options->Bridges)
3815 REJECT("If you set UseBridges, you must specify at least one bridge.");
3817 for (cl = options->Bridges; cl; cl = cl->next) {
3818 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
3819 if (!bridge_line)
3820 REJECT("Bridge line did not parse. See logs for details.");
3821 bridge_line_free(bridge_line);
3824 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
3825 if (parse_transport_line(options, cl->value, 1, 0) < 0)
3826 REJECT("Invalid client transport line. See logs for details.");
3829 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
3830 if (parse_transport_line(options, cl->value, 1, 1) < 0)
3831 REJECT("Invalid server transport line. See logs for details.");
3834 if (options->ServerTransportPlugin && !server_mode(options)) {
3835 log_notice(LD_GENERAL, "Tor is not configured as a relay but you specified"
3836 " a ServerTransportPlugin line (%s). The ServerTransportPlugin "
3837 "line will be ignored.",
3838 escaped(options->ServerTransportPlugin->value));
3841 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
3842 /** If get_bindaddr_from_transport_listen_line() fails with
3843 'transport' being NULL, it means that something went wrong
3844 while parsing the ServerTransportListenAddr line. */
3845 char *bindaddr = get_bindaddr_from_transport_listen_line(cl->value, NULL);
3846 if (!bindaddr)
3847 REJECT("ServerTransportListenAddr did not parse. See logs for details.");
3848 tor_free(bindaddr);
3851 if (options->ServerTransportListenAddr && !options->ServerTransportPlugin) {
3852 log_notice(LD_GENERAL, "You need at least a single managed-proxy to "
3853 "specify a transport listen address. The "
3854 "ServerTransportListenAddr line will be ignored.");
3857 for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
3858 /** If get_options_from_transport_options_line() fails with
3859 'transport' being NULL, it means that something went wrong
3860 while parsing the ServerTransportOptions line. */
3861 smartlist_t *options_sl =
3862 get_options_from_transport_options_line(cl->value, NULL);
3863 if (!options_sl)
3864 REJECT("ServerTransportOptions did not parse. See logs for details.");
3866 SMARTLIST_FOREACH(options_sl, char *, cp, tor_free(cp));
3867 smartlist_free(options_sl);
3870 if (options->ConstrainedSockets) {
3871 /* If the user wants to constrain socket buffer use, make sure the desired
3872 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3873 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3874 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3875 options->ConstrainedSockSize % 1024) {
3876 tor_asprintf(msg,
3877 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3878 "in 1024 byte increments.",
3879 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3880 return -1;
3882 if (options->DirPort_set) {
3883 /* Providing cached directory entries while system TCP buffers are scarce
3884 * will exacerbate the socket errors. Suggest that this be disabled. */
3885 COMPLAIN("You have requested constrained socket buffers while also "
3886 "serving directory entries via DirPort. It is strongly "
3887 "suggested that you disable serving directory requests when "
3888 "system TCP buffer resources are scarce.");
3892 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3893 options->V3AuthVotingInterval/2) {
3895 This doesn't work, but it seems like it should:
3896 what code is preventing the interval being less than twice the lead-up?
3897 if (options->TestingTorNetwork) {
3898 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3899 options->V3AuthVotingInterval) {
3900 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than "
3901 "V3AuthVotingInterval");
3902 } else {
3903 COMPLAIN("V3AuthVoteDelay plus V3AuthDistDelay is more than half "
3904 "V3AuthVotingInterval. This may lead to "
3905 "consensus instability, particularly if clocks drift.");
3907 } else {
3909 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3910 "V3AuthVotingInterval");
3916 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS) {
3917 if (options->TestingTorNetwork) {
3918 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS_TESTING) {
3919 REJECT("V3AuthVoteDelay is way too low.");
3920 } else {
3921 COMPLAIN("V3AuthVoteDelay is very low. "
3922 "This may lead to failure to vote for a consensus.");
3924 } else {
3925 REJECT("V3AuthVoteDelay is way too low.");
3929 if (options->V3AuthDistDelay < MIN_DIST_SECONDS) {
3930 if (options->TestingTorNetwork) {
3931 if (options->V3AuthDistDelay < MIN_DIST_SECONDS_TESTING) {
3932 REJECT("V3AuthDistDelay is way too low.");
3933 } else {
3934 COMPLAIN("V3AuthDistDelay is very low. "
3935 "This may lead to missing votes in a consensus.");
3937 } else {
3938 REJECT("V3AuthDistDelay is way too low.");
3942 if (options->V3AuthNIntervalsValid < 2)
3943 REJECT("V3AuthNIntervalsValid must be at least 2.");
3945 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3946 if (options->TestingTorNetwork) {
3947 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL_TESTING) {
3948 REJECT("V3AuthVotingInterval is insanely low.");
3949 } else {
3950 COMPLAIN("V3AuthVotingInterval is very low. "
3951 "This may lead to failure to synchronise for a consensus.");
3953 } else {
3954 REJECT("V3AuthVotingInterval is insanely low.");
3956 } else if (options->V3AuthVotingInterval > 24*60*60) {
3957 REJECT("V3AuthVotingInterval is insanely high.");
3958 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3959 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3962 if (rend_config_services(options, 1) < 0)
3963 REJECT("Failed to configure rendezvous options. See logs for details.");
3965 /* Parse client-side authorization for hidden services. */
3966 if (rend_parse_service_authorization(options, 1) < 0)
3967 REJECT("Failed to configure client authorization for hidden services. "
3968 "See logs for details.");
3970 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv4,
3971 AF_INET, 1, msg)<0)
3972 return -1;
3973 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv6,
3974 AF_INET6, 1, msg)<0)
3975 return -1;
3977 if (options->TestingTorNetwork &&
3978 !(options->DirAuthorities ||
3979 (options->AlternateDirAuthority &&
3980 options->AlternateBridgeAuthority))) {
3981 REJECT("TestingTorNetwork may only be configured in combination with "
3982 "a non-default set of DirAuthority or both of "
3983 "AlternateDirAuthority and AlternateBridgeAuthority configured.");
3986 if (options->AllowSingleHopExits && !options->DirAuthorities) {
3987 COMPLAIN("You have set AllowSingleHopExits; now your relay will allow "
3988 "others to make one-hop exits. However, since by default most "
3989 "clients avoid relays that set this option, most clients will "
3990 "ignore you.");
3993 #define CHECK_DEFAULT(arg) \
3994 STMT_BEGIN \
3995 if (!options->TestingTorNetwork && \
3996 !options->UsingTestNetworkDefaults_ && \
3997 !config_is_same(&options_format,options, \
3998 default_options,#arg)) { \
3999 REJECT(#arg " may only be changed in testing Tor " \
4000 "networks!"); \
4001 } STMT_END
4002 CHECK_DEFAULT(TestingV3AuthInitialVotingInterval);
4003 CHECK_DEFAULT(TestingV3AuthInitialVoteDelay);
4004 CHECK_DEFAULT(TestingV3AuthInitialDistDelay);
4005 CHECK_DEFAULT(TestingV3AuthVotingStartOffset);
4006 CHECK_DEFAULT(TestingAuthDirTimeToLearnReachability);
4007 CHECK_DEFAULT(TestingEstimatedDescriptorPropagationTime);
4008 CHECK_DEFAULT(TestingServerDownloadSchedule);
4009 CHECK_DEFAULT(TestingClientDownloadSchedule);
4010 CHECK_DEFAULT(TestingServerConsensusDownloadSchedule);
4011 CHECK_DEFAULT(TestingClientConsensusDownloadSchedule);
4012 CHECK_DEFAULT(TestingBridgeDownloadSchedule);
4013 CHECK_DEFAULT(TestingClientMaxIntervalWithoutRequest);
4014 CHECK_DEFAULT(TestingDirConnectionMaxStall);
4015 CHECK_DEFAULT(TestingConsensusMaxDownloadTries);
4016 CHECK_DEFAULT(TestingDescriptorMaxDownloadTries);
4017 CHECK_DEFAULT(TestingMicrodescMaxDownloadTries);
4018 CHECK_DEFAULT(TestingCertMaxDownloadTries);
4019 CHECK_DEFAULT(TestingAuthKeyLifetime);
4020 CHECK_DEFAULT(TestingLinkCertLifetime);
4021 CHECK_DEFAULT(TestingSigningKeySlop);
4022 CHECK_DEFAULT(TestingAuthKeySlop);
4023 CHECK_DEFAULT(TestingLinkKeySlop);
4024 #undef CHECK_DEFAULT
4026 if (options->SigningKeyLifetime < options->TestingSigningKeySlop*2)
4027 REJECT("SigningKeyLifetime is too short.");
4028 if (options->TestingLinkCertLifetime < options->TestingAuthKeySlop*2)
4029 REJECT("LinkCertLifetime is too short.");
4030 if (options->TestingAuthKeyLifetime < options->TestingLinkKeySlop*2)
4031 REJECT("TestingAuthKeyLifetime is too short.");
4033 if (options->TestingV3AuthInitialVotingInterval
4034 < MIN_VOTE_INTERVAL_TESTING_INITIAL) {
4035 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
4036 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
4037 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
4038 "30 minutes.");
4041 if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS_TESTING) {
4042 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
4045 if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS_TESTING) {
4046 REJECT("TestingV3AuthInitialDistDelay is way too low.");
4049 if (options->TestingV3AuthInitialVoteDelay +
4050 options->TestingV3AuthInitialDistDelay >=
4051 options->TestingV3AuthInitialVotingInterval) {
4052 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
4053 "must be less than TestingV3AuthInitialVotingInterval");
4056 if (options->TestingV3AuthVotingStartOffset >
4057 MIN(options->TestingV3AuthInitialVotingInterval,
4058 options->V3AuthVotingInterval)) {
4059 REJECT("TestingV3AuthVotingStartOffset is higher than the voting "
4060 "interval.");
4061 } else if (options->TestingV3AuthVotingStartOffset < 0) {
4062 REJECT("TestingV3AuthVotingStartOffset must be non-negative.");
4065 if (options->TestingAuthDirTimeToLearnReachability < 0) {
4066 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
4067 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
4068 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
4071 if (options->TestingEstimatedDescriptorPropagationTime < 0) {
4072 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
4073 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
4074 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
4077 if (options->TestingClientMaxIntervalWithoutRequest < 1) {
4078 REJECT("TestingClientMaxIntervalWithoutRequest is way too low.");
4079 } else if (options->TestingClientMaxIntervalWithoutRequest > 3600) {
4080 COMPLAIN("TestingClientMaxIntervalWithoutRequest is insanely high.");
4083 if (options->TestingDirConnectionMaxStall < 5) {
4084 REJECT("TestingDirConnectionMaxStall is way too low.");
4085 } else if (options->TestingDirConnectionMaxStall > 3600) {
4086 COMPLAIN("TestingDirConnectionMaxStall is insanely high.");
4089 if (options->TestingConsensusMaxDownloadTries < 2) {
4090 REJECT("TestingConsensusMaxDownloadTries must be greater than 2.");
4091 } else if (options->TestingConsensusMaxDownloadTries > 800) {
4092 COMPLAIN("TestingConsensusMaxDownloadTries is insanely high.");
4095 if (options->ClientBootstrapConsensusMaxDownloadTries < 2) {
4096 REJECT("ClientBootstrapConsensusMaxDownloadTries must be greater "
4097 "than 2."
4099 } else if (options->ClientBootstrapConsensusMaxDownloadTries > 800) {
4100 COMPLAIN("ClientBootstrapConsensusMaxDownloadTries is insanely "
4101 "high.");
4104 if (options->ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries
4105 < 2) {
4106 REJECT("ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries must "
4107 "be greater than 2."
4109 } else if (
4110 options->ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries
4111 > 800) {
4112 COMPLAIN("ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries is "
4113 "insanely high.");
4116 if (options->ClientBootstrapConsensusMaxInProgressTries < 1) {
4117 REJECT("ClientBootstrapConsensusMaxInProgressTries must be greater "
4118 "than 0.");
4119 } else if (options->ClientBootstrapConsensusMaxInProgressTries
4120 > 100) {
4121 COMPLAIN("ClientBootstrapConsensusMaxInProgressTries is insanely "
4122 "high.");
4125 if (options->TestingDescriptorMaxDownloadTries < 2) {
4126 REJECT("TestingDescriptorMaxDownloadTries must be greater than 1.");
4127 } else if (options->TestingDescriptorMaxDownloadTries > 800) {
4128 COMPLAIN("TestingDescriptorMaxDownloadTries is insanely high.");
4131 if (options->TestingMicrodescMaxDownloadTries < 2) {
4132 REJECT("TestingMicrodescMaxDownloadTries must be greater than 1.");
4133 } else if (options->TestingMicrodescMaxDownloadTries > 800) {
4134 COMPLAIN("TestingMicrodescMaxDownloadTries is insanely high.");
4137 if (options->TestingCertMaxDownloadTries < 2) {
4138 REJECT("TestingCertMaxDownloadTries must be greater than 1.");
4139 } else if (options->TestingCertMaxDownloadTries > 800) {
4140 COMPLAIN("TestingCertMaxDownloadTries is insanely high.");
4143 if (options->TestingEnableConnBwEvent &&
4144 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4145 REJECT("TestingEnableConnBwEvent may only be changed in testing "
4146 "Tor networks!");
4149 if (options->TestingEnableCellStatsEvent &&
4150 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4151 REJECT("TestingEnableCellStatsEvent may only be changed in testing "
4152 "Tor networks!");
4155 if (options->TestingEnableTbEmptyEvent &&
4156 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4157 REJECT("TestingEnableTbEmptyEvent may only be changed in testing "
4158 "Tor networks!");
4161 if (options->TestingTorNetwork) {
4162 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
4163 "almost unusable in the public Tor network, and is "
4164 "therefore only advised if you are building a "
4165 "testing Tor network!");
4168 if (options->AccelName && !options->HardwareAccel)
4169 options->HardwareAccel = 1;
4170 if (options->AccelDir && !options->AccelName)
4171 REJECT("Can't use hardware crypto accelerator dir without engine name.");
4173 if (options->PublishServerDescriptor)
4174 SMARTLIST_FOREACH(options->PublishServerDescriptor, const char *, pubdes, {
4175 if (!strcmp(pubdes, "1") || !strcmp(pubdes, "0"))
4176 if (smartlist_len(options->PublishServerDescriptor) > 1) {
4177 COMPLAIN("You have passed a list of multiple arguments to the "
4178 "PublishServerDescriptor option that includes 0 or 1. "
4179 "0 or 1 should only be used as the sole argument. "
4180 "This configuration will be rejected in a future release.");
4181 break;
4185 if (options->BridgeRelay == 1 && ! options->ORPort_set)
4186 REJECT("BridgeRelay is 1, ORPort is not set. This is an invalid "
4187 "combination.");
4189 return 0;
4192 #undef REJECT
4193 #undef COMPLAIN
4195 /* Given the value that the user has set for MaxMemInQueues, compute the
4196 * actual maximum value. We clip this value if it's too low, and autodetect
4197 * it if it's set to 0. */
4198 static uint64_t
4199 compute_real_max_mem_in_queues(const uint64_t val, int log_guess)
4201 uint64_t result;
4203 if (val == 0) {
4204 #define ONE_GIGABYTE (U64_LITERAL(1) << 30)
4205 #define ONE_MEGABYTE (U64_LITERAL(1) << 20)
4206 #if SIZEOF_VOID_P >= 8
4207 #define MAX_DEFAULT_MAXMEM (8*ONE_GIGABYTE)
4208 #else
4209 #define MAX_DEFAULT_MAXMEM (2*ONE_GIGABYTE)
4210 #endif
4211 /* The user didn't pick a memory limit. Choose a very large one
4212 * that is still smaller than the system memory */
4213 static int notice_sent = 0;
4214 size_t ram = 0;
4215 if (get_total_system_memory(&ram) < 0) {
4216 /* We couldn't determine our total system memory! */
4217 #if SIZEOF_VOID_P >= 8
4218 /* 64-bit system. Let's hope for 8 GB. */
4219 result = 8 * ONE_GIGABYTE;
4220 #else
4221 /* (presumably) 32-bit system. Let's hope for 1 GB. */
4222 result = ONE_GIGABYTE;
4223 #endif
4224 } else {
4225 /* We detected it, so let's pick 3/4 of the total RAM as our limit. */
4226 const uint64_t avail = (ram / 4) * 3;
4228 /* Make sure it's in range from 0.25 GB to 8 GB. */
4229 if (avail > MAX_DEFAULT_MAXMEM) {
4230 /* If you want to use more than this much RAM, you need to configure
4231 it yourself */
4232 result = MAX_DEFAULT_MAXMEM;
4233 } else if (avail < ONE_GIGABYTE / 4) {
4234 result = ONE_GIGABYTE / 4;
4235 } else {
4236 result = avail;
4239 if (log_guess && ! notice_sent) {
4240 log_notice(LD_CONFIG, "%sMaxMemInQueues is set to "U64_FORMAT" MB. "
4241 "You can override this by setting MaxMemInQueues by hand.",
4242 ram ? "Based on detected system memory, " : "",
4243 U64_PRINTF_ARG(result / ONE_MEGABYTE));
4244 notice_sent = 1;
4246 return result;
4247 } else if (val < ONE_GIGABYTE / 4) {
4248 log_warn(LD_CONFIG, "MaxMemInQueues must be at least 256 MB for now. "
4249 "Ideally, have it as large as you can afford.");
4250 return ONE_GIGABYTE / 4;
4251 } else {
4252 /* The value was fine all along */
4253 return val;
4257 /* If we have less than 300 MB suggest disabling dircache */
4258 #define DIRCACHE_MIN_MB_BANDWIDTH 300
4259 #define DIRCACHE_MIN_BANDWIDTH (DIRCACHE_MIN_MB_BANDWIDTH*ONE_MEGABYTE)
4260 #define STRINGIFY(val) #val
4262 /** Create a warning message for emitting if we are a dircache but may not have
4263 * enough system memory, or if we are not a dircache but probably should be.
4264 * Return -1 when a message is returned in *msg*, else return 0. */
4265 STATIC int
4266 have_enough_mem_for_dircache(const or_options_t *options, size_t total_mem,
4267 char **msg)
4269 *msg = NULL;
4270 /* XXX We should possibly be looking at MaxMemInQueues here
4271 * unconditionally. Or we should believe total_mem unconditionally. */
4272 if (total_mem == 0) {
4273 if (get_total_system_memory(&total_mem) < 0) {
4274 total_mem = options->MaxMemInQueues >= SIZE_MAX ?
4275 SIZE_MAX : (size_t)options->MaxMemInQueues;
4278 if (options->DirCache) {
4279 if (total_mem < DIRCACHE_MIN_BANDWIDTH) {
4280 if (options->BridgeRelay) {
4281 *msg = tor_strdup("Running a Bridge with less than "
4282 STRINGIFY(DIRCACHE_MIN_MB_BANDWIDTH) " MB of memory is "
4283 "not recommended.");
4284 } else {
4285 *msg = tor_strdup("Being a directory cache (default) with less than "
4286 STRINGIFY(DIRCACHE_MIN_MB_BANDWIDTH) " MB of memory is "
4287 "not recommended and may consume most of the available "
4288 "resources, consider disabling this functionality by "
4289 "setting the DirCache option to 0.");
4292 } else {
4293 if (total_mem >= DIRCACHE_MIN_BANDWIDTH) {
4294 *msg = tor_strdup("DirCache is disabled and we are configured as a "
4295 "relay. This may disqualify us from becoming a guard in the "
4296 "future.");
4299 return *msg == NULL ? 0 : -1;
4301 #undef STRINGIFY
4303 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
4304 * equal strings. */
4305 static int
4306 opt_streq(const char *s1, const char *s2)
4308 return 0 == strcmp_opt(s1, s2);
4311 /** Check if any of the previous options have changed but aren't allowed to. */
4312 static int
4313 options_transition_allowed(const or_options_t *old,
4314 const or_options_t *new_val,
4315 char **msg)
4317 if (!old)
4318 return 0;
4320 if (!opt_streq(old->PidFile, new_val->PidFile)) {
4321 *msg = tor_strdup("PidFile is not allowed to change.");
4322 return -1;
4325 if (old->RunAsDaemon != new_val->RunAsDaemon) {
4326 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
4327 "is not allowed.");
4328 return -1;
4331 if (old->Sandbox != new_val->Sandbox) {
4332 *msg = tor_strdup("While Tor is running, changing Sandbox "
4333 "is not allowed.");
4334 return -1;
4337 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
4338 tor_asprintf(msg,
4339 "While Tor is running, changing DataDirectory "
4340 "(\"%s\"->\"%s\") is not allowed.",
4341 old->DataDirectory, new_val->DataDirectory);
4342 return -1;
4345 if (!opt_streq(old->User, new_val->User)) {
4346 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
4347 return -1;
4350 if (old->KeepBindCapabilities != new_val->KeepBindCapabilities) {
4351 *msg = tor_strdup("While Tor is running, changing KeepBindCapabilities is "
4352 "not allowed.");
4353 return -1;
4356 if (!opt_streq(old->SyslogIdentityTag, new_val->SyslogIdentityTag)) {
4357 *msg = tor_strdup("While Tor is running, changing "
4358 "SyslogIdentityTag is not allowed.");
4359 return -1;
4362 if ((old->HardwareAccel != new_val->HardwareAccel)
4363 || !opt_streq(old->AccelName, new_val->AccelName)
4364 || !opt_streq(old->AccelDir, new_val->AccelDir)) {
4365 *msg = tor_strdup("While Tor is running, changing OpenSSL hardware "
4366 "acceleration engine is not allowed.");
4367 return -1;
4370 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
4371 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
4372 "is not allowed.");
4373 return -1;
4376 if (old->DisableAllSwap != new_val->DisableAllSwap) {
4377 *msg = tor_strdup("While Tor is running, changing DisableAllSwap "
4378 "is not allowed.");
4379 return -1;
4382 if (old->TokenBucketRefillInterval != new_val->TokenBucketRefillInterval) {
4383 *msg = tor_strdup("While Tor is running, changing TokenBucketRefill"
4384 "Interval is not allowed");
4385 return -1;
4388 if (old->HiddenServiceSingleHopMode != new_val->HiddenServiceSingleHopMode) {
4389 *msg = tor_strdup("While Tor is running, changing "
4390 "HiddenServiceSingleHopMode is not allowed.");
4391 return -1;
4394 if (old->HiddenServiceNonAnonymousMode !=
4395 new_val->HiddenServiceNonAnonymousMode) {
4396 *msg = tor_strdup("While Tor is running, changing "
4397 "HiddenServiceNonAnonymousMode is not allowed.");
4398 return -1;
4401 if (old->DisableDebuggerAttachment &&
4402 !new_val->DisableDebuggerAttachment) {
4403 *msg = tor_strdup("While Tor is running, disabling "
4404 "DisableDebuggerAttachment is not allowed.");
4405 return -1;
4408 if (sandbox_is_active()) {
4409 #define SB_NOCHANGE_STR(opt) \
4410 do { \
4411 if (! opt_streq(old->opt, new_val->opt)) { \
4412 *msg = tor_strdup("Can't change " #opt " while Sandbox is active"); \
4413 return -1; \
4415 } while (0)
4417 SB_NOCHANGE_STR(Address);
4418 SB_NOCHANGE_STR(PidFile);
4419 SB_NOCHANGE_STR(ServerDNSResolvConfFile);
4420 SB_NOCHANGE_STR(DirPortFrontPage);
4421 SB_NOCHANGE_STR(CookieAuthFile);
4422 SB_NOCHANGE_STR(ExtORPortCookieAuthFile);
4424 #undef SB_NOCHANGE_STR
4426 if (! config_lines_eq(old->Logs, new_val->Logs)) {
4427 *msg = tor_strdup("Can't change Logs while Sandbox is active");
4428 return -1;
4430 if (old->ConnLimit != new_val->ConnLimit) {
4431 *msg = tor_strdup("Can't change ConnLimit while Sandbox is active");
4432 return -1;
4434 if (server_mode(old) != server_mode(new_val)) {
4435 *msg = tor_strdup("Can't start/stop being a server while "
4436 "Sandbox is active");
4437 return -1;
4441 return 0;
4444 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
4445 * will require us to rotate the CPU and DNS workers; else return 0. */
4446 static int
4447 options_transition_affects_workers(const or_options_t *old_options,
4448 const or_options_t *new_options)
4450 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
4451 old_options->NumCPUs != new_options->NumCPUs ||
4452 !config_lines_eq(old_options->ORPort_lines, new_options->ORPort_lines) ||
4453 old_options->ServerDNSSearchDomains !=
4454 new_options->ServerDNSSearchDomains ||
4455 old_options->SafeLogging_ != new_options->SafeLogging_ ||
4456 old_options->ClientOnly != new_options->ClientOnly ||
4457 public_server_mode(old_options) != public_server_mode(new_options) ||
4458 !config_lines_eq(old_options->Logs, new_options->Logs) ||
4459 old_options->LogMessageDomains != new_options->LogMessageDomains)
4460 return 1;
4462 /* Check whether log options match. */
4464 /* Nothing that changed matters. */
4465 return 0;
4468 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
4469 * will require us to generate a new descriptor; else return 0. */
4470 static int
4471 options_transition_affects_descriptor(const or_options_t *old_options,
4472 const or_options_t *new_options)
4474 /* XXX We can be smarter here. If your DirPort isn't being
4475 * published and you just turned it off, no need to republish. Etc. */
4476 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
4477 !opt_streq(old_options->Nickname,new_options->Nickname) ||
4478 !opt_streq(old_options->Address,new_options->Address) ||
4479 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
4480 old_options->ExitRelay != new_options->ExitRelay ||
4481 old_options->ExitPolicyRejectPrivate !=
4482 new_options->ExitPolicyRejectPrivate ||
4483 old_options->ExitPolicyRejectLocalInterfaces !=
4484 new_options->ExitPolicyRejectLocalInterfaces ||
4485 old_options->IPv6Exit != new_options->IPv6Exit ||
4486 !config_lines_eq(old_options->ORPort_lines,
4487 new_options->ORPort_lines) ||
4488 !config_lines_eq(old_options->DirPort_lines,
4489 new_options->DirPort_lines) ||
4490 old_options->ClientOnly != new_options->ClientOnly ||
4491 old_options->DisableNetwork != new_options->DisableNetwork ||
4492 old_options->PublishServerDescriptor_ !=
4493 new_options->PublishServerDescriptor_ ||
4494 get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
4495 get_effective_bwburst(old_options) !=
4496 get_effective_bwburst(new_options) ||
4497 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
4498 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
4499 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
4500 old_options->AccountingMax != new_options->AccountingMax ||
4501 old_options->AccountingRule != new_options->AccountingRule ||
4502 public_server_mode(old_options) != public_server_mode(new_options) ||
4503 old_options->DirCache != new_options->DirCache ||
4504 old_options->AssumeReachable != new_options->AssumeReachable)
4505 return 1;
4507 return 0;
4510 #ifdef _WIN32
4511 /** Return the directory on windows where we expect to find our application
4512 * data. */
4513 static char *
4514 get_windows_conf_root(void)
4516 static int is_set = 0;
4517 static char path[MAX_PATH*2+1];
4518 TCHAR tpath[MAX_PATH] = {0};
4520 LPITEMIDLIST idl;
4521 IMalloc *m;
4522 HRESULT result;
4524 if (is_set)
4525 return path;
4527 /* Find X:\documents and settings\username\application data\ .
4528 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
4530 #ifdef ENABLE_LOCAL_APPDATA
4531 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
4532 #else
4533 #define APPDATA_PATH CSIDL_APPDATA
4534 #endif
4535 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
4536 getcwd(path,MAX_PATH);
4537 is_set = 1;
4538 log_warn(LD_CONFIG,
4539 "I couldn't find your application data folder: are you "
4540 "running an ancient version of Windows 95? Defaulting to \"%s\"",
4541 path);
4542 return path;
4544 /* Convert the path from an "ID List" (whatever that is!) to a path. */
4545 result = SHGetPathFromIDList(idl, tpath);
4546 #ifdef UNICODE
4547 wcstombs(path,tpath,sizeof(path));
4548 path[sizeof(path)-1] = '\0';
4549 #else
4550 strlcpy(path,tpath,sizeof(path));
4551 #endif
4553 /* Now we need to free the memory that the path-idl was stored in. In
4554 * typical Windows fashion, we can't just call 'free()' on it. */
4555 SHGetMalloc(&m);
4556 if (m) {
4557 m->lpVtbl->Free(m, idl);
4558 m->lpVtbl->Release(m);
4560 if (!SUCCEEDED(result)) {
4561 return NULL;
4563 strlcat(path,"\\tor",MAX_PATH);
4564 is_set = 1;
4565 return path;
4567 #endif
4569 /** Return the default location for our torrc file (if <b>defaults_file</b> is
4570 * false), or for the torrc-defaults file (if <b>defaults_file</b> is true). */
4571 static const char *
4572 get_default_conf_file(int defaults_file)
4574 #ifdef DISABLE_SYSTEM_TORRC
4575 (void) defaults_file;
4576 return NULL;
4577 #elif defined(_WIN32)
4578 if (defaults_file) {
4579 static char defaults_path[MAX_PATH+1];
4580 tor_snprintf(defaults_path, MAX_PATH, "%s\\torrc-defaults",
4581 get_windows_conf_root());
4582 return defaults_path;
4583 } else {
4584 static char path[MAX_PATH+1];
4585 tor_snprintf(path, MAX_PATH, "%s\\torrc",
4586 get_windows_conf_root());
4587 return path;
4589 #else
4590 return defaults_file ? CONFDIR "/torrc-defaults" : CONFDIR "/torrc";
4591 #endif
4594 /** Verify whether lst is a string containing valid-looking comma-separated
4595 * nicknames, or NULL. Will normalise <b>lst</b> to prefix '$' to any nickname
4596 * or fingerprint that needs it. Return 0 on success.
4597 * Warn and return -1 on failure.
4599 static int
4600 check_nickname_list(char **lst, const char *name, char **msg)
4602 int r = 0;
4603 smartlist_t *sl;
4604 int changes = 0;
4606 if (!*lst)
4607 return 0;
4608 sl = smartlist_new();
4610 smartlist_split_string(sl, *lst, ",",
4611 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
4613 SMARTLIST_FOREACH_BEGIN(sl, char *, s)
4615 if (!is_legal_nickname_or_hexdigest(s)) {
4616 // check if first char is dollar
4617 if (s[0] != '$') {
4618 // Try again but with a dollar symbol prepended
4619 char *prepended;
4620 tor_asprintf(&prepended, "$%s", s);
4622 if (is_legal_nickname_or_hexdigest(prepended)) {
4623 // The nickname is valid when it's prepended, swap the current
4624 // version with a prepended one
4625 tor_free(s);
4626 SMARTLIST_REPLACE_CURRENT(sl, s, prepended);
4627 changes = 1;
4628 continue;
4631 // Still not valid, free and fallback to error message
4632 tor_free(prepended);
4635 tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
4636 r = -1;
4637 break;
4640 SMARTLIST_FOREACH_END(s);
4642 // Replace the caller's nickname list with a fixed one
4643 if (changes && r == 0) {
4644 char *newNicknames = smartlist_join_strings(sl, ", ", 0, NULL);
4645 tor_free(*lst);
4646 *lst = newNicknames;
4649 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
4650 smartlist_free(sl);
4652 return r;
4655 /** Learn config file name from command line arguments, or use the default.
4657 * If <b>defaults_file</b> is true, we're looking for torrc-defaults;
4658 * otherwise, we're looking for the regular torrc_file.
4660 * Set *<b>using_default_fname</b> to true if we're using the default
4661 * configuration file name; or false if we've set it from the command line.
4663 * Set *<b>ignore_missing_torrc</b> to true if we should ignore the resulting
4664 * filename if it doesn't exist.
4666 static char *
4667 find_torrc_filename(config_line_t *cmd_arg,
4668 int defaults_file,
4669 int *using_default_fname, int *ignore_missing_torrc)
4671 char *fname=NULL;
4672 config_line_t *p_index;
4673 const char *fname_opt = defaults_file ? "--defaults-torrc" : "-f";
4674 const char *ignore_opt = defaults_file ? NULL : "--ignore-missing-torrc";
4676 if (defaults_file)
4677 *ignore_missing_torrc = 1;
4679 for (p_index = cmd_arg; p_index; p_index = p_index->next) {
4680 if (!strcmp(p_index->key, fname_opt)) {
4681 if (fname) {
4682 log_warn(LD_CONFIG, "Duplicate %s options on command line.",
4683 fname_opt);
4684 tor_free(fname);
4686 fname = expand_filename(p_index->value);
4689 char *absfname;
4690 absfname = make_path_absolute(fname);
4691 tor_free(fname);
4692 fname = absfname;
4695 *using_default_fname = 0;
4696 } else if (ignore_opt && !strcmp(p_index->key,ignore_opt)) {
4697 *ignore_missing_torrc = 1;
4701 if (*using_default_fname) {
4702 /* didn't find one, try CONFDIR */
4703 const char *dflt = get_default_conf_file(defaults_file);
4704 file_status_t st = file_status(dflt);
4705 if (dflt && (st == FN_FILE || st == FN_EMPTY)) {
4706 fname = tor_strdup(dflt);
4707 } else {
4708 #ifndef _WIN32
4709 char *fn = NULL;
4710 if (!defaults_file) {
4711 fn = expand_filename("~/.torrc");
4713 if (fn) {
4714 file_status_t hmst = file_status(fn);
4715 if (hmst == FN_FILE || hmst == FN_EMPTY || dflt == NULL) {
4716 fname = fn;
4717 } else {
4718 tor_free(fn);
4719 fname = tor_strdup(dflt);
4721 } else {
4722 fname = dflt ? tor_strdup(dflt) : NULL;
4724 #else
4725 fname = dflt ? tor_strdup(dflt) : NULL;
4726 #endif
4729 return fname;
4732 /** Read the torrc from standard input and return it as a string.
4733 * Upon failure, return NULL.
4735 static char *
4736 load_torrc_from_stdin(void)
4738 size_t sz_out;
4740 return read_file_to_str_until_eof(STDIN_FILENO,SIZE_MAX,&sz_out);
4743 /** Load a configuration file from disk, setting torrc_fname or
4744 * torrc_defaults_fname if successful.
4746 * If <b>defaults_file</b> is true, load torrc-defaults; otherwise load torrc.
4748 * Return the contents of the file on success, and NULL on failure.
4750 static char *
4751 load_torrc_from_disk(config_line_t *cmd_arg, int defaults_file)
4753 char *fname=NULL;
4754 char *cf = NULL;
4755 int using_default_torrc = 1;
4756 int ignore_missing_torrc = 0;
4757 char **fname_var = defaults_file ? &torrc_defaults_fname : &torrc_fname;
4759 if (*fname_var == NULL) {
4760 fname = find_torrc_filename(cmd_arg, defaults_file,
4761 &using_default_torrc, &ignore_missing_torrc);
4762 tor_free(*fname_var);
4763 *fname_var = fname;
4764 } else {
4765 fname = *fname_var;
4767 log_debug(LD_CONFIG, "Opening config file \"%s\"", fname?fname:"<NULL>");
4769 /* Open config file */
4770 file_status_t st = fname ? file_status(fname) : FN_EMPTY;
4771 if (fname == NULL ||
4772 !(st == FN_FILE || st == FN_EMPTY) ||
4773 !(cf = read_file_to_str(fname,0,NULL))) {
4774 if (using_default_torrc == 1 || ignore_missing_torrc) {
4775 if (!defaults_file)
4776 log_notice(LD_CONFIG, "Configuration file \"%s\" not present, "
4777 "using reasonable defaults.", fname);
4778 tor_free(fname); /* sets fname to NULL */
4779 *fname_var = NULL;
4780 cf = tor_strdup("");
4781 } else {
4782 log_warn(LD_CONFIG,
4783 "Unable to open configuration file \"%s\".", fname);
4784 goto err;
4786 } else {
4787 log_notice(LD_CONFIG, "Read configuration file \"%s\".", fname);
4790 return cf;
4791 err:
4792 tor_free(fname);
4793 *fname_var = NULL;
4794 return NULL;
4797 /** Read a configuration file into <b>options</b>, finding the configuration
4798 * file location based on the command line. After loading the file
4799 * call options_init_from_string() to load the config.
4800 * Return 0 if success, -1 if failure. */
4802 options_init_from_torrc(int argc, char **argv)
4804 char *cf=NULL, *cf_defaults=NULL;
4805 int command;
4806 int retval = -1;
4807 char *command_arg = NULL;
4808 char *errmsg=NULL;
4809 config_line_t *p_index = NULL;
4810 config_line_t *cmdline_only_options = NULL;
4812 /* Go through command-line variables */
4813 if (! have_parsed_cmdline) {
4814 /* Or we could redo the list every time we pass this place.
4815 * It does not really matter */
4816 if (config_parse_commandline(argc, argv, 0, &global_cmdline_options,
4817 &global_cmdline_only_options) < 0) {
4818 goto err;
4820 have_parsed_cmdline = 1;
4822 cmdline_only_options = global_cmdline_only_options;
4824 if (config_line_find(cmdline_only_options, "-h") ||
4825 config_line_find(cmdline_only_options, "--help")) {
4826 print_usage();
4827 exit(0);
4829 if (config_line_find(cmdline_only_options, "--list-torrc-options")) {
4830 /* For validating whether we've documented everything. */
4831 list_torrc_options();
4832 exit(0);
4834 if (config_line_find(cmdline_only_options, "--list-deprecated-options")) {
4835 /* For validating whether what we have deprecated really exists. */
4836 list_deprecated_options();
4837 exit(0);
4840 if (config_line_find(cmdline_only_options, "--version")) {
4841 printf("Tor version %s.\n",get_version());
4842 exit(0);
4845 if (config_line_find(cmdline_only_options, "--library-versions")) {
4846 printf("Tor version %s. \n", get_version());
4847 printf("Library versions\tCompiled\t\tRuntime\n");
4848 printf("Libevent\t\t%-15s\t\t%s\n",
4849 tor_libevent_get_header_version_str(),
4850 tor_libevent_get_version_str());
4851 printf("OpenSSL \t\t%-15s\t\t%s\n",
4852 crypto_openssl_get_header_version_str(),
4853 crypto_openssl_get_version_str());
4854 printf("Zlib \t\t%-15s\t\t%s\n",
4855 tor_zlib_get_header_version_str(),
4856 tor_zlib_get_version_str());
4857 //TODO: Hex versions?
4858 exit(0);
4861 command = CMD_RUN_TOR;
4862 for (p_index = cmdline_only_options; p_index; p_index = p_index->next) {
4863 if (!strcmp(p_index->key,"--keygen")) {
4864 command = CMD_KEYGEN;
4865 } else if (!strcmp(p_index->key,"--list-fingerprint")) {
4866 command = CMD_LIST_FINGERPRINT;
4867 } else if (!strcmp(p_index->key, "--hash-password")) {
4868 command = CMD_HASH_PASSWORD;
4869 command_arg = p_index->value;
4870 } else if (!strcmp(p_index->key, "--dump-config")) {
4871 command = CMD_DUMP_CONFIG;
4872 command_arg = p_index->value;
4873 } else if (!strcmp(p_index->key, "--verify-config")) {
4874 command = CMD_VERIFY_CONFIG;
4878 if (command == CMD_HASH_PASSWORD) {
4879 cf_defaults = tor_strdup("");
4880 cf = tor_strdup("");
4881 } else {
4882 cf_defaults = load_torrc_from_disk(cmdline_only_options, 1);
4884 const config_line_t *f_line = config_line_find(cmdline_only_options,
4885 "-f");
4887 const int read_torrc_from_stdin =
4888 (f_line != NULL && strcmp(f_line->value, "-") == 0);
4890 if (read_torrc_from_stdin) {
4891 cf = load_torrc_from_stdin();
4892 } else {
4893 cf = load_torrc_from_disk(cmdline_only_options, 0);
4896 if (!cf) {
4897 if (config_line_find(cmdline_only_options, "--allow-missing-torrc")) {
4898 cf = tor_strdup("");
4899 } else {
4900 goto err;
4905 retval = options_init_from_string(cf_defaults, cf, command, command_arg,
4906 &errmsg);
4908 if (retval < 0)
4909 goto err;
4911 if (config_line_find(cmdline_only_options, "--no-passphrase")) {
4912 if (command == CMD_KEYGEN) {
4913 get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_OFF;
4914 } else {
4915 log_err(LD_CONFIG, "--no-passphrase specified without --keygen!");
4916 exit(1);
4920 if (config_line_find(cmdline_only_options, "--newpass")) {
4921 if (command == CMD_KEYGEN) {
4922 get_options_mutable()->change_key_passphrase = 1;
4923 } else {
4924 log_err(LD_CONFIG, "--newpass specified without --keygen!");
4925 exit(1);
4930 const config_line_t *fd_line = config_line_find(cmdline_only_options,
4931 "--passphrase-fd");
4932 if (fd_line) {
4933 if (get_options()->keygen_force_passphrase == FORCE_PASSPHRASE_OFF) {
4934 log_err(LD_CONFIG, "--no-passphrase specified with --passphrase-fd!");
4935 exit(1);
4936 } else if (command != CMD_KEYGEN) {
4937 log_err(LD_CONFIG, "--passphrase-fd specified without --keygen!");
4938 exit(1);
4939 } else {
4940 const char *v = fd_line->value;
4941 int ok = 1;
4942 long fd = tor_parse_long(v, 10, 0, INT_MAX, &ok, NULL);
4943 if (fd < 0 || ok == 0) {
4944 log_err(LD_CONFIG, "Invalid --passphrase-fd value %s", escaped(v));
4945 exit(1);
4947 get_options_mutable()->keygen_passphrase_fd = (int)fd;
4948 get_options_mutable()->use_keygen_passphrase_fd = 1;
4949 get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_ON;
4955 const config_line_t *key_line = config_line_find(cmdline_only_options,
4956 "--master-key");
4957 if (key_line) {
4958 if (command != CMD_KEYGEN) {
4959 log_err(LD_CONFIG, "--master-key without --keygen!");
4960 exit(1);
4961 } else {
4962 get_options_mutable()->master_key_fname = tor_strdup(key_line->value);
4967 err:
4969 tor_free(cf);
4970 tor_free(cf_defaults);
4971 if (errmsg) {
4972 log_warn(LD_CONFIG,"%s", errmsg);
4973 tor_free(errmsg);
4975 return retval < 0 ? -1 : 0;
4978 /** Load the options from the configuration in <b>cf</b>, validate
4979 * them for consistency and take actions based on them.
4981 * Return 0 if success, negative on error:
4982 * * -1 for general errors.
4983 * * -2 for failure to parse/validate,
4984 * * -3 for transition not allowed
4985 * * -4 for error while setting the new options
4987 setopt_err_t
4988 options_init_from_string(const char *cf_defaults, const char *cf,
4989 int command, const char *command_arg,
4990 char **msg)
4992 or_options_t *oldoptions, *newoptions, *newdefaultoptions=NULL;
4993 config_line_t *cl;
4994 int retval;
4995 setopt_err_t err = SETOPT_ERR_MISC;
4996 tor_assert(msg);
4998 oldoptions = global_options; /* get_options unfortunately asserts if
4999 this is the first time we run*/
5001 newoptions = tor_malloc_zero(sizeof(or_options_t));
5002 newoptions->magic_ = OR_OPTIONS_MAGIC;
5003 options_init(newoptions);
5004 newoptions->command = command;
5005 newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
5007 for (int i = 0; i < 2; ++i) {
5008 const char *body = i==0 ? cf_defaults : cf;
5009 if (!body)
5010 continue;
5011 /* get config lines, assign them */
5012 retval = config_get_lines(body, &cl, 1);
5013 if (retval < 0) {
5014 err = SETOPT_ERR_PARSE;
5015 goto err;
5017 retval = config_assign(&options_format, newoptions, cl,
5018 CAL_WARN_DEPRECATIONS, msg);
5019 config_free_lines(cl);
5020 if (retval < 0) {
5021 err = SETOPT_ERR_PARSE;
5022 goto err;
5024 if (i==0)
5025 newdefaultoptions = config_dup(&options_format, newoptions);
5028 if (newdefaultoptions == NULL) {
5029 newdefaultoptions = config_dup(&options_format, global_default_options);
5032 /* Go through command-line variables too */
5033 retval = config_assign(&options_format, newoptions,
5034 global_cmdline_options, CAL_WARN_DEPRECATIONS, msg);
5035 if (retval < 0) {
5036 err = SETOPT_ERR_PARSE;
5037 goto err;
5040 /* If this is a testing network configuration, change defaults
5041 * for a list of dependent config options, re-initialize newoptions
5042 * with the new defaults, and assign all options to it second time. */
5043 if (newoptions->TestingTorNetwork) {
5044 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
5045 * this? We could, for example, make the parsing algorithm do two passes
5046 * over the configuration. If it finds any "suite" options like
5047 * TestingTorNetwork, it could change the defaults before its second pass.
5048 * Not urgent so long as this seems to work, but at any sign of trouble,
5049 * let's clean it up. -NM */
5051 /* Change defaults. */
5052 for (int i = 0; testing_tor_network_defaults[i].name; ++i) {
5053 const config_var_t *new_var = &testing_tor_network_defaults[i];
5054 config_var_t *old_var =
5055 config_find_option_mutable(&options_format, new_var->name);
5056 tor_assert(new_var);
5057 tor_assert(old_var);
5058 old_var->initvalue = new_var->initvalue;
5060 if ((config_find_deprecation(&options_format, new_var->name))) {
5061 log_warn(LD_GENERAL, "Testing options override the deprecated "
5062 "option %s. Is that intentional?",
5063 new_var->name);
5067 /* Clear newoptions and re-initialize them with new defaults. */
5068 or_options_free(newoptions);
5069 or_options_free(newdefaultoptions);
5070 newdefaultoptions = NULL;
5071 newoptions = tor_malloc_zero(sizeof(or_options_t));
5072 newoptions->magic_ = OR_OPTIONS_MAGIC;
5073 options_init(newoptions);
5074 newoptions->command = command;
5075 newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
5077 /* Assign all options a second time. */
5078 for (int i = 0; i < 2; ++i) {
5079 const char *body = i==0 ? cf_defaults : cf;
5080 if (!body)
5081 continue;
5082 /* get config lines, assign them */
5083 retval = config_get_lines(body, &cl, 1);
5084 if (retval < 0) {
5085 err = SETOPT_ERR_PARSE;
5086 goto err;
5088 retval = config_assign(&options_format, newoptions, cl, 0, msg);
5089 config_free_lines(cl);
5090 if (retval < 0) {
5091 err = SETOPT_ERR_PARSE;
5092 goto err;
5094 if (i==0)
5095 newdefaultoptions = config_dup(&options_format, newoptions);
5097 /* Assign command-line variables a second time too */
5098 retval = config_assign(&options_format, newoptions,
5099 global_cmdline_options, 0, msg);
5100 if (retval < 0) {
5101 err = SETOPT_ERR_PARSE;
5102 goto err;
5106 /* Validate newoptions */
5107 if (options_validate(oldoptions, newoptions, newdefaultoptions,
5108 0, msg) < 0) {
5109 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
5110 goto err;
5113 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
5114 err = SETOPT_ERR_TRANSITION;
5115 goto err;
5118 if (set_options(newoptions, msg)) {
5119 err = SETOPT_ERR_SETTING;
5120 goto err; /* frees and replaces old options */
5122 or_options_free(global_default_options);
5123 global_default_options = newdefaultoptions;
5125 return SETOPT_OK;
5127 err:
5128 or_options_free(newoptions);
5129 or_options_free(newdefaultoptions);
5130 if (*msg) {
5131 char *old_msg = *msg;
5132 tor_asprintf(msg, "Failed to parse/validate config: %s", old_msg);
5133 tor_free(old_msg);
5135 return err;
5138 /** Return the location for our configuration file. May return NULL.
5140 const char *
5141 get_torrc_fname(int defaults_fname)
5143 const char *fname = defaults_fname ? torrc_defaults_fname : torrc_fname;
5145 if (fname)
5146 return fname;
5147 else
5148 return get_default_conf_file(defaults_fname);
5151 /** Adjust the address map based on the MapAddress elements in the
5152 * configuration <b>options</b>
5154 void
5155 config_register_addressmaps(const or_options_t *options)
5157 smartlist_t *elts;
5158 config_line_t *opt;
5159 const char *from, *to, *msg;
5161 addressmap_clear_configured();
5162 elts = smartlist_new();
5163 for (opt = options->AddressMap; opt; opt = opt->next) {
5164 smartlist_split_string(elts, opt->value, NULL,
5165 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
5166 if (smartlist_len(elts) < 2) {
5167 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
5168 opt->value);
5169 goto cleanup;
5172 from = smartlist_get(elts,0);
5173 to = smartlist_get(elts,1);
5175 if (to[0] == '.' || from[0] == '.') {
5176 log_warn(LD_CONFIG,"MapAddress '%s' is ambiguous - address starts with a"
5177 "'.'. Ignoring.",opt->value);
5178 goto cleanup;
5181 if (addressmap_register_auto(from, to, 0, ADDRMAPSRC_TORRC, &msg) < 0) {
5182 log_warn(LD_CONFIG,"MapAddress '%s' failed: %s. Ignoring.", opt->value,
5183 msg);
5184 goto cleanup;
5187 if (smartlist_len(elts) > 2)
5188 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
5190 cleanup:
5191 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
5192 smartlist_clear(elts);
5194 smartlist_free(elts);
5197 /** As addressmap_register(), but detect the wildcarded status of "from" and
5198 * "to", and do not steal a reference to <b>to</b>. */
5199 /* XXXX move to connection_edge.c */
5201 addressmap_register_auto(const char *from, const char *to,
5202 time_t expires,
5203 addressmap_entry_source_t addrmap_source,
5204 const char **msg)
5206 int from_wildcard = 0, to_wildcard = 0;
5208 *msg = "whoops, forgot the error message";
5209 if (1) {
5210 if (!strcmp(to, "*") || !strcmp(from, "*")) {
5211 *msg = "can't remap from or to *";
5212 return -1;
5214 /* Detect asterisks in expressions of type: '*.example.com' */
5215 if (!strncmp(from,"*.",2)) {
5216 from += 2;
5217 from_wildcard = 1;
5219 if (!strncmp(to,"*.",2)) {
5220 to += 2;
5221 to_wildcard = 1;
5224 if (to_wildcard && !from_wildcard) {
5225 *msg = "can only use wildcard (i.e. '*.') if 'from' address "
5226 "uses wildcard also";
5227 return -1;
5230 if (address_is_invalid_destination(to, 1)) {
5231 *msg = "destination is invalid";
5232 return -1;
5235 addressmap_register(from, tor_strdup(to), expires, addrmap_source,
5236 from_wildcard, to_wildcard);
5238 return 0;
5242 * Initialize the logs based on the configuration file.
5244 static int
5245 options_init_logs(const or_options_t *old_options, or_options_t *options,
5246 int validate_only)
5248 config_line_t *opt;
5249 int ok;
5250 smartlist_t *elts;
5251 int run_as_daemon =
5252 #ifdef _WIN32
5254 #else
5255 options->RunAsDaemon;
5256 #endif
5258 if (options->LogTimeGranularity <= 0) {
5259 log_warn(LD_CONFIG, "Log time granularity '%d' has to be positive.",
5260 options->LogTimeGranularity);
5261 return -1;
5262 } else if (1000 % options->LogTimeGranularity != 0 &&
5263 options->LogTimeGranularity % 1000 != 0) {
5264 int granularity = options->LogTimeGranularity;
5265 if (granularity < 40) {
5266 do granularity++;
5267 while (1000 % granularity != 0);
5268 } else if (granularity < 1000) {
5269 granularity = 1000 / granularity;
5270 while (1000 % granularity != 0)
5271 granularity--;
5272 granularity = 1000 / granularity;
5273 } else {
5274 granularity = 1000 * ((granularity / 1000) + 1);
5276 log_warn(LD_CONFIG, "Log time granularity '%d' has to be either a "
5277 "divisor or a multiple of 1 second. Changing to "
5278 "'%d'.",
5279 options->LogTimeGranularity, granularity);
5280 if (!validate_only)
5281 set_log_time_granularity(granularity);
5282 } else {
5283 if (!validate_only)
5284 set_log_time_granularity(options->LogTimeGranularity);
5287 ok = 1;
5288 elts = smartlist_new();
5290 for (opt = options->Logs; opt; opt = opt->next) {
5291 log_severity_list_t *severity;
5292 const char *cfg = opt->value;
5293 severity = tor_malloc_zero(sizeof(log_severity_list_t));
5294 if (parse_log_severity_config(&cfg, severity) < 0) {
5295 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
5296 opt->value);
5297 ok = 0; goto cleanup;
5300 smartlist_split_string(elts, cfg, NULL,
5301 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
5303 if (smartlist_len(elts) == 0)
5304 smartlist_add(elts, tor_strdup("stdout"));
5306 if (smartlist_len(elts) == 1 &&
5307 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
5308 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
5309 int err = smartlist_len(elts) &&
5310 !strcasecmp(smartlist_get(elts,0), "stderr");
5311 if (!validate_only) {
5312 if (run_as_daemon) {
5313 log_warn(LD_CONFIG,
5314 "Can't log to %s with RunAsDaemon set; skipping stdout",
5315 err?"stderr":"stdout");
5316 } else {
5317 add_stream_log(severity, err?"<stderr>":"<stdout>",
5318 fileno(err?stderr:stdout));
5321 goto cleanup;
5323 if (smartlist_len(elts) == 1 &&
5324 !strcasecmp(smartlist_get(elts,0), "syslog")) {
5325 #ifdef HAVE_SYSLOG_H
5326 if (!validate_only) {
5327 add_syslog_log(severity, options->SyslogIdentityTag);
5329 #else
5330 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
5331 #endif
5332 goto cleanup;
5335 if (smartlist_len(elts) == 2 &&
5336 !strcasecmp(smartlist_get(elts,0), "file")) {
5337 if (!validate_only) {
5338 char *fname = expand_filename(smartlist_get(elts, 1));
5339 /* Truncate if TruncateLogFile is set and we haven't seen this option
5340 line before. */
5341 int truncate_log = 0;
5342 if (options->TruncateLogFile) {
5343 truncate_log = 1;
5344 if (old_options) {
5345 config_line_t *opt2;
5346 for (opt2 = old_options->Logs; opt2; opt2 = opt2->next)
5347 if (!strcmp(opt->value, opt2->value)) {
5348 truncate_log = 0;
5349 break;
5353 if (add_file_log(severity, fname, truncate_log) < 0) {
5354 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
5355 opt->value, strerror(errno));
5356 ok = 0;
5358 tor_free(fname);
5360 goto cleanup;
5363 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
5364 opt->value);
5365 ok = 0; goto cleanup;
5367 cleanup:
5368 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
5369 smartlist_clear(elts);
5370 tor_free(severity);
5372 smartlist_free(elts);
5374 if (ok && !validate_only)
5375 logs_set_domain_logging(options->LogMessageDomains);
5377 return ok?0:-1;
5380 /** Given a smartlist of SOCKS arguments to be passed to a transport
5381 * proxy in <b>args</b>, validate them and return -1 if they are
5382 * corrupted. Return 0 if they seem OK. */
5383 static int
5384 validate_transport_socks_arguments(const smartlist_t *args)
5386 char *socks_string = NULL;
5387 size_t socks_string_len;
5389 tor_assert(args);
5390 tor_assert(smartlist_len(args) > 0);
5392 SMARTLIST_FOREACH_BEGIN(args, const char *, s) {
5393 if (!string_is_key_value(LOG_WARN, s)) { /* items should be k=v items */
5394 log_warn(LD_CONFIG, "'%s' is not a k=v item.", s);
5395 return -1;
5397 } SMARTLIST_FOREACH_END(s);
5399 socks_string = pt_stringify_socks_args(args);
5400 if (!socks_string)
5401 return -1;
5403 socks_string_len = strlen(socks_string);
5404 tor_free(socks_string);
5406 if (socks_string_len > MAX_SOCKS5_AUTH_SIZE_TOTAL) {
5407 log_warn(LD_CONFIG, "SOCKS arguments can't be more than %u bytes (%lu).",
5408 MAX_SOCKS5_AUTH_SIZE_TOTAL,
5409 (unsigned long) socks_string_len);
5410 return -1;
5413 return 0;
5416 /** Deallocate a bridge_line_t structure. */
5417 /* private */ void
5418 bridge_line_free(bridge_line_t *bridge_line)
5420 if (!bridge_line)
5421 return;
5423 if (bridge_line->socks_args) {
5424 SMARTLIST_FOREACH(bridge_line->socks_args, char*, s, tor_free(s));
5425 smartlist_free(bridge_line->socks_args);
5427 tor_free(bridge_line->transport_name);
5428 tor_free(bridge_line);
5431 /** Parse the contents of a string, <b>line</b>, containing a Bridge line,
5432 * into a bridge_line_t.
5434 * Validates that the IP:PORT, fingerprint, and SOCKS arguments (given to the
5435 * Pluggable Transport, if a one was specified) are well-formed.
5437 * Returns NULL If the Bridge line could not be validated, and returns a
5438 * bridge_line_t containing the parsed information otherwise.
5440 * Bridge line format:
5441 * Bridge [transport] IP:PORT [id-fingerprint] [k=v] [k=v] ...
5443 /* private */ bridge_line_t *
5444 parse_bridge_line(const char *line)
5446 smartlist_t *items = NULL;
5447 char *addrport=NULL, *fingerprint=NULL;
5448 char *field=NULL;
5449 bridge_line_t *bridge_line = tor_malloc_zero(sizeof(bridge_line_t));
5451 items = smartlist_new();
5452 smartlist_split_string(items, line, NULL,
5453 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5454 if (smartlist_len(items) < 1) {
5455 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
5456 goto err;
5459 /* first field is either a transport name or addrport */
5460 field = smartlist_get(items, 0);
5461 smartlist_del_keeporder(items, 0);
5463 if (string_is_C_identifier(field)) {
5464 /* It's a transport name. */
5465 bridge_line->transport_name = field;
5466 if (smartlist_len(items) < 1) {
5467 log_warn(LD_CONFIG, "Too few items to Bridge line.");
5468 goto err;
5470 addrport = smartlist_get(items, 0); /* Next field is addrport then. */
5471 smartlist_del_keeporder(items, 0);
5472 } else {
5473 addrport = field;
5476 if (tor_addr_port_parse(LOG_INFO, addrport,
5477 &bridge_line->addr, &bridge_line->port, 443)<0) {
5478 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
5479 goto err;
5482 /* If transports are enabled, next field could be a fingerprint or a
5483 socks argument. If transports are disabled, next field must be
5484 a fingerprint. */
5485 if (smartlist_len(items)) {
5486 if (bridge_line->transport_name) { /* transports enabled: */
5487 field = smartlist_get(items, 0);
5488 smartlist_del_keeporder(items, 0);
5490 /* If it's a key=value pair, then it's a SOCKS argument for the
5491 transport proxy... */
5492 if (string_is_key_value(LOG_DEBUG, field)) {
5493 bridge_line->socks_args = smartlist_new();
5494 smartlist_add(bridge_line->socks_args, field);
5495 } else { /* ...otherwise, it's the bridge fingerprint. */
5496 fingerprint = field;
5499 } else { /* transports disabled: */
5500 fingerprint = smartlist_join_strings(items, "", 0, NULL);
5504 /* Handle fingerprint, if it was provided. */
5505 if (fingerprint) {
5506 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
5507 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
5508 goto err;
5510 if (base16_decode(bridge_line->digest, DIGEST_LEN,
5511 fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
5512 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
5513 goto err;
5517 /* If we are using transports, any remaining items in the smartlist
5518 should be k=v values. */
5519 if (bridge_line->transport_name && smartlist_len(items)) {
5520 if (!bridge_line->socks_args)
5521 bridge_line->socks_args = smartlist_new();
5523 /* append remaining items of 'items' to 'socks_args' */
5524 smartlist_add_all(bridge_line->socks_args, items);
5525 smartlist_clear(items);
5527 tor_assert(smartlist_len(bridge_line->socks_args) > 0);
5530 if (bridge_line->socks_args) {
5531 if (validate_transport_socks_arguments(bridge_line->socks_args) < 0)
5532 goto err;
5535 goto done;
5537 err:
5538 bridge_line_free(bridge_line);
5539 bridge_line = NULL;
5541 done:
5542 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5543 smartlist_free(items);
5544 tor_free(addrport);
5545 tor_free(fingerprint);
5547 return bridge_line;
5550 /** Read the contents of a ClientTransportPlugin or ServerTransportPlugin
5551 * line from <b>line</b>, depending on the value of <b>server</b>. Return 0
5552 * if the line is well-formed, and -1 if it isn't.
5554 * If <b>validate_only</b> is 0, the line is well-formed, and the transport is
5555 * needed by some bridge:
5556 * - If it's an external proxy line, add the transport described in the line to
5557 * our internal transport list.
5558 * - If it's a managed proxy line, launch the managed proxy.
5561 STATIC int
5562 parse_transport_line(const or_options_t *options,
5563 const char *line, int validate_only,
5564 int server)
5567 smartlist_t *items = NULL;
5568 int r;
5569 const char *transports = NULL;
5570 smartlist_t *transport_list = NULL;
5571 char *type = NULL;
5572 char *addrport = NULL;
5573 tor_addr_t addr;
5574 uint16_t port = 0;
5575 int socks_ver = PROXY_NONE;
5577 /* managed proxy options */
5578 int is_managed = 0;
5579 char **proxy_argv = NULL;
5580 char **tmp = NULL;
5581 int proxy_argc, i;
5582 int is_useless_proxy = 1;
5584 int line_length;
5586 /* Split the line into space-separated tokens */
5587 items = smartlist_new();
5588 smartlist_split_string(items, line, NULL,
5589 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5590 line_length = smartlist_len(items);
5592 if (line_length < 3) {
5593 log_warn(LD_CONFIG,
5594 "Too few arguments on %sTransportPlugin line.",
5595 server ? "Server" : "Client");
5596 goto err;
5599 /* Get the first line element, split it to commas into
5600 transport_list (in case it's multiple transports) and validate
5601 the transport names. */
5602 transports = smartlist_get(items, 0);
5603 transport_list = smartlist_new();
5604 smartlist_split_string(transport_list, transports, ",",
5605 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
5606 SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
5607 /* validate transport names */
5608 if (!string_is_C_identifier(transport_name)) {
5609 log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
5610 transport_name);
5611 goto err;
5614 /* see if we actually need the transports provided by this proxy */
5615 if (!validate_only && transport_is_needed(transport_name))
5616 is_useless_proxy = 0;
5617 } SMARTLIST_FOREACH_END(transport_name);
5619 type = smartlist_get(items, 1);
5620 if (!strcmp(type, "exec")) {
5621 is_managed = 1;
5622 } else if (server && !strcmp(type, "proxy")) {
5623 /* 'proxy' syntax only with ServerTransportPlugin */
5624 is_managed = 0;
5625 } else if (!server && !strcmp(type, "socks4")) {
5626 /* 'socks4' syntax only with ClientTransportPlugin */
5627 is_managed = 0;
5628 socks_ver = PROXY_SOCKS4;
5629 } else if (!server && !strcmp(type, "socks5")) {
5630 /* 'socks5' syntax only with ClientTransportPlugin */
5631 is_managed = 0;
5632 socks_ver = PROXY_SOCKS5;
5633 } else {
5634 log_warn(LD_CONFIG,
5635 "Strange %sTransportPlugin type '%s'",
5636 server ? "Server" : "Client", type);
5637 goto err;
5640 if (is_managed && options->Sandbox) {
5641 log_warn(LD_CONFIG,
5642 "Managed proxies are not compatible with Sandbox mode."
5643 "(%sTransportPlugin line was %s)",
5644 server ? "Server" : "Client", escaped(line));
5645 goto err;
5648 if (is_managed) {
5649 /* managed */
5651 if (!server && !validate_only && is_useless_proxy) {
5652 log_info(LD_GENERAL,
5653 "Pluggable transport proxy (%s) does not provide "
5654 "any needed transports and will not be launched.",
5655 line);
5659 * If we are not just validating, use the rest of the line as the
5660 * argv of the proxy to be launched. Also, make sure that we are
5661 * only launching proxies that contribute useful transports.
5664 if (!validate_only && (server || !is_useless_proxy)) {
5665 proxy_argc = line_length - 2;
5666 tor_assert(proxy_argc > 0);
5667 proxy_argv = tor_calloc((proxy_argc + 1), sizeof(char *));
5668 tmp = proxy_argv;
5670 for (i = 0; i < proxy_argc; i++) {
5671 /* store arguments */
5672 *tmp++ = smartlist_get(items, 2);
5673 smartlist_del_keeporder(items, 2);
5675 *tmp = NULL; /* terminated with NULL, just like execve() likes it */
5677 /* kickstart the thing */
5678 if (server) {
5679 pt_kickstart_server_proxy(transport_list, proxy_argv);
5680 } else {
5681 pt_kickstart_client_proxy(transport_list, proxy_argv);
5684 } else {
5685 /* external */
5687 /* ClientTransportPlugins connecting through a proxy is managed only. */
5688 if (!server && (options->Socks4Proxy || options->Socks5Proxy ||
5689 options->HTTPSProxy)) {
5690 log_warn(LD_CONFIG, "You have configured an external proxy with another "
5691 "proxy type. (Socks4Proxy|Socks5Proxy|HTTPSProxy)");
5692 goto err;
5695 if (smartlist_len(transport_list) != 1) {
5696 log_warn(LD_CONFIG,
5697 "You can't have an external proxy with more than "
5698 "one transport.");
5699 goto err;
5702 addrport = smartlist_get(items, 2);
5704 if (tor_addr_port_lookup(addrport, &addr, &port) < 0) {
5705 log_warn(LD_CONFIG,
5706 "Error parsing transport address '%s'", addrport);
5707 goto err;
5710 if (!port) {
5711 log_warn(LD_CONFIG,
5712 "Transport address '%s' has no port.", addrport);
5713 goto err;
5716 if (!validate_only) {
5717 log_info(LD_DIR, "%s '%s' at %s.",
5718 server ? "Server transport" : "Transport",
5719 transports, fmt_addrport(&addr, port));
5721 if (!server) {
5722 transport_add_from_config(&addr, port,
5723 smartlist_get(transport_list, 0),
5724 socks_ver);
5729 r = 0;
5730 goto done;
5732 err:
5733 r = -1;
5735 done:
5736 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5737 smartlist_free(items);
5738 if (transport_list) {
5739 SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
5740 smartlist_free(transport_list);
5743 return r;
5746 /** Given a ServerTransportListenAddr <b>line</b>, return its
5747 * <address:port> string. Return NULL if the line was not
5748 * well-formed.
5750 * If <b>transport</b> is set, return NULL if the line is not
5751 * referring to <b>transport</b>.
5753 * The returned string is allocated on the heap and it's the
5754 * responsibility of the caller to free it. */
5755 static char *
5756 get_bindaddr_from_transport_listen_line(const char *line,const char *transport)
5758 smartlist_t *items = NULL;
5759 const char *parsed_transport = NULL;
5760 char *addrport = NULL;
5761 tor_addr_t addr;
5762 uint16_t port = 0;
5764 items = smartlist_new();
5765 smartlist_split_string(items, line, NULL,
5766 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5768 if (smartlist_len(items) < 2) {
5769 log_warn(LD_CONFIG,"Too few arguments on ServerTransportListenAddr line.");
5770 goto err;
5773 parsed_transport = smartlist_get(items, 0);
5774 addrport = tor_strdup(smartlist_get(items, 1));
5776 /* If 'transport' is given, check if it matches the one on the line */
5777 if (transport && strcmp(transport, parsed_transport))
5778 goto err;
5780 /* Validate addrport */
5781 if (tor_addr_port_parse(LOG_WARN, addrport, &addr, &port, -1)<0) {
5782 log_warn(LD_CONFIG, "Error parsing ServerTransportListenAddr "
5783 "address '%s'", addrport);
5784 goto err;
5787 goto done;
5789 err:
5790 tor_free(addrport);
5791 addrport = NULL;
5793 done:
5794 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5795 smartlist_free(items);
5797 return addrport;
5800 /** Given a ServerTransportOptions <b>line</b>, return a smartlist
5801 * with the options. Return NULL if the line was not well-formed.
5803 * If <b>transport</b> is set, return NULL if the line is not
5804 * referring to <b>transport</b>.
5806 * The returned smartlist and its strings are allocated on the heap
5807 * and it's the responsibility of the caller to free it. */
5808 smartlist_t *
5809 get_options_from_transport_options_line(const char *line,const char *transport)
5811 smartlist_t *items = smartlist_new();
5812 smartlist_t *options = smartlist_new();
5813 const char *parsed_transport = NULL;
5815 smartlist_split_string(items, line, NULL,
5816 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5818 if (smartlist_len(items) < 2) {
5819 log_warn(LD_CONFIG,"Too few arguments on ServerTransportOptions line.");
5820 goto err;
5823 parsed_transport = smartlist_get(items, 0);
5824 /* If 'transport' is given, check if it matches the one on the line */
5825 if (transport && strcmp(transport, parsed_transport))
5826 goto err;
5828 SMARTLIST_FOREACH_BEGIN(items, const char *, option) {
5829 if (option_sl_idx == 0) /* skip the transport field (first field)*/
5830 continue;
5832 /* validate that it's a k=v value */
5833 if (!string_is_key_value(LOG_WARN, option)) {
5834 log_warn(LD_CONFIG, "%s is not a k=v value.", escaped(option));
5835 goto err;
5838 /* add it to the options smartlist */
5839 smartlist_add(options, tor_strdup(option));
5840 log_debug(LD_CONFIG, "Added %s to the list of options", escaped(option));
5841 } SMARTLIST_FOREACH_END(option);
5843 goto done;
5845 err:
5846 SMARTLIST_FOREACH(options, char*, s, tor_free(s));
5847 smartlist_free(options);
5848 options = NULL;
5850 done:
5851 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5852 smartlist_free(items);
5854 return options;
5857 /** Given the name of a pluggable transport in <b>transport</b>, check
5858 * the configuration file to see if the user has explicitly asked for
5859 * it to listen on a specific port. Return a <address:port> string if
5860 * so, otherwise NULL. */
5861 char *
5862 get_transport_bindaddr_from_config(const char *transport)
5864 config_line_t *cl;
5865 const or_options_t *options = get_options();
5867 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
5868 char *bindaddr =
5869 get_bindaddr_from_transport_listen_line(cl->value, transport);
5870 if (bindaddr)
5871 return bindaddr;
5874 return NULL;
5877 /** Given the name of a pluggable transport in <b>transport</b>, check
5878 * the configuration file to see if the user has asked us to pass any
5879 * parameters to the pluggable transport. Return a smartlist
5880 * containing the parameters, otherwise NULL. */
5881 smartlist_t *
5882 get_options_for_server_transport(const char *transport)
5884 config_line_t *cl;
5885 const or_options_t *options = get_options();
5887 for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
5888 smartlist_t *options_sl =
5889 get_options_from_transport_options_line(cl->value, transport);
5890 if (options_sl)
5891 return options_sl;
5894 return NULL;
5897 /** Read the contents of a DirAuthority line from <b>line</b>. If
5898 * <b>validate_only</b> is 0, and the line is well-formed, and it
5899 * shares any bits with <b>required_type</b> or <b>required_type</b>
5900 * is NO_DIRINFO (zero), then add the dirserver described in the line
5901 * (minus whatever bits it's missing) as a valid authority.
5902 * Return 0 on success or filtering out by type,
5903 * or -1 if the line isn't well-formed or if we can't add it. */
5904 STATIC int
5905 parse_dir_authority_line(const char *line, dirinfo_type_t required_type,
5906 int validate_only)
5908 smartlist_t *items = NULL;
5909 int r;
5910 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
5911 tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
5912 uint16_t dir_port = 0, or_port = 0;
5913 char digest[DIGEST_LEN];
5914 char v3_digest[DIGEST_LEN];
5915 dirinfo_type_t type = 0;
5916 double weight = 1.0;
5918 items = smartlist_new();
5919 smartlist_split_string(items, line, NULL,
5920 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5921 if (smartlist_len(items) < 1) {
5922 log_warn(LD_CONFIG, "No arguments on DirAuthority line.");
5923 goto err;
5926 if (is_legal_nickname(smartlist_get(items, 0))) {
5927 nickname = smartlist_get(items, 0);
5928 smartlist_del_keeporder(items, 0);
5931 while (smartlist_len(items)) {
5932 char *flag = smartlist_get(items, 0);
5933 if (TOR_ISDIGIT(flag[0]))
5934 break;
5935 if (!strcasecmp(flag, "hs") ||
5936 !strcasecmp(flag, "no-hs")) {
5937 log_warn(LD_CONFIG, "The DirAuthority options 'hs' and 'no-hs' are "
5938 "obsolete; you don't need them any more.");
5939 } else if (!strcasecmp(flag, "bridge")) {
5940 type |= BRIDGE_DIRINFO;
5941 } else if (!strcasecmp(flag, "no-v2")) {
5942 /* obsolete, but may still be contained in DirAuthority lines generated
5943 by various tools */;
5944 } else if (!strcasecmpstart(flag, "orport=")) {
5945 int ok;
5946 char *portstring = flag + strlen("orport=");
5947 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
5948 if (!ok)
5949 log_warn(LD_CONFIG, "Invalid orport '%s' on DirAuthority line.",
5950 portstring);
5951 } else if (!strcmpstart(flag, "weight=")) {
5952 int ok;
5953 const char *wstring = flag + strlen("weight=");
5954 weight = tor_parse_double(wstring, 0, (double)UINT64_MAX, &ok, NULL);
5955 if (!ok) {
5956 log_warn(LD_CONFIG, "Invalid weight '%s' on DirAuthority line.",flag);
5957 weight=1.0;
5959 } else if (!strcasecmpstart(flag, "v3ident=")) {
5960 char *idstr = flag + strlen("v3ident=");
5961 if (strlen(idstr) != HEX_DIGEST_LEN ||
5962 base16_decode(v3_digest, DIGEST_LEN,
5963 idstr, HEX_DIGEST_LEN) != DIGEST_LEN) {
5964 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirAuthority line",
5965 flag);
5966 } else {
5967 type |= V3_DIRINFO|EXTRAINFO_DIRINFO|MICRODESC_DIRINFO;
5969 } else if (!strcasecmpstart(flag, "ipv6=")) {
5970 if (ipv6_addrport_ptr) {
5971 log_warn(LD_CONFIG, "Redundant ipv6 addr/port on DirAuthority line");
5972 } else {
5973 if (tor_addr_port_parse(LOG_WARN, flag+strlen("ipv6="),
5974 &ipv6_addrport.addr, &ipv6_addrport.port,
5975 -1) < 0
5976 || tor_addr_family(&ipv6_addrport.addr) != AF_INET6) {
5977 log_warn(LD_CONFIG, "Bad ipv6 addr/port %s on DirAuthority line",
5978 escaped(flag));
5979 goto err;
5981 ipv6_addrport_ptr = &ipv6_addrport;
5983 } else {
5984 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirAuthority line",
5985 flag);
5987 tor_free(flag);
5988 smartlist_del_keeporder(items, 0);
5991 if (smartlist_len(items) < 2) {
5992 log_warn(LD_CONFIG, "Too few arguments to DirAuthority line.");
5993 goto err;
5995 addrport = smartlist_get(items, 0);
5996 smartlist_del_keeporder(items, 0);
5997 if (addr_port_lookup(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
5998 log_warn(LD_CONFIG, "Error parsing DirAuthority address '%s'", addrport);
5999 goto err;
6001 if (!dir_port) {
6002 log_warn(LD_CONFIG, "Missing port in DirAuthority address '%s'",addrport);
6003 goto err;
6006 fingerprint = smartlist_join_strings(items, "", 0, NULL);
6007 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
6008 log_warn(LD_CONFIG, "Key digest '%s' for DirAuthority is wrong length %d.",
6009 fingerprint, (int)strlen(fingerprint));
6010 goto err;
6012 if (base16_decode(digest, DIGEST_LEN,
6013 fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
6014 log_warn(LD_CONFIG, "Unable to decode DirAuthority key digest.");
6015 goto err;
6018 if (!validate_only && (!required_type || required_type & type)) {
6019 dir_server_t *ds;
6020 if (required_type)
6021 type &= required_type; /* pare down what we think of them as an
6022 * authority for. */
6023 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
6024 address, (int)dir_port, (char*)smartlist_get(items,0));
6025 if (!(ds = trusted_dir_server_new(nickname, address, dir_port, or_port,
6026 ipv6_addrport_ptr,
6027 digest, v3_digest, type, weight)))
6028 goto err;
6029 dir_server_add(ds);
6032 r = 0;
6033 goto done;
6035 err:
6036 r = -1;
6038 done:
6039 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
6040 smartlist_free(items);
6041 tor_free(addrport);
6042 tor_free(address);
6043 tor_free(nickname);
6044 tor_free(fingerprint);
6045 return r;
6048 /** Read the contents of a FallbackDir line from <b>line</b>. If
6049 * <b>validate_only</b> is 0, and the line is well-formed, then add the
6050 * dirserver described in the line as a fallback directory. Return 0 on
6051 * success, or -1 if the line isn't well-formed or if we can't add it. */
6053 parse_dir_fallback_line(const char *line,
6054 int validate_only)
6056 int r = -1;
6057 smartlist_t *items = smartlist_new(), *positional = smartlist_new();
6058 int orport = -1;
6059 uint16_t dirport;
6060 tor_addr_t addr;
6061 int ok;
6062 char id[DIGEST_LEN];
6063 char *address=NULL;
6064 tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
6065 double weight=1.0;
6067 memset(id, 0, sizeof(id));
6068 smartlist_split_string(items, line, NULL,
6069 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6070 SMARTLIST_FOREACH_BEGIN(items, const char *, cp) {
6071 const char *eq = strchr(cp, '=');
6072 ok = 1;
6073 if (! eq) {
6074 smartlist_add(positional, (char*)cp);
6075 continue;
6077 if (!strcmpstart(cp, "orport=")) {
6078 orport = (int)tor_parse_long(cp+strlen("orport="), 10,
6079 1, 65535, &ok, NULL);
6080 } else if (!strcmpstart(cp, "id=")) {
6081 ok = base16_decode(id, DIGEST_LEN, cp+strlen("id="),
6082 strlen(cp)-strlen("id=")) == DIGEST_LEN;
6083 } else if (!strcasecmpstart(cp, "ipv6=")) {
6084 if (ipv6_addrport_ptr) {
6085 log_warn(LD_CONFIG, "Redundant ipv6 addr/port on FallbackDir line");
6086 } else {
6087 if (tor_addr_port_parse(LOG_WARN, cp+strlen("ipv6="),
6088 &ipv6_addrport.addr, &ipv6_addrport.port,
6089 -1) < 0
6090 || tor_addr_family(&ipv6_addrport.addr) != AF_INET6) {
6091 log_warn(LD_CONFIG, "Bad ipv6 addr/port %s on FallbackDir line",
6092 escaped(cp));
6093 goto end;
6095 ipv6_addrport_ptr = &ipv6_addrport;
6097 } else if (!strcmpstart(cp, "weight=")) {
6098 int num_ok;
6099 const char *wstring = cp + strlen("weight=");
6100 weight = tor_parse_double(wstring, 0, (double)UINT64_MAX, &num_ok, NULL);
6101 if (!num_ok) {
6102 log_warn(LD_CONFIG, "Invalid weight '%s' on FallbackDir line.", cp);
6103 weight=1.0;
6107 if (!ok) {
6108 log_warn(LD_CONFIG, "Bad FallbackDir option %s", escaped(cp));
6109 goto end;
6111 } SMARTLIST_FOREACH_END(cp);
6113 if (smartlist_len(positional) != 1) {
6114 log_warn(LD_CONFIG, "Couldn't parse FallbackDir line %s", escaped(line));
6115 goto end;
6118 if (tor_digest_is_zero(id)) {
6119 log_warn(LD_CONFIG, "Missing identity on FallbackDir line");
6120 goto end;
6123 if (orport <= 0) {
6124 log_warn(LD_CONFIG, "Missing orport on FallbackDir line");
6125 goto end;
6128 if (tor_addr_port_split(LOG_INFO, smartlist_get(positional, 0),
6129 &address, &dirport) < 0 ||
6130 tor_addr_parse(&addr, address)<0) {
6131 log_warn(LD_CONFIG, "Couldn't parse address:port %s on FallbackDir line",
6132 (const char*)smartlist_get(positional, 0));
6133 goto end;
6136 if (!validate_only) {
6137 dir_server_t *ds;
6138 ds = fallback_dir_server_new(&addr, dirport, orport, ipv6_addrport_ptr,
6139 id, weight);
6140 if (!ds) {
6141 log_warn(LD_CONFIG, "Couldn't create FallbackDir %s", escaped(line));
6142 goto end;
6144 dir_server_add(ds);
6147 r = 0;
6149 end:
6150 SMARTLIST_FOREACH(items, char *, cp, tor_free(cp));
6151 smartlist_free(items);
6152 smartlist_free(positional);
6153 tor_free(address);
6154 return r;
6157 /** Allocate and return a new port_cfg_t with reasonable defaults. */
6158 STATIC port_cfg_t *
6159 port_cfg_new(size_t namelen)
6161 tor_assert(namelen <= SIZE_T_CEILING - sizeof(port_cfg_t) - 1);
6162 port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t) + namelen + 1);
6163 cfg->entry_cfg.ipv4_traffic = 1;
6164 cfg->entry_cfg.dns_request = 1;
6165 cfg->entry_cfg.onion_traffic = 1;
6166 cfg->entry_cfg.cache_ipv4_answers = 1;
6167 cfg->entry_cfg.prefer_ipv6_virtaddr = 1;
6168 return cfg;
6171 /** Free all storage held in <b>port</b> */
6172 STATIC void
6173 port_cfg_free(port_cfg_t *port)
6175 tor_free(port);
6178 /** Warn for every port in <b>ports</b> of type <b>listener_type</b> that is
6179 * on a publicly routable address. */
6180 static void
6181 warn_nonlocal_client_ports(const smartlist_t *ports, const char *portname,
6182 int listener_type)
6184 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
6185 if (port->type != listener_type)
6186 continue;
6187 if (port->is_unix_addr) {
6188 /* Unix sockets aren't accessible over a network. */
6189 } else if (!tor_addr_is_internal(&port->addr, 1)) {
6190 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
6191 "Other people on the Internet might find your computer and "
6192 "use it as an open proxy. Please don't allow this unless you "
6193 "have a good reason.",
6194 fmt_addrport(&port->addr, port->port), portname);
6195 } else if (!tor_addr_is_loopback(&port->addr)) {
6196 log_notice(LD_CONFIG, "You configured a non-loopback address '%s' "
6197 "for %sPort. This allows everybody on your local network to "
6198 "use your machine as a proxy. Make sure this is what you "
6199 "wanted.",
6200 fmt_addrport(&port->addr, port->port), portname);
6202 } SMARTLIST_FOREACH_END(port);
6205 /** Warn for every Extended ORPort port in <b>ports</b> that is on a
6206 * publicly routable address. */
6207 static void
6208 warn_nonlocal_ext_orports(const smartlist_t *ports, const char *portname)
6210 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
6211 if (port->type != CONN_TYPE_EXT_OR_LISTENER)
6212 continue;
6213 if (port->is_unix_addr)
6214 continue;
6215 /* XXX maybe warn even if address is RFC1918? */
6216 if (!tor_addr_is_internal(&port->addr, 1)) {
6217 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
6218 "This is not advised; this address is supposed to only be "
6219 "exposed on localhost so that your pluggable transport "
6220 "proxies can connect to it.",
6221 fmt_addrport(&port->addr, port->port), portname);
6223 } SMARTLIST_FOREACH_END(port);
6226 /** Given a list of port_cfg_t in <b>ports</b>, warn if any controller port
6227 * there is listening on any non-loopback address. If <b>forbid_nonlocal</b>
6228 * is true, then emit a stronger warning and remove the port from the list.
6230 static void
6231 warn_nonlocal_controller_ports(smartlist_t *ports, unsigned forbid_nonlocal)
6233 int warned = 0;
6234 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
6235 if (port->type != CONN_TYPE_CONTROL_LISTENER)
6236 continue;
6237 if (port->is_unix_addr)
6238 continue;
6239 if (!tor_addr_is_loopback(&port->addr)) {
6240 if (forbid_nonlocal) {
6241 if (!warned)
6242 log_warn(LD_CONFIG,
6243 "You have a ControlPort set to accept "
6244 "unauthenticated connections from a non-local address. "
6245 "This means that programs not running on your computer "
6246 "can reconfigure your Tor, without even having to guess a "
6247 "password. That's so bad that I'm closing your ControlPort "
6248 "for you. If you need to control your Tor remotely, try "
6249 "enabling authentication and using a tool like stunnel or "
6250 "ssh to encrypt remote access.");
6251 warned = 1;
6252 port_cfg_free(port);
6253 SMARTLIST_DEL_CURRENT(ports, port);
6254 } else {
6255 log_warn(LD_CONFIG, "You have a ControlPort set to accept "
6256 "connections from a non-local address. This means that "
6257 "programs not running on your computer can reconfigure your "
6258 "Tor. That's pretty bad, since the controller "
6259 "protocol isn't encrypted! Maybe you should just listen on "
6260 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
6261 "remote connections to your control port.");
6262 return; /* No point in checking the rest */
6265 } SMARTLIST_FOREACH_END(port);
6269 * Take a string (<b>line</b>) that begins with either an address:port, a
6270 * port, or an AF_UNIX address, optionally quoted, prefixed with
6271 * "unix:". Parse that line, and on success, set <b>addrport_out</b> to a new
6272 * string containing the beginning portion (without prefix). Iff there was a
6273 * unix: prefix, set <b>is_unix_out</b> to true. On success, also set
6274 * <b>rest_out</b> to point to the part of the line after the address portion.
6276 * Return 0 on success, -1 on failure.
6279 port_cfg_line_extract_addrport(const char *line,
6280 char **addrport_out,
6281 int *is_unix_out,
6282 const char **rest_out)
6284 tor_assert(line);
6285 tor_assert(addrport_out);
6286 tor_assert(is_unix_out);
6287 tor_assert(rest_out);
6289 line = eat_whitespace(line);
6291 if (!strcmpstart(line, unix_q_socket_prefix)) {
6292 // It starts with unix:"
6293 size_t sz;
6294 *is_unix_out = 1;
6295 *addrport_out = NULL;
6296 line += strlen(unix_socket_prefix); /*No q: Keep the quote */
6297 *rest_out = unescape_string(line, addrport_out, &sz);
6298 if (!*rest_out || (*addrport_out && sz != strlen(*addrport_out))) {
6299 tor_free(*addrport_out);
6300 return -1;
6302 *rest_out = eat_whitespace(*rest_out);
6303 return 0;
6304 } else {
6305 // Is there a unix: prefix?
6306 if (!strcmpstart(line, unix_socket_prefix)) {
6307 line += strlen(unix_socket_prefix);
6308 *is_unix_out = 1;
6309 } else {
6310 *is_unix_out = 0;
6313 const char *end = find_whitespace(line);
6314 if (BUG(!end)) {
6315 end = strchr(line, '\0'); // LCOV_EXCL_LINE -- this can't be NULL
6317 tor_assert(end && end >= line);
6318 *addrport_out = tor_strndup(line, end - line);
6319 *rest_out = eat_whitespace(end);
6320 return 0;
6324 static void
6325 warn_client_dns_cache(const char *option, int disabling)
6327 if (disabling)
6328 return;
6330 warn_deprecated_option(option,
6331 "Client-side DNS cacheing enables a wide variety of route-"
6332 "capture attacks. If a single bad exit node lies to you about "
6333 "an IP address, cacheing that address would make you visit "
6334 "an address of the attacker's choice every time you connected "
6335 "to your destination.");
6339 * Parse port configuration for a single port type.
6341 * Read entries of the "FooPort" type from the list <b>ports</b>, and
6342 * entries of the "FooListenAddress" type from the list
6343 * <b>listenaddrs</b>. Two syntaxes are supported: a legacy syntax
6344 * where FooPort is at most a single entry containing a port number and
6345 * where FooListenAddress has any number of address:port combinations;
6346 * and a new syntax where there are no FooListenAddress entries and
6347 * where FooPort can have any number of entries of the format
6348 * "[Address:][Port] IsolationOptions".
6350 * In log messages, describe the port type as <b>portname</b>.
6352 * If no address is specified, default to <b>defaultaddr</b>. If no
6353 * FooPort is given, default to defaultport (if 0, there is no default).
6355 * If CL_PORT_NO_STREAM_OPTIONS is set in <b>flags</b>, do not allow stream
6356 * isolation options in the FooPort entries.
6358 * If CL_PORT_WARN_NONLOCAL is set in <b>flags</b>, warn if any of the
6359 * ports are not on a local address. If CL_PORT_FORBID_NONLOCAL is set,
6360 * this is a control port with no password set: don't even allow it.
6362 * Unless CL_PORT_ALLOW_EXTRA_LISTENADDR is set in <b>flags</b>, warn
6363 * if FooListenAddress is set but FooPort is 0.
6365 * If CL_PORT_SERVER_OPTIONS is set in <b>flags</b>, do not allow stream
6366 * isolation options in the FooPort entries; instead allow the
6367 * server-port option set.
6369 * If CL_PORT_TAKES_HOSTNAMES is set in <b>flags</b>, allow the options
6370 * {No,}IPv{4,6}Traffic.
6372 * On success, if <b>out</b> is given, add a new port_cfg_t entry to
6373 * <b>out</b> for every port that the client should listen on. Return 0
6374 * on success, -1 on failure.
6376 STATIC int
6377 parse_port_config(smartlist_t *out,
6378 const config_line_t *ports,
6379 const config_line_t *listenaddrs,
6380 const char *portname,
6381 int listener_type,
6382 const char *defaultaddr,
6383 int defaultport,
6384 const unsigned flags)
6386 smartlist_t *elts;
6387 int retval = -1;
6388 const unsigned is_control = (listener_type == CONN_TYPE_CONTROL_LISTENER);
6389 const unsigned is_ext_orport = (listener_type == CONN_TYPE_EXT_OR_LISTENER);
6390 const unsigned allow_no_stream_options = flags & CL_PORT_NO_STREAM_OPTIONS;
6391 const unsigned use_server_options = flags & CL_PORT_SERVER_OPTIONS;
6392 const unsigned warn_nonlocal = flags & CL_PORT_WARN_NONLOCAL;
6393 const unsigned forbid_nonlocal = flags & CL_PORT_FORBID_NONLOCAL;
6394 const unsigned default_to_group_writable =
6395 flags & CL_PORT_DFLT_GROUP_WRITABLE;
6396 const unsigned allow_spurious_listenaddr =
6397 flags & CL_PORT_ALLOW_EXTRA_LISTENADDR;
6398 const unsigned takes_hostnames = flags & CL_PORT_TAKES_HOSTNAMES;
6399 const unsigned is_unix_socket = flags & CL_PORT_IS_UNIXSOCKET;
6400 int got_zero_port=0, got_nonzero_port=0;
6401 char *unix_socket_path = NULL;
6403 /* FooListenAddress is deprecated; let's make it work like it used to work,
6404 * though. */
6405 if (listenaddrs) {
6406 int mainport = defaultport;
6408 if (ports && ports->next) {
6409 log_warn(LD_CONFIG, "%sListenAddress can't be used when there are "
6410 "multiple %sPort lines", portname, portname);
6411 return -1;
6412 } else if (ports) {
6413 if (!strcmp(ports->value, "auto")) {
6414 mainport = CFG_AUTO_PORT;
6415 } else {
6416 int ok;
6417 mainport = (int)tor_parse_long(ports->value, 10, 0, 65535, &ok, NULL);
6418 if (!ok) {
6419 log_warn(LD_CONFIG, "%sListenAddress can only be used with a single "
6420 "%sPort with value \"auto\" or 1-65535 and no options set.",
6421 portname, portname);
6422 return -1;
6427 if (mainport == 0) {
6428 if (allow_spurious_listenaddr)
6429 return 1; /*DOCDOC*/
6430 log_warn(LD_CONFIG, "%sPort must be defined if %sListenAddress is used",
6431 portname, portname);
6432 return -1;
6435 if (use_server_options && out) {
6436 /* Add a no_listen port. */
6437 port_cfg_t *cfg = port_cfg_new(0);
6438 cfg->type = listener_type;
6439 cfg->port = mainport;
6440 tor_addr_make_unspec(&cfg->addr); /* Server ports default to 0.0.0.0 */
6441 cfg->server_cfg.no_listen = 1;
6442 cfg->server_cfg.bind_ipv4_only = 1;
6443 /* cfg->entry_cfg defaults are already set by port_cfg_new */
6444 smartlist_add(out, cfg);
6447 for (; listenaddrs; listenaddrs = listenaddrs->next) {
6448 tor_addr_t addr;
6449 uint16_t port = 0;
6450 if (tor_addr_port_lookup(listenaddrs->value, &addr, &port) < 0) {
6451 log_warn(LD_CONFIG, "Unable to parse %sListenAddress '%s'",
6452 portname, listenaddrs->value);
6453 return -1;
6455 if (out) {
6456 port_cfg_t *cfg = port_cfg_new(0);
6457 cfg->type = listener_type;
6458 cfg->port = port ? port : mainport;
6459 tor_addr_copy(&cfg->addr, &addr);
6460 cfg->entry_cfg.session_group = SESSION_GROUP_UNSET;
6461 cfg->entry_cfg.isolation_flags = ISO_DEFAULT;
6462 cfg->server_cfg.no_advertise = 1;
6463 smartlist_add(out, cfg);
6467 if (warn_nonlocal && out) {
6468 if (is_control)
6469 warn_nonlocal_controller_ports(out, forbid_nonlocal);
6470 else if (is_ext_orport)
6471 warn_nonlocal_ext_orports(out, portname);
6472 else
6473 warn_nonlocal_client_ports(out, portname, listener_type);
6475 return 0;
6476 } /* end if (listenaddrs) */
6478 /* No ListenAddress lines. If there's no FooPort, then maybe make a default
6479 * one. */
6480 if (! ports) {
6481 if (defaultport && defaultaddr && out) {
6482 port_cfg_t *cfg = port_cfg_new(is_unix_socket ? strlen(defaultaddr) : 0);
6483 cfg->type = listener_type;
6484 if (is_unix_socket) {
6485 tor_addr_make_unspec(&cfg->addr);
6486 memcpy(cfg->unix_addr, defaultaddr, strlen(defaultaddr) + 1);
6487 cfg->is_unix_addr = 1;
6488 } else {
6489 cfg->port = defaultport;
6490 tor_addr_parse(&cfg->addr, defaultaddr);
6492 cfg->entry_cfg.session_group = SESSION_GROUP_UNSET;
6493 cfg->entry_cfg.isolation_flags = ISO_DEFAULT;
6494 smartlist_add(out, cfg);
6496 return 0;
6499 /* At last we can actually parse the FooPort lines. The syntax is:
6500 * [Addr:](Port|auto) [Options].*/
6501 elts = smartlist_new();
6502 char *addrport = NULL;
6504 for (; ports; ports = ports->next) {
6505 tor_addr_t addr;
6506 int port;
6507 int sessiongroup = SESSION_GROUP_UNSET;
6508 unsigned isolation = ISO_DEFAULT;
6509 int prefer_no_auth = 0;
6510 int socks_iso_keep_alive = 0;
6512 uint16_t ptmp=0;
6513 int ok;
6514 /* This must be kept in sync with port_cfg_new's defaults */
6515 int no_listen = 0, no_advertise = 0, all_addrs = 0,
6516 bind_ipv4_only = 0, bind_ipv6_only = 0,
6517 ipv4_traffic = 1, ipv6_traffic = 0, prefer_ipv6 = 0, dns_request = 1,
6518 onion_traffic = 1,
6519 cache_ipv4 = 1, use_cached_ipv4 = 0,
6520 cache_ipv6 = 0, use_cached_ipv6 = 0,
6521 prefer_ipv6_automap = 1, world_writable = 0, group_writable = 0,
6522 relax_dirmode_check = 0,
6523 has_used_unix_socket_only_option = 0;
6525 int is_unix_tagged_addr = 0;
6526 const char *rest_of_line = NULL;
6527 if (port_cfg_line_extract_addrport(ports->value,
6528 &addrport, &is_unix_tagged_addr, &rest_of_line)<0) {
6529 log_warn(LD_CONFIG, "Invalid %sPort line with unparsable address",
6530 portname);
6531 goto err;
6533 if (strlen(addrport) == 0) {
6534 log_warn(LD_CONFIG, "Invalid %sPort line with no address", portname);
6535 goto err;
6538 /* Split the remainder... */
6539 smartlist_split_string(elts, rest_of_line, NULL,
6540 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
6542 /* Let's start to check if it's a Unix socket path. */
6543 if (is_unix_tagged_addr) {
6544 #ifndef HAVE_SYS_UN_H
6545 log_warn(LD_CONFIG, "Unix sockets not supported on this system.");
6546 goto err;
6547 #endif
6548 unix_socket_path = addrport;
6549 addrport = NULL;
6552 if (unix_socket_path &&
6553 ! conn_listener_type_supports_af_unix(listener_type)) {
6554 log_warn(LD_CONFIG, "%sPort does not support unix sockets", portname);
6555 goto err;
6558 if (unix_socket_path) {
6559 port = 1;
6560 } else if (is_unix_socket) {
6561 if (BUG(!addrport))
6562 goto err; // LCOV_EXCL_LINE unreachable, but coverity can't tell that
6563 unix_socket_path = tor_strdup(addrport);
6564 if (!strcmp(addrport, "0"))
6565 port = 0;
6566 else
6567 port = 1;
6568 } else if (!strcmp(addrport, "auto")) {
6569 port = CFG_AUTO_PORT;
6570 int af = tor_addr_parse(&addr, defaultaddr);
6571 tor_assert(af >= 0);
6572 } else if (!strcasecmpend(addrport, ":auto")) {
6573 char *addrtmp = tor_strndup(addrport, strlen(addrport)-5);
6574 port = CFG_AUTO_PORT;
6575 if (tor_addr_port_lookup(addrtmp, &addr, &ptmp)<0 || ptmp) {
6576 log_warn(LD_CONFIG, "Invalid address '%s' for %sPort",
6577 escaped(addrport), portname);
6578 tor_free(addrtmp);
6579 goto err;
6581 tor_free(addrtmp);
6582 } else {
6583 /* Try parsing integer port before address, because, who knows?
6584 "9050" might be a valid address. */
6585 port = (int) tor_parse_long(addrport, 10, 0, 65535, &ok, NULL);
6586 if (ok) {
6587 int af = tor_addr_parse(&addr, defaultaddr);
6588 tor_assert(af >= 0);
6589 } else if (tor_addr_port_lookup(addrport, &addr, &ptmp) == 0) {
6590 if (ptmp == 0) {
6591 log_warn(LD_CONFIG, "%sPort line has address but no port", portname);
6592 goto err;
6594 port = ptmp;
6595 } else {
6596 log_warn(LD_CONFIG, "Couldn't parse address %s for %sPort",
6597 escaped(addrport), portname);
6598 goto err;
6602 if (unix_socket_path && default_to_group_writable)
6603 group_writable = 1;
6605 /* Now parse the rest of the options, if any. */
6606 if (use_server_options) {
6607 /* This is a server port; parse advertising options */
6608 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
6609 if (!strcasecmp(elt, "NoAdvertise")) {
6610 no_advertise = 1;
6611 } else if (!strcasecmp(elt, "NoListen")) {
6612 no_listen = 1;
6613 #if 0
6614 /* not implemented yet. */
6615 } else if (!strcasecmp(elt, "AllAddrs")) {
6617 all_addrs = 1;
6618 #endif
6619 } else if (!strcasecmp(elt, "IPv4Only")) {
6620 bind_ipv4_only = 1;
6621 } else if (!strcasecmp(elt, "IPv6Only")) {
6622 bind_ipv6_only = 1;
6623 } else {
6624 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6625 portname, escaped(elt));
6627 } SMARTLIST_FOREACH_END(elt);
6629 if (no_advertise && no_listen) {
6630 log_warn(LD_CONFIG, "Tried to set both NoListen and NoAdvertise "
6631 "on %sPort line '%s'",
6632 portname, escaped(ports->value));
6633 goto err;
6635 if (bind_ipv4_only && bind_ipv6_only) {
6636 log_warn(LD_CONFIG, "Tried to set both IPv4Only and IPv6Only "
6637 "on %sPort line '%s'",
6638 portname, escaped(ports->value));
6639 goto err;
6641 if (bind_ipv4_only && tor_addr_family(&addr) == AF_INET6) {
6642 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv6",
6643 portname);
6644 goto err;
6646 if (bind_ipv6_only && tor_addr_family(&addr) == AF_INET) {
6647 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv4",
6648 portname);
6649 goto err;
6651 } else {
6652 /* This is a client port; parse isolation options */
6653 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
6654 int no = 0, isoflag = 0;
6655 const char *elt_orig = elt;
6657 if (!strcasecmpstart(elt, "SessionGroup=")) {
6658 int group = (int)tor_parse_long(elt+strlen("SessionGroup="),
6659 10, 0, INT_MAX, &ok, NULL);
6660 if (!ok || !allow_no_stream_options) {
6661 log_warn(LD_CONFIG, "Invalid %sPort option '%s'",
6662 portname, escaped(elt));
6663 goto err;
6665 if (sessiongroup >= 0) {
6666 log_warn(LD_CONFIG, "Multiple SessionGroup options on %sPort",
6667 portname);
6668 goto err;
6670 sessiongroup = group;
6671 continue;
6674 if (!strcasecmpstart(elt, "No")) {
6675 no = 1;
6676 elt += 2;
6679 if (!strcasecmp(elt, "GroupWritable")) {
6680 group_writable = !no;
6681 has_used_unix_socket_only_option = 1;
6682 continue;
6683 } else if (!strcasecmp(elt, "WorldWritable")) {
6684 world_writable = !no;
6685 has_used_unix_socket_only_option = 1;
6686 continue;
6687 } else if (!strcasecmp(elt, "RelaxDirModeCheck")) {
6688 relax_dirmode_check = !no;
6689 has_used_unix_socket_only_option = 1;
6690 continue;
6693 if (allow_no_stream_options) {
6694 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6695 portname, escaped(elt));
6696 continue;
6699 if (takes_hostnames) {
6700 if (!strcasecmp(elt, "IPv4Traffic")) {
6701 ipv4_traffic = ! no;
6702 continue;
6703 } else if (!strcasecmp(elt, "IPv6Traffic")) {
6704 ipv6_traffic = ! no;
6705 continue;
6706 } else if (!strcasecmp(elt, "PreferIPv6")) {
6707 prefer_ipv6 = ! no;
6708 continue;
6709 } else if (!strcasecmp(elt, "DNSRequest")) {
6710 dns_request = ! no;
6711 continue;
6712 } else if (!strcasecmp(elt, "OnionTraffic")) {
6713 onion_traffic = ! no;
6714 continue;
6715 } else if (!strcasecmp(elt, "OnionTrafficOnly")) {
6716 /* Only connect to .onion addresses. Equivalent to
6717 * NoDNSRequest, NoIPv4Traffic, NoIPv6Traffic. The option
6718 * NoOnionTrafficOnly is not supported, it's too confusing. */
6719 if (no) {
6720 log_warn(LD_CONFIG, "Unsupported %sPort option 'No%s'. Use "
6721 "DNSRequest, IPv4Traffic, and/or IPv6Traffic instead.",
6722 portname, escaped(elt));
6723 } else {
6724 ipv4_traffic = ipv6_traffic = dns_request = 0;
6726 continue;
6729 if (!strcasecmp(elt, "CacheIPv4DNS")) {
6730 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6731 cache_ipv4 = ! no;
6732 continue;
6733 } else if (!strcasecmp(elt, "CacheIPv6DNS")) {
6734 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6735 cache_ipv6 = ! no;
6736 continue;
6737 } else if (!strcasecmp(elt, "CacheDNS")) {
6738 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6739 cache_ipv4 = cache_ipv6 = ! no;
6740 continue;
6741 } else if (!strcasecmp(elt, "UseIPv4Cache")) {
6742 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6743 use_cached_ipv4 = ! no;
6744 continue;
6745 } else if (!strcasecmp(elt, "UseIPv6Cache")) {
6746 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6747 use_cached_ipv6 = ! no;
6748 continue;
6749 } else if (!strcasecmp(elt, "UseDNSCache")) {
6750 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6751 use_cached_ipv4 = use_cached_ipv6 = ! no;
6752 continue;
6753 } else if (!strcasecmp(elt, "PreferIPv6Automap")) {
6754 prefer_ipv6_automap = ! no;
6755 continue;
6756 } else if (!strcasecmp(elt, "PreferSOCKSNoAuth")) {
6757 prefer_no_auth = ! no;
6758 continue;
6759 } else if (!strcasecmp(elt, "KeepAliveIsolateSOCKSAuth")) {
6760 socks_iso_keep_alive = ! no;
6761 continue;
6764 if (!strcasecmpend(elt, "s"))
6765 elt[strlen(elt)-1] = '\0'; /* kill plurals. */
6767 if (!strcasecmp(elt, "IsolateDestPort")) {
6768 isoflag = ISO_DESTPORT;
6769 } else if (!strcasecmp(elt, "IsolateDestAddr")) {
6770 isoflag = ISO_DESTADDR;
6771 } else if (!strcasecmp(elt, "IsolateSOCKSAuth")) {
6772 isoflag = ISO_SOCKSAUTH;
6773 } else if (!strcasecmp(elt, "IsolateClientProtocol")) {
6774 isoflag = ISO_CLIENTPROTO;
6775 } else if (!strcasecmp(elt, "IsolateClientAddr")) {
6776 isoflag = ISO_CLIENTADDR;
6777 } else {
6778 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6779 portname, escaped(elt_orig));
6782 if (no) {
6783 isolation &= ~isoflag;
6784 } else {
6785 isolation |= isoflag;
6787 } SMARTLIST_FOREACH_END(elt);
6790 if (port)
6791 got_nonzero_port = 1;
6792 else
6793 got_zero_port = 1;
6795 if (dns_request == 0 && listener_type == CONN_TYPE_AP_DNS_LISTENER) {
6796 log_warn(LD_CONFIG, "You have a %sPort entry with DNS disabled; that "
6797 "won't work.", portname);
6798 goto err;
6801 if (ipv4_traffic == 0 && ipv6_traffic == 0 && onion_traffic == 0
6802 && listener_type != CONN_TYPE_AP_DNS_LISTENER) {
6803 log_warn(LD_CONFIG, "You have a %sPort entry with all of IPv4 and "
6804 "IPv6 and .onion disabled; that won't work.", portname);
6805 goto err;
6808 if (dns_request == 1 && ipv4_traffic == 0 && ipv6_traffic == 0
6809 && listener_type != CONN_TYPE_AP_DNS_LISTENER) {
6810 log_warn(LD_CONFIG, "You have a %sPort entry with DNSRequest enabled, "
6811 "but IPv4 and IPv6 disabled; DNS-based sites won't work.",
6812 portname);
6813 goto err;
6816 if ( has_used_unix_socket_only_option && ! unix_socket_path) {
6817 log_warn(LD_CONFIG, "You have a %sPort entry with GroupWritable, "
6818 "WorldWritable, or RelaxDirModeCheck, but it is not a "
6819 "unix socket.", portname);
6820 goto err;
6823 if (!(isolation & ISO_SOCKSAUTH) && socks_iso_keep_alive) {
6824 log_warn(LD_CONFIG, "You have a %sPort entry with both "
6825 "NoIsolateSOCKSAuth and KeepAliveIsolateSOCKSAuth set.",
6826 portname);
6827 goto err;
6830 if (unix_socket_path && (isolation & ISO_CLIENTADDR)) {
6831 /* `IsolateClientAddr` is nonsensical in the context of AF_LOCAL.
6832 * just silently remove the isolation flag.
6834 isolation &= ~ISO_CLIENTADDR;
6837 if (out && port) {
6838 size_t namelen = unix_socket_path ? strlen(unix_socket_path) : 0;
6839 port_cfg_t *cfg = port_cfg_new(namelen);
6840 if (unix_socket_path) {
6841 tor_addr_make_unspec(&cfg->addr);
6842 memcpy(cfg->unix_addr, unix_socket_path, namelen + 1);
6843 cfg->is_unix_addr = 1;
6844 tor_free(unix_socket_path);
6845 } else {
6846 tor_addr_copy(&cfg->addr, &addr);
6847 cfg->port = port;
6849 cfg->type = listener_type;
6850 cfg->is_world_writable = world_writable;
6851 cfg->is_group_writable = group_writable;
6852 cfg->relax_dirmode_check = relax_dirmode_check;
6853 cfg->entry_cfg.isolation_flags = isolation;
6854 cfg->entry_cfg.session_group = sessiongroup;
6855 cfg->server_cfg.no_advertise = no_advertise;
6856 cfg->server_cfg.no_listen = no_listen;
6857 cfg->server_cfg.all_addrs = all_addrs;
6858 cfg->server_cfg.bind_ipv4_only = bind_ipv4_only;
6859 cfg->server_cfg.bind_ipv6_only = bind_ipv6_only;
6860 cfg->entry_cfg.ipv4_traffic = ipv4_traffic;
6861 cfg->entry_cfg.ipv6_traffic = ipv6_traffic;
6862 cfg->entry_cfg.prefer_ipv6 = prefer_ipv6;
6863 cfg->entry_cfg.dns_request = dns_request;
6864 cfg->entry_cfg.onion_traffic = onion_traffic;
6865 cfg->entry_cfg.cache_ipv4_answers = cache_ipv4;
6866 cfg->entry_cfg.cache_ipv6_answers = cache_ipv6;
6867 cfg->entry_cfg.use_cached_ipv4_answers = use_cached_ipv4;
6868 cfg->entry_cfg.use_cached_ipv6_answers = use_cached_ipv6;
6869 cfg->entry_cfg.prefer_ipv6_virtaddr = prefer_ipv6_automap;
6870 cfg->entry_cfg.socks_prefer_no_auth = prefer_no_auth;
6871 if (! (isolation & ISO_SOCKSAUTH))
6872 cfg->entry_cfg.socks_prefer_no_auth = 1;
6873 cfg->entry_cfg.socks_iso_keep_alive = socks_iso_keep_alive;
6875 smartlist_add(out, cfg);
6877 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
6878 smartlist_clear(elts);
6879 tor_free(addrport);
6882 if (warn_nonlocal && out) {
6883 if (is_control)
6884 warn_nonlocal_controller_ports(out, forbid_nonlocal);
6885 else if (is_ext_orport)
6886 warn_nonlocal_ext_orports(out, portname);
6887 else
6888 warn_nonlocal_client_ports(out, portname, listener_type);
6891 if (got_zero_port && got_nonzero_port) {
6892 log_warn(LD_CONFIG, "You specified a nonzero %sPort along with '%sPort 0' "
6893 "in the same configuration. Did you mean to disable %sPort or "
6894 "not?", portname, portname, portname);
6895 goto err;
6898 retval = 0;
6899 err:
6900 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
6901 smartlist_free(elts);
6902 tor_free(unix_socket_path);
6903 tor_free(addrport);
6904 return retval;
6907 /** Return the number of ports which are actually going to listen with type
6908 * <b>listenertype</b>. Do not count no_listen ports. Only count unix
6909 * sockets if count_sockets is true. */
6910 static int
6911 count_real_listeners(const smartlist_t *ports, int listenertype,
6912 int count_sockets)
6914 int n = 0;
6915 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
6916 if (port->server_cfg.no_listen)
6917 continue;
6918 if (!count_sockets && port->is_unix_addr)
6919 continue;
6920 if (port->type != listenertype)
6921 continue;
6922 ++n;
6923 } SMARTLIST_FOREACH_END(port);
6924 return n;
6927 /** Parse all ports from <b>options</b>. On success, set *<b>n_ports_out</b>
6928 * to the number of ports that are listed, update the *Port_set values in
6929 * <b>options</b>, and return 0. On failure, set *<b>msg</b> to a
6930 * description of the problem and return -1.
6932 * If <b>validate_only</b> is false, set configured_client_ports to the
6933 * new list of ports parsed from <b>options</b>.
6935 static int
6936 parse_ports(or_options_t *options, int validate_only,
6937 char **msg, int *n_ports_out,
6938 int *world_writable_control_socket)
6940 smartlist_t *ports;
6941 int retval = -1;
6943 ports = smartlist_new();
6945 *n_ports_out = 0;
6947 const unsigned gw_flag = options->SocksSocketsGroupWritable ?
6948 CL_PORT_DFLT_GROUP_WRITABLE : 0;
6949 if (parse_port_config(ports,
6950 options->SocksPort_lines, options->SocksListenAddress,
6951 "Socks", CONN_TYPE_AP_LISTENER,
6952 "127.0.0.1", 9050,
6953 CL_PORT_WARN_NONLOCAL|CL_PORT_ALLOW_EXTRA_LISTENADDR|
6954 CL_PORT_TAKES_HOSTNAMES|gw_flag) < 0) {
6955 *msg = tor_strdup("Invalid SocksPort/SocksListenAddress configuration");
6956 goto err;
6958 if (parse_port_config(ports,
6959 options->DNSPort_lines, options->DNSListenAddress,
6960 "DNS", CONN_TYPE_AP_DNS_LISTENER,
6961 "127.0.0.1", 0,
6962 CL_PORT_WARN_NONLOCAL|CL_PORT_TAKES_HOSTNAMES) < 0) {
6963 *msg = tor_strdup("Invalid DNSPort/DNSListenAddress configuration");
6964 goto err;
6966 if (parse_port_config(ports,
6967 options->TransPort_lines, options->TransListenAddress,
6968 "Trans", CONN_TYPE_AP_TRANS_LISTENER,
6969 "127.0.0.1", 0,
6970 CL_PORT_WARN_NONLOCAL) < 0) {
6971 *msg = tor_strdup("Invalid TransPort/TransListenAddress configuration");
6972 goto err;
6974 if (parse_port_config(ports,
6975 options->NATDPort_lines, options->NATDListenAddress,
6976 "NATD", CONN_TYPE_AP_NATD_LISTENER,
6977 "127.0.0.1", 0,
6978 CL_PORT_WARN_NONLOCAL) < 0) {
6979 *msg = tor_strdup("Invalid NatdPort/NatdListenAddress configuration");
6980 goto err;
6983 unsigned control_port_flags = CL_PORT_NO_STREAM_OPTIONS |
6984 CL_PORT_WARN_NONLOCAL;
6985 const int any_passwords = (options->HashedControlPassword ||
6986 options->HashedControlSessionPassword ||
6987 options->CookieAuthentication);
6988 if (! any_passwords)
6989 control_port_flags |= CL_PORT_FORBID_NONLOCAL;
6990 if (options->ControlSocketsGroupWritable)
6991 control_port_flags |= CL_PORT_DFLT_GROUP_WRITABLE;
6993 if (parse_port_config(ports,
6994 options->ControlPort_lines,
6995 options->ControlListenAddress,
6996 "Control", CONN_TYPE_CONTROL_LISTENER,
6997 "127.0.0.1", 0,
6998 control_port_flags) < 0) {
6999 *msg = tor_strdup("Invalid ControlPort/ControlListenAddress "
7000 "configuration");
7001 goto err;
7004 if (parse_port_config(ports, options->ControlSocket, NULL,
7005 "ControlSocket",
7006 CONN_TYPE_CONTROL_LISTENER, NULL, 0,
7007 control_port_flags | CL_PORT_IS_UNIXSOCKET) < 0) {
7008 *msg = tor_strdup("Invalid ControlSocket configuration");
7009 goto err;
7012 if (! options->ClientOnly) {
7013 if (parse_port_config(ports,
7014 options->ORPort_lines, options->ORListenAddress,
7015 "OR", CONN_TYPE_OR_LISTENER,
7016 "0.0.0.0", 0,
7017 CL_PORT_SERVER_OPTIONS) < 0) {
7018 *msg = tor_strdup("Invalid ORPort/ORListenAddress configuration");
7019 goto err;
7021 if (parse_port_config(ports,
7022 options->ExtORPort_lines, NULL,
7023 "ExtOR", CONN_TYPE_EXT_OR_LISTENER,
7024 "127.0.0.1", 0,
7025 CL_PORT_SERVER_OPTIONS|CL_PORT_WARN_NONLOCAL) < 0) {
7026 *msg = tor_strdup("Invalid ExtORPort configuration");
7027 goto err;
7029 if (parse_port_config(ports,
7030 options->DirPort_lines, options->DirListenAddress,
7031 "Dir", CONN_TYPE_DIR_LISTENER,
7032 "0.0.0.0", 0,
7033 CL_PORT_SERVER_OPTIONS) < 0) {
7034 *msg = tor_strdup("Invalid DirPort/DirListenAddress configuration");
7035 goto err;
7039 int n_low_ports = 0;
7040 if (check_server_ports(ports, options, &n_low_ports) < 0) {
7041 *msg = tor_strdup("Misconfigured server ports");
7042 goto err;
7044 if (have_low_ports < 0)
7045 have_low_ports = (n_low_ports > 0);
7047 *n_ports_out = smartlist_len(ports);
7049 retval = 0;
7051 /* Update the *Port_set options. The !! here is to force a boolean out of
7052 an integer. */
7053 options->ORPort_set =
7054 !! count_real_listeners(ports, CONN_TYPE_OR_LISTENER, 0);
7055 options->SocksPort_set =
7056 !! count_real_listeners(ports, CONN_TYPE_AP_LISTENER, 1);
7057 options->TransPort_set =
7058 !! count_real_listeners(ports, CONN_TYPE_AP_TRANS_LISTENER, 1);
7059 options->NATDPort_set =
7060 !! count_real_listeners(ports, CONN_TYPE_AP_NATD_LISTENER, 1);
7061 /* Use options->ControlSocket to test if a control socket is set */
7062 options->ControlPort_set =
7063 !! count_real_listeners(ports, CONN_TYPE_CONTROL_LISTENER, 0);
7064 options->DirPort_set =
7065 !! count_real_listeners(ports, CONN_TYPE_DIR_LISTENER, 0);
7066 options->DNSPort_set =
7067 !! count_real_listeners(ports, CONN_TYPE_AP_DNS_LISTENER, 1);
7068 options->ExtORPort_set =
7069 !! count_real_listeners(ports, CONN_TYPE_EXT_OR_LISTENER, 0);
7071 if (world_writable_control_socket) {
7072 SMARTLIST_FOREACH(ports, port_cfg_t *, p,
7073 if (p->type == CONN_TYPE_CONTROL_LISTENER &&
7074 p->is_unix_addr &&
7075 p->is_world_writable) {
7076 *world_writable_control_socket = 1;
7077 break;
7081 if (!validate_only) {
7082 if (configured_ports) {
7083 SMARTLIST_FOREACH(configured_ports,
7084 port_cfg_t *, p, port_cfg_free(p));
7085 smartlist_free(configured_ports);
7087 configured_ports = ports;
7088 ports = NULL; /* prevent free below. */
7091 err:
7092 if (ports) {
7093 SMARTLIST_FOREACH(ports, port_cfg_t *, p, port_cfg_free(p));
7094 smartlist_free(ports);
7096 return retval;
7099 /* Does port bind to IPv4? */
7100 static int
7101 port_binds_ipv4(const port_cfg_t *port)
7103 return tor_addr_family(&port->addr) == AF_INET ||
7104 (tor_addr_family(&port->addr) == AF_UNSPEC
7105 && !port->server_cfg.bind_ipv6_only);
7108 /* Does port bind to IPv6? */
7109 static int
7110 port_binds_ipv6(const port_cfg_t *port)
7112 return tor_addr_family(&port->addr) == AF_INET6 ||
7113 (tor_addr_family(&port->addr) == AF_UNSPEC
7114 && !port->server_cfg.bind_ipv4_only);
7117 /** Given a list of <b>port_cfg_t</b> in <b>ports</b>, check them for internal
7118 * consistency and warn as appropriate. Set *<b>n_low_ports_out</b> to the
7119 * number of sub-1024 ports we will be binding. */
7120 static int
7121 check_server_ports(const smartlist_t *ports,
7122 const or_options_t *options,
7123 int *n_low_ports_out)
7125 int n_orport_advertised = 0;
7126 int n_orport_advertised_ipv4 = 0;
7127 int n_orport_listeners = 0;
7128 int n_dirport_advertised = 0;
7129 int n_dirport_listeners = 0;
7130 int n_low_port = 0;
7131 int r = 0;
7133 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
7134 if (port->type == CONN_TYPE_DIR_LISTENER) {
7135 if (! port->server_cfg.no_advertise)
7136 ++n_dirport_advertised;
7137 if (! port->server_cfg.no_listen)
7138 ++n_dirport_listeners;
7139 } else if (port->type == CONN_TYPE_OR_LISTENER) {
7140 if (! port->server_cfg.no_advertise) {
7141 ++n_orport_advertised;
7142 if (port_binds_ipv4(port))
7143 ++n_orport_advertised_ipv4;
7145 if (! port->server_cfg.no_listen)
7146 ++n_orport_listeners;
7147 } else {
7148 continue;
7150 #ifndef _WIN32
7151 if (!port->server_cfg.no_listen && port->port < 1024)
7152 ++n_low_port;
7153 #endif
7154 } SMARTLIST_FOREACH_END(port);
7156 if (n_orport_advertised && !n_orport_listeners) {
7157 log_warn(LD_CONFIG, "We are advertising an ORPort, but not actually "
7158 "listening on one.");
7159 r = -1;
7161 if (n_orport_listeners && !n_orport_advertised) {
7162 log_warn(LD_CONFIG, "We are listening on an ORPort, but not advertising "
7163 "any ORPorts. This will keep us from building a %s "
7164 "descriptor, and make us impossible to use.",
7165 options->BridgeRelay ? "bridge" : "router");
7166 r = -1;
7168 if (n_dirport_advertised && !n_dirport_listeners) {
7169 log_warn(LD_CONFIG, "We are advertising a DirPort, but not actually "
7170 "listening on one.");
7171 r = -1;
7173 if (n_dirport_advertised > 1) {
7174 log_warn(LD_CONFIG, "Can't advertise more than one DirPort.");
7175 r = -1;
7177 if (n_orport_advertised && !n_orport_advertised_ipv4 &&
7178 !options->BridgeRelay) {
7179 log_warn(LD_CONFIG, "Configured non-bridge only to listen on an IPv6 "
7180 "address.");
7181 r = -1;
7184 if (n_low_port && options->AccountingMax &&
7185 (!have_capability_support() || options->KeepBindCapabilities == 0)) {
7186 const char *extra = "";
7187 if (options->KeepBindCapabilities == 0 && have_capability_support())
7188 extra = ", and you have disabled KeepBindCapabilities.";
7189 log_warn(LD_CONFIG,
7190 "You have set AccountingMax to use hibernation. You have also "
7191 "chosen a low DirPort or OrPort%s."
7192 "This combination can make Tor stop "
7193 "working when it tries to re-attach the port after a period of "
7194 "hibernation. Please choose a different port or turn off "
7195 "hibernation unless you know this combination will work on your "
7196 "platform.", extra);
7199 if (n_low_ports_out)
7200 *n_low_ports_out = n_low_port;
7202 return r;
7205 /** Return a list of port_cfg_t for client ports parsed from the
7206 * options. */
7207 MOCK_IMPL(const smartlist_t *,
7208 get_configured_ports,(void))
7210 if (!configured_ports)
7211 configured_ports = smartlist_new();
7212 return configured_ports;
7215 /** Return an address:port string representation of the address
7216 * where the first <b>listener_type</b> listener waits for
7217 * connections. Return NULL if we couldn't find a listener. The
7218 * string is allocated on the heap and it's the responsibility of the
7219 * caller to free it after use.
7221 * This function is meant to be used by the pluggable transport proxy
7222 * spawning code, please make sure that it fits your purposes before
7223 * using it. */
7224 char *
7225 get_first_listener_addrport_string(int listener_type)
7227 static const char *ipv4_localhost = "127.0.0.1";
7228 static const char *ipv6_localhost = "[::1]";
7229 const char *address;
7230 uint16_t port;
7231 char *string = NULL;
7233 if (!configured_ports)
7234 return NULL;
7236 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
7237 if (cfg->server_cfg.no_listen)
7238 continue;
7240 if (cfg->type == listener_type &&
7241 tor_addr_family(&cfg->addr) != AF_UNSPEC) {
7243 /* We found the first listener of the type we are interested in! */
7245 /* If a listener is listening on INADDR_ANY, assume that it's
7246 also listening on 127.0.0.1, and point the transport proxy
7247 there: */
7248 if (tor_addr_is_null(&cfg->addr))
7249 address = tor_addr_is_v4(&cfg->addr) ? ipv4_localhost : ipv6_localhost;
7250 else
7251 address = fmt_and_decorate_addr(&cfg->addr);
7253 /* If a listener is configured with port 'auto', we are forced
7254 to iterate all listener connections and find out in which
7255 port it ended up listening: */
7256 if (cfg->port == CFG_AUTO_PORT) {
7257 port = router_get_active_listener_port_by_type_af(listener_type,
7258 tor_addr_family(&cfg->addr));
7259 if (!port)
7260 return NULL;
7261 } else {
7262 port = cfg->port;
7265 tor_asprintf(&string, "%s:%u", address, port);
7267 return string;
7270 } SMARTLIST_FOREACH_END(cfg);
7272 return NULL;
7275 /** Return the first advertised port of type <b>listener_type</b> in
7276 * <b>address_family</b>. Returns 0 when no port is found, and when passed
7277 * AF_UNSPEC. */
7279 get_first_advertised_port_by_type_af(int listener_type, int address_family)
7281 if (address_family == AF_UNSPEC)
7282 return 0;
7284 const smartlist_t *conf_ports = get_configured_ports();
7285 SMARTLIST_FOREACH_BEGIN(conf_ports, const port_cfg_t *, cfg) {
7286 if (cfg->type == listener_type &&
7287 !cfg->server_cfg.no_advertise) {
7288 if ((address_family == AF_INET && port_binds_ipv4(cfg)) ||
7289 (address_family == AF_INET6 && port_binds_ipv6(cfg))) {
7290 return cfg->port;
7293 } SMARTLIST_FOREACH_END(cfg);
7294 return 0;
7297 /** Return the first advertised address of type <b>listener_type</b> in
7298 * <b>address_family</b>. Returns NULL if there is no advertised address,
7299 * and when passed AF_UNSPEC. */
7300 const tor_addr_t *
7301 get_first_advertised_addr_by_type_af(int listener_type, int address_family)
7303 if (address_family == AF_UNSPEC)
7304 return NULL;
7305 if (!configured_ports)
7306 return NULL;
7307 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
7308 if (cfg->type == listener_type &&
7309 !cfg->server_cfg.no_advertise) {
7310 if ((address_family == AF_INET && port_binds_ipv4(cfg)) ||
7311 (address_family == AF_INET6 && port_binds_ipv6(cfg))) {
7312 return &cfg->addr;
7315 } SMARTLIST_FOREACH_END(cfg);
7316 return NULL;
7319 /** Return 1 if a port exists of type <b>listener_type</b> on <b>addr</b> and
7320 * <b>port</b>. If <b>check_wildcard</b> is true, INADDR[6]_ANY and AF_UNSPEC
7321 * addresses match any address of the appropriate family; and port -1 matches
7322 * any port.
7323 * To match auto ports, pass CFG_PORT_AUTO. (Does not match on the actual
7324 * automatically chosen listener ports.) */
7326 port_exists_by_type_addr_port(int listener_type, const tor_addr_t *addr,
7327 int port, int check_wildcard)
7329 if (!configured_ports || !addr)
7330 return 0;
7331 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
7332 if (cfg->type == listener_type) {
7333 if (cfg->port == port || (check_wildcard && port == -1)) {
7334 /* Exact match */
7335 if (tor_addr_eq(&cfg->addr, addr)) {
7336 return 1;
7338 /* Skip wildcard matches if we're not doing them */
7339 if (!check_wildcard) {
7340 continue;
7342 /* Wildcard matches IPv4 */
7343 const int cfg_v4 = port_binds_ipv4(cfg);
7344 const int cfg_any_v4 = tor_addr_is_null(&cfg->addr) && cfg_v4;
7345 const int addr_v4 = tor_addr_family(addr) == AF_INET ||
7346 tor_addr_family(addr) == AF_UNSPEC;
7347 const int addr_any_v4 = tor_addr_is_null(&cfg->addr) && addr_v4;
7348 if ((cfg_any_v4 && addr_v4) || (cfg_v4 && addr_any_v4)) {
7349 return 1;
7351 /* Wildcard matches IPv6 */
7352 const int cfg_v6 = port_binds_ipv6(cfg);
7353 const int cfg_any_v6 = tor_addr_is_null(&cfg->addr) && cfg_v6;
7354 const int addr_v6 = tor_addr_family(addr) == AF_INET6 ||
7355 tor_addr_family(addr) == AF_UNSPEC;
7356 const int addr_any_v6 = tor_addr_is_null(&cfg->addr) && addr_v6;
7357 if ((cfg_any_v6 && addr_v6) || (cfg_v6 && addr_any_v6)) {
7358 return 1;
7362 } SMARTLIST_FOREACH_END(cfg);
7363 return 0;
7366 /* Like port_exists_by_type_addr_port, but accepts a host-order IPv4 address
7367 * instead. */
7369 port_exists_by_type_addr32h_port(int listener_type, uint32_t addr_ipv4h,
7370 int port, int check_wildcard)
7372 tor_addr_t ipv4;
7373 tor_addr_from_ipv4h(&ipv4, addr_ipv4h);
7374 return port_exists_by_type_addr_port(listener_type, &ipv4, port,
7375 check_wildcard);
7378 /** Adjust the value of options->DataDirectory, or fill it in if it's
7379 * absent. Return 0 on success, -1 on failure. */
7380 static int
7381 normalize_data_directory(or_options_t *options)
7383 #ifdef _WIN32
7384 char *p;
7385 if (options->DataDirectory)
7386 return 0; /* all set */
7387 p = tor_malloc(MAX_PATH);
7388 strlcpy(p,get_windows_conf_root(),MAX_PATH);
7389 options->DataDirectory = p;
7390 return 0;
7391 #else
7392 const char *d = options->DataDirectory;
7393 if (!d)
7394 d = "~/.tor";
7396 if (strncmp(d,"~/",2) == 0) {
7397 char *fn = expand_filename(d);
7398 if (!fn) {
7399 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
7400 return -1;
7402 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
7403 /* If our homedir is /, we probably don't want to use it. */
7404 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
7405 * want. */
7406 log_warn(LD_CONFIG,
7407 "Default DataDirectory is \"~/.tor\". This expands to "
7408 "\"%s\", which is probably not what you want. Using "
7409 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
7410 tor_free(fn);
7411 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
7413 tor_free(options->DataDirectory);
7414 options->DataDirectory = fn;
7416 return 0;
7417 #endif
7420 /** Check and normalize the value of options->DataDirectory; return 0 if it
7421 * is sane, -1 otherwise. */
7422 static int
7423 validate_data_directory(or_options_t *options)
7425 if (normalize_data_directory(options) < 0)
7426 return -1;
7427 tor_assert(options->DataDirectory);
7428 if (strlen(options->DataDirectory) > (512-128)) {
7429 log_warn(LD_CONFIG, "DataDirectory is too long.");
7430 return -1;
7432 return 0;
7435 /** This string must remain the same forevermore. It is how we
7436 * recognize that the torrc file doesn't need to be backed up. */
7437 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
7438 "if you edit it, comments will not be preserved"
7439 /** This string can change; it tries to give the reader an idea
7440 * that editing this file by hand is not a good plan. */
7441 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
7442 "to torrc.orig.1 or similar, and Tor will ignore it"
7444 /** Save a configuration file for the configuration in <b>options</b>
7445 * into the file <b>fname</b>. If the file already exists, and
7446 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
7447 * replace it. Return 0 on success, -1 on failure. */
7448 static int
7449 write_configuration_file(const char *fname, const or_options_t *options)
7451 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
7452 int rename_old = 0, r;
7454 if (!fname)
7455 return -1;
7457 switch (file_status(fname)) {
7458 /* create backups of old config files, even if they're empty */
7459 case FN_FILE:
7460 case FN_EMPTY:
7461 old_val = read_file_to_str(fname, 0, NULL);
7462 if (!old_val || strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
7463 rename_old = 1;
7465 tor_free(old_val);
7466 break;
7467 case FN_NOENT:
7468 break;
7469 case FN_ERROR:
7470 case FN_DIR:
7471 default:
7472 log_warn(LD_CONFIG,
7473 "Config file \"%s\" is not a file? Failing.", fname);
7474 return -1;
7477 if (!(new_conf = options_dump(options, OPTIONS_DUMP_MINIMAL))) {
7478 log_warn(LD_BUG, "Couldn't get configuration string");
7479 goto err;
7482 tor_asprintf(&new_val, "%s\n%s\n\n%s",
7483 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
7485 if (rename_old) {
7486 int i = 1;
7487 char *fn_tmp = NULL;
7488 while (1) {
7489 tor_asprintf(&fn_tmp, "%s.orig.%d", fname, i);
7490 if (file_status(fn_tmp) == FN_NOENT)
7491 break;
7492 tor_free(fn_tmp);
7493 ++i;
7495 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
7496 if (tor_rename(fname, fn_tmp) < 0) {//XXXX sandbox doesn't allow
7497 log_warn(LD_FS,
7498 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
7499 fname, fn_tmp, strerror(errno));
7500 tor_free(fn_tmp);
7501 goto err;
7503 tor_free(fn_tmp);
7506 if (write_str_to_file(fname, new_val, 0) < 0)
7507 goto err;
7509 r = 0;
7510 goto done;
7511 err:
7512 r = -1;
7513 done:
7514 tor_free(new_val);
7515 tor_free(new_conf);
7516 return r;
7520 * Save the current configuration file value to disk. Return 0 on
7521 * success, -1 on failure.
7524 options_save_current(void)
7526 /* This fails if we can't write to our configuration file.
7528 * If we try falling back to datadirectory or something, we have a better
7529 * chance of saving the configuration, but a better chance of doing
7530 * something the user never expected. */
7531 return write_configuration_file(get_torrc_fname(0), get_options());
7534 /** Return the number of cpus configured in <b>options</b>. If we are
7535 * told to auto-detect the number of cpus, return the auto-detected number. */
7537 get_num_cpus(const or_options_t *options)
7539 if (options->NumCPUs == 0) {
7540 int n = compute_num_cpus();
7541 return (n >= 1) ? n : 1;
7542 } else {
7543 return options->NumCPUs;
7548 * Initialize the libevent library.
7550 static void
7551 init_libevent(const or_options_t *options)
7553 tor_libevent_cfg cfg;
7555 tor_assert(options);
7557 configure_libevent_logging();
7558 /* If the kernel complains that some method (say, epoll) doesn't
7559 * exist, we don't care about it, since libevent will cope.
7561 suppress_libevent_log_msg("Function not implemented");
7563 memset(&cfg, 0, sizeof(cfg));
7564 cfg.num_cpus = get_num_cpus(options);
7565 cfg.msec_per_tick = options->TokenBucketRefillInterval;
7567 tor_libevent_initialize(&cfg);
7569 suppress_libevent_log_msg(NULL);
7572 /** Return a newly allocated string holding a filename relative to the data
7573 * directory. If <b>sub1</b> is present, it is the first path component after
7574 * the data directory. If <b>sub2</b> is also present, it is the second path
7575 * component after the data directory. If <b>suffix</b> is present, it
7576 * is appended to the filename.
7578 * Examples:
7579 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
7580 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
7581 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
7582 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
7584 * Note: Consider using the get_datadir_fname* macros in or.h.
7586 MOCK_IMPL(char *,
7587 options_get_datadir_fname2_suffix,(const or_options_t *options,
7588 const char *sub1, const char *sub2,
7589 const char *suffix))
7591 char *fname = NULL;
7592 size_t len;
7593 tor_assert(options);
7594 tor_assert(options->DataDirectory);
7595 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
7596 len = strlen(options->DataDirectory);
7597 if (sub1) {
7598 len += strlen(sub1)+1;
7599 if (sub2)
7600 len += strlen(sub2)+1;
7602 if (suffix)
7603 len += strlen(suffix);
7604 len++;
7605 fname = tor_malloc(len);
7606 if (sub1) {
7607 if (sub2) {
7608 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
7609 options->DataDirectory, sub1, sub2);
7610 } else {
7611 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
7612 options->DataDirectory, sub1);
7614 } else {
7615 strlcpy(fname, options->DataDirectory, len);
7617 if (suffix)
7618 strlcat(fname, suffix, len);
7619 return fname;
7622 /** Check wether the data directory has a private subdirectory
7623 * <b>subdir</b>. If not, try to create it. Return 0 on success,
7624 * -1 otherwise. */
7626 check_or_create_data_subdir(const char *subdir)
7628 char *statsdir = get_datadir_fname(subdir);
7629 int return_val = 0;
7631 if (check_private_dir(statsdir, CPD_CREATE, get_options()->User) < 0) {
7632 log_warn(LD_HIST, "Unable to create %s/ directory!", subdir);
7633 return_val = -1;
7635 tor_free(statsdir);
7636 return return_val;
7639 /** Create a file named <b>fname</b> with contents <b>str</b> in the
7640 * subdirectory <b>subdir</b> of the data directory. <b>descr</b>
7641 * should be a short description of the file's content and will be
7642 * used for the warning message, if it's present and the write process
7643 * fails. Return 0 on success, -1 otherwise.*/
7645 write_to_data_subdir(const char* subdir, const char* fname,
7646 const char* str, const char* descr)
7648 char *filename = get_datadir_fname2(subdir, fname);
7649 int return_val = 0;
7651 if (write_str_to_file(filename, str, 0) < 0) {
7652 log_warn(LD_HIST, "Unable to write %s to disk!", descr ? descr : fname);
7653 return_val = -1;
7655 tor_free(filename);
7656 return return_val;
7659 /** Given a file name check to see whether the file exists but has not been
7660 * modified for a very long time. If so, remove it. */
7661 void
7662 remove_file_if_very_old(const char *fname, time_t now)
7664 #define VERY_OLD_FILE_AGE (28*24*60*60)
7665 struct stat st;
7667 log_debug(LD_FS, "stat()ing %s", fname);
7668 if (stat(sandbox_intern_string(fname), &st)==0 &&
7669 st.st_mtime < now-VERY_OLD_FILE_AGE) {
7670 char buf[ISO_TIME_LEN+1];
7671 format_local_iso_time(buf, st.st_mtime);
7672 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
7673 "Removing it.", fname, buf);
7674 if (unlink(fname) != 0) {
7675 log_warn(LD_FS, "Failed to unlink %s: %s",
7676 fname, strerror(errno));
7681 /** Return a smartlist of ports that must be forwarded by
7682 * tor-fw-helper. The smartlist contains the ports in a string format
7683 * that is understandable by tor-fw-helper. */
7684 smartlist_t *
7685 get_list_of_ports_to_forward(void)
7687 smartlist_t *ports_to_forward = smartlist_new();
7688 int port = 0;
7690 /** XXX TODO tor-fw-helper does not support forwarding ports to
7691 other hosts than the local one. If the user is binding to a
7692 different IP address, tor-fw-helper won't work. */
7693 port = router_get_advertised_or_port(get_options()); /* Get ORPort */
7694 if (port)
7695 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
7697 port = router_get_advertised_dir_port(get_options(), 0); /* Get DirPort */
7698 if (port)
7699 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
7701 /* Get ports of transport proxies */
7703 smartlist_t *transport_ports = get_transport_proxy_ports();
7704 if (transport_ports) {
7705 smartlist_add_all(ports_to_forward, transport_ports);
7706 smartlist_free(transport_ports);
7710 if (!smartlist_len(ports_to_forward)) {
7711 smartlist_free(ports_to_forward);
7712 ports_to_forward = NULL;
7715 return ports_to_forward;
7718 /** Helper to implement GETINFO functions about configuration variables (not
7719 * their values). Given a "config/names" question, set *<b>answer</b> to a
7720 * new string describing the supported configuration variables and their
7721 * types. */
7723 getinfo_helper_config(control_connection_t *conn,
7724 const char *question, char **answer,
7725 const char **errmsg)
7727 (void) conn;
7728 (void) errmsg;
7729 if (!strcmp(question, "config/names")) {
7730 smartlist_t *sl = smartlist_new();
7731 int i;
7732 for (i = 0; option_vars_[i].name; ++i) {
7733 const config_var_t *var = &option_vars_[i];
7734 const char *type;
7735 /* don't tell controller about triple-underscore options */
7736 if (!strncmp(option_vars_[i].name, "___", 3))
7737 continue;
7738 switch (var->type) {
7739 case CONFIG_TYPE_STRING: type = "String"; break;
7740 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
7741 case CONFIG_TYPE_UINT: type = "Integer"; break;
7742 case CONFIG_TYPE_INT: type = "SignedInteger"; break;
7743 case CONFIG_TYPE_PORT: type = "Port"; break;
7744 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
7745 case CONFIG_TYPE_MSEC_INTERVAL: type = "TimeMsecInterval"; break;
7746 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
7747 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
7748 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
7749 case CONFIG_TYPE_AUTOBOOL: type = "Boolean+Auto"; break;
7750 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
7751 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
7752 case CONFIG_TYPE_CSV: type = "CommaList"; break;
7753 case CONFIG_TYPE_CSV_INTERVAL: type = "TimeIntervalCommaList"; break;
7754 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
7755 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
7756 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
7757 default:
7758 case CONFIG_TYPE_OBSOLETE:
7759 type = NULL; break;
7761 if (!type)
7762 continue;
7763 smartlist_add_asprintf(sl, "%s %s\n",var->name,type);
7765 *answer = smartlist_join_strings(sl, "", 0, NULL);
7766 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
7767 smartlist_free(sl);
7768 } else if (!strcmp(question, "config/defaults")) {
7769 smartlist_t *sl = smartlist_new();
7770 int dirauth_lines_seen = 0, fallback_lines_seen = 0;
7771 for (int i = 0; option_vars_[i].name; ++i) {
7772 const config_var_t *var = &option_vars_[i];
7773 if (var->initvalue != NULL) {
7774 if (strcmp(option_vars_[i].name, "DirAuthority") == 0) {
7776 * Count dirauth lines we have a default for; we'll use the
7777 * count later to decide whether to add the defaults manually
7779 ++dirauth_lines_seen;
7781 if (strcmp(option_vars_[i].name, "FallbackDir") == 0) {
7783 * Similarly count fallback lines, so that we can decided later
7784 * to add the defaults manually.
7786 ++fallback_lines_seen;
7788 char *val = esc_for_log(var->initvalue);
7789 smartlist_add_asprintf(sl, "%s %s\n",var->name,val);
7790 tor_free(val);
7794 if (dirauth_lines_seen == 0) {
7796 * We didn't see any directory authorities with default values,
7797 * so add the list of default authorities manually.
7801 * default_authorities is defined earlier in this file and
7802 * is a const char ** NULL-terminated array of dirauth config
7803 * lines.
7805 for (const char **i = default_authorities; *i != NULL; ++i) {
7806 char *val = esc_for_log(*i);
7807 smartlist_add_asprintf(sl, "DirAuthority %s\n", val);
7808 tor_free(val);
7812 if (fallback_lines_seen == 0 &&
7813 get_options()->UseDefaultFallbackDirs == 1) {
7815 * We didn't see any explicitly configured fallback mirrors,
7816 * so add the defaults to the list manually.
7818 * default_fallbacks is included earlier in this file and
7819 * is a const char ** NULL-terminated array of fallback config lines.
7821 const char **i;
7823 for (i = default_fallbacks; *i != NULL; ++i) {
7824 char *val = esc_for_log(*i);
7825 smartlist_add_asprintf(sl, "FallbackDir %s\n", val);
7826 tor_free(val);
7830 *answer = smartlist_join_strings(sl, "", 0, NULL);
7831 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
7832 smartlist_free(sl);
7834 return 0;
7837 /** Parse outbound bind address option lines. If <b>validate_only</b>
7838 * is not 0 update OutboundBindAddressIPv4_ and
7839 * OutboundBindAddressIPv6_ in <b>options</b>. On failure, set
7840 * <b>msg</b> (if provided) to a newly allocated string containing a
7841 * description of the problem and return -1. */
7842 static int
7843 parse_outbound_addresses(or_options_t *options, int validate_only, char **msg)
7845 const config_line_t *lines = options->OutboundBindAddress;
7846 int found_v4 = 0, found_v6 = 0;
7848 if (!validate_only) {
7849 memset(&options->OutboundBindAddressIPv4_, 0,
7850 sizeof(options->OutboundBindAddressIPv4_));
7851 memset(&options->OutboundBindAddressIPv6_, 0,
7852 sizeof(options->OutboundBindAddressIPv6_));
7854 while (lines) {
7855 tor_addr_t addr, *dst_addr = NULL;
7856 int af = tor_addr_parse(&addr, lines->value);
7857 switch (af) {
7858 case AF_INET:
7859 if (found_v4) {
7860 if (msg)
7861 tor_asprintf(msg, "Multiple IPv4 outbound bind addresses "
7862 "configured: %s", lines->value);
7863 return -1;
7865 found_v4 = 1;
7866 dst_addr = &options->OutboundBindAddressIPv4_;
7867 break;
7868 case AF_INET6:
7869 if (found_v6) {
7870 if (msg)
7871 tor_asprintf(msg, "Multiple IPv6 outbound bind addresses "
7872 "configured: %s", lines->value);
7873 return -1;
7875 found_v6 = 1;
7876 dst_addr = &options->OutboundBindAddressIPv6_;
7877 break;
7878 default:
7879 if (msg)
7880 tor_asprintf(msg, "Outbound bind address '%s' didn't parse.",
7881 lines->value);
7882 return -1;
7884 if (!validate_only)
7885 tor_addr_copy(dst_addr, &addr);
7886 lines = lines->next;
7888 return 0;
7891 /** Load one of the geoip files, <a>family</a> determining which
7892 * one. <a>default_fname</a> is used if on Windows and
7893 * <a>fname</a> equals "<default>". */
7894 static void
7895 config_load_geoip_file_(sa_family_t family,
7896 const char *fname,
7897 const char *default_fname)
7899 #ifdef _WIN32
7900 char *free_fname = NULL; /* Used to hold any temporary-allocated value */
7901 /* XXXX Don't use this "<default>" junk; make our filename options
7902 * understand prefixes somehow. -NM */
7903 if (!strcmp(fname, "<default>")) {
7904 const char *conf_root = get_windows_conf_root();
7905 tor_asprintf(&free_fname, "%s\\%s", conf_root, default_fname);
7906 fname = free_fname;
7908 geoip_load_file(family, fname);
7909 tor_free(free_fname);
7910 #else
7911 (void)default_fname;
7912 geoip_load_file(family, fname);
7913 #endif
7916 /** Load geoip files for IPv4 and IPv6 if <a>options</a> and
7917 * <a>old_options</a> indicate we should. */
7918 static void
7919 config_maybe_load_geoip_files_(const or_options_t *options,
7920 const or_options_t *old_options)
7922 /* XXXX Reload GeoIPFile on SIGHUP. -NM */
7924 if (options->GeoIPFile &&
7925 ((!old_options || !opt_streq(old_options->GeoIPFile,
7926 options->GeoIPFile))
7927 || !geoip_is_loaded(AF_INET)))
7928 config_load_geoip_file_(AF_INET, options->GeoIPFile, "geoip");
7929 if (options->GeoIPv6File &&
7930 ((!old_options || !opt_streq(old_options->GeoIPv6File,
7931 options->GeoIPv6File))
7932 || !geoip_is_loaded(AF_INET6)))
7933 config_load_geoip_file_(AF_INET6, options->GeoIPv6File, "geoip6");
7936 /** Initialize cookie authentication (used so far by the ControlPort
7937 * and Extended ORPort).
7939 * Allocate memory and create a cookie (of length <b>cookie_len</b>)
7940 * in <b>cookie_out</b>.
7941 * Then write it down to <b>fname</b> and prepend it with <b>header</b>.
7943 * If <b>group_readable</b> is set, set <b>fname</b> to be readable
7944 * by the default GID.
7946 * If the whole procedure was successful, set
7947 * <b>cookie_is_set_out</b> to True. */
7949 init_cookie_authentication(const char *fname, const char *header,
7950 int cookie_len, int group_readable,
7951 uint8_t **cookie_out, int *cookie_is_set_out)
7953 char cookie_file_str_len = strlen(header) + cookie_len;
7954 char *cookie_file_str = tor_malloc(cookie_file_str_len);
7955 int retval = -1;
7957 /* We don't want to generate a new cookie every time we call
7958 * options_act(). One should be enough. */
7959 if (*cookie_is_set_out) {
7960 retval = 0; /* we are all set */
7961 goto done;
7964 /* If we've already set the cookie, free it before re-setting
7965 it. This can happen if we previously generated a cookie, but
7966 couldn't write it to a disk. */
7967 if (*cookie_out)
7968 tor_free(*cookie_out);
7970 /* Generate the cookie */
7971 *cookie_out = tor_malloc(cookie_len);
7972 crypto_rand((char *)*cookie_out, cookie_len);
7974 /* Create the string that should be written on the file. */
7975 memcpy(cookie_file_str, header, strlen(header));
7976 memcpy(cookie_file_str+strlen(header), *cookie_out, cookie_len);
7977 if (write_bytes_to_file(fname, cookie_file_str, cookie_file_str_len, 1)) {
7978 log_warn(LD_FS,"Error writing auth cookie to %s.", escaped(fname));
7979 goto done;
7982 #ifndef _WIN32
7983 if (group_readable) {
7984 if (chmod(fname, 0640)) {
7985 log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
7988 #else
7989 (void) group_readable;
7990 #endif
7992 /* Success! */
7993 log_info(LD_GENERAL, "Generated auth cookie file in '%s'.", escaped(fname));
7994 *cookie_is_set_out = 1;
7995 retval = 0;
7997 done:
7998 memwipe(cookie_file_str, 0, cookie_file_str_len);
7999 tor_free(cookie_file_str);
8000 return retval;