Add a new ipv6=address:orport flag to DirAuthority and FallbackDir
[tor.git] / src / or / config.c
blob894bd893d9ae50e3185f88fe30528e7a909cee44
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-2015, 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 "config.h"
22 #include "connection.h"
23 #include "connection_edge.h"
24 #include "connection_or.h"
25 #include "control.h"
26 #include "confparse.h"
27 #include "cpuworker.h"
28 #include "dirserv.h"
29 #include "dirvote.h"
30 #include "dns.h"
31 #include "entrynodes.h"
32 #include "geoip.h"
33 #include "hibernate.h"
34 #include "main.h"
35 #include "networkstatus.h"
36 #include "nodelist.h"
37 #include "policies.h"
38 #include "relay.h"
39 #include "rendclient.h"
40 #include "rendservice.h"
41 #include "rephist.h"
42 #include "router.h"
43 #include "sandbox.h"
44 #include "util.h"
45 #include "routerlist.h"
46 #include "routerset.h"
47 #include "scheduler.h"
48 #include "statefile.h"
49 #include "transports.h"
50 #include "ext_orport.h"
51 #include "torgzip.h"
52 #ifdef _WIN32
53 #include <shlobj.h>
54 #endif
56 #include "procmon.h"
58 #ifdef HAVE_SYSTEMD
59 # if defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__)
60 /* Systemd's use of gcc's __INCLUDE_LEVEL__ extension macro appears to confuse
61 * Coverity. Here's a kludge to unconfuse it.
63 # define __INCLUDE_LEVEL__ 2
64 # endif
65 #include <systemd/sd-daemon.h>
66 #endif
68 /* From main.c */
69 extern int quiet_level;
71 /* Prefix used to indicate a Unix socket in a FooPort configuration. */
72 static const char unix_socket_prefix[] = "unix:";
74 /** A list of abbreviations and aliases to map command-line options, obsolete
75 * option names, or alternative option names, to their current values. */
76 static config_abbrev_t option_abbrevs_[] = {
77 PLURAL(AuthDirBadDirCC),
78 PLURAL(AuthDirBadExitCC),
79 PLURAL(AuthDirInvalidCC),
80 PLURAL(AuthDirRejectCC),
81 PLURAL(EntryNode),
82 PLURAL(ExcludeNode),
83 PLURAL(Tor2webRendezvousPoint),
84 PLURAL(FirewallPort),
85 PLURAL(LongLivedPort),
86 PLURAL(HiddenServiceNode),
87 PLURAL(HiddenServiceExcludeNode),
88 PLURAL(NumCPU),
89 PLURAL(RendNode),
90 PLURAL(RecommendedPackage),
91 PLURAL(RendExcludeNode),
92 PLURAL(StrictEntryNode),
93 PLURAL(StrictExitNode),
94 PLURAL(StrictNode),
95 { "l", "Log", 1, 0},
96 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
97 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
98 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
99 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
100 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
101 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
102 { "DirServer", "DirAuthority", 0, 0}, /* XXXX024 later, make this warn? */
103 { "MaxConn", "ConnLimit", 0, 1},
104 { "MaxMemInCellQueues", "MaxMemInQueues", 0, 0},
105 { "ORBindAddress", "ORListenAddress", 0, 0},
106 { "DirBindAddress", "DirListenAddress", 0, 0},
107 { "SocksBindAddress", "SocksListenAddress", 0, 0},
108 { "UseHelperNodes", "UseEntryGuards", 0, 0},
109 { "NumHelperNodes", "NumEntryGuards", 0, 0},
110 { "UseEntryNodes", "UseEntryGuards", 0, 0},
111 { "NumEntryNodes", "NumEntryGuards", 0, 0},
112 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
113 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
114 { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0},
115 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
116 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
117 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
118 { "VirtualAddrNetwork", "VirtualAddrNetworkIPv4", 0, 0},
119 { "_UseFilteringSSLBufferevents", "UseFilteringSSLBufferevents", 0, 1},
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, BOOL, "0"),
194 V(ClientRejectInternalAddresses, BOOL, "1"),
195 V(ClientTransportPlugin, LINELIST, NULL),
196 V(ClientUseIPv6, BOOL, "0"),
197 V(ConsensusParams, STRING, NULL),
198 V(ConnLimit, UINT, "1000"),
199 V(ConnDirectionStatistics, BOOL, "0"),
200 V(ConstrainedSockets, BOOL, "0"),
201 V(ConstrainedSockSize, MEMUNIT, "8192"),
202 V(ContactInfo, STRING, NULL),
203 V(ControlListenAddress, LINELIST, NULL),
204 VPORT(ControlPort, LINELIST, NULL),
205 V(ControlPortFileGroupReadable,BOOL, "0"),
206 V(ControlPortWriteToFile, FILENAME, NULL),
207 V(ControlSocket, LINELIST, NULL),
208 V(ControlSocketsGroupWritable, BOOL, "0"),
209 V(SocksSocketsGroupWritable, BOOL, "0"),
210 V(CookieAuthentication, BOOL, "0"),
211 V(CookieAuthFileGroupReadable, BOOL, "0"),
212 V(CookieAuthFile, STRING, NULL),
213 V(CountPrivateBandwidth, BOOL, "0"),
214 V(DataDirectory, FILENAME, NULL),
215 V(DataDirectoryGroupReadable, BOOL, "0"),
216 V(DisableNetwork, BOOL, "0"),
217 V(DirAllowPrivateAddresses, BOOL, "0"),
218 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
219 V(DirListenAddress, LINELIST, NULL),
220 V(DirPolicy, LINELIST, NULL),
221 VPORT(DirPort, LINELIST, NULL),
222 V(DirPortFrontPage, FILENAME, NULL),
223 VAR("DirReqStatistics", BOOL, DirReqStatistics_option, "1"),
224 VAR("DirAuthority", LINELIST, DirAuthorities, NULL),
225 V(DirAuthorityFallbackRate, DOUBLE, "1.0"),
226 V(DisableAllSwap, BOOL, "0"),
227 V(DisableDebuggerAttachment, BOOL, "1"),
228 V(DisableIOCP, BOOL, "1"),
229 OBSOLETE("DisableV2DirectoryInfo_"),
230 OBSOLETE("DynamicDHGroups"),
231 VPORT(DNSPort, LINELIST, NULL),
232 V(DNSListenAddress, LINELIST, NULL),
233 V(DownloadExtraInfo, BOOL, "0"),
234 V(TestingEnableConnBwEvent, BOOL, "0"),
235 V(TestingEnableCellStatsEvent, BOOL, "0"),
236 V(TestingEnableTbEmptyEvent, BOOL, "0"),
237 V(EnforceDistinctSubnets, BOOL, "1"),
238 V(EntryNodes, ROUTERSET, NULL),
239 V(EntryStatistics, BOOL, "0"),
240 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
241 V(ExcludeNodes, ROUTERSET, NULL),
242 V(ExcludeExitNodes, ROUTERSET, NULL),
243 V(ExcludeSingleHopRelays, BOOL, "1"),
244 V(ExitNodes, ROUTERSET, NULL),
245 V(ExitPolicy, LINELIST, NULL),
246 V(ExitPolicyRejectPrivate, BOOL, "1"),
247 V(ExitPortStatistics, BOOL, "0"),
248 V(ExtendAllowPrivateAddresses, BOOL, "0"),
249 V(ExitRelay, AUTOBOOL, "auto"),
250 VPORT(ExtORPort, LINELIST, NULL),
251 V(ExtORPortCookieAuthFile, STRING, NULL),
252 V(ExtORPortCookieAuthFileGroupReadable, BOOL, "0"),
253 V(ExtraInfoStatistics, BOOL, "1"),
254 V(FallbackDir, LINELIST, NULL),
256 OBSOLETE("FallbackNetworkstatusFile"),
257 V(FascistFirewall, BOOL, "0"),
258 V(FirewallPorts, CSV, ""),
259 V(FastFirstHopPK, AUTOBOOL, "auto"),
260 V(FetchDirInfoEarly, BOOL, "0"),
261 V(FetchDirInfoExtraEarly, BOOL, "0"),
262 V(FetchServerDescriptors, BOOL, "1"),
263 V(FetchHidServDescriptors, BOOL, "1"),
264 V(FetchUselessDescriptors, BOOL, "0"),
265 OBSOLETE("FetchV2Networkstatus"),
266 V(GeoIPExcludeUnknown, AUTOBOOL, "auto"),
267 #ifdef _WIN32
268 V(GeoIPFile, FILENAME, "<default>"),
269 V(GeoIPv6File, FILENAME, "<default>"),
270 #else
271 V(GeoIPFile, FILENAME,
272 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
273 V(GeoIPv6File, FILENAME,
274 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip6"),
275 #endif
276 OBSOLETE("Group"),
277 V(GuardLifetime, INTERVAL, "0 minutes"),
278 V(HardwareAccel, BOOL, "0"),
279 V(HeartbeatPeriod, INTERVAL, "6 hours"),
280 V(AccelName, STRING, NULL),
281 V(AccelDir, FILENAME, NULL),
282 V(HashedControlPassword, LINELIST, NULL),
283 OBSOLETE("HidServDirectoryV2"),
284 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
285 VAR("HiddenServiceDirGroupReadable", LINELIST_S, RendConfigLines, NULL),
286 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
287 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
288 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
289 VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
290 VAR("HiddenServiceAllowUnknownPorts",LINELIST_S, RendConfigLines, NULL),
291 VAR("HiddenServiceMaxStreams",LINELIST_S, RendConfigLines, NULL),
292 VAR("HiddenServiceMaxStreamsCloseCircuit",LINELIST_S, RendConfigLines, NULL),
293 VAR("HiddenServiceNumIntroductionPoints", LINELIST_S, RendConfigLines, NULL),
294 V(HiddenServiceStatistics, BOOL, "1"),
295 V(HidServAuth, LINELIST, NULL),
296 V(CloseHSClientCircuitsImmediatelyOnTimeout, BOOL, "0"),
297 V(CloseHSServiceRendCircuitsImmediatelyOnTimeout, BOOL, "0"),
298 V(HTTPProxy, STRING, NULL),
299 V(HTTPProxyAuthenticator, STRING, NULL),
300 V(HTTPSProxy, STRING, NULL),
301 V(HTTPSProxyAuthenticator, STRING, NULL),
302 V(IPv6Exit, BOOL, "0"),
303 VAR("ServerTransportPlugin", LINELIST, ServerTransportPlugin, NULL),
304 V(ServerTransportListenAddr, LINELIST, NULL),
305 V(ServerTransportOptions, LINELIST, NULL),
306 V(SigningKeyLifetime, INTERVAL, "30 days"),
307 V(Socks4Proxy, STRING, NULL),
308 V(Socks5Proxy, STRING, NULL),
309 V(Socks5ProxyUsername, STRING, NULL),
310 V(Socks5ProxyPassword, STRING, NULL),
311 V(KeepalivePeriod, INTERVAL, "5 minutes"),
312 VAR("Log", LINELIST, Logs, NULL),
313 V(LogMessageDomains, BOOL, "0"),
314 V(LogTimeGranularity, MSEC_INTERVAL, "1 second"),
315 V(TruncateLogFile, BOOL, "0"),
316 V(SyslogIdentityTag, STRING, NULL),
317 V(LongLivedPorts, CSV,
318 "21,22,706,1863,5050,5190,5222,5223,6523,6667,6697,8300"),
319 VAR("MapAddress", LINELIST, AddressMap, NULL),
320 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
321 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
322 V(MaxClientCircuitsPending, UINT, "32"),
323 VAR("MaxMemInQueues", MEMUNIT, MaxMemInQueues_raw, "0"),
324 OBSOLETE("MaxOnionsPending"),
325 V(MaxOnionQueueDelay, MSEC_INTERVAL, "1750 msec"),
326 V(MinMeasuredBWsForAuthToIgnoreAdvertised, INT, "500"),
327 V(MyFamily, STRING, NULL),
328 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
329 OBSOLETE("NamingAuthoritativeDirectory"),
330 V(NATDListenAddress, LINELIST, NULL),
331 VPORT(NATDPort, LINELIST, NULL),
332 V(Nickname, STRING, NULL),
333 V(PredictedPortsRelevanceTime, INTERVAL, "1 hour"),
334 V(WarnUnsafeSocks, BOOL, "1"),
335 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
336 V(NumCPUs, UINT, "0"),
337 V(NumDirectoryGuards, UINT, "0"),
338 V(NumEntryGuards, UINT, "0"),
339 V(OfflineMasterKey, BOOL, "0"),
340 V(ORListenAddress, LINELIST, NULL),
341 VPORT(ORPort, LINELIST, NULL),
342 V(OutboundBindAddress, LINELIST, NULL),
344 OBSOLETE("PathBiasDisableRate"),
345 V(PathBiasCircThreshold, INT, "-1"),
346 V(PathBiasNoticeRate, DOUBLE, "-1"),
347 V(PathBiasWarnRate, DOUBLE, "-1"),
348 V(PathBiasExtremeRate, DOUBLE, "-1"),
349 V(PathBiasScaleThreshold, INT, "-1"),
350 OBSOLETE("PathBiasScaleFactor"),
351 OBSOLETE("PathBiasMultFactor"),
352 V(PathBiasDropGuards, AUTOBOOL, "0"),
353 OBSOLETE("PathBiasUseCloseCounts"),
355 V(PathBiasUseThreshold, INT, "-1"),
356 V(PathBiasNoticeUseRate, DOUBLE, "-1"),
357 V(PathBiasExtremeUseRate, DOUBLE, "-1"),
358 V(PathBiasScaleUseThreshold, INT, "-1"),
360 V(PathsNeededToBuildCircuits, DOUBLE, "-1"),
361 V(PerConnBWBurst, MEMUNIT, "0"),
362 V(PerConnBWRate, MEMUNIT, "0"),
363 V(PidFile, STRING, NULL),
364 V(TestingTorNetwork, BOOL, "0"),
365 V(TestingMinExitFlagThreshold, MEMUNIT, "0"),
366 V(TestingMinFastFlagThreshold, MEMUNIT, "0"),
368 V(TestingLinkCertLifetime, INTERVAL, "2 days"),
369 V(TestingAuthKeyLifetime, INTERVAL, "2 days"),
370 V(TestingLinkKeySlop, INTERVAL, "3 hours"),
371 V(TestingAuthKeySlop, INTERVAL, "3 hours"),
372 V(TestingSigningKeySlop, INTERVAL, "1 day"),
374 V(OptimisticData, AUTOBOOL, "auto"),
375 V(PortForwarding, BOOL, "0"),
376 V(PortForwardingHelper, FILENAME, "tor-fw-helper"),
377 OBSOLETE("PreferTunneledDirConns"),
378 V(ProtocolWarnings, BOOL, "0"),
379 V(PublishServerDescriptor, CSV, "1"),
380 V(PublishHidServDescriptors, BOOL, "1"),
381 V(ReachableAddresses, LINELIST, NULL),
382 V(ReachableDirAddresses, LINELIST, NULL),
383 V(ReachableORAddresses, LINELIST, NULL),
384 V(RecommendedVersions, LINELIST, NULL),
385 V(RecommendedClientVersions, LINELIST, NULL),
386 V(RecommendedServerVersions, LINELIST, NULL),
387 V(RecommendedPackages, LINELIST, NULL),
388 V(RefuseUnknownExits, AUTOBOOL, "auto"),
389 V(RejectPlaintextPorts, CSV, ""),
390 V(RelayBandwidthBurst, MEMUNIT, "0"),
391 V(RelayBandwidthRate, MEMUNIT, "0"),
392 V(RendPostPeriod, INTERVAL, "1 hour"),
393 V(RephistTrackTime, INTERVAL, "24 hours"),
394 V(RunAsDaemon, BOOL, "0"),
395 OBSOLETE("RunTesting"), // currently unused
396 V(Sandbox, BOOL, "0"),
397 V(SafeLogging, STRING, "1"),
398 V(SafeSocks, BOOL, "0"),
399 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
400 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
401 V(ServerDNSDetectHijacking, BOOL, "1"),
402 V(ServerDNSRandomizeCase, BOOL, "1"),
403 V(ServerDNSResolvConfFile, STRING, NULL),
404 V(ServerDNSSearchDomains, BOOL, "0"),
405 V(ServerDNSTestAddresses, CSV,
406 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
407 V(SchedulerLowWaterMark__, MEMUNIT, "100 MB"),
408 V(SchedulerHighWaterMark__, MEMUNIT, "101 MB"),
409 V(SchedulerMaxFlushCells__, UINT, "1000"),
410 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
411 V(SocksListenAddress, LINELIST, NULL),
412 V(SocksPolicy, LINELIST, NULL),
413 VPORT(SocksPort, LINELIST, NULL),
414 V(SocksTimeout, INTERVAL, "2 minutes"),
415 V(SSLKeyLifetime, INTERVAL, "0"),
416 OBSOLETE("StrictEntryNodes"),
417 OBSOLETE("StrictExitNodes"),
418 V(StrictNodes, BOOL, "0"),
419 OBSOLETE("Support022HiddenServices"),
420 V(TestSocks, BOOL, "0"),
421 V(TokenBucketRefillInterval, MSEC_INTERVAL, "100 msec"),
422 V(Tor2webMode, BOOL, "0"),
423 V(Tor2webRendezvousPoints, ROUTERSET, NULL),
424 V(TLSECGroup, STRING, NULL),
425 V(TrackHostExits, CSV, NULL),
426 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
427 V(TransListenAddress, LINELIST, NULL),
428 VPORT(TransPort, LINELIST, NULL),
429 V(TransProxyType, STRING, "default"),
430 OBSOLETE("TunnelDirConns"),
431 V(UpdateBridgesFromAuthority, BOOL, "0"),
432 V(UseBridges, BOOL, "0"),
433 V(UseEntryGuards, BOOL, "1"),
434 V(UseEntryGuardsAsDirGuards, BOOL, "1"),
435 V(UseGuardFraction, AUTOBOOL, "auto"),
436 V(UseMicrodescriptors, AUTOBOOL, "auto"),
437 V(UseNTorHandshake, AUTOBOOL, "1"),
438 V(User, STRING, NULL),
439 V(UserspaceIOCPBuffers, BOOL, "0"),
440 OBSOLETE("V1AuthoritativeDirectory"),
441 OBSOLETE("V2AuthoritativeDirectory"),
442 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
443 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
444 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
445 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
446 V(TestingV3AuthVotingStartOffset, INTERVAL, "0"),
447 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
448 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
449 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
450 V(V3AuthNIntervalsValid, UINT, "3"),
451 V(V3AuthUseLegacyKey, BOOL, "0"),
452 V(V3BandwidthsFile, FILENAME, NULL),
453 V(GuardfractionFile, FILENAME, NULL),
454 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
455 OBSOLETE("VoteOnHidServDirectoriesV2"),
456 V(VirtualAddrNetworkIPv4, STRING, "127.192.0.0/10"),
457 V(VirtualAddrNetworkIPv6, STRING, "[FE80::]/10"),
458 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
459 V(UseFilteringSSLBufferevents, BOOL, "0"),
460 VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
461 VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
462 VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
463 VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
464 VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
465 NULL),
466 VAR("__OwningControllerProcess",STRING,OwningControllerProcess, NULL),
467 V(MinUptimeHidServDirectoryV2, INTERVAL, "96 hours"),
468 V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 60, 60, 120, "
469 "300, 900, 2147483647"),
470 V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 60, 300, 600, "
471 "2147483647"),
472 V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
473 "300, 600, 1800, 1800, 1800, 1800, "
474 "1800, 3600, 7200"),
475 V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
476 "300, 600, 1800, 3600, 3600, 3600, "
477 "10800, 21600, 43200"),
478 V(TestingBridgeDownloadSchedule, CSV_INTERVAL, "3600, 900, 900, 3600"),
479 V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "10 minutes"),
480 V(TestingDirConnectionMaxStall, INTERVAL, "5 minutes"),
481 V(TestingConsensusMaxDownloadTries, UINT, "8"),
482 V(TestingDescriptorMaxDownloadTries, UINT, "8"),
483 V(TestingMicrodescMaxDownloadTries, UINT, "8"),
484 V(TestingCertMaxDownloadTries, UINT, "8"),
485 V(TestingDirAuthVoteExit, ROUTERSET, NULL),
486 V(TestingDirAuthVoteExitIsStrict, BOOL, "0"),
487 V(TestingDirAuthVoteGuard, ROUTERSET, NULL),
488 V(TestingDirAuthVoteGuardIsStrict, BOOL, "0"),
489 V(TestingDirAuthVoteHSDir, ROUTERSET, NULL),
490 V(TestingDirAuthVoteHSDirIsStrict, BOOL, "0"),
491 VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "0"),
493 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
496 /** Override default values with these if the user sets the TestingTorNetwork
497 * option. */
498 static const config_var_t testing_tor_network_defaults[] = {
499 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
500 V(DirAllowPrivateAddresses, BOOL, "1"),
501 V(EnforceDistinctSubnets, BOOL, "0"),
502 V(AssumeReachable, BOOL, "1"),
503 V(AuthDirMaxServersPerAddr, UINT, "0"),
504 V(AuthDirMaxServersPerAuthAddr,UINT, "0"),
505 V(ClientDNSRejectInternalAddresses, BOOL,"0"),
506 V(ClientRejectInternalAddresses, BOOL, "0"),
507 V(CountPrivateBandwidth, BOOL, "1"),
508 V(ExitPolicyRejectPrivate, BOOL, "0"),
509 V(ExtendAllowPrivateAddresses, BOOL, "1"),
510 V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
511 V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
512 V(V3AuthDistDelay, INTERVAL, "20 seconds"),
513 V(TestingV3AuthInitialVotingInterval, INTERVAL, "150 seconds"),
514 V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
515 V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
516 V(TestingV3AuthVotingStartOffset, INTERVAL, "0"),
517 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
518 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
519 V(MinUptimeHidServDirectoryV2, INTERVAL, "0 minutes"),
520 V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 5, 10, 15, "
521 "20, 30, 60"),
522 V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, 15, 20, "
523 "30, 60"),
524 V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
525 "15, 20, 30, 60"),
526 V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
527 "15, 20, 30, 60"),
528 V(TestingBridgeDownloadSchedule, CSV_INTERVAL, "60, 30, 30, 60"),
529 V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "5 seconds"),
530 V(TestingDirConnectionMaxStall, INTERVAL, "30 seconds"),
531 V(TestingConsensusMaxDownloadTries, UINT, "80"),
532 V(TestingDescriptorMaxDownloadTries, UINT, "80"),
533 V(TestingMicrodescMaxDownloadTries, UINT, "80"),
534 V(TestingCertMaxDownloadTries, UINT, "80"),
535 V(TestingEnableConnBwEvent, BOOL, "1"),
536 V(TestingEnableCellStatsEvent, BOOL, "1"),
537 V(TestingEnableTbEmptyEvent, BOOL, "1"),
538 VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "1"),
539 V(RendPostPeriod, INTERVAL, "2 minutes"),
541 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
544 #undef VAR
545 #undef V
546 #undef OBSOLETE
548 #ifdef _WIN32
549 static char *get_windows_conf_root(void);
550 #endif
551 static int options_act_reversible(const or_options_t *old_options, char **msg);
552 static int options_act(const or_options_t *old_options);
553 static int options_transition_allowed(const or_options_t *old,
554 const or_options_t *new,
555 char **msg);
556 static int options_transition_affects_workers(
557 const or_options_t *old_options, const or_options_t *new_options);
558 static int options_transition_affects_descriptor(
559 const or_options_t *old_options, const or_options_t *new_options);
560 static int check_nickname_list(char **lst, const char *name, char **msg);
561 static char *get_bindaddr_from_transport_listen_line(const char *line,
562 const char *transport);
563 static int parse_dir_authority_line(const char *line,
564 dirinfo_type_t required_type,
565 int validate_only);
566 static int parse_ports(or_options_t *options, int validate_only,
567 char **msg_out, int *n_ports_out,
568 int *world_writable_control_socket);
569 static int check_server_ports(const smartlist_t *ports,
570 const or_options_t *options);
572 static int validate_data_directory(or_options_t *options);
573 static int write_configuration_file(const char *fname,
574 const or_options_t *options);
575 static int options_init_logs(const or_options_t *old_options,
576 or_options_t *options, int validate_only);
578 static void init_libevent(const or_options_t *options);
579 static int opt_streq(const char *s1, const char *s2);
580 static int parse_outbound_addresses(or_options_t *options, int validate_only,
581 char **msg);
582 static void config_maybe_load_geoip_files_(const or_options_t *options,
583 const or_options_t *old_options);
584 static int options_validate_cb(void *old_options, void *options,
585 void *default_options,
586 int from_setconf, char **msg);
587 static uint64_t compute_real_max_mem_in_queues(const uint64_t val,
588 int log_guess);
590 /** Magic value for or_options_t. */
591 #define OR_OPTIONS_MAGIC 9090909
593 /** Configuration format for or_options_t. */
594 STATIC config_format_t options_format = {
595 sizeof(or_options_t),
596 OR_OPTIONS_MAGIC,
597 STRUCT_OFFSET(or_options_t, magic_),
598 option_abbrevs_,
599 option_vars_,
600 options_validate_cb,
601 NULL
605 * Functions to read and write the global options pointer.
608 /** Command-line and config-file options. */
609 static or_options_t *global_options = NULL;
610 /** The fallback options_t object; this is where we look for options not
611 * in torrc before we fall back to Tor's defaults. */
612 static or_options_t *global_default_options = NULL;
613 /** Name of most recently read torrc file. */
614 static char *torrc_fname = NULL;
615 /** Name of the most recently read torrc-defaults file.*/
616 static char *torrc_defaults_fname;
617 /** Configuration options set by command line. */
618 static config_line_t *global_cmdline_options = NULL;
619 /** Non-configuration options set by the command line */
620 static config_line_t *global_cmdline_only_options = NULL;
621 /** Boolean: Have we parsed the command line? */
622 static int have_parsed_cmdline = 0;
623 /** Contents of most recently read DirPortFrontPage file. */
624 static char *global_dirfrontpagecontents = NULL;
625 /** List of port_cfg_t for all configured ports. */
626 static smartlist_t *configured_ports = NULL;
628 /** Return the contents of our frontpage string, or NULL if not configured. */
629 MOCK_IMPL(const char*,
630 get_dirportfrontpage, (void))
632 return global_dirfrontpagecontents;
635 /** Return the currently configured options. */
636 or_options_t *
637 get_options_mutable(void)
639 tor_assert(global_options);
640 return global_options;
643 /** Returns the currently configured options */
644 MOCK_IMPL(const or_options_t *,
645 get_options,(void))
647 return get_options_mutable();
650 /** Change the current global options to contain <b>new_val</b> instead of
651 * their current value; take action based on the new value; free the old value
652 * as necessary. Returns 0 on success, -1 on failure.
655 set_options(or_options_t *new_val, char **msg)
657 int i;
658 smartlist_t *elements;
659 config_line_t *line;
660 or_options_t *old_options = global_options;
661 global_options = new_val;
662 /* Note that we pass the *old* options below, for comparison. It
663 * pulls the new options directly out of global_options. */
664 if (options_act_reversible(old_options, msg)<0) {
665 tor_assert(*msg);
666 global_options = old_options;
667 return -1;
669 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
670 log_err(LD_BUG,
671 "Acting on config options left us in a broken state. Dying.");
672 exit(1);
674 /* Issues a CONF_CHANGED event to notify controller of the change. If Tor is
675 * just starting up then the old_options will be undefined. */
676 if (old_options && old_options != global_options) {
677 elements = smartlist_new();
678 for (i=0; options_format.vars[i].name; ++i) {
679 const config_var_t *var = &options_format.vars[i];
680 const char *var_name = var->name;
681 if (var->type == CONFIG_TYPE_LINELIST_S ||
682 var->type == CONFIG_TYPE_OBSOLETE) {
683 continue;
685 if (!config_is_same(&options_format, new_val, old_options, var_name)) {
686 line = config_get_assigned_option(&options_format, new_val,
687 var_name, 1);
689 if (line) {
690 config_line_t *next;
691 for (; line; line = next) {
692 next = line->next;
693 smartlist_add(elements, line->key);
694 smartlist_add(elements, line->value);
695 tor_free(line);
697 } else {
698 smartlist_add(elements, tor_strdup(options_format.vars[i].name));
699 smartlist_add(elements, NULL);
703 control_event_conf_changed(elements);
704 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
705 smartlist_free(elements);
708 if (old_options != global_options)
709 config_free(&options_format, old_options);
711 return 0;
714 extern const char tor_git_revision[]; /* from tor_main.c */
716 /** The version of this Tor process, as parsed. */
717 static char *the_tor_version = NULL;
718 /** A shorter version of this Tor process's version, for export in our router
719 * descriptor. (Does not include the git version, if any.) */
720 static char *the_short_tor_version = NULL;
722 /** Return the current Tor version. */
723 const char *
724 get_version(void)
726 if (the_tor_version == NULL) {
727 if (strlen(tor_git_revision)) {
728 tor_asprintf(&the_tor_version, "%s (git-%s)", get_short_version(),
729 tor_git_revision);
730 } else {
731 the_tor_version = tor_strdup(get_short_version());
734 return the_tor_version;
737 /** Return the current Tor version, without any git tag. */
738 const char *
739 get_short_version(void)
742 if (the_short_tor_version == NULL) {
743 #ifdef TOR_BUILD_TAG
744 tor_asprintf(&the_short_tor_version, "%s (%s)", VERSION, TOR_BUILD_TAG);
745 #else
746 the_short_tor_version = tor_strdup(VERSION);
747 #endif
749 return the_short_tor_version;
752 /** Release additional memory allocated in options
754 STATIC void
755 or_options_free(or_options_t *options)
757 if (!options)
758 return;
760 routerset_free(options->ExcludeExitNodesUnion_);
761 if (options->NodeFamilySets) {
762 SMARTLIST_FOREACH(options->NodeFamilySets, routerset_t *,
763 rs, routerset_free(rs));
764 smartlist_free(options->NodeFamilySets);
766 tor_free(options->BridgePassword_AuthDigest_);
767 tor_free(options->command_arg);
768 tor_free(options->master_key_fname);
769 config_free(&options_format, options);
772 /** Release all memory and resources held by global configuration structures.
774 void
775 config_free_all(void)
777 or_options_free(global_options);
778 global_options = NULL;
779 or_options_free(global_default_options);
780 global_default_options = NULL;
782 config_free_lines(global_cmdline_options);
783 global_cmdline_options = NULL;
785 config_free_lines(global_cmdline_only_options);
786 global_cmdline_only_options = NULL;
788 if (configured_ports) {
789 SMARTLIST_FOREACH(configured_ports,
790 port_cfg_t *, p, port_cfg_free(p));
791 smartlist_free(configured_ports);
792 configured_ports = NULL;
795 tor_free(torrc_fname);
796 tor_free(torrc_defaults_fname);
797 tor_free(the_tor_version);
798 tor_free(global_dirfrontpagecontents);
800 tor_free(the_short_tor_version);
801 tor_free(the_tor_version);
804 /** Make <b>address</b> -- a piece of information related to our operation as
805 * a client -- safe to log according to the settings in options->SafeLogging,
806 * and return it.
808 * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
810 const char *
811 safe_str_client(const char *address)
813 tor_assert(address);
814 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
815 return "[scrubbed]";
816 else
817 return address;
820 /** Make <b>address</b> -- a piece of information of unspecified sensitivity
821 * -- safe to log according to the settings in options->SafeLogging, and
822 * return it.
824 * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
825 * otherwise.)
827 const char *
828 safe_str(const char *address)
830 tor_assert(address);
831 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
832 return "[scrubbed]";
833 else
834 return address;
837 /** Equivalent to escaped(safe_str_client(address)). See reentrancy note on
838 * escaped(): don't use this outside the main thread, or twice in the same
839 * log statement. */
840 const char *
841 escaped_safe_str_client(const char *address)
843 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
844 return "[scrubbed]";
845 else
846 return escaped(address);
849 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
850 * escaped(): don't use this outside the main thread, or twice in the same
851 * log statement. */
852 const char *
853 escaped_safe_str(const char *address)
855 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
856 return "[scrubbed]";
857 else
858 return escaped(address);
861 /** List of default directory authorities */
863 static const char *default_authorities[] = {
864 "moria1 orport=9101 "
865 "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
866 "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
867 "tor26 orport=443 "
868 "v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
869 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
870 "dizum orport=443 "
871 "v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
872 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
873 "Tonga orport=443 bridge "
874 "82.94.251.203:80 4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
875 "gabelmoo orport=443 "
876 "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
877 "131.188.40.189:80 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
878 "dannenberg orport=443 "
879 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
880 "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
881 "urras orport=80 "
882 "v3ident=80550987E1D626E3EBA5E5E75A458DE0626D088C "
883 "208.83.223.34:443 0AD3 FA88 4D18 F89E EA2D 89C0 1937 9E0E 7FD9 4417",
884 "maatuska orport=80 "
885 "v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
886 "171.25.193.9:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
887 "Faravahar orport=443 "
888 "v3ident=EFCBE720AB3A82B99F9E953CD5BF50F7EEFC7B97 "
889 "154.35.175.225:80 CF6D 0AAF B385 BE71 B8E1 11FC 5CFF 4B47 9237 33BC",
890 "longclaw orport=443 "
891 "v3ident=23D15D965BC35114467363C165C4F724B64B4F66 "
892 "199.254.238.52:80 74A9 1064 6BCE EFBC D2E8 74FC 1DC9 9743 0F96 8145",
893 NULL
896 /** Add the default directory authorities directly into the trusted dir list,
897 * but only add them insofar as they share bits with <b>type</b>.
898 * Each authority's bits are restricted to the bits shared with <b>type</b>.
899 * If <b>type</b> is ALL_DIRINFO or NO_DIRINFO (zero), add all authorities. */
900 static void
901 add_default_trusted_dir_authorities(dirinfo_type_t type)
903 int i;
904 for (i=0; default_authorities[i]; i++) {
905 if (parse_dir_authority_line(default_authorities[i], type, 0)<0) {
906 log_err(LD_BUG, "Couldn't parse internal DirAuthority line %s",
907 default_authorities[i]);
912 /** Add the default fallback directory servers into the fallback directory
913 * server list. */
914 MOCK_IMPL(void,
915 add_default_fallback_dir_servers,(void))
917 int i;
918 const char *fallback[] = {
919 NULL
921 for (i=0; fallback[i]; i++) {
922 if (parse_dir_fallback_line(fallback[i], 0)<0) {
923 log_err(LD_BUG, "Couldn't parse internal FallbackDir line %s",
924 fallback[i]);
929 /** Look at all the config options for using alternate directory
930 * authorities, and make sure none of them are broken. Also, warn the
931 * user if we changed any dangerous ones.
933 static int
934 validate_dir_servers(or_options_t *options, or_options_t *old_options)
936 config_line_t *cl;
938 if (options->DirAuthorities &&
939 (options->AlternateDirAuthority || options->AlternateBridgeAuthority)) {
940 log_warn(LD_CONFIG,
941 "You cannot set both DirAuthority and Alternate*Authority.");
942 return -1;
945 /* do we want to complain to the user about being partitionable? */
946 if ((options->DirAuthorities &&
947 (!old_options ||
948 !config_lines_eq(options->DirAuthorities,
949 old_options->DirAuthorities))) ||
950 (options->AlternateDirAuthority &&
951 (!old_options ||
952 !config_lines_eq(options->AlternateDirAuthority,
953 old_options->AlternateDirAuthority)))) {
954 log_warn(LD_CONFIG,
955 "You have used DirAuthority or AlternateDirAuthority to "
956 "specify alternate directory authorities in "
957 "your configuration. This is potentially dangerous: it can "
958 "make you look different from all other Tor users, and hurt "
959 "your anonymity. Even if you've specified the same "
960 "authorities as Tor uses by default, the defaults could "
961 "change in the future. Be sure you know what you're doing.");
964 /* Now go through the four ways you can configure an alternate
965 * set of directory authorities, and make sure none are broken. */
966 for (cl = options->DirAuthorities; cl; cl = cl->next)
967 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
968 return -1;
969 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
970 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
971 return -1;
972 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
973 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
974 return -1;
975 for (cl = options->FallbackDir; cl; cl = cl->next)
976 if (parse_dir_fallback_line(cl->value, 1)<0)
977 return -1;
978 return 0;
981 /** Look at all the config options and assign new dir authorities
982 * as appropriate.
985 consider_adding_dir_servers(const or_options_t *options,
986 const or_options_t *old_options)
988 config_line_t *cl;
989 int need_to_update =
990 !smartlist_len(router_get_trusted_dir_servers()) ||
991 !smartlist_len(router_get_fallback_dir_servers()) || !old_options ||
992 !config_lines_eq(options->DirAuthorities, old_options->DirAuthorities) ||
993 !config_lines_eq(options->FallbackDir, old_options->FallbackDir) ||
994 !config_lines_eq(options->AlternateBridgeAuthority,
995 old_options->AlternateBridgeAuthority) ||
996 !config_lines_eq(options->AlternateDirAuthority,
997 old_options->AlternateDirAuthority);
999 if (!need_to_update)
1000 return 0; /* all done */
1002 /* "You cannot set both DirAuthority and Alternate*Authority."
1003 * Checking that this restriction holds allows us to simplify
1004 * the unit tests. */
1005 tor_assert(!(options->DirAuthorities &&
1006 (options->AlternateDirAuthority
1007 || options->AlternateBridgeAuthority)));
1009 /* Start from a clean slate. */
1010 clear_dir_servers();
1012 if (!options->DirAuthorities) {
1013 /* then we may want some of the defaults */
1014 dirinfo_type_t type = NO_DIRINFO;
1015 if (!options->AlternateBridgeAuthority) {
1016 type |= BRIDGE_DIRINFO;
1018 if (!options->AlternateDirAuthority) {
1019 type |= V3_DIRINFO | EXTRAINFO_DIRINFO | MICRODESC_DIRINFO;
1020 /* Only add the default fallback directories when the DirAuthorities,
1021 * AlternateDirAuthority, and FallbackDir directory config options
1022 * are set to their defaults. */
1023 if (!options->FallbackDir) {
1024 add_default_fallback_dir_servers();
1027 /* if type == NO_DIRINFO, we don't want to add any of the
1028 * default authorities, because we've replaced them all */
1029 if (type != NO_DIRINFO)
1030 add_default_trusted_dir_authorities(type);
1033 for (cl = options->DirAuthorities; cl; cl = cl->next)
1034 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1035 return -1;
1036 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1037 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1038 return -1;
1039 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1040 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1041 return -1;
1042 for (cl = options->FallbackDir; cl; cl = cl->next)
1043 if (parse_dir_fallback_line(cl->value, 0)<0)
1044 return -1;
1045 return 0;
1048 /** Fetch the active option list, and take actions based on it. All of the
1049 * things we do should survive being done repeatedly. If present,
1050 * <b>old_options</b> contains the previous value of the options.
1052 * Return 0 if all goes well, return -1 if things went badly.
1054 static int
1055 options_act_reversible(const or_options_t *old_options, char **msg)
1057 smartlist_t *new_listeners = smartlist_new();
1058 smartlist_t *replaced_listeners = smartlist_new();
1059 static int libevent_initialized = 0;
1060 or_options_t *options = get_options_mutable();
1061 int running_tor = options->command == CMD_RUN_TOR;
1062 int set_conn_limit = 0;
1063 int r = -1;
1064 int logs_marked = 0, logs_initialized = 0;
1065 int old_min_log_level = get_min_log_level();
1067 /* Daemonize _first_, since we only want to open most of this stuff in
1068 * the subprocess. Libevent bases can't be reliably inherited across
1069 * processes. */
1070 if (running_tor && options->RunAsDaemon) {
1071 /* No need to roll back, since you can't change the value. */
1072 start_daemon();
1075 #ifdef HAVE_SYSTEMD
1076 /* Our PID may have changed, inform supervisor */
1077 sd_notifyf(0, "MAINPID=%ld\n", (long int)getpid());
1078 #endif
1080 #ifndef HAVE_SYS_UN_H
1081 if (options->ControlSocket || options->ControlSocketsGroupWritable) {
1082 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported "
1083 "on this OS/with this build.");
1084 goto rollback;
1086 #else
1087 if (options->ControlSocketsGroupWritable && !options->ControlSocket) {
1088 *msg = tor_strdup("Setting ControlSocketGroupWritable without setting"
1089 "a ControlSocket makes no sense.");
1090 goto rollback;
1092 #endif
1094 if (running_tor) {
1095 int n_ports=0;
1096 /* We need to set the connection limit before we can open the listeners. */
1097 if (! sandbox_is_active()) {
1098 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1099 &options->ConnLimit_) < 0) {
1100 *msg = tor_strdup("Problem with ConnLimit value. "
1101 "See logs for details.");
1102 goto rollback;
1104 set_conn_limit = 1;
1105 } else {
1106 tor_assert(old_options);
1107 options->ConnLimit_ = old_options->ConnLimit_;
1110 /* Set up libevent. (We need to do this before we can register the
1111 * listeners as listeners.) */
1112 if (running_tor && !libevent_initialized) {
1113 init_libevent(options);
1114 libevent_initialized = 1;
1116 /* This has to come up after libevent is initialized. */
1117 control_initialize_event_queue();
1120 * Initialize the scheduler - this has to come after
1121 * options_init_from_torrc() sets up libevent - why yes, that seems
1122 * completely sensible to hide the libevent setup in the option parsing
1123 * code! It also needs to happen before init_keys(), so it needs to
1124 * happen here too. How yucky. */
1125 scheduler_init();
1128 /* Adjust the port configuration so we can launch listeners. */
1129 if (parse_ports(options, 0, msg, &n_ports, NULL)) {
1130 if (!*msg)
1131 *msg = tor_strdup("Unexpected problem parsing port config");
1132 goto rollback;
1135 /* Set the hibernation state appropriately.*/
1136 consider_hibernation(time(NULL));
1138 /* Launch the listeners. (We do this before we setuid, so we can bind to
1139 * ports under 1024.) We don't want to rebind if we're hibernating. If
1140 * networking is disabled, this will close all but the control listeners,
1141 * but disable those. */
1142 if (!we_are_hibernating()) {
1143 if (retry_all_listeners(replaced_listeners, new_listeners,
1144 options->DisableNetwork) < 0) {
1145 *msg = tor_strdup("Failed to bind one of the listener ports.");
1146 goto rollback;
1149 if (options->DisableNetwork) {
1150 /* Aggressively close non-controller stuff, NOW */
1151 log_notice(LD_NET, "DisableNetwork is set. Tor will not make or accept "
1152 "non-control network connections. Shutting down all existing "
1153 "connections.");
1154 connection_mark_all_noncontrol_connections();
1155 /* We can't complete circuits until the network is re-enabled. */
1156 note_that_we_maybe_cant_complete_circuits();
1160 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1161 /* Open /dev/pf before dropping privileges. */
1162 if (options->TransPort_set &&
1163 options->TransProxyType_parsed == TPT_DEFAULT) {
1164 if (get_pf_socket() < 0) {
1165 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1166 goto rollback;
1169 #endif
1171 /* Attempt to lock all current and future memory with mlockall() only once */
1172 if (options->DisableAllSwap) {
1173 if (tor_mlockall() == -1) {
1174 *msg = tor_strdup("DisableAllSwap failure. Do you have proper "
1175 "permissions?");
1176 goto done;
1180 /* Setuid/setgid as appropriate */
1181 if (options->User) {
1182 if (switch_id(options->User) != 0) {
1183 /* No need to roll back, since you can't change the value. */
1184 *msg = tor_strdup("Problem with User value. See logs for details.");
1185 goto done;
1189 /* Ensure data directory is private; create if possible. */
1190 cpd_check_t cpd_opts = running_tor ? CPD_CREATE : CPD_CHECK;
1191 if (options->DataDirectoryGroupReadable)
1192 cpd_opts |= CPD_GROUP_READ;
1193 if (check_private_dir(options->DataDirectory,
1194 cpd_opts,
1195 options->User)<0) {
1196 tor_asprintf(msg,
1197 "Couldn't access/create private data directory \"%s\"",
1198 options->DataDirectory);
1200 goto done;
1201 /* No need to roll back, since you can't change the value. */
1204 #ifndef _WIN32
1205 if (options->DataDirectoryGroupReadable) {
1206 /* Only new dirs created get new opts, also enforce group read. */
1207 if (chmod(options->DataDirectory, 0750)) {
1208 log_warn(LD_FS,"Unable to make %s group-readable: %s",
1209 options->DataDirectory, strerror(errno));
1212 #endif
1214 /* Bail out at this point if we're not going to be a client or server:
1215 * we don't run Tor itself. */
1216 if (!running_tor)
1217 goto commit;
1219 mark_logs_temp(); /* Close current logs once new logs are open. */
1220 logs_marked = 1;
1221 /* Configure the tor_log(s) */
1222 if (options_init_logs(old_options, options, 0)<0) {
1223 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1224 goto rollback;
1226 logs_initialized = 1;
1228 commit:
1229 r = 0;
1230 if (logs_marked) {
1231 log_severity_list_t *severity =
1232 tor_malloc_zero(sizeof(log_severity_list_t));
1233 close_temp_logs();
1234 add_callback_log(severity, control_event_logmsg);
1235 control_adjust_event_log_severity();
1236 tor_free(severity);
1237 tor_log_update_sigsafe_err_fds();
1239 if (logs_initialized) {
1240 flush_log_messages_from_startup();
1244 const char *badness = NULL;
1245 int bad_safelog = 0, bad_severity = 0, new_badness = 0;
1246 if (options->SafeLogging_ != SAFELOG_SCRUB_ALL) {
1247 bad_safelog = 1;
1248 if (!old_options || old_options->SafeLogging_ != options->SafeLogging_)
1249 new_badness = 1;
1251 if (get_min_log_level() >= LOG_INFO) {
1252 bad_severity = 1;
1253 if (get_min_log_level() != old_min_log_level)
1254 new_badness = 1;
1256 if (bad_safelog && bad_severity)
1257 badness = "you disabled SafeLogging, and "
1258 "you're logging more than \"notice\"";
1259 else if (bad_safelog)
1260 badness = "you disabled SafeLogging";
1261 else
1262 badness = "you're logging more than \"notice\"";
1263 if (new_badness)
1264 log_warn(LD_GENERAL, "Your log may contain sensitive information - %s. "
1265 "Don't log unless it serves an important reason. "
1266 "Overwrite the log afterwards.", badness);
1269 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1271 int marked = conn->marked_for_close;
1272 log_notice(LD_NET, "Closing old %s on %s:%d",
1273 conn_type_to_string(conn->type), conn->address, conn->port);
1274 connection_close_immediate(conn);
1275 if (!marked) {
1276 connection_mark_for_close(conn);
1279 goto done;
1281 rollback:
1282 r = -1;
1283 tor_assert(*msg);
1285 if (logs_marked) {
1286 rollback_log_changes();
1287 control_adjust_event_log_severity();
1290 if (set_conn_limit && old_options)
1291 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1292 &options->ConnLimit_);
1294 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1296 log_notice(LD_NET, "Closing partially-constructed %s on %s:%d",
1297 conn_type_to_string(conn->type), conn->address, conn->port);
1298 connection_close_immediate(conn);
1299 connection_mark_for_close(conn);
1302 done:
1303 smartlist_free(new_listeners);
1304 smartlist_free(replaced_listeners);
1305 return r;
1308 /** If we need to have a GEOIP ip-to-country map to run with our configured
1309 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1311 options_need_geoip_info(const or_options_t *options, const char **reason_out)
1313 int bridge_usage =
1314 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1315 int routerset_usage =
1316 routerset_needs_geoip(options->EntryNodes) ||
1317 routerset_needs_geoip(options->ExitNodes) ||
1318 routerset_needs_geoip(options->ExcludeExitNodes) ||
1319 routerset_needs_geoip(options->ExcludeNodes) ||
1320 routerset_needs_geoip(options->Tor2webRendezvousPoints);
1322 if (routerset_usage && reason_out) {
1323 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1324 "countries, and we need GEOIP information to figure out which ones they "
1325 "are.";
1326 } else if (bridge_usage && reason_out) {
1327 *reason_out = "We've been configured to see which countries can access "
1328 "us as a bridge, and we need GEOIP information to tell which countries "
1329 "clients are in.";
1331 return bridge_usage || routerset_usage;
1334 /** Return the bandwidthrate that we are going to report to the authorities
1335 * based on the config options. */
1336 uint32_t
1337 get_effective_bwrate(const or_options_t *options)
1339 uint64_t bw = options->BandwidthRate;
1340 if (bw > options->MaxAdvertisedBandwidth)
1341 bw = options->MaxAdvertisedBandwidth;
1342 if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1343 bw = options->RelayBandwidthRate;
1344 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1345 return (uint32_t)bw;
1348 /** Return the bandwidthburst that we are going to report to the authorities
1349 * based on the config options. */
1350 uint32_t
1351 get_effective_bwburst(const or_options_t *options)
1353 uint64_t bw = options->BandwidthBurst;
1354 if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1355 bw = options->RelayBandwidthBurst;
1356 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1357 return (uint32_t)bw;
1360 /** Return True if any changes from <b>old_options</b> to
1361 * <b>new_options</b> needs us to refresh our TLS context. */
1362 static int
1363 options_transition_requires_fresh_tls_context(const or_options_t *old_options,
1364 const or_options_t *new_options)
1366 tor_assert(new_options);
1368 if (!old_options)
1369 return 0;
1371 if (!opt_streq(old_options->TLSECGroup, new_options->TLSECGroup))
1372 return 1;
1374 return 0;
1377 /** Fetch the active option list, and take actions based on it. All of the
1378 * things we do should survive being done repeatedly. If present,
1379 * <b>old_options</b> contains the previous value of the options.
1381 * Return 0 if all goes well, return -1 if it's time to die.
1383 * Note: We haven't moved all the "act on new configuration" logic
1384 * here yet. Some is still in do_hup() and other places.
1386 static int
1387 options_act(const or_options_t *old_options)
1389 config_line_t *cl;
1390 or_options_t *options = get_options_mutable();
1391 int running_tor = options->command == CMD_RUN_TOR;
1392 char *msg=NULL;
1393 const int transition_affects_workers =
1394 old_options && options_transition_affects_workers(old_options, options);
1395 int old_ewma_enabled;
1397 /* disable ptrace and later, other basic debugging techniques */
1399 /* Remember if we already disabled debugger attachment */
1400 static int disabled_debugger_attach = 0;
1401 /* Remember if we already warned about being configured not to disable
1402 * debugger attachment */
1403 static int warned_debugger_attach = 0;
1404 /* Don't disable debugger attachment when we're running the unit tests. */
1405 if (options->DisableDebuggerAttachment && !disabled_debugger_attach &&
1406 running_tor) {
1407 int ok = tor_disable_debugger_attach();
1408 if (warned_debugger_attach && ok == 1) {
1409 log_notice(LD_CONFIG, "Disabled attaching debuggers for unprivileged "
1410 "users.");
1412 disabled_debugger_attach = (ok == 1);
1413 } else if (!options->DisableDebuggerAttachment &&
1414 !warned_debugger_attach) {
1415 log_notice(LD_CONFIG, "Not disabling debugger attaching for "
1416 "unprivileged users.");
1417 warned_debugger_attach = 1;
1421 /* Write control ports to disk as appropriate */
1422 control_ports_write_to_file();
1424 if (running_tor && !have_lockfile()) {
1425 if (try_locking(options, 1) < 0)
1426 return -1;
1429 if (consider_adding_dir_servers(options, old_options) < 0)
1430 return -1;
1432 #ifdef NON_ANONYMOUS_MODE_ENABLED
1433 log_warn(LD_GENERAL, "This copy of Tor was compiled to run in a "
1434 "non-anonymous mode. It will provide NO ANONYMITY.");
1435 #endif
1437 #ifdef ENABLE_TOR2WEB_MODE
1438 if (!options->Tor2webMode) {
1439 log_err(LD_CONFIG, "This copy of Tor was compiled to run in "
1440 "'tor2web mode'. It can only be run with the Tor2webMode torrc "
1441 "option enabled.");
1442 return -1;
1444 #else
1445 if (options->Tor2webMode) {
1446 log_err(LD_CONFIG, "This copy of Tor was not compiled to run in "
1447 "'tor2web mode'. It cannot be run with the Tor2webMode torrc "
1448 "option enabled. To enable Tor2webMode recompile with the "
1449 "--enable-tor2web-mode option.");
1450 return -1;
1452 #endif
1454 /* If we are a bridge with a pluggable transport proxy but no
1455 Extended ORPort, inform the user that she is missing out. */
1456 if (server_mode(options) && options->ServerTransportPlugin &&
1457 !options->ExtORPort_lines) {
1458 log_notice(LD_CONFIG, "We use pluggable transports but the Extended "
1459 "ORPort is disabled. Tor and your pluggable transports proxy "
1460 "communicate with each other via the Extended ORPort so it "
1461 "is suggested you enable it: it will also allow your Bridge "
1462 "to collect statistics about its clients that use pluggable "
1463 "transports. Please enable it using the ExtORPort torrc option "
1464 "(e.g. set 'ExtORPort auto').");
1467 if (options->Bridges) {
1468 mark_bridge_list();
1469 for (cl = options->Bridges; cl; cl = cl->next) {
1470 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
1471 if (!bridge_line) {
1472 log_warn(LD_BUG,
1473 "Previously validated Bridge line could not be added!");
1474 return -1;
1476 bridge_add_from_config(bridge_line);
1478 sweep_bridge_list();
1481 if (running_tor && rend_config_services(options, 0)<0) {
1482 log_warn(LD_BUG,
1483 "Previously validated hidden services line could not be added!");
1484 return -1;
1487 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1488 log_warn(LD_BUG, "Previously validated client authorization for "
1489 "hidden services could not be added!");
1490 return -1;
1493 /* Load state */
1494 if (! or_state_loaded() && running_tor) {
1495 if (or_state_load())
1496 return -1;
1497 rep_hist_load_mtbf_data(time(NULL));
1500 /* If we have an ExtORPort, initialize its auth cookie. */
1501 if (running_tor &&
1502 init_ext_or_cookie_authentication(!!options->ExtORPort_lines) < 0) {
1503 log_warn(LD_CONFIG,"Error creating Extended ORPort cookie file.");
1504 return -1;
1507 mark_transport_list();
1508 pt_prepare_proxy_list_for_config_read();
1509 if (!options->DisableNetwork) {
1510 if (options->ClientTransportPlugin) {
1511 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
1512 if (parse_transport_line(options, cl->value, 0, 0) < 0) {
1513 log_warn(LD_BUG,
1514 "Previously validated ClientTransportPlugin line "
1515 "could not be added!");
1516 return -1;
1521 if (options->ServerTransportPlugin && server_mode(options)) {
1522 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
1523 if (parse_transport_line(options, cl->value, 0, 1) < 0) {
1524 log_warn(LD_BUG,
1525 "Previously validated ServerTransportPlugin line "
1526 "could not be added!");
1527 return -1;
1532 sweep_transport_list();
1533 sweep_proxy_list();
1535 /* Start the PT proxy configuration. By doing this configuration
1536 here, we also figure out which proxies need to be restarted and
1537 which not. */
1538 if (pt_proxies_configuration_pending() && !net_is_disabled())
1539 pt_configure_remaining_proxies();
1541 /* Bail out at this point if we're not going to be a client or server:
1542 * we want to not fork, and to log stuff to stderr. */
1543 if (!running_tor)
1544 return 0;
1546 /* Finish backgrounding the process */
1547 if (options->RunAsDaemon) {
1548 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1549 finish_daemon(options->DataDirectory);
1552 /* We want to reinit keys as needed before we do much of anything else:
1553 keys are important, and other things can depend on them. */
1554 if (transition_affects_workers ||
1555 (options->V3AuthoritativeDir && (!old_options ||
1556 !old_options->V3AuthoritativeDir))) {
1557 if (init_keys() < 0) {
1558 log_warn(LD_BUG,"Error initializing keys; exiting");
1559 return -1;
1561 } else if (old_options &&
1562 options_transition_requires_fresh_tls_context(old_options,
1563 options)) {
1564 if (router_initialize_tls_context() < 0) {
1565 log_warn(LD_BUG,"Error initializing TLS context.");
1566 return -1;
1570 /* Write our PID to the PID file. If we do not have write permissions we
1571 * will log a warning */
1572 if (options->PidFile && !sandbox_is_active()) {
1573 write_pidfile(options->PidFile);
1576 /* Register addressmap directives */
1577 config_register_addressmaps(options);
1578 parse_virtual_addr_network(options->VirtualAddrNetworkIPv4, AF_INET,0,NULL);
1579 parse_virtual_addr_network(options->VirtualAddrNetworkIPv6, AF_INET6,0,NULL);
1581 /* Update address policies. */
1582 if (policies_parse_from_options(options) < 0) {
1583 /* This should be impossible, but let's be sure. */
1584 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1585 return -1;
1588 if (init_control_cookie_authentication(options->CookieAuthentication) < 0) {
1589 log_warn(LD_CONFIG,"Error creating control cookie authentication file.");
1590 return -1;
1593 monitor_owning_controller_process(options->OwningControllerProcess);
1595 /* reload keys as needed for rendezvous services. */
1596 if (rend_service_load_all_keys()<0) {
1597 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1598 return -1;
1601 /* Set up scheduler thresholds */
1602 scheduler_set_watermarks((uint32_t)options->SchedulerLowWaterMark__,
1603 (uint32_t)options->SchedulerHighWaterMark__,
1604 (options->SchedulerMaxFlushCells__ > 0) ?
1605 options->SchedulerMaxFlushCells__ : 1000);
1607 /* Set up accounting */
1608 if (accounting_parse_options(options, 0)<0) {
1609 log_warn(LD_CONFIG,"Error in accounting options");
1610 return -1;
1612 if (accounting_is_enabled(options))
1613 configure_accounting(time(NULL));
1615 #ifdef USE_BUFFEREVENTS
1616 /* If we're using the bufferevents implementation and our rate limits
1617 * changed, we need to tell the rate-limiting system about it. */
1618 if (!old_options ||
1619 old_options->BandwidthRate != options->BandwidthRate ||
1620 old_options->BandwidthBurst != options->BandwidthBurst ||
1621 old_options->RelayBandwidthRate != options->RelayBandwidthRate ||
1622 old_options->RelayBandwidthBurst != options->RelayBandwidthBurst)
1623 connection_bucket_init();
1624 #endif
1626 old_ewma_enabled = cell_ewma_enabled();
1627 /* Change the cell EWMA settings */
1628 cell_ewma_set_scale_factor(options, networkstatus_get_latest_consensus());
1629 /* If we just enabled ewma, set the cmux policy on all active channels */
1630 if (cell_ewma_enabled() && !old_ewma_enabled) {
1631 channel_set_cmux_policy_everywhere(&ewma_policy);
1632 } else if (!cell_ewma_enabled() && old_ewma_enabled) {
1633 /* Turn it off everywhere */
1634 channel_set_cmux_policy_everywhere(NULL);
1637 /* Update the BridgePassword's hashed version as needed. We store this as a
1638 * digest so that we can do side-channel-proof comparisons on it.
1640 if (options->BridgePassword) {
1641 char *http_authenticator;
1642 http_authenticator = alloc_http_authenticator(options->BridgePassword);
1643 if (!http_authenticator) {
1644 log_warn(LD_BUG, "Unable to allocate HTTP authenticator. Not setting "
1645 "BridgePassword.");
1646 return -1;
1648 options->BridgePassword_AuthDigest_ = tor_malloc(DIGEST256_LEN);
1649 crypto_digest256(options->BridgePassword_AuthDigest_,
1650 http_authenticator, strlen(http_authenticator),
1651 DIGEST_SHA256);
1652 tor_free(http_authenticator);
1655 if (parse_outbound_addresses(options, 0, &msg) < 0) {
1656 log_warn(LD_BUG, "Failed parsing outbound bind addresses: %s", msg);
1657 tor_free(msg);
1658 return -1;
1661 config_maybe_load_geoip_files_(options, old_options);
1663 if (geoip_is_loaded(AF_INET) && options->GeoIPExcludeUnknown) {
1664 /* ExcludeUnknown is true or "auto" */
1665 const int is_auto = options->GeoIPExcludeUnknown == -1;
1666 int changed;
1668 changed = routerset_add_unknown_ccs(&options->ExcludeNodes, is_auto);
1669 changed += routerset_add_unknown_ccs(&options->ExcludeExitNodes, is_auto);
1671 if (changed)
1672 routerset_add_unknown_ccs(&options->ExcludeExitNodesUnion_, is_auto);
1675 /* Check for transitions that need action. */
1676 if (old_options) {
1677 int revise_trackexithosts = 0;
1678 int revise_automap_entries = 0;
1679 if ((options->UseEntryGuards && !old_options->UseEntryGuards) ||
1680 options->UseBridges != old_options->UseBridges ||
1681 (options->UseBridges &&
1682 !config_lines_eq(options->Bridges, old_options->Bridges)) ||
1683 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes) ||
1684 !routerset_equal(old_options->ExcludeExitNodes,
1685 options->ExcludeExitNodes) ||
1686 !routerset_equal(old_options->EntryNodes, options->EntryNodes) ||
1687 !routerset_equal(old_options->ExitNodes, options->ExitNodes) ||
1688 !routerset_equal(old_options->Tor2webRendezvousPoints,
1689 options->Tor2webRendezvousPoints) ||
1690 options->StrictNodes != old_options->StrictNodes) {
1691 log_info(LD_CIRC,
1692 "Changed to using entry guards or bridges, or changed "
1693 "preferred or excluded node lists. "
1694 "Abandoning previous circuits.");
1695 circuit_mark_all_unused_circs();
1696 circuit_mark_all_dirty_circs_as_unusable();
1697 revise_trackexithosts = 1;
1700 if (!smartlist_strings_eq(old_options->TrackHostExits,
1701 options->TrackHostExits))
1702 revise_trackexithosts = 1;
1704 if (revise_trackexithosts)
1705 addressmap_clear_excluded_trackexithosts(options);
1707 if (!options->AutomapHostsOnResolve) {
1708 if (old_options->AutomapHostsOnResolve)
1709 revise_automap_entries = 1;
1710 } else {
1711 if (!smartlist_strings_eq(old_options->AutomapHostsSuffixes,
1712 options->AutomapHostsSuffixes))
1713 revise_automap_entries = 1;
1714 else if (!opt_streq(old_options->VirtualAddrNetworkIPv4,
1715 options->VirtualAddrNetworkIPv4) ||
1716 !opt_streq(old_options->VirtualAddrNetworkIPv6,
1717 options->VirtualAddrNetworkIPv6))
1718 revise_automap_entries = 1;
1721 if (revise_automap_entries)
1722 addressmap_clear_invalid_automaps(options);
1724 /* How long should we delay counting bridge stats after becoming a bridge?
1725 * We use this so we don't count people who used our bridge thinking it is
1726 * a relay. If you change this, don't forget to change the log message
1727 * below. It's 4 hours (the time it takes to stop being used by clients)
1728 * plus some extra time for clock skew. */
1729 #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
1731 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
1732 int was_relay = 0;
1733 if (options->BridgeRelay) {
1734 time_t int_start = time(NULL);
1735 if (config_lines_eq(old_options->ORPort_lines,options->ORPort_lines)) {
1736 int_start += RELAY_BRIDGE_STATS_DELAY;
1737 was_relay = 1;
1739 geoip_bridge_stats_init(int_start);
1740 log_info(LD_CONFIG, "We are acting as a bridge now. Starting new "
1741 "GeoIP stats interval%s.", was_relay ? " in 6 "
1742 "hours from now" : "");
1743 } else {
1744 geoip_bridge_stats_term();
1745 log_info(LD_GENERAL, "We are no longer acting as a bridge. "
1746 "Forgetting GeoIP stats.");
1750 if (transition_affects_workers) {
1751 log_info(LD_GENERAL,
1752 "Worker-related options changed. Rotating workers.");
1754 if (server_mode(options) && !server_mode(old_options)) {
1755 cpu_init();
1756 ip_address_changed(0);
1757 if (have_completed_a_circuit() || !any_predicted_circuits(time(NULL)))
1758 inform_testing_reachability();
1760 cpuworkers_rotate_keyinfo();
1761 if (dns_reset())
1762 return -1;
1763 } else {
1764 if (dns_reset())
1765 return -1;
1768 if (options->PerConnBWRate != old_options->PerConnBWRate ||
1769 options->PerConnBWBurst != old_options->PerConnBWBurst)
1770 connection_or_update_token_buckets(get_connection_array(), options);
1773 /* Only collect directory-request statistics on relays and bridges. */
1774 options->DirReqStatistics = options->DirReqStatistics_option &&
1775 server_mode(options);
1777 if (options->CellStatistics || options->DirReqStatistics ||
1778 options->EntryStatistics || options->ExitPortStatistics ||
1779 options->ConnDirectionStatistics ||
1780 options->HiddenServiceStatistics ||
1781 options->BridgeAuthoritativeDir) {
1782 time_t now = time(NULL);
1783 int print_notice = 0;
1785 /* Only collect other relay-only statistics on relays. */
1786 if (!public_server_mode(options)) {
1787 options->CellStatistics = 0;
1788 options->EntryStatistics = 0;
1789 options->ConnDirectionStatistics = 0;
1790 options->HiddenServiceStatistics = 0;
1791 options->ExitPortStatistics = 0;
1794 if ((!old_options || !old_options->CellStatistics) &&
1795 options->CellStatistics) {
1796 rep_hist_buffer_stats_init(now);
1797 print_notice = 1;
1799 if ((!old_options || !old_options->DirReqStatistics) &&
1800 options->DirReqStatistics) {
1801 if (geoip_is_loaded(AF_INET)) {
1802 geoip_dirreq_stats_init(now);
1803 print_notice = 1;
1804 } else {
1805 /* disable statistics collection since we have no geoip file */
1806 options->DirReqStatistics = 0;
1807 if (options->ORPort_set)
1808 log_notice(LD_CONFIG, "Configured to measure directory request "
1809 "statistics, but no GeoIP database found. "
1810 "Please specify a GeoIP database using the "
1811 "GeoIPFile option.");
1814 if ((!old_options || !old_options->EntryStatistics) &&
1815 options->EntryStatistics && !should_record_bridge_info(options)) {
1816 if (geoip_is_loaded(AF_INET) || geoip_is_loaded(AF_INET6)) {
1817 geoip_entry_stats_init(now);
1818 print_notice = 1;
1819 } else {
1820 options->EntryStatistics = 0;
1821 log_notice(LD_CONFIG, "Configured to measure entry node "
1822 "statistics, but no GeoIP database found. "
1823 "Please specify a GeoIP database using the "
1824 "GeoIPFile option.");
1827 if ((!old_options || !old_options->ExitPortStatistics) &&
1828 options->ExitPortStatistics) {
1829 rep_hist_exit_stats_init(now);
1830 print_notice = 1;
1832 if ((!old_options || !old_options->ConnDirectionStatistics) &&
1833 options->ConnDirectionStatistics) {
1834 rep_hist_conn_stats_init(now);
1836 if ((!old_options || !old_options->HiddenServiceStatistics) &&
1837 options->HiddenServiceStatistics) {
1838 log_info(LD_CONFIG, "Configured to measure hidden service statistics.");
1839 rep_hist_hs_stats_init(now);
1841 if ((!old_options || !old_options->BridgeAuthoritativeDir) &&
1842 options->BridgeAuthoritativeDir) {
1843 rep_hist_desc_stats_init(now);
1844 print_notice = 1;
1846 if (print_notice)
1847 log_notice(LD_CONFIG, "Configured to measure statistics. Look for "
1848 "the *-stats files that will first be written to the "
1849 "data directory in 24 hours from now.");
1852 /* If we used to have statistics enabled but we just disabled them,
1853 stop gathering them. */
1854 if (old_options && old_options->CellStatistics &&
1855 !options->CellStatistics)
1856 rep_hist_buffer_stats_term();
1857 if (old_options && old_options->DirReqStatistics &&
1858 !options->DirReqStatistics)
1859 geoip_dirreq_stats_term();
1860 if (old_options && old_options->EntryStatistics &&
1861 !options->EntryStatistics)
1862 geoip_entry_stats_term();
1863 if (old_options && old_options->HiddenServiceStatistics &&
1864 !options->HiddenServiceStatistics)
1865 rep_hist_hs_stats_term();
1866 if (old_options && old_options->ExitPortStatistics &&
1867 !options->ExitPortStatistics)
1868 rep_hist_exit_stats_term();
1869 if (old_options && old_options->ConnDirectionStatistics &&
1870 !options->ConnDirectionStatistics)
1871 rep_hist_conn_stats_term();
1872 if (old_options && old_options->BridgeAuthoritativeDir &&
1873 !options->BridgeAuthoritativeDir)
1874 rep_hist_desc_stats_term();
1876 /* Check if we need to parse and add the EntryNodes config option. */
1877 if (options->EntryNodes &&
1878 (!old_options ||
1879 !routerset_equal(old_options->EntryNodes,options->EntryNodes) ||
1880 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes)))
1881 entry_nodes_should_be_added();
1883 /* Since our options changed, we might need to regenerate and upload our
1884 * server descriptor.
1886 if (!old_options ||
1887 options_transition_affects_descriptor(old_options, options))
1888 mark_my_descriptor_dirty("config change");
1890 /* We may need to reschedule some directory stuff if our status changed. */
1891 if (old_options) {
1892 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1893 dirvote_recalculate_timing(options, time(NULL));
1894 if (!bool_eq(directory_fetches_dir_info_early(options),
1895 directory_fetches_dir_info_early(old_options)) ||
1896 !bool_eq(directory_fetches_dir_info_later(options),
1897 directory_fetches_dir_info_later(old_options))) {
1898 /* Make sure update_router_have_minimum_dir_info() gets called. */
1899 router_dir_info_changed();
1900 /* We might need to download a new consensus status later or sooner than
1901 * we had expected. */
1902 update_consensus_networkstatus_fetch_time(time(NULL));
1906 /* Load the webpage we're going to serve every time someone asks for '/' on
1907 our DirPort. */
1908 tor_free(global_dirfrontpagecontents);
1909 if (options->DirPortFrontPage) {
1910 global_dirfrontpagecontents =
1911 read_file_to_str(options->DirPortFrontPage, 0, NULL);
1912 if (!global_dirfrontpagecontents) {
1913 log_warn(LD_CONFIG,
1914 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1915 options->DirPortFrontPage);
1919 return 0;
1922 typedef enum {
1923 TAKES_NO_ARGUMENT = 0,
1924 ARGUMENT_NECESSARY = 1,
1925 ARGUMENT_OPTIONAL = 2
1926 } takes_argument_t;
1928 static const struct {
1929 const char *name;
1930 takes_argument_t takes_argument;
1931 } CMDLINE_ONLY_OPTIONS[] = {
1932 { "-f", ARGUMENT_NECESSARY },
1933 { "--allow-missing-torrc", TAKES_NO_ARGUMENT },
1934 { "--defaults-torrc", ARGUMENT_NECESSARY },
1935 { "--hash-password", ARGUMENT_NECESSARY },
1936 { "--dump-config", ARGUMENT_OPTIONAL },
1937 { "--list-fingerprint", TAKES_NO_ARGUMENT },
1938 { "--keygen", TAKES_NO_ARGUMENT },
1939 { "--newpass", TAKES_NO_ARGUMENT },
1940 #if 0
1941 /* XXXX028: This is not working yet in 0.2.7, so disabling with the
1942 * minimal code modification. */
1943 { "--master-key", ARGUMENT_NECESSARY },
1944 #endif
1945 { "--no-passphrase", TAKES_NO_ARGUMENT },
1946 { "--passphrase-fd", ARGUMENT_NECESSARY },
1947 { "--verify-config", TAKES_NO_ARGUMENT },
1948 { "--ignore-missing-torrc", TAKES_NO_ARGUMENT },
1949 { "--quiet", TAKES_NO_ARGUMENT },
1950 { "--hush", TAKES_NO_ARGUMENT },
1951 { "--version", TAKES_NO_ARGUMENT },
1952 { "--library-versions", TAKES_NO_ARGUMENT },
1953 { "-h", TAKES_NO_ARGUMENT },
1954 { "--help", TAKES_NO_ARGUMENT },
1955 { "--list-torrc-options", TAKES_NO_ARGUMENT },
1956 { "--nt-service", TAKES_NO_ARGUMENT },
1957 { "-nt-service", TAKES_NO_ARGUMENT },
1958 { NULL, 0 },
1961 /** Helper: Read a list of configuration options from the command line. If
1962 * successful, or if ignore_errors is set, put them in *<b>result</b>, put the
1963 * commandline-only options in *<b>cmdline_result</b>, and return 0;
1964 * otherwise, return -1 and leave *<b>result</b> and <b>cmdline_result</b>
1965 * alone. */
1967 config_parse_commandline(int argc, char **argv, int ignore_errors,
1968 config_line_t **result,
1969 config_line_t **cmdline_result)
1971 config_line_t *param = NULL;
1973 config_line_t *front = NULL;
1974 config_line_t **new = &front;
1976 config_line_t *front_cmdline = NULL;
1977 config_line_t **new_cmdline = &front_cmdline;
1979 char *s, *arg;
1980 int i = 1;
1982 while (i < argc) {
1983 unsigned command = CONFIG_LINE_NORMAL;
1984 takes_argument_t want_arg = ARGUMENT_NECESSARY;
1985 int is_cmdline = 0;
1986 int j;
1988 for (j = 0; CMDLINE_ONLY_OPTIONS[j].name != NULL; ++j) {
1989 if (!strcmp(argv[i], CMDLINE_ONLY_OPTIONS[j].name)) {
1990 is_cmdline = 1;
1991 want_arg = CMDLINE_ONLY_OPTIONS[j].takes_argument;
1992 break;
1996 s = argv[i];
1998 /* Each keyword may be prefixed with one or two dashes. */
1999 if (*s == '-')
2000 s++;
2001 if (*s == '-')
2002 s++;
2003 /* Figure out the command, if any. */
2004 if (*s == '+') {
2005 s++;
2006 command = CONFIG_LINE_APPEND;
2007 } else if (*s == '/') {
2008 s++;
2009 command = CONFIG_LINE_CLEAR;
2010 /* A 'clear' command has no argument. */
2011 want_arg = 0;
2014 const int is_last = (i == argc-1);
2016 if (want_arg == ARGUMENT_NECESSARY && is_last) {
2017 if (ignore_errors) {
2018 arg = strdup("");
2019 } else {
2020 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
2021 argv[i]);
2022 config_free_lines(front);
2023 config_free_lines(front_cmdline);
2024 return -1;
2026 } else if (want_arg == ARGUMENT_OPTIONAL && is_last) {
2027 arg = tor_strdup("");
2028 } else {
2029 arg = (want_arg != TAKES_NO_ARGUMENT) ? tor_strdup(argv[i+1]) :
2030 tor_strdup("");
2033 param = tor_malloc_zero(sizeof(config_line_t));
2034 param->key = is_cmdline ? tor_strdup(argv[i]) :
2035 tor_strdup(config_expand_abbrev(&options_format, s, 1, 1));
2036 param->value = arg;
2037 param->command = command;
2038 param->next = NULL;
2039 log_debug(LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
2040 param->key, param->value);
2042 if (is_cmdline) {
2043 *new_cmdline = param;
2044 new_cmdline = &((*new_cmdline)->next);
2045 } else {
2046 *new = param;
2047 new = &((*new)->next);
2050 i += want_arg ? 2 : 1;
2052 *cmdline_result = front_cmdline;
2053 *result = front;
2054 return 0;
2057 /** Return true iff key is a valid configuration option. */
2059 option_is_recognized(const char *key)
2061 const config_var_t *var = config_find_option(&options_format, key);
2062 return (var != NULL);
2065 /** Return the canonical name of a configuration option, or NULL
2066 * if no such option exists. */
2067 const char *
2068 option_get_canonical_name(const char *key)
2070 const config_var_t *var = config_find_option(&options_format, key);
2071 return var ? var->name : NULL;
2074 /** Return a canonical list of the options assigned for key.
2076 config_line_t *
2077 option_get_assignment(const or_options_t *options, const char *key)
2079 return config_get_assigned_option(&options_format, options, key, 1);
2082 /** Try assigning <b>list</b> to the global options. You do this by duping
2083 * options, assigning list to the new one, then validating it. If it's
2084 * ok, then throw out the old one and stick with the new one. Else,
2085 * revert to old and return failure. Return SETOPT_OK on success, or
2086 * a setopt_err_t on failure.
2088 * If not success, point *<b>msg</b> to a newly allocated string describing
2089 * what went wrong.
2091 setopt_err_t
2092 options_trial_assign(config_line_t *list, int use_defaults,
2093 int clear_first, char **msg)
2095 int r;
2096 or_options_t *trial_options = config_dup(&options_format, get_options());
2098 if ((r=config_assign(&options_format, trial_options,
2099 list, use_defaults, clear_first, msg)) < 0) {
2100 config_free(&options_format, trial_options);
2101 return r;
2104 if (options_validate(get_options_mutable(), trial_options,
2105 global_default_options, 1, msg) < 0) {
2106 config_free(&options_format, trial_options);
2107 return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2110 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2111 config_free(&options_format, trial_options);
2112 return SETOPT_ERR_TRANSITION;
2115 if (set_options(trial_options, msg)<0) {
2116 config_free(&options_format, trial_options);
2117 return SETOPT_ERR_SETTING;
2120 /* we liked it. put it in place. */
2121 return SETOPT_OK;
2124 /** Print a usage message for tor. */
2125 static void
2126 print_usage(void)
2128 printf(
2129 "Copyright (c) 2001-2004, Roger Dingledine\n"
2130 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2131 "Copyright (c) 2007-2015, The Tor Project, Inc.\n\n"
2132 "tor -f <torrc> [args]\n"
2133 "See man page for options, or https://www.torproject.org/ for "
2134 "documentation.\n");
2137 /** Print all non-obsolete torrc options. */
2138 static void
2139 list_torrc_options(void)
2141 int i;
2142 smartlist_t *lines = smartlist_new();
2143 for (i = 0; option_vars_[i].name; ++i) {
2144 const config_var_t *var = &option_vars_[i];
2145 if (var->type == CONFIG_TYPE_OBSOLETE ||
2146 var->type == CONFIG_TYPE_LINELIST_V)
2147 continue;
2148 printf("%s\n", var->name);
2150 smartlist_free(lines);
2153 /** Last value actually set by resolve_my_address. */
2154 static uint32_t last_resolved_addr = 0;
2156 /** Accessor for last_resolved_addr from outside this file. */
2157 uint32_t
2158 get_last_resolved_addr(void)
2160 return last_resolved_addr;
2163 /** Reset last_resolved_addr from outside this file. */
2164 void
2165 reset_last_resolved_addr(void)
2167 last_resolved_addr = 0;
2171 * Attempt getting our non-local (as judged by tor_addr_is_internal()
2172 * function) IP address using following techniques, listed in
2173 * order from best (most desirable, try first) to worst (least
2174 * desirable, try if everything else fails).
2176 * First, attempt using <b>options-\>Address</b> to get our
2177 * non-local IP address.
2179 * If <b>options-\>Address</b> represents a non-local IP address,
2180 * consider it ours.
2182 * If <b>options-\>Address</b> is a DNS name that resolves to
2183 * a non-local IP address, consider this IP address ours.
2185 * If <b>options-\>Address</b> is NULL, fall back to getting local
2186 * hostname and using it in above-described ways to try and
2187 * get our IP address.
2189 * In case local hostname cannot be resolved to a non-local IP
2190 * address, try getting an IP address of network interface
2191 * in hopes it will be non-local one.
2193 * Fail if one or more of the following is true:
2194 * - DNS name in <b>options-\>Address</b> cannot be resolved.
2195 * - <b>options-\>Address</b> is a local host address.
2196 * - Attempt to getting local hostname fails.
2197 * - Attempt to getting network interface address fails.
2199 * Return 0 if all is well, or -1 if we can't find a suitable
2200 * public IP address.
2202 * If we are returning 0:
2203 * - Put our public IP address (in host order) into *<b>addr_out</b>.
2204 * - If <b>method_out</b> is non-NULL, set *<b>method_out</b> to a static
2205 * string describing how we arrived at our answer.
2206 * - "CONFIGURED" - parsed from IP address string in
2207 * <b>options-\>Address</b>
2208 * - "RESOLVED" - resolved from DNS name in <b>options-\>Address</b>
2209 * - "GETHOSTNAME" - resolved from a local hostname.
2210 * - "INTERFACE" - retrieved from a network interface.
2211 * - If <b>hostname_out</b> is non-NULL, and we resolved a hostname to
2212 * get our address, set *<b>hostname_out</b> to a newly allocated string
2213 * holding that hostname. (If we didn't get our address by resolving a
2214 * hostname, set *<b>hostname_out</b> to NULL.)
2216 * XXXX ipv6
2219 resolve_my_address(int warn_severity, const or_options_t *options,
2220 uint32_t *addr_out,
2221 const char **method_out, char **hostname_out)
2223 struct in_addr in;
2224 uint32_t addr; /* host order */
2225 char hostname[256];
2226 const char *method_used;
2227 const char *hostname_used;
2228 int explicit_ip=1;
2229 int explicit_hostname=1;
2230 int from_interface=0;
2231 char *addr_string = NULL;
2232 const char *address = options->Address;
2233 int notice_severity = warn_severity <= LOG_NOTICE ?
2234 LOG_NOTICE : warn_severity;
2236 tor_addr_t myaddr;
2237 tor_assert(addr_out);
2240 * Step one: Fill in 'hostname' to be our best guess.
2243 if (address && *address) {
2244 strlcpy(hostname, address, sizeof(hostname));
2245 } else { /* then we need to guess our address */
2246 explicit_ip = 0; /* it's implicit */
2247 explicit_hostname = 0; /* it's implicit */
2249 if (tor_gethostname(hostname, sizeof(hostname)) < 0) {
2250 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2251 return -1;
2253 log_debug(LD_CONFIG, "Guessed local host name as '%s'", hostname);
2257 * Step two: Now that we know 'hostname', parse it or resolve it. If
2258 * it doesn't parse or resolve, look at the interface address. Set 'addr'
2259 * to be our (host-order) 32-bit answer.
2262 if (tor_inet_aton(hostname, &in) == 0) {
2263 /* then we have to resolve it */
2264 explicit_ip = 0;
2265 if (tor_lookup_hostname(hostname, &addr)) { /* failed to resolve */
2266 uint32_t interface_ip; /* host order */
2268 if (explicit_hostname) {
2269 log_fn(warn_severity, LD_CONFIG,
2270 "Could not resolve local Address '%s'. Failing.", hostname);
2271 return -1;
2273 log_fn(notice_severity, LD_CONFIG,
2274 "Could not resolve guessed local hostname '%s'. "
2275 "Trying something else.", hostname);
2276 if (get_interface_address(warn_severity, &interface_ip)) {
2277 log_fn(warn_severity, LD_CONFIG,
2278 "Could not get local interface IP address. Failing.");
2279 return -1;
2281 from_interface = 1;
2282 addr = interface_ip;
2283 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2284 "local interface. Using that.", fmt_addr32(addr));
2285 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2286 } else { /* resolved hostname into addr */
2287 tor_addr_from_ipv4h(&myaddr, addr);
2289 if (!explicit_hostname &&
2290 tor_addr_is_internal(&myaddr, 0)) {
2291 tor_addr_t interface_ip;
2293 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2294 "resolves to a private IP address (%s). Trying something "
2295 "else.", hostname, fmt_addr32(addr));
2297 if (get_interface_address6(warn_severity, AF_INET, &interface_ip)<0) {
2298 log_fn(warn_severity, LD_CONFIG,
2299 "Could not get local interface IP address. Too bad.");
2300 } else if (tor_addr_is_internal(&interface_ip, 0)) {
2301 log_fn(notice_severity, LD_CONFIG,
2302 "Interface IP address '%s' is a private address too. "
2303 "Ignoring.", fmt_addr(&interface_ip));
2304 } else {
2305 from_interface = 1;
2306 addr = tor_addr_to_ipv4h(&interface_ip);
2307 log_fn(notice_severity, LD_CONFIG,
2308 "Learned IP address '%s' for local interface."
2309 " Using that.", fmt_addr32(addr));
2310 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2314 } else {
2315 addr = ntohl(in.s_addr); /* set addr so that addr_string is not
2316 * illformed */
2320 * Step three: Check whether 'addr' is an internal IP address, and error
2321 * out if it is and we don't want that.
2324 tor_addr_from_ipv4h(&myaddr,addr);
2326 addr_string = tor_dup_ip(addr);
2327 if (tor_addr_is_internal(&myaddr, 0)) {
2328 /* make sure we're ok with publishing an internal IP */
2329 if (!options->DirAuthorities && !options->AlternateDirAuthority) {
2330 /* if they are using the default authorities, disallow internal IPs
2331 * always. */
2332 log_fn(warn_severity, LD_CONFIG,
2333 "Address '%s' resolves to private IP address '%s'. "
2334 "Tor servers that use the default DirAuthorities must have "
2335 "public IP addresses.", hostname, addr_string);
2336 tor_free(addr_string);
2337 return -1;
2339 if (!explicit_ip) {
2340 /* even if they've set their own authorities, require an explicit IP if
2341 * they're using an internal address. */
2342 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2343 "IP address '%s'. Please set the Address config option to be "
2344 "the IP address you want to use.", hostname, addr_string);
2345 tor_free(addr_string);
2346 return -1;
2351 * Step four: We have a winner! 'addr' is our answer for sure, and
2352 * 'addr_string' is its string form. Fill out the various fields to
2353 * say how we decided it.
2356 log_debug(LD_CONFIG, "Resolved Address to '%s'.", addr_string);
2358 if (explicit_ip) {
2359 method_used = "CONFIGURED";
2360 hostname_used = NULL;
2361 } else if (explicit_hostname) {
2362 method_used = "RESOLVED";
2363 hostname_used = hostname;
2364 } else if (from_interface) {
2365 method_used = "INTERFACE";
2366 hostname_used = NULL;
2367 } else {
2368 method_used = "GETHOSTNAME";
2369 hostname_used = hostname;
2372 *addr_out = addr;
2373 if (method_out)
2374 *method_out = method_used;
2375 if (hostname_out)
2376 *hostname_out = hostname_used ? tor_strdup(hostname_used) : NULL;
2379 * Step five: Check if the answer has changed since last time (or if
2380 * there was no last time), and if so call various functions to keep
2381 * us up-to-date.
2384 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2385 /* Leave this as a notice, regardless of the requested severity,
2386 * at least until dynamic IP address support becomes bulletproof. */
2387 log_notice(LD_NET,
2388 "Your IP address seems to have changed to %s "
2389 "(METHOD=%s%s%s). Updating.",
2390 addr_string, method_used,
2391 hostname_used ? " HOSTNAME=" : "",
2392 hostname_used ? hostname_used : "");
2393 ip_address_changed(0);
2396 if (last_resolved_addr != *addr_out) {
2397 control_event_server_status(LOG_NOTICE,
2398 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s%s%s",
2399 addr_string, method_used,
2400 hostname_used ? " HOSTNAME=" : "",
2401 hostname_used ? hostname_used : "");
2403 last_resolved_addr = *addr_out;
2406 * And finally, clean up and return success.
2409 tor_free(addr_string);
2410 return 0;
2413 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2414 * on a private network.
2416 MOCK_IMPL(int,
2417 is_local_addr, (const tor_addr_t *addr))
2419 if (tor_addr_is_internal(addr, 0))
2420 return 1;
2421 /* Check whether ip is on the same /24 as we are. */
2422 if (get_options()->EnforceDistinctSubnets == 0)
2423 return 0;
2424 if (tor_addr_family(addr) == AF_INET) {
2425 /*XXXX023 IP6 what corresponds to an /24? */
2426 uint32_t ip = tor_addr_to_ipv4h(addr);
2428 /* It's possible that this next check will hit before the first time
2429 * resolve_my_address actually succeeds. (For clients, it is likely that
2430 * resolve_my_address will never be called at all). In those cases,
2431 * last_resolved_addr will be 0, and so checking to see whether ip is on
2432 * the same /24 as last_resolved_addr will be the same as checking whether
2433 * it was on net 0, which is already done by tor_addr_is_internal.
2435 if ((last_resolved_addr & (uint32_t)0xffffff00ul)
2436 == (ip & (uint32_t)0xffffff00ul))
2437 return 1;
2439 return 0;
2442 /** Return a new empty or_options_t. Used for testing. */
2443 or_options_t *
2444 options_new(void)
2446 return config_new(&options_format);
2449 /** Set <b>options</b> to hold reasonable defaults for most options.
2450 * Each option defaults to zero. */
2451 void
2452 options_init(or_options_t *options)
2454 config_init(&options_format, options);
2457 /** Return a string containing a possible configuration file that would give
2458 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2459 * include options that are the same as Tor's defaults.
2461 char *
2462 options_dump(const or_options_t *options, int how_to_dump)
2464 const or_options_t *use_defaults;
2465 int minimal;
2466 switch (how_to_dump) {
2467 case OPTIONS_DUMP_MINIMAL:
2468 use_defaults = global_default_options;
2469 minimal = 1;
2470 break;
2471 case OPTIONS_DUMP_DEFAULTS:
2472 use_defaults = NULL;
2473 minimal = 1;
2474 break;
2475 case OPTIONS_DUMP_ALL:
2476 use_defaults = NULL;
2477 minimal = 0;
2478 break;
2479 default:
2480 log_warn(LD_BUG, "Bogus value for how_to_dump==%d", how_to_dump);
2481 return NULL;
2484 return config_dump(&options_format, use_defaults, options, minimal, 0);
2487 /** Return 0 if every element of sl is a string holding a decimal
2488 * representation of a port number, or if sl is NULL.
2489 * Otherwise set *msg and return -1. */
2490 static int
2491 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2493 int i;
2494 tor_assert(name);
2496 if (!sl)
2497 return 0;
2499 SMARTLIST_FOREACH(sl, const char *, cp,
2501 i = atoi(cp);
2502 if (i < 1 || i > 65535) {
2503 tor_asprintf(msg, "Port '%s' out of range in %s", cp, name);
2504 return -1;
2507 return 0;
2510 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2511 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2512 * Else return 0.
2514 static int
2515 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2517 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2518 /* This handles an understandable special case where somebody says "2gb"
2519 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2520 --*value;
2522 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2523 tor_asprintf(msg, "%s ("U64_FORMAT") must be at most %d",
2524 desc, U64_PRINTF_ARG(*value),
2525 ROUTER_MAX_DECLARED_BANDWIDTH);
2526 return -1;
2528 return 0;
2531 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2532 * and write it to <b>options</b>-\>PublishServerDescriptor_. Treat "1"
2533 * as "v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2534 * Treat "0" as "".
2535 * Return 0 on success or -1 if not a recognized authority type (in which
2536 * case the value of PublishServerDescriptor_ is undefined). */
2537 static int
2538 compute_publishserverdescriptor(or_options_t *options)
2540 smartlist_t *list = options->PublishServerDescriptor;
2541 dirinfo_type_t *auth = &options->PublishServerDescriptor_;
2542 *auth = NO_DIRINFO;
2543 if (!list) /* empty list, answer is none */
2544 return 0;
2545 SMARTLIST_FOREACH_BEGIN(list, const char *, string) {
2546 if (!strcasecmp(string, "v1"))
2547 log_warn(LD_CONFIG, "PublishServerDescriptor v1 has no effect, because "
2548 "there are no v1 directory authorities anymore.");
2549 else if (!strcmp(string, "1"))
2550 if (options->BridgeRelay)
2551 *auth |= BRIDGE_DIRINFO;
2552 else
2553 *auth |= V3_DIRINFO;
2554 else if (!strcasecmp(string, "v2"))
2555 log_warn(LD_CONFIG, "PublishServerDescriptor v2 has no effect, because "
2556 "there are no v2 directory authorities anymore.");
2557 else if (!strcasecmp(string, "v3"))
2558 *auth |= V3_DIRINFO;
2559 else if (!strcasecmp(string, "bridge"))
2560 *auth |= BRIDGE_DIRINFO;
2561 else if (!strcasecmp(string, "hidserv"))
2562 log_warn(LD_CONFIG,
2563 "PublishServerDescriptor hidserv is invalid. See "
2564 "PublishHidServDescriptors.");
2565 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2566 /* no authority */;
2567 else
2568 return -1;
2569 } SMARTLIST_FOREACH_END(string);
2570 return 0;
2573 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2574 * services can overload the directory system. */
2575 #define MIN_REND_POST_PERIOD (10*60)
2576 #define MIN_REND_POST_PERIOD_TESTING (5)
2578 /** Higest allowable value for PredictedPortsRelevanceTime; if this is
2579 * too high, our selection of exits will decrease for an extended
2580 * period of time to an uncomfortable level .*/
2581 #define MAX_PREDICTED_CIRCS_RELEVANCE (60*60)
2583 /** Highest allowable value for RendPostPeriod. */
2584 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2586 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2587 * will generate too many circuits and potentially overload the network. */
2588 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2590 /** Highest allowable value for MaxCircuitDirtiness: prevents time_t
2591 * overflows. */
2592 #define MAX_MAX_CIRCUIT_DIRTINESS (30*24*60*60)
2594 /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
2595 * will generate too many circuits and potentially overload the network. */
2596 #define MIN_CIRCUIT_STREAM_TIMEOUT 10
2598 /** Lowest allowable value for HeartbeatPeriod; if this is too low, we might
2599 * expose more information than we're comfortable with. */
2600 #define MIN_HEARTBEAT_PERIOD (30*60)
2602 /** Lowest recommended value for CircuitBuildTimeout; if it is set too low
2603 * and LearnCircuitBuildTimeout is off, the failure rate for circuit
2604 * construction may be very high. In that case, if it is set below this
2605 * threshold emit a warning.
2606 * */
2607 #define RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT (10)
2609 static int
2610 options_validate_cb(void *old_options, void *options, void *default_options,
2611 int from_setconf, char **msg)
2613 return options_validate(old_options, options, default_options,
2614 from_setconf, msg);
2617 #define REJECT(arg) \
2618 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2619 #ifdef __GNUC__
2620 #define COMPLAIN(args...) \
2621 STMT_BEGIN log_warn(LD_CONFIG, args); STMT_END
2622 #else
2623 #define COMPLAIN(args, ...) \
2624 STMT_BEGIN log_warn(LD_CONFIG, args, ##__VA_ARGS__); STMT_END
2625 #endif
2627 /** Log a warning message iff <b>filepath</b> is not absolute.
2628 * Warning message must contain option name <b>option</b> and
2629 * an absolute path that <b>filepath<b> will resolve to.
2631 * In case <b>filepath</b> is absolute, do nothing.
2633 static void
2634 warn_if_option_path_is_relative(const char *option,
2635 char *filepath)
2637 if (filepath && path_is_relative(filepath)) {
2638 char *abs_path = make_path_absolute(filepath);
2639 COMPLAIN("Path for %s (%s) is relative and will resolve to %s."
2640 " Is this what you wanted?", option, filepath, abs_path);
2641 tor_free(abs_path);
2645 /** Scan <b>options</b> for occurances of relative file/directory
2646 * path and log a warning whenever it is found.
2648 static void
2649 warn_about_relative_paths(or_options_t *options)
2651 tor_assert(options);
2653 warn_if_option_path_is_relative("CookieAuthFile",
2654 options->CookieAuthFile);
2655 warn_if_option_path_is_relative("ExtORPortCookieAuthFile",
2656 options->ExtORPortCookieAuthFile);
2657 warn_if_option_path_is_relative("DirPortFrontPage",
2658 options->DirPortFrontPage);
2659 warn_if_option_path_is_relative("V3BandwidthsFile",
2660 options->V3BandwidthsFile);
2661 warn_if_option_path_is_relative("ControlPortWriteToFile",
2662 options->ControlPortWriteToFile);
2663 warn_if_option_path_is_relative("GeoIPFile",options->GeoIPFile);
2664 warn_if_option_path_is_relative("GeoIPv6File",options->GeoIPv6File);
2665 warn_if_option_path_is_relative("Log",options->DebugLogFile);
2666 warn_if_option_path_is_relative("AccelDir",options->AccelDir);
2667 warn_if_option_path_is_relative("DataDirectory",options->DataDirectory);
2668 warn_if_option_path_is_relative("PidFile",options->PidFile);
2670 for (config_line_t *hs_line = options->RendConfigLines; hs_line;
2671 hs_line = hs_line->next) {
2672 if (!strcasecmp(hs_line->key, "HiddenServiceDir"))
2673 warn_if_option_path_is_relative("HiddenServiceDir",hs_line->value);
2677 /** Return 0 if every setting in <b>options</b> is reasonable, is a
2678 * permissible transition from <b>old_options</b>, and none of the
2679 * testing-only settings differ from <b>default_options</b> unless in
2680 * testing mode. Else return -1. Should have no side effects, except for
2681 * normalizing the contents of <b>options</b>.
2683 * On error, tor_strdup an error explanation into *<b>msg</b>.
2685 * XXX
2686 * If <b>from_setconf</b>, we were called by the controller, and our
2687 * Log line should stay empty. If it's 0, then give us a default log
2688 * if there are no logs defined.
2690 STATIC int
2691 options_validate(or_options_t *old_options, or_options_t *options,
2692 or_options_t *default_options, int from_setconf, char **msg)
2694 int i;
2695 config_line_t *cl;
2696 const char *uname = get_uname();
2697 int n_ports=0;
2698 int world_writable_control_socket=0;
2700 tor_assert(msg);
2701 *msg = NULL;
2703 warn_about_relative_paths(options);
2705 if (server_mode(options) &&
2706 (!strcmpstart(uname, "Windows 95") ||
2707 !strcmpstart(uname, "Windows 98") ||
2708 !strcmpstart(uname, "Windows Me"))) {
2709 log_warn(LD_CONFIG, "Tor is running as a server, but you are "
2710 "running %s; this probably won't work. See "
2711 "https://www.torproject.org/docs/faq.html#BestOSForRelay "
2712 "for details.", uname);
2715 if (parse_ports(options, 1, msg, &n_ports,
2716 &world_writable_control_socket) < 0)
2717 return -1;
2719 if (parse_outbound_addresses(options, 1, msg) < 0)
2720 return -1;
2722 if (validate_data_directory(options)<0)
2723 REJECT("Invalid DataDirectory");
2725 if (options->Nickname == NULL) {
2726 if (server_mode(options)) {
2727 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
2729 } else {
2730 if (!is_legal_nickname(options->Nickname)) {
2731 tor_asprintf(msg,
2732 "Nickname '%s' is wrong length or contains illegal characters.",
2733 options->Nickname);
2734 return -1;
2738 if (server_mode(options) && !options->ContactInfo)
2739 log_notice(LD_CONFIG, "Your ContactInfo config option is not set. "
2740 "Please consider setting it, so we can contact you if your server is "
2741 "misconfigured or something else goes wrong.");
2743 /* Special case on first boot if no Log options are given. */
2744 if (!options->Logs && !options->RunAsDaemon && !from_setconf) {
2745 if (quiet_level == 0)
2746 config_line_append(&options->Logs, "Log", "notice stdout");
2747 else if (quiet_level == 1)
2748 config_line_append(&options->Logs, "Log", "warn stdout");
2751 /* Validate the tor_log(s) */
2752 if (options_init_logs(old_options, options, 1)<0)
2753 REJECT("Failed to validate Log options. See logs for details.");
2755 if (authdir_mode(options)) {
2756 /* confirm that our address isn't broken, so we can complain now */
2757 uint32_t tmp;
2758 if (resolve_my_address(LOG_WARN, options, &tmp, NULL, NULL) < 0)
2759 REJECT("Failed to resolve/guess local address. See logs for details.");
2762 if (server_mode(options) && options->RendConfigLines)
2763 log_warn(LD_CONFIG,
2764 "Tor is currently configured as a relay and a hidden service. "
2765 "That's not very secure: you should probably run your hidden service "
2766 "in a separate Tor process, at least -- see "
2767 "https://trac.torproject.org/8742");
2769 /* XXXX require that the only port not be DirPort? */
2770 /* XXXX require that at least one port be listened-upon. */
2771 if (n_ports == 0 && !options->RendConfigLines)
2772 log_warn(LD_CONFIG,
2773 "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
2774 "undefined, and there aren't any hidden services configured. "
2775 "Tor will still run, but probably won't do anything.");
2777 options->TransProxyType_parsed = TPT_DEFAULT;
2778 #ifdef USE_TRANSPARENT
2779 if (options->TransProxyType) {
2780 if (!strcasecmp(options->TransProxyType, "default")) {
2781 options->TransProxyType_parsed = TPT_DEFAULT;
2782 } else if (!strcasecmp(options->TransProxyType, "pf-divert")) {
2783 #if !defined(__OpenBSD__) && !defined( DARWIN )
2784 /* Later versions of OS X have pf */
2785 REJECT("pf-divert is a OpenBSD-specific "
2786 "and OS X/Darwin-specific feature.");
2787 #else
2788 options->TransProxyType_parsed = TPT_PF_DIVERT;
2789 #endif
2790 } else if (!strcasecmp(options->TransProxyType, "tproxy")) {
2791 #if !defined(__linux__)
2792 REJECT("TPROXY is a Linux-specific feature.");
2793 #else
2794 options->TransProxyType_parsed = TPT_TPROXY;
2795 #endif
2796 } else if (!strcasecmp(options->TransProxyType, "ipfw")) {
2797 #if !defined(__FreeBSD__) && !defined( DARWIN )
2798 /* Earlier versions of OS X have ipfw */
2799 REJECT("ipfw is a FreeBSD-specific"
2800 "and OS X/Darwin-specific feature.");
2801 #else
2802 options->TransProxyType_parsed = TPT_IPFW;
2803 #endif
2804 } else {
2805 REJECT("Unrecognized value for TransProxyType");
2808 if (strcasecmp(options->TransProxyType, "default") &&
2809 !options->TransPort_set) {
2810 REJECT("Cannot use TransProxyType without any valid TransPort or "
2811 "TransListenAddress.");
2814 #else
2815 if (options->TransPort_set)
2816 REJECT("TransPort and TransListenAddress are disabled "
2817 "in this build.");
2818 #endif
2820 if (options->TokenBucketRefillInterval <= 0
2821 || options->TokenBucketRefillInterval > 1000) {
2822 REJECT("TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
2825 if (options->ExcludeExitNodes || options->ExcludeNodes) {
2826 options->ExcludeExitNodesUnion_ = routerset_new();
2827 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeExitNodes);
2828 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeNodes);
2831 if (options->SchedulerLowWaterMark__ == 0 ||
2832 options->SchedulerLowWaterMark__ > UINT32_MAX) {
2833 log_warn(LD_GENERAL, "Bad SchedulerLowWaterMark__ option");
2834 return -1;
2835 } else if (options->SchedulerHighWaterMark__ <=
2836 options->SchedulerLowWaterMark__ ||
2837 options->SchedulerHighWaterMark__ > UINT32_MAX) {
2838 log_warn(LD_GENERAL, "Bad SchedulerHighWaterMark option");
2839 return -1;
2842 if (options->NodeFamilies) {
2843 options->NodeFamilySets = smartlist_new();
2844 for (cl = options->NodeFamilies; cl; cl = cl->next) {
2845 routerset_t *rs = routerset_new();
2846 if (routerset_parse(rs, cl->value, cl->key) == 0) {
2847 smartlist_add(options->NodeFamilySets, rs);
2848 } else {
2849 routerset_free(rs);
2854 if (options->TLSECGroup && (strcasecmp(options->TLSECGroup, "P256") &&
2855 strcasecmp(options->TLSECGroup, "P224"))) {
2856 COMPLAIN("Unrecognized TLSECGroup: Falling back to the default.");
2857 tor_free(options->TLSECGroup);
2859 if (!evaluate_ecgroup_for_tls(options->TLSECGroup)) {
2860 REJECT("Unsupported TLSECGroup.");
2863 if (options->ExcludeNodes && options->StrictNodes) {
2864 COMPLAIN("You have asked to exclude certain relays from all positions "
2865 "in your circuits. Expect hidden services and other Tor "
2866 "features to be broken in unpredictable ways.");
2869 for (cl = options->RecommendedPackages; cl; cl = cl->next) {
2870 if (! validate_recommended_package_line(cl->value)) {
2871 log_warn(LD_CONFIG, "Invalid RecommendedPackage line %s will be ignored",
2872 escaped(cl->value));
2876 if (options->AuthoritativeDir) {
2877 if (!options->ContactInfo && !options->TestingTorNetwork)
2878 REJECT("Authoritative directory servers must set ContactInfo");
2879 if (!options->RecommendedClientVersions)
2880 options->RecommendedClientVersions =
2881 config_lines_dup(options->RecommendedVersions);
2882 if (!options->RecommendedServerVersions)
2883 options->RecommendedServerVersions =
2884 config_lines_dup(options->RecommendedVersions);
2885 if (options->VersioningAuthoritativeDir &&
2886 (!options->RecommendedClientVersions ||
2887 !options->RecommendedServerVersions))
2888 REJECT("Versioning authoritative dir servers must set "
2889 "Recommended*Versions.");
2890 if (options->UseEntryGuards) {
2891 log_info(LD_CONFIG, "Authoritative directory servers can't set "
2892 "UseEntryGuards. Disabling.");
2893 options->UseEntryGuards = 0;
2895 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
2896 log_info(LD_CONFIG, "Authoritative directories always try to download "
2897 "extra-info documents. Setting DownloadExtraInfo.");
2898 options->DownloadExtraInfo = 1;
2900 if (!(options->BridgeAuthoritativeDir ||
2901 options->V3AuthoritativeDir))
2902 REJECT("AuthoritativeDir is set, but none of "
2903 "(Bridge/V3)AuthoritativeDir is set.");
2904 /* If we have a v3bandwidthsfile and it's broken, complain on startup */
2905 if (options->V3BandwidthsFile && !old_options) {
2906 dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
2908 /* same for guardfraction file */
2909 if (options->GuardfractionFile && !old_options) {
2910 dirserv_read_guardfraction_file(options->GuardfractionFile, NULL);
2914 if (options->AuthoritativeDir && !options->DirPort_set)
2915 REJECT("Running as authoritative directory, but no DirPort set.");
2917 if (options->AuthoritativeDir && !options->ORPort_set)
2918 REJECT("Running as authoritative directory, but no ORPort set.");
2920 if (options->AuthoritativeDir && options->ClientOnly)
2921 REJECT("Running as authoritative directory, but ClientOnly also set.");
2923 if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
2924 REJECT("FetchDirInfoExtraEarly requires that you also set "
2925 "FetchDirInfoEarly");
2927 if (options->ConnLimit <= 0) {
2928 tor_asprintf(msg,
2929 "ConnLimit must be greater than 0, but was set to %d",
2930 options->ConnLimit);
2931 return -1;
2934 if (options->PathsNeededToBuildCircuits >= 0.0) {
2935 if (options->PathsNeededToBuildCircuits < 0.25) {
2936 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too low. Increasing "
2937 "to 0.25");
2938 options->PathsNeededToBuildCircuits = 0.25;
2939 } else if (options->PathsNeededToBuildCircuits > 0.95) {
2940 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too high. Decreasing "
2941 "to 0.95");
2942 options->PathsNeededToBuildCircuits = 0.95;
2946 if (options->MaxClientCircuitsPending <= 0 ||
2947 options->MaxClientCircuitsPending > MAX_MAX_CLIENT_CIRCUITS_PENDING) {
2948 tor_asprintf(msg,
2949 "MaxClientCircuitsPending must be between 1 and %d, but "
2950 "was set to %d", MAX_MAX_CLIENT_CIRCUITS_PENDING,
2951 options->MaxClientCircuitsPending);
2952 return -1;
2955 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
2956 return -1;
2958 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
2959 return -1;
2961 if (validate_ports_csv(options->RejectPlaintextPorts,
2962 "RejectPlaintextPorts", msg) < 0)
2963 return -1;
2965 if (validate_ports_csv(options->WarnPlaintextPorts,
2966 "WarnPlaintextPorts", msg) < 0)
2967 return -1;
2969 if (options->FascistFirewall && !options->ReachableAddresses) {
2970 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
2971 /* We already have firewall ports set, so migrate them to
2972 * ReachableAddresses, which will set ReachableORAddresses and
2973 * ReachableDirAddresses if they aren't set explicitly. */
2974 smartlist_t *instead = smartlist_new();
2975 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
2976 new_line->key = tor_strdup("ReachableAddresses");
2977 /* If we're configured with the old format, we need to prepend some
2978 * open ports. */
2979 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
2981 int p = atoi(portno);
2982 if (p<0) continue;
2983 smartlist_add_asprintf(instead, "*:%d", p);
2985 new_line->value = smartlist_join_strings(instead,",",0,NULL);
2986 /* These have been deprecated since 0.1.1.5-alpha-cvs */
2987 log_notice(LD_CONFIG,
2988 "Converting FascistFirewall and FirewallPorts "
2989 "config options to new format: \"ReachableAddresses %s\"",
2990 new_line->value);
2991 options->ReachableAddresses = new_line;
2992 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
2993 smartlist_free(instead);
2994 } else {
2995 /* We do not have FirewallPorts set, so add 80 to
2996 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
2997 if (!options->ReachableDirAddresses) {
2998 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
2999 new_line->key = tor_strdup("ReachableDirAddresses");
3000 new_line->value = tor_strdup("*:80");
3001 options->ReachableDirAddresses = new_line;
3002 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3003 "to new format: \"ReachableDirAddresses *:80\"");
3005 if (!options->ReachableORAddresses) {
3006 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3007 new_line->key = tor_strdup("ReachableORAddresses");
3008 new_line->value = tor_strdup("*:443");
3009 options->ReachableORAddresses = new_line;
3010 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3011 "to new format: \"ReachableORAddresses *:443\"");
3016 for (i=0; i<3; i++) {
3017 config_line_t **linep =
3018 (i==0) ? &options->ReachableAddresses :
3019 (i==1) ? &options->ReachableORAddresses :
3020 &options->ReachableDirAddresses;
3021 if (!*linep)
3022 continue;
3023 /* We need to end with a reject *:*, not an implicit accept *:* */
3024 for (;;) {
3025 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
3026 break;
3027 linep = &((*linep)->next);
3028 if (!*linep) {
3029 *linep = tor_malloc_zero(sizeof(config_line_t));
3030 (*linep)->key = tor_strdup(
3031 (i==0) ? "ReachableAddresses" :
3032 (i==1) ? "ReachableORAddresses" :
3033 "ReachableDirAddresses");
3034 (*linep)->value = tor_strdup("reject *:*");
3035 break;
3040 if ((options->ReachableAddresses ||
3041 options->ReachableORAddresses ||
3042 options->ReachableDirAddresses) &&
3043 server_mode(options))
3044 REJECT("Servers must be able to freely connect to the rest "
3045 "of the Internet, so they must not set Reachable*Addresses "
3046 "or FascistFirewall.");
3048 if (options->UseBridges &&
3049 server_mode(options))
3050 REJECT("Servers must be able to freely connect to the rest "
3051 "of the Internet, so they must not set UseBridges.");
3053 /* If both of these are set, we'll end up with funny behavior where we
3054 * demand enough entrynodes be up and running else we won't build
3055 * circuits, yet we never actually use them. */
3056 if (options->UseBridges && options->EntryNodes)
3057 REJECT("You cannot set both UseBridges and EntryNodes.");
3059 if (options->EntryNodes && !options->UseEntryGuards) {
3060 REJECT("If EntryNodes is set, UseEntryGuards must be enabled.");
3063 options->MaxMemInQueues =
3064 compute_real_max_mem_in_queues(options->MaxMemInQueues_raw,
3065 server_mode(options));
3066 options->MaxMemInQueues_low_threshold = (options->MaxMemInQueues / 4) * 3;
3068 options->AllowInvalid_ = 0;
3070 if (options->AllowInvalidNodes) {
3071 SMARTLIST_FOREACH_BEGIN(options->AllowInvalidNodes, const char *, cp) {
3072 if (!strcasecmp(cp, "entry"))
3073 options->AllowInvalid_ |= ALLOW_INVALID_ENTRY;
3074 else if (!strcasecmp(cp, "exit"))
3075 options->AllowInvalid_ |= ALLOW_INVALID_EXIT;
3076 else if (!strcasecmp(cp, "middle"))
3077 options->AllowInvalid_ |= ALLOW_INVALID_MIDDLE;
3078 else if (!strcasecmp(cp, "introduction"))
3079 options->AllowInvalid_ |= ALLOW_INVALID_INTRODUCTION;
3080 else if (!strcasecmp(cp, "rendezvous"))
3081 options->AllowInvalid_ |= ALLOW_INVALID_RENDEZVOUS;
3082 else {
3083 tor_asprintf(msg,
3084 "Unrecognized value '%s' in AllowInvalidNodes", cp);
3085 return -1;
3087 } SMARTLIST_FOREACH_END(cp);
3090 if (!options->SafeLogging ||
3091 !strcasecmp(options->SafeLogging, "0")) {
3092 options->SafeLogging_ = SAFELOG_SCRUB_NONE;
3093 } else if (!strcasecmp(options->SafeLogging, "relay")) {
3094 options->SafeLogging_ = SAFELOG_SCRUB_RELAY;
3095 } else if (!strcasecmp(options->SafeLogging, "1")) {
3096 options->SafeLogging_ = SAFELOG_SCRUB_ALL;
3097 } else {
3098 tor_asprintf(msg,
3099 "Unrecognized value '%s' in SafeLogging",
3100 escaped(options->SafeLogging));
3101 return -1;
3104 if (compute_publishserverdescriptor(options) < 0) {
3105 tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
3106 return -1;
3109 if ((options->BridgeRelay
3110 || options->PublishServerDescriptor_ & BRIDGE_DIRINFO)
3111 && (options->PublishServerDescriptor_ & V3_DIRINFO)) {
3112 REJECT("Bridges are not supposed to publish router descriptors to the "
3113 "directory authorities. Please correct your "
3114 "PublishServerDescriptor line.");
3117 if (options->BridgeRelay && options->DirPort_set) {
3118 log_warn(LD_CONFIG, "Can't set a DirPort on a bridge relay; disabling "
3119 "DirPort");
3120 config_free_lines(options->DirPort_lines);
3121 options->DirPort_lines = NULL;
3122 options->DirPort_set = 0;
3125 if (options->MinUptimeHidServDirectoryV2 < 0) {
3126 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3127 "least 0 seconds. Changing to 0.");
3128 options->MinUptimeHidServDirectoryV2 = 0;
3131 const int min_rendpostperiod =
3132 options->TestingTorNetwork ?
3133 MIN_REND_POST_PERIOD_TESTING : MIN_REND_POST_PERIOD;
3134 if (options->RendPostPeriod < min_rendpostperiod) {
3135 log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
3136 "raising to %d seconds.", min_rendpostperiod);
3137 options->RendPostPeriod = min_rendpostperiod;;
3140 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3141 log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3142 MAX_DIR_PERIOD);
3143 options->RendPostPeriod = MAX_DIR_PERIOD;
3146 if (options->PredictedPortsRelevanceTime >
3147 MAX_PREDICTED_CIRCS_RELEVANCE) {
3148 log_warn(LD_CONFIG, "PredictedPortsRelevanceTime is too large; "
3149 "clipping to %ds.", MAX_PREDICTED_CIRCS_RELEVANCE);
3150 options->PredictedPortsRelevanceTime = MAX_PREDICTED_CIRCS_RELEVANCE;
3153 #ifdef ENABLE_TOR2WEB_MODE
3154 if (options->Tor2webMode && options->LearnCircuitBuildTimeout) {
3155 /* LearnCircuitBuildTimeout and Tor2webMode are incompatible in
3156 * two ways:
3158 * - LearnCircuitBuildTimeout results in a low CBT, which
3159 * Tor2webMode's use of one-hop rendezvous circuits lowers
3160 * much further, producing *far* too many timeouts.
3162 * - The adaptive CBT code does not update its timeout estimate
3163 * using build times for single-hop circuits.
3165 * If we fix both of these issues someday, we should test
3166 * Tor2webMode with LearnCircuitBuildTimeout on again. */
3167 log_notice(LD_CONFIG,"Tor2webMode is enabled; turning "
3168 "LearnCircuitBuildTimeout off.");
3169 options->LearnCircuitBuildTimeout = 0;
3172 if (options->Tor2webMode && options->UseEntryGuards) {
3173 /* tor2web mode clients do not (and should not) use entry guards
3174 * in any meaningful way. Further, tor2web mode causes the hidden
3175 * service client code to do things which break the path bias
3176 * detector, and it's far easier to turn off entry guards (and
3177 * thus the path bias detector with it) than to figure out how to
3178 * make a piece of code which cannot possibly help tor2web mode
3179 * users compatible with tor2web mode.
3181 log_notice(LD_CONFIG,
3182 "Tor2WebMode is enabled; disabling UseEntryGuards.");
3183 options->UseEntryGuards = 0;
3185 #endif
3187 if (options->Tor2webRendezvousPoints && !options->Tor2webMode) {
3188 REJECT("Tor2webRendezvousPoints cannot be set without Tor2webMode.");
3191 if (!(options->UseEntryGuards) &&
3192 (options->RendConfigLines != NULL)) {
3193 log_warn(LD_CONFIG,
3194 "UseEntryGuards is disabled, but you have configured one or more "
3195 "hidden services on this Tor instance. Your hidden services "
3196 "will be very easy to locate using a well-known attack -- see "
3197 "http://freehaven.net/anonbib/#hs-attack06 for details.");
3200 if (options->EntryNodes &&
3201 routerset_is_list(options->EntryNodes) &&
3202 (routerset_len(options->EntryNodes) == 1) &&
3203 (options->RendConfigLines != NULL)) {
3204 tor_asprintf(msg,
3205 "You have one single EntryNodes and at least one hidden service "
3206 "configured. This is bad because it's very easy to locate your "
3207 "entry guard which can then lead to the deanonymization of your "
3208 "hidden service -- for more details, see "
3209 "https://trac.torproject.org/projects/tor/ticket/14917. "
3210 "For this reason, the use of one EntryNodes with an hidden "
3211 "service is prohibited until a better solution is found.");
3212 return -1;
3215 if (!options->LearnCircuitBuildTimeout && options->CircuitBuildTimeout &&
3216 options->CircuitBuildTimeout < RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT) {
3217 log_warn(LD_CONFIG,
3218 "CircuitBuildTimeout is shorter (%d seconds) than the recommended "
3219 "minimum (%d seconds), and LearnCircuitBuildTimeout is disabled. "
3220 "If tor isn't working, raise this value or enable "
3221 "LearnCircuitBuildTimeout.",
3222 options->CircuitBuildTimeout,
3223 RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT );
3224 } else if (!options->LearnCircuitBuildTimeout &&
3225 !options->CircuitBuildTimeout) {
3226 log_notice(LD_CONFIG, "You disabled LearnCircuitBuildTimeout, but didn't "
3227 "a CircuitBuildTimeout. I'll pick a plausible default.");
3230 if (options->PathBiasNoticeRate > 1.0) {
3231 tor_asprintf(msg,
3232 "PathBiasNoticeRate is too high. "
3233 "It must be between 0 and 1.0");
3234 return -1;
3236 if (options->PathBiasWarnRate > 1.0) {
3237 tor_asprintf(msg,
3238 "PathBiasWarnRate is too high. "
3239 "It must be between 0 and 1.0");
3240 return -1;
3242 if (options->PathBiasExtremeRate > 1.0) {
3243 tor_asprintf(msg,
3244 "PathBiasExtremeRate is too high. "
3245 "It must be between 0 and 1.0");
3246 return -1;
3248 if (options->PathBiasNoticeUseRate > 1.0) {
3249 tor_asprintf(msg,
3250 "PathBiasNoticeUseRate is too high. "
3251 "It must be between 0 and 1.0");
3252 return -1;
3254 if (options->PathBiasExtremeUseRate > 1.0) {
3255 tor_asprintf(msg,
3256 "PathBiasExtremeUseRate is too high. "
3257 "It must be between 0 and 1.0");
3258 return -1;
3261 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3262 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3263 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3264 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3267 if (options->MaxCircuitDirtiness > MAX_MAX_CIRCUIT_DIRTINESS) {
3268 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too high; "
3269 "setting to %d days.", MAX_MAX_CIRCUIT_DIRTINESS/86400);
3270 options->MaxCircuitDirtiness = MAX_MAX_CIRCUIT_DIRTINESS;
3273 if (options->CircuitStreamTimeout &&
3274 options->CircuitStreamTimeout < MIN_CIRCUIT_STREAM_TIMEOUT) {
3275 log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
3276 "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
3277 options->CircuitStreamTimeout = MIN_CIRCUIT_STREAM_TIMEOUT;
3280 if (options->HeartbeatPeriod &&
3281 options->HeartbeatPeriod < MIN_HEARTBEAT_PERIOD) {
3282 log_warn(LD_CONFIG, "HeartbeatPeriod option is too short; "
3283 "raising to %d seconds.", MIN_HEARTBEAT_PERIOD);
3284 options->HeartbeatPeriod = MIN_HEARTBEAT_PERIOD;
3287 if (options->KeepalivePeriod < 1)
3288 REJECT("KeepalivePeriod option must be positive.");
3290 if (options->PortForwarding && options->Sandbox) {
3291 REJECT("PortForwarding is not compatible with Sandbox; at most one can "
3292 "be set");
3295 if (ensure_bandwidth_cap(&options->BandwidthRate,
3296 "BandwidthRate", msg) < 0)
3297 return -1;
3298 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3299 "BandwidthBurst", msg) < 0)
3300 return -1;
3301 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3302 "MaxAdvertisedBandwidth", msg) < 0)
3303 return -1;
3304 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3305 "RelayBandwidthRate", msg) < 0)
3306 return -1;
3307 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3308 "RelayBandwidthBurst", msg) < 0)
3309 return -1;
3310 if (ensure_bandwidth_cap(&options->PerConnBWRate,
3311 "PerConnBWRate", msg) < 0)
3312 return -1;
3313 if (ensure_bandwidth_cap(&options->PerConnBWBurst,
3314 "PerConnBWBurst", msg) < 0)
3315 return -1;
3316 if (ensure_bandwidth_cap(&options->AuthDirFastGuarantee,
3317 "AuthDirFastGuarantee", msg) < 0)
3318 return -1;
3319 if (ensure_bandwidth_cap(&options->AuthDirGuardBWGuarantee,
3320 "AuthDirGuardBWGuarantee", msg) < 0)
3321 return -1;
3323 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3324 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3325 if (options->RelayBandwidthBurst && !options->RelayBandwidthRate)
3326 options->RelayBandwidthRate = options->RelayBandwidthBurst;
3328 if (server_mode(options)) {
3329 const unsigned required_min_bw =
3330 public_server_mode(options) ?
3331 RELAY_REQUIRED_MIN_BANDWIDTH : BRIDGE_REQUIRED_MIN_BANDWIDTH;
3332 const char * const optbridge =
3333 public_server_mode(options) ? "" : "bridge ";
3334 if (options->BandwidthRate < required_min_bw) {
3335 tor_asprintf(msg,
3336 "BandwidthRate is set to %d bytes/second. "
3337 "For %sservers, it must be at least %u.",
3338 (int)options->BandwidthRate, optbridge,
3339 required_min_bw);
3340 return -1;
3341 } else if (options->MaxAdvertisedBandwidth <
3342 required_min_bw/2) {
3343 tor_asprintf(msg,
3344 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3345 "For %sservers, it must be at least %u.",
3346 (int)options->MaxAdvertisedBandwidth, optbridge,
3347 required_min_bw/2);
3348 return -1;
3350 if (options->RelayBandwidthRate &&
3351 options->RelayBandwidthRate < required_min_bw) {
3352 tor_asprintf(msg,
3353 "RelayBandwidthRate is set to %d bytes/second. "
3354 "For %sservers, it must be at least %u.",
3355 (int)options->RelayBandwidthRate, optbridge,
3356 required_min_bw);
3357 return -1;
3361 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3362 REJECT("RelayBandwidthBurst must be at least equal "
3363 "to RelayBandwidthRate.");
3365 if (options->BandwidthRate > options->BandwidthBurst)
3366 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3368 /* if they set relaybandwidth* really high but left bandwidth*
3369 * at the default, raise the defaults. */
3370 if (options->RelayBandwidthRate > options->BandwidthRate)
3371 options->BandwidthRate = options->RelayBandwidthRate;
3372 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3373 options->BandwidthBurst = options->RelayBandwidthBurst;
3375 if (accounting_parse_options(options, 1)<0)
3376 REJECT("Failed to parse accounting options. See logs for details.");
3378 if (options->AccountingMax) {
3379 if (options->RendConfigLines && server_mode(options)) {
3380 log_warn(LD_CONFIG, "Using accounting with a hidden service and an "
3381 "ORPort is risky: your hidden service(s) and your public "
3382 "address will all turn off at the same time, which may alert "
3383 "observers that they are being run by the same party.");
3384 } else if (config_count_key(options->RendConfigLines,
3385 "HiddenServiceDir") > 1) {
3386 log_warn(LD_CONFIG, "Using accounting with multiple hidden services is "
3387 "risky: they will all turn off at the same time, which may "
3388 "alert observers that they are being run by the same party.");
3392 options->AccountingRule = ACCT_MAX;
3393 if (options->AccountingRule_option) {
3394 if (!strcmp(options->AccountingRule_option, "sum"))
3395 options->AccountingRule = ACCT_SUM;
3396 else if (!strcmp(options->AccountingRule_option, "max"))
3397 options->AccountingRule = ACCT_MAX;
3398 else
3399 REJECT("AccountingRule must be 'sum' or 'max'");
3402 if (options->HTTPProxy) { /* parse it now */
3403 if (tor_addr_port_lookup(options->HTTPProxy,
3404 &options->HTTPProxyAddr, &options->HTTPProxyPort) < 0)
3405 REJECT("HTTPProxy failed to parse or resolve. Please fix.");
3406 if (options->HTTPProxyPort == 0) { /* give it a default */
3407 options->HTTPProxyPort = 80;
3411 if (options->HTTPProxyAuthenticator) {
3412 if (strlen(options->HTTPProxyAuthenticator) >= 512)
3413 REJECT("HTTPProxyAuthenticator is too long (>= 512 chars).");
3416 if (options->HTTPSProxy) { /* parse it now */
3417 if (tor_addr_port_lookup(options->HTTPSProxy,
3418 &options->HTTPSProxyAddr, &options->HTTPSProxyPort) <0)
3419 REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
3420 if (options->HTTPSProxyPort == 0) { /* give it a default */
3421 options->HTTPSProxyPort = 443;
3425 if (options->HTTPSProxyAuthenticator) {
3426 if (strlen(options->HTTPSProxyAuthenticator) >= 512)
3427 REJECT("HTTPSProxyAuthenticator is too long (>= 512 chars).");
3430 if (options->Socks4Proxy) { /* parse it now */
3431 if (tor_addr_port_lookup(options->Socks4Proxy,
3432 &options->Socks4ProxyAddr,
3433 &options->Socks4ProxyPort) <0)
3434 REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
3435 if (options->Socks4ProxyPort == 0) { /* give it a default */
3436 options->Socks4ProxyPort = 1080;
3440 if (options->Socks5Proxy) { /* parse it now */
3441 if (tor_addr_port_lookup(options->Socks5Proxy,
3442 &options->Socks5ProxyAddr,
3443 &options->Socks5ProxyPort) <0)
3444 REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
3445 if (options->Socks5ProxyPort == 0) { /* give it a default */
3446 options->Socks5ProxyPort = 1080;
3450 /* Check if more than one exclusive proxy type has been enabled. */
3451 if (!!options->Socks4Proxy + !!options->Socks5Proxy +
3452 !!options->HTTPSProxy > 1)
3453 REJECT("You have configured more than one proxy type. "
3454 "(Socks4Proxy|Socks5Proxy|HTTPSProxy)");
3456 /* Check if the proxies will give surprising behavior. */
3457 if (options->HTTPProxy && !(options->Socks4Proxy ||
3458 options->Socks5Proxy ||
3459 options->HTTPSProxy)) {
3460 log_warn(LD_CONFIG, "HTTPProxy configured, but no SOCKS proxy or "
3461 "HTTPS proxy configured. Watch out: this configuration will "
3462 "proxy unencrypted directory connections only.");
3465 if (options->Socks5ProxyUsername) {
3466 size_t len;
3468 len = strlen(options->Socks5ProxyUsername);
3469 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
3470 REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
3472 if (!options->Socks5ProxyPassword)
3473 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3475 len = strlen(options->Socks5ProxyPassword);
3476 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
3477 REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
3478 } else if (options->Socks5ProxyPassword)
3479 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3481 if (options->HashedControlPassword) {
3482 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3483 if (!sl) {
3484 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3485 } else {
3486 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3487 smartlist_free(sl);
3491 if (options->HashedControlSessionPassword) {
3492 smartlist_t *sl = decode_hashed_passwords(
3493 options->HashedControlSessionPassword);
3494 if (!sl) {
3495 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3496 } else {
3497 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3498 smartlist_free(sl);
3502 if (options->OwningControllerProcess) {
3503 const char *validate_pspec_msg = NULL;
3504 if (tor_validate_process_specifier(options->OwningControllerProcess,
3505 &validate_pspec_msg)) {
3506 tor_asprintf(msg, "Bad OwningControllerProcess: %s",
3507 validate_pspec_msg);
3508 return -1;
3512 if ((options->ControlPort_set || world_writable_control_socket) &&
3513 !options->HashedControlPassword &&
3514 !options->HashedControlSessionPassword &&
3515 !options->CookieAuthentication) {
3516 log_warn(LD_CONFIG, "Control%s is %s, but no authentication method "
3517 "has been configured. This means that any program on your "
3518 "computer can reconfigure your Tor. That's bad! You should "
3519 "upgrade your Tor controller as soon as possible.",
3520 options->ControlPort_set ? "Port" : "Socket",
3521 options->ControlPort_set ? "open" : "world writable");
3524 if (options->CookieAuthFileGroupReadable && !options->CookieAuthFile) {
3525 log_warn(LD_CONFIG, "CookieAuthFileGroupReadable is set, but will have "
3526 "no effect: you must specify an explicit CookieAuthFile to "
3527 "have it group-readable.");
3530 if (options->MyFamily && options->BridgeRelay) {
3531 log_warn(LD_CONFIG, "Listing a family for a bridge relay is not "
3532 "supported: it can reveal bridge fingerprints to censors. "
3533 "You should also make sure you aren't listing this bridge's "
3534 "fingerprint in any other MyFamily.");
3536 if (check_nickname_list(&options->MyFamily, "MyFamily", msg))
3537 return -1;
3538 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3539 routerset_t *rs = routerset_new();
3540 if (routerset_parse(rs, cl->value, cl->key)) {
3541 routerset_free(rs);
3542 return -1;
3544 routerset_free(rs);
3547 if (validate_addr_policies(options, msg) < 0)
3548 return -1;
3550 if (validate_dir_servers(options, old_options) < 0)
3551 REJECT("Directory authority/fallback line did not parse. See logs "
3552 "for details.");
3554 if (options->UseBridges && !options->Bridges)
3555 REJECT("If you set UseBridges, you must specify at least one bridge.");
3557 for (cl = options->Bridges; cl; cl = cl->next) {
3558 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
3559 if (!bridge_line)
3560 REJECT("Bridge line did not parse. See logs for details.");
3561 bridge_line_free(bridge_line);
3564 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
3565 if (parse_transport_line(options, cl->value, 1, 0) < 0)
3566 REJECT("Invalid client transport line. See logs for details.");
3569 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
3570 if (parse_transport_line(options, cl->value, 1, 1) < 0)
3571 REJECT("Invalid server transport line. See logs for details.");
3574 if (options->ServerTransportPlugin && !server_mode(options)) {
3575 log_notice(LD_GENERAL, "Tor is not configured as a relay but you specified"
3576 " a ServerTransportPlugin line (%s). The ServerTransportPlugin "
3577 "line will be ignored.",
3578 escaped(options->ServerTransportPlugin->value));
3581 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
3582 /** If get_bindaddr_from_transport_listen_line() fails with
3583 'transport' being NULL, it means that something went wrong
3584 while parsing the ServerTransportListenAddr line. */
3585 char *bindaddr = get_bindaddr_from_transport_listen_line(cl->value, NULL);
3586 if (!bindaddr)
3587 REJECT("ServerTransportListenAddr did not parse. See logs for details.");
3588 tor_free(bindaddr);
3591 if (options->ServerTransportListenAddr && !options->ServerTransportPlugin) {
3592 log_notice(LD_GENERAL, "You need at least a single managed-proxy to "
3593 "specify a transport listen address. The "
3594 "ServerTransportListenAddr line will be ignored.");
3597 for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
3598 /** If get_options_from_transport_options_line() fails with
3599 'transport' being NULL, it means that something went wrong
3600 while parsing the ServerTransportOptions line. */
3601 smartlist_t *options_sl =
3602 get_options_from_transport_options_line(cl->value, NULL);
3603 if (!options_sl)
3604 REJECT("ServerTransportOptions did not parse. See logs for details.");
3606 SMARTLIST_FOREACH(options_sl, char *, cp, tor_free(cp));
3607 smartlist_free(options_sl);
3610 if (options->ConstrainedSockets) {
3611 /* If the user wants to constrain socket buffer use, make sure the desired
3612 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3613 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3614 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3615 options->ConstrainedSockSize % 1024) {
3616 tor_asprintf(msg,
3617 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3618 "in 1024 byte increments.",
3619 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3620 return -1;
3622 if (options->DirPort_set) {
3623 /* Providing cached directory entries while system TCP buffers are scarce
3624 * will exacerbate the socket errors. Suggest that this be disabled. */
3625 COMPLAIN("You have requested constrained socket buffers while also "
3626 "serving directory entries via DirPort. It is strongly "
3627 "suggested that you disable serving directory requests when "
3628 "system TCP buffer resources are scarce.");
3632 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3633 options->V3AuthVotingInterval/2) {
3635 This doesn't work, but it seems like it should:
3636 what code is preventing the interval being less than twice the lead-up?
3637 if (options->TestingTorNetwork) {
3638 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3639 options->V3AuthVotingInterval) {
3640 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than "
3641 "V3AuthVotingInterval");
3642 } else {
3643 COMPLAIN("V3AuthVoteDelay plus V3AuthDistDelay is more than half "
3644 "V3AuthVotingInterval. This may lead to "
3645 "consensus instability, particularly if clocks drift.");
3647 } else {
3649 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3650 "V3AuthVotingInterval");
3656 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS) {
3657 if (options->TestingTorNetwork) {
3658 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS_TESTING) {
3659 REJECT("V3AuthVoteDelay is way too low.");
3660 } else {
3661 COMPLAIN("V3AuthVoteDelay is very low. "
3662 "This may lead to failure to vote for a consensus.");
3664 } else {
3665 REJECT("V3AuthVoteDelay is way too low.");
3669 if (options->V3AuthDistDelay < MIN_DIST_SECONDS) {
3670 if (options->TestingTorNetwork) {
3671 if (options->V3AuthDistDelay < MIN_DIST_SECONDS_TESTING) {
3672 REJECT("V3AuthDistDelay is way too low.");
3673 } else {
3674 COMPLAIN("V3AuthDistDelay is very low. "
3675 "This may lead to missing votes in a consensus.");
3677 } else {
3678 REJECT("V3AuthDistDelay is way too low.");
3682 if (options->V3AuthNIntervalsValid < 2)
3683 REJECT("V3AuthNIntervalsValid must be at least 2.");
3685 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3686 if (options->TestingTorNetwork) {
3687 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL_TESTING) {
3688 REJECT("V3AuthVotingInterval is insanely low.");
3689 } else {
3690 COMPLAIN("V3AuthVotingInterval is very low. "
3691 "This may lead to failure to synchronise for a consensus.");
3693 } else {
3694 REJECT("V3AuthVotingInterval is insanely low.");
3696 } else if (options->V3AuthVotingInterval > 24*60*60) {
3697 REJECT("V3AuthVotingInterval is insanely high.");
3698 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3699 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3702 if (rend_config_services(options, 1) < 0)
3703 REJECT("Failed to configure rendezvous options. See logs for details.");
3705 /* Parse client-side authorization for hidden services. */
3706 if (rend_parse_service_authorization(options, 1) < 0)
3707 REJECT("Failed to configure client authorization for hidden services. "
3708 "See logs for details.");
3710 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv4,
3711 AF_INET, 1, msg)<0)
3712 return -1;
3713 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv6,
3714 AF_INET6, 1, msg)<0)
3715 return -1;
3717 if (options->TestingTorNetwork &&
3718 !(options->DirAuthorities ||
3719 (options->AlternateDirAuthority &&
3720 options->AlternateBridgeAuthority))) {
3721 REJECT("TestingTorNetwork may only be configured in combination with "
3722 "a non-default set of DirAuthority or both of "
3723 "AlternateDirAuthority and AlternateBridgeAuthority configured.");
3726 if (options->AllowSingleHopExits && !options->DirAuthorities) {
3727 COMPLAIN("You have set AllowSingleHopExits; now your relay will allow "
3728 "others to make one-hop exits. However, since by default most "
3729 "clients avoid relays that set this option, most clients will "
3730 "ignore you.");
3733 #define CHECK_DEFAULT(arg) \
3734 STMT_BEGIN \
3735 if (!options->TestingTorNetwork && \
3736 !options->UsingTestNetworkDefaults_ && \
3737 !config_is_same(&options_format,options, \
3738 default_options,#arg)) { \
3739 REJECT(#arg " may only be changed in testing Tor " \
3740 "networks!"); \
3741 } STMT_END
3742 CHECK_DEFAULT(TestingV3AuthInitialVotingInterval);
3743 CHECK_DEFAULT(TestingV3AuthInitialVoteDelay);
3744 CHECK_DEFAULT(TestingV3AuthInitialDistDelay);
3745 CHECK_DEFAULT(TestingV3AuthVotingStartOffset);
3746 CHECK_DEFAULT(TestingAuthDirTimeToLearnReachability);
3747 CHECK_DEFAULT(TestingEstimatedDescriptorPropagationTime);
3748 CHECK_DEFAULT(TestingServerDownloadSchedule);
3749 CHECK_DEFAULT(TestingClientDownloadSchedule);
3750 CHECK_DEFAULT(TestingServerConsensusDownloadSchedule);
3751 CHECK_DEFAULT(TestingClientConsensusDownloadSchedule);
3752 CHECK_DEFAULT(TestingBridgeDownloadSchedule);
3753 CHECK_DEFAULT(TestingClientMaxIntervalWithoutRequest);
3754 CHECK_DEFAULT(TestingDirConnectionMaxStall);
3755 CHECK_DEFAULT(TestingConsensusMaxDownloadTries);
3756 CHECK_DEFAULT(TestingDescriptorMaxDownloadTries);
3757 CHECK_DEFAULT(TestingMicrodescMaxDownloadTries);
3758 CHECK_DEFAULT(TestingCertMaxDownloadTries);
3759 CHECK_DEFAULT(TestingAuthKeyLifetime);
3760 CHECK_DEFAULT(TestingLinkCertLifetime);
3761 CHECK_DEFAULT(TestingSigningKeySlop);
3762 CHECK_DEFAULT(TestingAuthKeySlop);
3763 CHECK_DEFAULT(TestingLinkKeySlop);
3764 #undef CHECK_DEFAULT
3766 if (options->SigningKeyLifetime < options->TestingSigningKeySlop*2)
3767 REJECT("SigningKeyLifetime is too short.");
3768 if (options->TestingLinkCertLifetime < options->TestingAuthKeySlop*2)
3769 REJECT("LinkCertLifetime is too short.");
3770 if (options->TestingAuthKeyLifetime < options->TestingLinkKeySlop*2)
3771 REJECT("TestingAuthKeyLifetime is too short.");
3773 if (options->TestingV3AuthInitialVotingInterval
3774 < MIN_VOTE_INTERVAL_TESTING_INITIAL) {
3775 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3776 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
3777 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3778 "30 minutes.");
3781 if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS_TESTING) {
3782 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3785 if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS_TESTING) {
3786 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3789 if (options->TestingV3AuthInitialVoteDelay +
3790 options->TestingV3AuthInitialDistDelay >=
3791 options->TestingV3AuthInitialVotingInterval) {
3792 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3793 "must be less than TestingV3AuthInitialVotingInterval");
3796 if (options->TestingV3AuthVotingStartOffset >
3797 MIN(options->TestingV3AuthInitialVotingInterval,
3798 options->V3AuthVotingInterval)) {
3799 REJECT("TestingV3AuthVotingStartOffset is higher than the voting "
3800 "interval.");
3801 } else if (options->TestingV3AuthVotingStartOffset < 0) {
3802 REJECT("TestingV3AuthVotingStartOffset must be non-negative.");
3805 if (options->TestingAuthDirTimeToLearnReachability < 0) {
3806 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3807 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
3808 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3811 if (options->TestingEstimatedDescriptorPropagationTime < 0) {
3812 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3813 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
3814 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3817 if (options->TestingClientMaxIntervalWithoutRequest < 1) {
3818 REJECT("TestingClientMaxIntervalWithoutRequest is way too low.");
3819 } else if (options->TestingClientMaxIntervalWithoutRequest > 3600) {
3820 COMPLAIN("TestingClientMaxIntervalWithoutRequest is insanely high.");
3823 if (options->TestingDirConnectionMaxStall < 5) {
3824 REJECT("TestingDirConnectionMaxStall is way too low.");
3825 } else if (options->TestingDirConnectionMaxStall > 3600) {
3826 COMPLAIN("TestingDirConnectionMaxStall is insanely high.");
3829 if (options->TestingConsensusMaxDownloadTries < 2) {
3830 REJECT("TestingConsensusMaxDownloadTries must be greater than 1.");
3831 } else if (options->TestingConsensusMaxDownloadTries > 800) {
3832 COMPLAIN("TestingConsensusMaxDownloadTries is insanely high.");
3835 if (options->TestingDescriptorMaxDownloadTries < 2) {
3836 REJECT("TestingDescriptorMaxDownloadTries must be greater than 1.");
3837 } else if (options->TestingDescriptorMaxDownloadTries > 800) {
3838 COMPLAIN("TestingDescriptorMaxDownloadTries is insanely high.");
3841 if (options->TestingMicrodescMaxDownloadTries < 2) {
3842 REJECT("TestingMicrodescMaxDownloadTries must be greater than 1.");
3843 } else if (options->TestingMicrodescMaxDownloadTries > 800) {
3844 COMPLAIN("TestingMicrodescMaxDownloadTries is insanely high.");
3847 if (options->TestingCertMaxDownloadTries < 2) {
3848 REJECT("TestingCertMaxDownloadTries must be greater than 1.");
3849 } else if (options->TestingCertMaxDownloadTries > 800) {
3850 COMPLAIN("TestingCertMaxDownloadTries is insanely high.");
3853 if (options->TestingEnableConnBwEvent &&
3854 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
3855 REJECT("TestingEnableConnBwEvent may only be changed in testing "
3856 "Tor networks!");
3859 if (options->TestingEnableCellStatsEvent &&
3860 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
3861 REJECT("TestingEnableCellStatsEvent may only be changed in testing "
3862 "Tor networks!");
3865 if (options->TestingEnableTbEmptyEvent &&
3866 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
3867 REJECT("TestingEnableTbEmptyEvent may only be changed in testing "
3868 "Tor networks!");
3871 if (options->TestingTorNetwork) {
3872 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
3873 "almost unusable in the public Tor network, and is "
3874 "therefore only advised if you are building a "
3875 "testing Tor network!");
3878 if (options->AccelName && !options->HardwareAccel)
3879 options->HardwareAccel = 1;
3880 if (options->AccelDir && !options->AccelName)
3881 REJECT("Can't use hardware crypto accelerator dir without engine name.");
3883 if (options->PublishServerDescriptor)
3884 SMARTLIST_FOREACH(options->PublishServerDescriptor, const char *, pubdes, {
3885 if (!strcmp(pubdes, "1") || !strcmp(pubdes, "0"))
3886 if (smartlist_len(options->PublishServerDescriptor) > 1) {
3887 COMPLAIN("You have passed a list of multiple arguments to the "
3888 "PublishServerDescriptor option that includes 0 or 1. "
3889 "0 or 1 should only be used as the sole argument. "
3890 "This configuration will be rejected in a future release.");
3891 break;
3895 if (options->BridgeRelay == 1 && ! options->ORPort_set)
3896 REJECT("BridgeRelay is 1, ORPort is not set. This is an invalid "
3897 "combination.");
3899 return 0;
3902 #undef REJECT
3903 #undef COMPLAIN
3905 /* Given the value that the user has set for MaxMemInQueues, compute the
3906 * actual maximum value. We clip this value if it's too low, and autodetect
3907 * it if it's set to 0. */
3908 static uint64_t
3909 compute_real_max_mem_in_queues(const uint64_t val, int log_guess)
3911 uint64_t result;
3913 if (val == 0) {
3914 #define ONE_GIGABYTE (U64_LITERAL(1) << 30)
3915 #define ONE_MEGABYTE (U64_LITERAL(1) << 20)
3916 #if SIZEOF_VOID_P >= 8
3917 #define MAX_DEFAULT_MAXMEM (8*ONE_GIGABYTE)
3918 #else
3919 #define MAX_DEFAULT_MAXMEM (2*ONE_GIGABYTE)
3920 #endif
3921 /* The user didn't pick a memory limit. Choose a very large one
3922 * that is still smaller than the system memory */
3923 static int notice_sent = 0;
3924 size_t ram = 0;
3925 if (get_total_system_memory(&ram) < 0) {
3926 /* We couldn't determine our total system memory! */
3927 #if SIZEOF_VOID_P >= 8
3928 /* 64-bit system. Let's hope for 8 GB. */
3929 result = 8 * ONE_GIGABYTE;
3930 #else
3931 /* (presumably) 32-bit system. Let's hope for 1 GB. */
3932 result = ONE_GIGABYTE;
3933 #endif
3934 } else {
3935 /* We detected it, so let's pick 3/4 of the total RAM as our limit. */
3936 const uint64_t avail = (ram / 4) * 3;
3938 /* Make sure it's in range from 0.25 GB to 8 GB. */
3939 if (avail > MAX_DEFAULT_MAXMEM) {
3940 /* If you want to use more than this much RAM, you need to configure
3941 it yourself */
3942 result = MAX_DEFAULT_MAXMEM;
3943 } else if (avail < ONE_GIGABYTE / 4) {
3944 result = ONE_GIGABYTE / 4;
3945 } else {
3946 result = avail;
3949 if (log_guess && ! notice_sent) {
3950 log_notice(LD_CONFIG, "%sMaxMemInQueues is set to "U64_FORMAT" MB. "
3951 "You can override this by setting MaxMemInQueues by hand.",
3952 ram ? "Based on detected system memory, " : "",
3953 U64_PRINTF_ARG(result / ONE_MEGABYTE));
3954 notice_sent = 1;
3956 return result;
3957 } else if (val < ONE_GIGABYTE / 4) {
3958 log_warn(LD_CONFIG, "MaxMemInQueues must be at least 256 MB for now. "
3959 "Ideally, have it as large as you can afford.");
3960 return ONE_GIGABYTE / 4;
3961 } else {
3962 /* The value was fine all along */
3963 return val;
3967 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3968 * equal strings. */
3969 static int
3970 opt_streq(const char *s1, const char *s2)
3972 return 0 == strcmp_opt(s1, s2);
3975 /** Check if any of the previous options have changed but aren't allowed to. */
3976 static int
3977 options_transition_allowed(const or_options_t *old,
3978 const or_options_t *new_val,
3979 char **msg)
3981 if (!old)
3982 return 0;
3984 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3985 *msg = tor_strdup("PidFile is not allowed to change.");
3986 return -1;
3989 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3990 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3991 "is not allowed.");
3992 return -1;
3995 if (old->Sandbox != new_val->Sandbox) {
3996 *msg = tor_strdup("While Tor is running, changing Sandbox "
3997 "is not allowed.");
3998 return -1;
4001 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
4002 tor_asprintf(msg,
4003 "While Tor is running, changing DataDirectory "
4004 "(\"%s\"->\"%s\") is not allowed.",
4005 old->DataDirectory, new_val->DataDirectory);
4006 return -1;
4009 if (!opt_streq(old->User, new_val->User)) {
4010 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
4011 return -1;
4014 if (!opt_streq(old->SyslogIdentityTag, new_val->SyslogIdentityTag)) {
4015 *msg = tor_strdup("While Tor is running, changing "
4016 "SyslogIdentityTag is not allowed.");
4017 return -1;
4020 if ((old->HardwareAccel != new_val->HardwareAccel)
4021 || !opt_streq(old->AccelName, new_val->AccelName)
4022 || !opt_streq(old->AccelDir, new_val->AccelDir)) {
4023 *msg = tor_strdup("While Tor is running, changing OpenSSL hardware "
4024 "acceleration engine is not allowed.");
4025 return -1;
4028 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
4029 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
4030 "is not allowed.");
4031 return -1;
4034 if (old->DisableAllSwap != new_val->DisableAllSwap) {
4035 *msg = tor_strdup("While Tor is running, changing DisableAllSwap "
4036 "is not allowed.");
4037 return -1;
4040 if (old->TokenBucketRefillInterval != new_val->TokenBucketRefillInterval) {
4041 *msg = tor_strdup("While Tor is running, changing TokenBucketRefill"
4042 "Interval is not allowed");
4043 return -1;
4046 if (old->DisableIOCP != new_val->DisableIOCP) {
4047 *msg = tor_strdup("While Tor is running, changing DisableIOCP "
4048 "is not allowed.");
4049 return -1;
4052 if (old->DisableDebuggerAttachment &&
4053 !new_val->DisableDebuggerAttachment) {
4054 *msg = tor_strdup("While Tor is running, disabling "
4055 "DisableDebuggerAttachment is not allowed.");
4056 return -1;
4059 if (sandbox_is_active()) {
4060 #define SB_NOCHANGE_STR(opt) \
4061 do { \
4062 if (! opt_streq(old->opt, new_val->opt)) { \
4063 *msg = tor_strdup("Can't change " #opt " while Sandbox is active"); \
4064 return -1; \
4066 } while (0)
4068 SB_NOCHANGE_STR(PidFile);
4069 SB_NOCHANGE_STR(ServerDNSResolvConfFile);
4070 SB_NOCHANGE_STR(DirPortFrontPage);
4071 SB_NOCHANGE_STR(CookieAuthFile);
4072 SB_NOCHANGE_STR(ExtORPortCookieAuthFile);
4074 #undef SB_NOCHANGE_STR
4076 if (! config_lines_eq(old->Logs, new_val->Logs)) {
4077 *msg = tor_strdup("Can't change Logs while Sandbox is active");
4078 return -1;
4080 if (old->ConnLimit != new_val->ConnLimit) {
4081 *msg = tor_strdup("Can't change ConnLimit while Sandbox is active");
4082 return -1;
4084 if (server_mode(old) != server_mode(new_val)) {
4085 *msg = tor_strdup("Can't start/stop being a server while "
4086 "Sandbox is active");
4087 return -1;
4091 return 0;
4094 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
4095 * will require us to rotate the CPU and DNS workers; else return 0. */
4096 static int
4097 options_transition_affects_workers(const or_options_t *old_options,
4098 const or_options_t *new_options)
4100 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
4101 old_options->NumCPUs != new_options->NumCPUs ||
4102 !config_lines_eq(old_options->ORPort_lines, new_options->ORPort_lines) ||
4103 old_options->ServerDNSSearchDomains !=
4104 new_options->ServerDNSSearchDomains ||
4105 old_options->SafeLogging_ != new_options->SafeLogging_ ||
4106 old_options->ClientOnly != new_options->ClientOnly ||
4107 public_server_mode(old_options) != public_server_mode(new_options) ||
4108 !config_lines_eq(old_options->Logs, new_options->Logs) ||
4109 old_options->LogMessageDomains != new_options->LogMessageDomains)
4110 return 1;
4112 /* Check whether log options match. */
4114 /* Nothing that changed matters. */
4115 return 0;
4118 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
4119 * will require us to generate a new descriptor; else return 0. */
4120 static int
4121 options_transition_affects_descriptor(const or_options_t *old_options,
4122 const or_options_t *new_options)
4124 /* XXX We can be smarter here. If your DirPort isn't being
4125 * published and you just turned it off, no need to republish. Etc. */
4126 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
4127 !opt_streq(old_options->Nickname,new_options->Nickname) ||
4128 !opt_streq(old_options->Address,new_options->Address) ||
4129 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
4130 old_options->ExitRelay != new_options->ExitRelay ||
4131 old_options->ExitPolicyRejectPrivate !=
4132 new_options->ExitPolicyRejectPrivate ||
4133 old_options->IPv6Exit != new_options->IPv6Exit ||
4134 !config_lines_eq(old_options->ORPort_lines,
4135 new_options->ORPort_lines) ||
4136 !config_lines_eq(old_options->DirPort_lines,
4137 new_options->DirPort_lines) ||
4138 old_options->ClientOnly != new_options->ClientOnly ||
4139 old_options->DisableNetwork != new_options->DisableNetwork ||
4140 old_options->PublishServerDescriptor_ !=
4141 new_options->PublishServerDescriptor_ ||
4142 get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
4143 get_effective_bwburst(old_options) !=
4144 get_effective_bwburst(new_options) ||
4145 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
4146 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
4147 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
4148 old_options->AccountingMax != new_options->AccountingMax ||
4149 public_server_mode(old_options) != public_server_mode(new_options))
4150 return 1;
4152 return 0;
4155 #ifdef _WIN32
4156 /** Return the directory on windows where we expect to find our application
4157 * data. */
4158 static char *
4159 get_windows_conf_root(void)
4161 static int is_set = 0;
4162 static char path[MAX_PATH*2+1];
4163 TCHAR tpath[MAX_PATH] = {0};
4165 LPITEMIDLIST idl;
4166 IMalloc *m;
4167 HRESULT result;
4169 if (is_set)
4170 return path;
4172 /* Find X:\documents and settings\username\application data\ .
4173 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
4175 #ifdef ENABLE_LOCAL_APPDATA
4176 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
4177 #else
4178 #define APPDATA_PATH CSIDL_APPDATA
4179 #endif
4180 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
4181 getcwd(path,MAX_PATH);
4182 is_set = 1;
4183 log_warn(LD_CONFIG,
4184 "I couldn't find your application data folder: are you "
4185 "running an ancient version of Windows 95? Defaulting to \"%s\"",
4186 path);
4187 return path;
4189 /* Convert the path from an "ID List" (whatever that is!) to a path. */
4190 result = SHGetPathFromIDList(idl, tpath);
4191 #ifdef UNICODE
4192 wcstombs(path,tpath,sizeof(path));
4193 path[sizeof(path)-1] = '\0';
4194 #else
4195 strlcpy(path,tpath,sizeof(path));
4196 #endif
4198 /* Now we need to free the memory that the path-idl was stored in. In
4199 * typical Windows fashion, we can't just call 'free()' on it. */
4200 SHGetMalloc(&m);
4201 if (m) {
4202 m->lpVtbl->Free(m, idl);
4203 m->lpVtbl->Release(m);
4205 if (!SUCCEEDED(result)) {
4206 return NULL;
4208 strlcat(path,"\\tor",MAX_PATH);
4209 is_set = 1;
4210 return path;
4212 #endif
4214 /** Return the default location for our torrc file (if <b>defaults_file</b> is
4215 * false), or for the torrc-defaults file (if <b>defaults_file</b> is true). */
4216 static const char *
4217 get_default_conf_file(int defaults_file)
4219 #ifdef DISABLE_SYSTEM_TORRC
4220 (void) defaults_file;
4221 return NULL;
4222 #elif defined(_WIN32)
4223 if (defaults_file) {
4224 static char defaults_path[MAX_PATH+1];
4225 tor_snprintf(defaults_path, MAX_PATH, "%s\\torrc-defaults",
4226 get_windows_conf_root());
4227 return defaults_path;
4228 } else {
4229 static char path[MAX_PATH+1];
4230 tor_snprintf(path, MAX_PATH, "%s\\torrc",
4231 get_windows_conf_root());
4232 return path;
4234 #else
4235 return defaults_file ? CONFDIR "/torrc-defaults" : CONFDIR "/torrc";
4236 #endif
4239 /** Verify whether lst is a string containing valid-looking comma-separated
4240 * nicknames, or NULL. Will normalise <b>lst</b> to prefix '$' to any nickname
4241 * or fingerprint that needs it. Return 0 on success.
4242 * Warn and return -1 on failure.
4244 static int
4245 check_nickname_list(char **lst, const char *name, char **msg)
4247 int r = 0;
4248 smartlist_t *sl;
4249 int changes = 0;
4251 if (!*lst)
4252 return 0;
4253 sl = smartlist_new();
4255 smartlist_split_string(sl, *lst, ",",
4256 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
4258 SMARTLIST_FOREACH_BEGIN(sl, char *, s)
4260 if (!is_legal_nickname_or_hexdigest(s)) {
4261 // check if first char is dollar
4262 if (s[0] != '$') {
4263 // Try again but with a dollar symbol prepended
4264 char *prepended;
4265 tor_asprintf(&prepended, "$%s", s);
4267 if (is_legal_nickname_or_hexdigest(prepended)) {
4268 // The nickname is valid when it's prepended, swap the current
4269 // version with a prepended one
4270 tor_free(s);
4271 SMARTLIST_REPLACE_CURRENT(sl, s, prepended);
4272 changes = 1;
4273 continue;
4276 // Still not valid, free and fallback to error message
4277 tor_free(prepended);
4280 tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
4281 r = -1;
4282 break;
4285 SMARTLIST_FOREACH_END(s);
4287 // Replace the caller's nickname list with a fixed one
4288 if (changes && r == 0) {
4289 char *newNicknames = smartlist_join_strings(sl, ", ", 0, NULL);
4290 tor_free(*lst);
4291 *lst = newNicknames;
4294 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
4295 smartlist_free(sl);
4297 return r;
4300 /** Learn config file name from command line arguments, or use the default.
4302 * If <b>defaults_file</b> is true, we're looking for torrc-defaults;
4303 * otherwise, we're looking for the regular torrc_file.
4305 * Set *<b>using_default_fname</b> to true if we're using the default
4306 * configuration file name; or false if we've set it from the command line.
4308 * Set *<b>ignore_missing_torrc</b> to true if we should ignore the resulting
4309 * filename if it doesn't exist.
4311 static char *
4312 find_torrc_filename(config_line_t *cmd_arg,
4313 int defaults_file,
4314 int *using_default_fname, int *ignore_missing_torrc)
4316 char *fname=NULL;
4317 config_line_t *p_index;
4318 const char *fname_opt = defaults_file ? "--defaults-torrc" : "-f";
4319 const char *ignore_opt = defaults_file ? NULL : "--ignore-missing-torrc";
4321 if (defaults_file)
4322 *ignore_missing_torrc = 1;
4324 for (p_index = cmd_arg; p_index; p_index = p_index->next) {
4325 if (!strcmp(p_index->key, fname_opt)) {
4326 if (fname) {
4327 log_warn(LD_CONFIG, "Duplicate %s options on command line.",
4328 fname_opt);
4329 tor_free(fname);
4331 fname = expand_filename(p_index->value);
4334 char *absfname;
4335 absfname = make_path_absolute(fname);
4336 tor_free(fname);
4337 fname = absfname;
4340 *using_default_fname = 0;
4341 } else if (ignore_opt && !strcmp(p_index->key,ignore_opt)) {
4342 *ignore_missing_torrc = 1;
4346 if (*using_default_fname) {
4347 /* didn't find one, try CONFDIR */
4348 const char *dflt = get_default_conf_file(defaults_file);
4349 file_status_t st = file_status(dflt);
4350 if (dflt && (st == FN_FILE || st == FN_EMPTY)) {
4351 fname = tor_strdup(dflt);
4352 } else {
4353 #ifndef _WIN32
4354 char *fn = NULL;
4355 if (!defaults_file) {
4356 fn = expand_filename("~/.torrc");
4358 if (fn) {
4359 file_status_t hmst = file_status(fn);
4360 if (hmst == FN_FILE || hmst == FN_EMPTY || dflt == NULL) {
4361 fname = fn;
4362 } else {
4363 tor_free(fn);
4364 fname = tor_strdup(dflt);
4366 } else {
4367 fname = dflt ? tor_strdup(dflt) : NULL;
4369 #else
4370 fname = dflt ? tor_strdup(dflt) : NULL;
4371 #endif
4374 return fname;
4377 /** Read the torrc from standard input and return it as a string.
4378 * Upon failure, return NULL.
4380 static char *
4381 load_torrc_from_stdin(void)
4383 size_t sz_out;
4385 return read_file_to_str_until_eof(STDIN_FILENO,SIZE_MAX,&sz_out);
4388 /** Load a configuration file from disk, setting torrc_fname or
4389 * torrc_defaults_fname if successful.
4391 * If <b>defaults_file</b> is true, load torrc-defaults; otherwise load torrc.
4393 * Return the contents of the file on success, and NULL on failure.
4395 static char *
4396 load_torrc_from_disk(config_line_t *cmd_arg, int defaults_file)
4398 char *fname=NULL;
4399 char *cf = NULL;
4400 int using_default_torrc = 1;
4401 int ignore_missing_torrc = 0;
4402 char **fname_var = defaults_file ? &torrc_defaults_fname : &torrc_fname;
4404 if (*fname_var == NULL) {
4405 fname = find_torrc_filename(cmd_arg, defaults_file,
4406 &using_default_torrc, &ignore_missing_torrc);
4407 tor_free(*fname_var);
4408 *fname_var = fname;
4409 } else {
4410 fname = *fname_var;
4412 log_debug(LD_CONFIG, "Opening config file \"%s\"", fname?fname:"<NULL>");
4414 /* Open config file */
4415 file_status_t st = fname ? file_status(fname) : FN_EMPTY;
4416 if (fname == NULL ||
4417 !(st == FN_FILE || st == FN_EMPTY) ||
4418 !(cf = read_file_to_str(fname,0,NULL))) {
4419 if (using_default_torrc == 1 || ignore_missing_torrc) {
4420 if (!defaults_file)
4421 log_notice(LD_CONFIG, "Configuration file \"%s\" not present, "
4422 "using reasonable defaults.", fname);
4423 tor_free(fname); /* sets fname to NULL */
4424 *fname_var = NULL;
4425 cf = tor_strdup("");
4426 } else {
4427 log_warn(LD_CONFIG,
4428 "Unable to open configuration file \"%s\".", fname);
4429 goto err;
4431 } else {
4432 log_notice(LD_CONFIG, "Read configuration file \"%s\".", fname);
4435 return cf;
4436 err:
4437 tor_free(fname);
4438 *fname_var = NULL;
4439 return NULL;
4442 /** Read a configuration file into <b>options</b>, finding the configuration
4443 * file location based on the command line. After loading the file
4444 * call options_init_from_string() to load the config.
4445 * Return 0 if success, -1 if failure. */
4447 options_init_from_torrc(int argc, char **argv)
4449 char *cf=NULL, *cf_defaults=NULL;
4450 int command;
4451 int retval = -1;
4452 char *command_arg = NULL;
4453 char *errmsg=NULL;
4454 config_line_t *p_index = NULL;
4455 config_line_t *cmdline_only_options = NULL;
4457 /* Go through command-line variables */
4458 if (! have_parsed_cmdline) {
4459 /* Or we could redo the list every time we pass this place.
4460 * It does not really matter */
4461 if (config_parse_commandline(argc, argv, 0, &global_cmdline_options,
4462 &global_cmdline_only_options) < 0) {
4463 goto err;
4465 have_parsed_cmdline = 1;
4467 cmdline_only_options = global_cmdline_only_options;
4469 if (config_line_find(cmdline_only_options, "-h") ||
4470 config_line_find(cmdline_only_options, "--help")) {
4471 print_usage();
4472 exit(0);
4474 if (config_line_find(cmdline_only_options, "--list-torrc-options")) {
4475 /* For documenting validating whether we've documented everything. */
4476 list_torrc_options();
4477 exit(0);
4480 if (config_line_find(cmdline_only_options, "--version")) {
4481 printf("Tor version %s.\n",get_version());
4482 exit(0);
4485 if (config_line_find(cmdline_only_options, "--library-versions")) {
4486 printf("Tor version %s. \n", get_version());
4487 printf("Library versions\tCompiled\t\tRuntime\n");
4488 printf("Libevent\t\t%-15s\t\t%s\n",
4489 tor_libevent_get_header_version_str(),
4490 tor_libevent_get_version_str());
4491 printf("OpenSSL \t\t%-15s\t\t%s\n",
4492 crypto_openssl_get_header_version_str(),
4493 crypto_openssl_get_version_str());
4494 printf("Zlib \t\t%-15s\t\t%s\n",
4495 tor_zlib_get_header_version_str(),
4496 tor_zlib_get_version_str());
4497 //TODO: Hex versions?
4498 exit(0);
4501 command = CMD_RUN_TOR;
4502 for (p_index = cmdline_only_options; p_index; p_index = p_index->next) {
4503 if (!strcmp(p_index->key,"--keygen")) {
4504 command = CMD_KEYGEN;
4505 } else if (!strcmp(p_index->key,"--list-fingerprint")) {
4506 command = CMD_LIST_FINGERPRINT;
4507 } else if (!strcmp(p_index->key, "--hash-password")) {
4508 command = CMD_HASH_PASSWORD;
4509 command_arg = p_index->value;
4510 } else if (!strcmp(p_index->key, "--dump-config")) {
4511 command = CMD_DUMP_CONFIG;
4512 command_arg = p_index->value;
4513 } else if (!strcmp(p_index->key, "--verify-config")) {
4514 command = CMD_VERIFY_CONFIG;
4518 if (command == CMD_HASH_PASSWORD) {
4519 cf_defaults = tor_strdup("");
4520 cf = tor_strdup("");
4521 } else {
4522 cf_defaults = load_torrc_from_disk(cmdline_only_options, 1);
4524 const config_line_t *f_line = config_line_find(cmdline_only_options,
4525 "-f");
4527 const int read_torrc_from_stdin =
4528 (f_line != NULL && strcmp(f_line->value, "-") == 0);
4530 if (read_torrc_from_stdin) {
4531 cf = load_torrc_from_stdin();
4532 } else {
4533 cf = load_torrc_from_disk(cmdline_only_options, 0);
4536 if (!cf) {
4537 if (config_line_find(cmdline_only_options, "--allow-missing-torrc")) {
4538 cf = tor_strdup("");
4539 } else {
4540 goto err;
4545 retval = options_init_from_string(cf_defaults, cf, command, command_arg,
4546 &errmsg);
4548 if (retval < 0)
4549 goto err;
4551 if (config_line_find(cmdline_only_options, "--no-passphrase")) {
4552 if (command == CMD_KEYGEN) {
4553 get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_OFF;
4554 } else {
4555 log_err(LD_CONFIG, "--no-passphrase specified without --keygen!");
4556 exit(1);
4560 if (config_line_find(cmdline_only_options, "--newpass")) {
4561 if (command == CMD_KEYGEN) {
4562 get_options_mutable()->change_key_passphrase = 1;
4563 } else {
4564 log_err(LD_CONFIG, "--newpass specified without --keygen!");
4565 exit(1);
4570 const config_line_t *fd_line = config_line_find(cmdline_only_options,
4571 "--passphrase-fd");
4572 if (fd_line) {
4573 if (get_options()->keygen_force_passphrase == FORCE_PASSPHRASE_OFF) {
4574 log_err(LD_CONFIG, "--no-passphrase specified with --passphrase-fd!");
4575 exit(1);
4576 } else if (command != CMD_KEYGEN) {
4577 log_err(LD_CONFIG, "--passphrase-fd specified without --keygen!");
4578 exit(1);
4579 } else {
4580 const char *v = fd_line->value;
4581 int ok = 1;
4582 long fd = tor_parse_long(v, 10, 0, INT_MAX, &ok, NULL);
4583 if (fd < 0 || ok == 0) {
4584 log_err(LD_CONFIG, "Invalid --passphrase-fd value %s", escaped(v));
4585 exit(1);
4587 get_options_mutable()->keygen_passphrase_fd = (int)fd;
4588 get_options_mutable()->use_keygen_passphrase_fd = 1;
4589 get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_ON;
4595 const config_line_t *key_line = config_line_find(cmdline_only_options,
4596 "--master-key");
4597 if (key_line) {
4598 if (command != CMD_KEYGEN) {
4599 log_err(LD_CONFIG, "--master-key without --keygen!");
4600 exit(1);
4601 } else {
4602 get_options_mutable()->master_key_fname = tor_strdup(key_line->value);
4607 err:
4609 tor_free(cf);
4610 tor_free(cf_defaults);
4611 if (errmsg) {
4612 log_warn(LD_CONFIG,"%s", errmsg);
4613 tor_free(errmsg);
4615 return retval < 0 ? -1 : 0;
4618 /** Load the options from the configuration in <b>cf</b>, validate
4619 * them for consistency and take actions based on them.
4621 * Return 0 if success, negative on error:
4622 * * -1 for general errors.
4623 * * -2 for failure to parse/validate,
4624 * * -3 for transition not allowed
4625 * * -4 for error while setting the new options
4627 setopt_err_t
4628 options_init_from_string(const char *cf_defaults, const char *cf,
4629 int command, const char *command_arg,
4630 char **msg)
4632 or_options_t *oldoptions, *newoptions, *newdefaultoptions=NULL;
4633 config_line_t *cl;
4634 int retval, i;
4635 setopt_err_t err = SETOPT_ERR_MISC;
4636 tor_assert(msg);
4638 oldoptions = global_options; /* get_options unfortunately asserts if
4639 this is the first time we run*/
4641 newoptions = tor_malloc_zero(sizeof(or_options_t));
4642 newoptions->magic_ = OR_OPTIONS_MAGIC;
4643 options_init(newoptions);
4644 newoptions->command = command;
4645 newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
4647 for (i = 0; i < 2; ++i) {
4648 const char *body = i==0 ? cf_defaults : cf;
4649 if (!body)
4650 continue;
4651 /* get config lines, assign them */
4652 retval = config_get_lines(body, &cl, 1);
4653 if (retval < 0) {
4654 err = SETOPT_ERR_PARSE;
4655 goto err;
4657 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4658 config_free_lines(cl);
4659 if (retval < 0) {
4660 err = SETOPT_ERR_PARSE;
4661 goto err;
4663 if (i==0)
4664 newdefaultoptions = config_dup(&options_format, newoptions);
4667 if (newdefaultoptions == NULL) {
4668 newdefaultoptions = config_dup(&options_format, global_default_options);
4671 /* Go through command-line variables too */
4672 retval = config_assign(&options_format, newoptions,
4673 global_cmdline_options, 0, 0, msg);
4674 if (retval < 0) {
4675 err = SETOPT_ERR_PARSE;
4676 goto err;
4679 /* If this is a testing network configuration, change defaults
4680 * for a list of dependent config options, re-initialize newoptions
4681 * with the new defaults, and assign all options to it second time. */
4682 if (newoptions->TestingTorNetwork) {
4683 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4684 * this? We could, for example, make the parsing algorithm do two passes
4685 * over the configuration. If it finds any "suite" options like
4686 * TestingTorNetwork, it could change the defaults before its second pass.
4687 * Not urgent so long as this seems to work, but at any sign of trouble,
4688 * let's clean it up. -NM */
4690 /* Change defaults. */
4691 int i;
4692 for (i = 0; testing_tor_network_defaults[i].name; ++i) {
4693 const config_var_t *new_var = &testing_tor_network_defaults[i];
4694 config_var_t *old_var =
4695 config_find_option_mutable(&options_format, new_var->name);
4696 tor_assert(new_var);
4697 tor_assert(old_var);
4698 old_var->initvalue = new_var->initvalue;
4701 /* Clear newoptions and re-initialize them with new defaults. */
4702 config_free(&options_format, newoptions);
4703 config_free(&options_format, newdefaultoptions);
4704 newdefaultoptions = NULL;
4705 newoptions = tor_malloc_zero(sizeof(or_options_t));
4706 newoptions->magic_ = OR_OPTIONS_MAGIC;
4707 options_init(newoptions);
4708 newoptions->command = command;
4709 newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
4711 /* Assign all options a second time. */
4712 for (i = 0; i < 2; ++i) {
4713 const char *body = i==0 ? cf_defaults : cf;
4714 if (!body)
4715 continue;
4716 /* get config lines, assign them */
4717 retval = config_get_lines(body, &cl, 1);
4718 if (retval < 0) {
4719 err = SETOPT_ERR_PARSE;
4720 goto err;
4722 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4723 config_free_lines(cl);
4724 if (retval < 0) {
4725 err = SETOPT_ERR_PARSE;
4726 goto err;
4728 if (i==0)
4729 newdefaultoptions = config_dup(&options_format, newoptions);
4731 /* Assign command-line variables a second time too */
4732 retval = config_assign(&options_format, newoptions,
4733 global_cmdline_options, 0, 0, msg);
4734 if (retval < 0) {
4735 err = SETOPT_ERR_PARSE;
4736 goto err;
4740 /* Validate newoptions */
4741 if (options_validate(oldoptions, newoptions, newdefaultoptions,
4742 0, msg) < 0) {
4743 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
4744 goto err;
4747 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
4748 err = SETOPT_ERR_TRANSITION;
4749 goto err;
4752 if (set_options(newoptions, msg)) {
4753 err = SETOPT_ERR_SETTING;
4754 goto err; /* frees and replaces old options */
4756 config_free(&options_format, global_default_options);
4757 global_default_options = newdefaultoptions;
4759 return SETOPT_OK;
4761 err:
4762 config_free(&options_format, newoptions);
4763 config_free(&options_format, newdefaultoptions);
4764 if (*msg) {
4765 char *old_msg = *msg;
4766 tor_asprintf(msg, "Failed to parse/validate config: %s", old_msg);
4767 tor_free(old_msg);
4769 return err;
4772 /** Return the location for our configuration file. May return NULL.
4774 const char *
4775 get_torrc_fname(int defaults_fname)
4777 const char *fname = defaults_fname ? torrc_defaults_fname : torrc_fname;
4779 if (fname)
4780 return fname;
4781 else
4782 return get_default_conf_file(defaults_fname);
4785 /** Adjust the address map based on the MapAddress elements in the
4786 * configuration <b>options</b>
4788 void
4789 config_register_addressmaps(const or_options_t *options)
4791 smartlist_t *elts;
4792 config_line_t *opt;
4793 const char *from, *to, *msg;
4795 addressmap_clear_configured();
4796 elts = smartlist_new();
4797 for (opt = options->AddressMap; opt; opt = opt->next) {
4798 smartlist_split_string(elts, opt->value, NULL,
4799 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4800 if (smartlist_len(elts) < 2) {
4801 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
4802 opt->value);
4803 goto cleanup;
4806 from = smartlist_get(elts,0);
4807 to = smartlist_get(elts,1);
4809 if (to[0] == '.' || from[0] == '.') {
4810 log_warn(LD_CONFIG,"MapAddress '%s' is ambiguous - address starts with a"
4811 "'.'. Ignoring.",opt->value);
4812 goto cleanup;
4815 if (addressmap_register_auto(from, to, 0, ADDRMAPSRC_TORRC, &msg) < 0) {
4816 log_warn(LD_CONFIG,"MapAddress '%s' failed: %s. Ignoring.", opt->value,
4817 msg);
4818 goto cleanup;
4821 if (smartlist_len(elts) > 2)
4822 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
4824 cleanup:
4825 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4826 smartlist_clear(elts);
4828 smartlist_free(elts);
4831 /** As addressmap_register(), but detect the wildcarded status of "from" and
4832 * "to", and do not steal a reference to <b>to</b>. */
4833 /* XXXX024 move to connection_edge.c */
4835 addressmap_register_auto(const char *from, const char *to,
4836 time_t expires,
4837 addressmap_entry_source_t addrmap_source,
4838 const char **msg)
4840 int from_wildcard = 0, to_wildcard = 0;
4842 *msg = "whoops, forgot the error message";
4843 if (1) {
4844 if (!strcmp(to, "*") || !strcmp(from, "*")) {
4845 *msg = "can't remap from or to *";
4846 return -1;
4848 /* Detect asterisks in expressions of type: '*.example.com' */
4849 if (!strncmp(from,"*.",2)) {
4850 from += 2;
4851 from_wildcard = 1;
4853 if (!strncmp(to,"*.",2)) {
4854 to += 2;
4855 to_wildcard = 1;
4858 if (to_wildcard && !from_wildcard) {
4859 *msg = "can only use wildcard (i.e. '*.') if 'from' address "
4860 "uses wildcard also";
4861 return -1;
4864 if (address_is_invalid_destination(to, 1)) {
4865 *msg = "destination is invalid";
4866 return -1;
4869 addressmap_register(from, tor_strdup(to), expires, addrmap_source,
4870 from_wildcard, to_wildcard);
4872 return 0;
4876 * Initialize the logs based on the configuration file.
4878 static int
4879 options_init_logs(const or_options_t *old_options, or_options_t *options,
4880 int validate_only)
4882 config_line_t *opt;
4883 int ok;
4884 smartlist_t *elts;
4885 int daemon =
4886 #ifdef _WIN32
4888 #else
4889 options->RunAsDaemon;
4890 #endif
4892 if (options->LogTimeGranularity <= 0) {
4893 log_warn(LD_CONFIG, "Log time granularity '%d' has to be positive.",
4894 options->LogTimeGranularity);
4895 return -1;
4896 } else if (1000 % options->LogTimeGranularity != 0 &&
4897 options->LogTimeGranularity % 1000 != 0) {
4898 int granularity = options->LogTimeGranularity;
4899 if (granularity < 40) {
4900 do granularity++;
4901 while (1000 % granularity != 0);
4902 } else if (granularity < 1000) {
4903 granularity = 1000 / granularity;
4904 while (1000 % granularity != 0)
4905 granularity--;
4906 granularity = 1000 / granularity;
4907 } else {
4908 granularity = 1000 * ((granularity / 1000) + 1);
4910 log_warn(LD_CONFIG, "Log time granularity '%d' has to be either a "
4911 "divisor or a multiple of 1 second. Changing to "
4912 "'%d'.",
4913 options->LogTimeGranularity, granularity);
4914 if (!validate_only)
4915 set_log_time_granularity(granularity);
4916 } else {
4917 if (!validate_only)
4918 set_log_time_granularity(options->LogTimeGranularity);
4921 ok = 1;
4922 elts = smartlist_new();
4924 for (opt = options->Logs; opt; opt = opt->next) {
4925 log_severity_list_t *severity;
4926 const char *cfg = opt->value;
4927 severity = tor_malloc_zero(sizeof(log_severity_list_t));
4928 if (parse_log_severity_config(&cfg, severity) < 0) {
4929 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
4930 opt->value);
4931 ok = 0; goto cleanup;
4934 smartlist_split_string(elts, cfg, NULL,
4935 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4937 if (smartlist_len(elts) == 0)
4938 smartlist_add(elts, tor_strdup("stdout"));
4940 if (smartlist_len(elts) == 1 &&
4941 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
4942 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
4943 int err = smartlist_len(elts) &&
4944 !strcasecmp(smartlist_get(elts,0), "stderr");
4945 if (!validate_only) {
4946 if (daemon) {
4947 log_warn(LD_CONFIG,
4948 "Can't log to %s with RunAsDaemon set; skipping stdout",
4949 err?"stderr":"stdout");
4950 } else {
4951 add_stream_log(severity, err?"<stderr>":"<stdout>",
4952 fileno(err?stderr:stdout));
4955 goto cleanup;
4957 if (smartlist_len(elts) == 1 &&
4958 !strcasecmp(smartlist_get(elts,0), "syslog")) {
4959 #ifdef HAVE_SYSLOG_H
4960 if (!validate_only) {
4961 add_syslog_log(severity, options->SyslogIdentityTag);
4963 #else
4964 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
4965 #endif
4966 goto cleanup;
4969 if (smartlist_len(elts) == 2 &&
4970 !strcasecmp(smartlist_get(elts,0), "file")) {
4971 if (!validate_only) {
4972 char *fname = expand_filename(smartlist_get(elts, 1));
4973 /* Truncate if TruncateLogFile is set and we haven't seen this option
4974 line before. */
4975 int truncate = 0;
4976 if (options->TruncateLogFile) {
4977 truncate = 1;
4978 if (old_options) {
4979 config_line_t *opt2;
4980 for (opt2 = old_options->Logs; opt2; opt2 = opt2->next)
4981 if (!strcmp(opt->value, opt2->value)) {
4982 truncate = 0;
4983 break;
4987 if (add_file_log(severity, fname, truncate) < 0) {
4988 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
4989 opt->value, strerror(errno));
4990 ok = 0;
4992 tor_free(fname);
4994 goto cleanup;
4997 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
4998 opt->value);
4999 ok = 0; goto cleanup;
5001 cleanup:
5002 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
5003 smartlist_clear(elts);
5004 tor_free(severity);
5006 smartlist_free(elts);
5008 if (ok && !validate_only)
5009 logs_set_domain_logging(options->LogMessageDomains);
5011 return ok?0:-1;
5014 /** Given a smartlist of SOCKS arguments to be passed to a transport
5015 * proxy in <b>args</b>, validate them and return -1 if they are
5016 * corrupted. Return 0 if they seem OK. */
5017 static int
5018 validate_transport_socks_arguments(const smartlist_t *args)
5020 char *socks_string = NULL;
5021 size_t socks_string_len;
5023 tor_assert(args);
5024 tor_assert(smartlist_len(args) > 0);
5026 SMARTLIST_FOREACH_BEGIN(args, const char *, s) {
5027 if (!string_is_key_value(LOG_WARN, s)) { /* items should be k=v items */
5028 log_warn(LD_CONFIG, "'%s' is not a k=v item.", s);
5029 return -1;
5031 } SMARTLIST_FOREACH_END(s);
5033 socks_string = pt_stringify_socks_args(args);
5034 if (!socks_string)
5035 return -1;
5037 socks_string_len = strlen(socks_string);
5038 tor_free(socks_string);
5040 if (socks_string_len > MAX_SOCKS5_AUTH_SIZE_TOTAL) {
5041 log_warn(LD_CONFIG, "SOCKS arguments can't be more than %u bytes (%lu).",
5042 MAX_SOCKS5_AUTH_SIZE_TOTAL,
5043 (unsigned long) socks_string_len);
5044 return -1;
5047 return 0;
5050 /** Deallocate a bridge_line_t structure. */
5051 /* private */ void
5052 bridge_line_free(bridge_line_t *bridge_line)
5054 if (!bridge_line)
5055 return;
5057 if (bridge_line->socks_args) {
5058 SMARTLIST_FOREACH(bridge_line->socks_args, char*, s, tor_free(s));
5059 smartlist_free(bridge_line->socks_args);
5061 tor_free(bridge_line->transport_name);
5062 tor_free(bridge_line);
5065 /** Read the contents of a Bridge line from <b>line</b>. Return 0
5066 * if the line is well-formed, and -1 if it isn't. If
5067 * <b>validate_only</b> is 0, and the line is well-formed, then add
5068 * the bridge described in the line to our internal bridge list.
5070 * Bridge line format:
5071 * Bridge [transport] IP:PORT [id-fingerprint] [k=v] [k=v] ...
5073 /* private */ bridge_line_t *
5074 parse_bridge_line(const char *line)
5076 smartlist_t *items = NULL;
5077 char *addrport=NULL, *fingerprint=NULL;
5078 char *field=NULL;
5079 bridge_line_t *bridge_line = tor_malloc_zero(sizeof(bridge_line_t));
5081 items = smartlist_new();
5082 smartlist_split_string(items, line, NULL,
5083 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5084 if (smartlist_len(items) < 1) {
5085 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
5086 goto err;
5089 /* first field is either a transport name or addrport */
5090 field = smartlist_get(items, 0);
5091 smartlist_del_keeporder(items, 0);
5093 if (string_is_C_identifier(field)) {
5094 /* It's a transport name. */
5095 bridge_line->transport_name = field;
5096 if (smartlist_len(items) < 1) {
5097 log_warn(LD_CONFIG, "Too few items to Bridge line.");
5098 goto err;
5100 addrport = smartlist_get(items, 0); /* Next field is addrport then. */
5101 smartlist_del_keeporder(items, 0);
5102 } else {
5103 addrport = field;
5106 if (tor_addr_port_parse(LOG_INFO, addrport,
5107 &bridge_line->addr, &bridge_line->port, 443)<0) {
5108 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
5109 goto err;
5112 /* If transports are enabled, next field could be a fingerprint or a
5113 socks argument. If transports are disabled, next field must be
5114 a fingerprint. */
5115 if (smartlist_len(items)) {
5116 if (bridge_line->transport_name) { /* transports enabled: */
5117 field = smartlist_get(items, 0);
5118 smartlist_del_keeporder(items, 0);
5120 /* If it's a key=value pair, then it's a SOCKS argument for the
5121 transport proxy... */
5122 if (string_is_key_value(LOG_DEBUG, field)) {
5123 bridge_line->socks_args = smartlist_new();
5124 smartlist_add(bridge_line->socks_args, field);
5125 } else { /* ...otherwise, it's the bridge fingerprint. */
5126 fingerprint = field;
5129 } else { /* transports disabled: */
5130 fingerprint = smartlist_join_strings(items, "", 0, NULL);
5134 /* Handle fingerprint, if it was provided. */
5135 if (fingerprint) {
5136 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
5137 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
5138 goto err;
5140 if (base16_decode(bridge_line->digest, DIGEST_LEN,
5141 fingerprint, HEX_DIGEST_LEN)<0) {
5142 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
5143 goto err;
5147 /* If we are using transports, any remaining items in the smartlist
5148 should be k=v values. */
5149 if (bridge_line->transport_name && smartlist_len(items)) {
5150 if (!bridge_line->socks_args)
5151 bridge_line->socks_args = smartlist_new();
5153 /* append remaining items of 'items' to 'socks_args' */
5154 smartlist_add_all(bridge_line->socks_args, items);
5155 smartlist_clear(items);
5157 tor_assert(smartlist_len(bridge_line->socks_args) > 0);
5160 if (bridge_line->socks_args) {
5161 if (validate_transport_socks_arguments(bridge_line->socks_args) < 0)
5162 goto err;
5165 goto done;
5167 err:
5168 bridge_line_free(bridge_line);
5169 bridge_line = NULL;
5171 done:
5172 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5173 smartlist_free(items);
5174 tor_free(addrport);
5175 tor_free(fingerprint);
5177 return bridge_line;
5180 /** Read the contents of a ClientTransportPlugin or ServerTransportPlugin
5181 * line from <b>line</b>, depending on the value of <b>server</b>. Return 0
5182 * if the line is well-formed, and -1 if it isn't.
5184 * If <b>validate_only</b> is 0, the line is well-formed, and the transport is
5185 * needed by some bridge:
5186 * - If it's an external proxy line, add the transport described in the line to
5187 * our internal transport list.
5188 * - If it's a managed proxy line, launch the managed proxy.
5191 STATIC int
5192 parse_transport_line(const or_options_t *options,
5193 const char *line, int validate_only,
5194 int server)
5197 smartlist_t *items = NULL;
5198 int r;
5199 const char *transports = NULL;
5200 smartlist_t *transport_list = NULL;
5201 char *type = NULL;
5202 char *addrport = NULL;
5203 tor_addr_t addr;
5204 uint16_t port = 0;
5205 int socks_ver = PROXY_NONE;
5207 /* managed proxy options */
5208 int is_managed = 0;
5209 char **proxy_argv = NULL;
5210 char **tmp = NULL;
5211 int proxy_argc, i;
5212 int is_useless_proxy = 1;
5214 int line_length;
5216 /* Split the line into space-separated tokens */
5217 items = smartlist_new();
5218 smartlist_split_string(items, line, NULL,
5219 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5220 line_length = smartlist_len(items);
5222 if (line_length < 3) {
5223 log_warn(LD_CONFIG,
5224 "Too few arguments on %sTransportPlugin line.",
5225 server ? "Server" : "Client");
5226 goto err;
5229 /* Get the first line element, split it to commas into
5230 transport_list (in case it's multiple transports) and validate
5231 the transport names. */
5232 transports = smartlist_get(items, 0);
5233 transport_list = smartlist_new();
5234 smartlist_split_string(transport_list, transports, ",",
5235 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
5236 SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
5237 /* validate transport names */
5238 if (!string_is_C_identifier(transport_name)) {
5239 log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
5240 transport_name);
5241 goto err;
5244 /* see if we actually need the transports provided by this proxy */
5245 if (!validate_only && transport_is_needed(transport_name))
5246 is_useless_proxy = 0;
5247 } SMARTLIST_FOREACH_END(transport_name);
5249 type = smartlist_get(items, 1);
5250 if (!strcmp(type, "exec")) {
5251 is_managed = 1;
5252 } else if (server && !strcmp(type, "proxy")) {
5253 /* 'proxy' syntax only with ServerTransportPlugin */
5254 is_managed = 0;
5255 } else if (!server && !strcmp(type, "socks4")) {
5256 /* 'socks4' syntax only with ClientTransportPlugin */
5257 is_managed = 0;
5258 socks_ver = PROXY_SOCKS4;
5259 } else if (!server && !strcmp(type, "socks5")) {
5260 /* 'socks5' syntax only with ClientTransportPlugin */
5261 is_managed = 0;
5262 socks_ver = PROXY_SOCKS5;
5263 } else {
5264 log_warn(LD_CONFIG,
5265 "Strange %sTransportPlugin type '%s'",
5266 server ? "Server" : "Client", type);
5267 goto err;
5270 if (is_managed && options->Sandbox) {
5271 log_warn(LD_CONFIG,
5272 "Managed proxies are not compatible with Sandbox mode."
5273 "(%sTransportPlugin line was %s)",
5274 server ? "Server" : "Client", escaped(line));
5275 goto err;
5278 if (is_managed) {
5279 /* managed */
5281 if (!server && !validate_only && is_useless_proxy) {
5282 log_info(LD_GENERAL,
5283 "Pluggable transport proxy (%s) does not provide "
5284 "any needed transports and will not be launched.",
5285 line);
5289 * If we are not just validating, use the rest of the line as the
5290 * argv of the proxy to be launched. Also, make sure that we are
5291 * only launching proxies that contribute useful transports.
5294 if (!validate_only && (server || !is_useless_proxy)) {
5295 proxy_argc = line_length - 2;
5296 tor_assert(proxy_argc > 0);
5297 proxy_argv = tor_calloc((proxy_argc + 1), sizeof(char *));
5298 tmp = proxy_argv;
5300 for (i = 0; i < proxy_argc; i++) {
5301 /* store arguments */
5302 *tmp++ = smartlist_get(items, 2);
5303 smartlist_del_keeporder(items, 2);
5305 *tmp = NULL; /* terminated with NULL, just like execve() likes it */
5307 /* kickstart the thing */
5308 if (server) {
5309 pt_kickstart_server_proxy(transport_list, proxy_argv);
5310 } else {
5311 pt_kickstart_client_proxy(transport_list, proxy_argv);
5314 } else {
5315 /* external */
5317 /* ClientTransportPlugins connecting through a proxy is managed only. */
5318 if (!server && (options->Socks4Proxy || options->Socks5Proxy ||
5319 options->HTTPSProxy)) {
5320 log_warn(LD_CONFIG, "You have configured an external proxy with another "
5321 "proxy type. (Socks4Proxy|Socks5Proxy|HTTPSProxy)");
5322 goto err;
5325 if (smartlist_len(transport_list) != 1) {
5326 log_warn(LD_CONFIG,
5327 "You can't have an external proxy with more than "
5328 "one transport.");
5329 goto err;
5332 addrport = smartlist_get(items, 2);
5334 if (tor_addr_port_lookup(addrport, &addr, &port) < 0) {
5335 log_warn(LD_CONFIG,
5336 "Error parsing transport address '%s'", addrport);
5337 goto err;
5340 if (!port) {
5341 log_warn(LD_CONFIG,
5342 "Transport address '%s' has no port.", addrport);
5343 goto err;
5346 if (!validate_only) {
5347 log_info(LD_DIR, "%s '%s' at %s.",
5348 server ? "Server transport" : "Transport",
5349 transports, fmt_addrport(&addr, port));
5351 if (!server) {
5352 transport_add_from_config(&addr, port,
5353 smartlist_get(transport_list, 0),
5354 socks_ver);
5359 r = 0;
5360 goto done;
5362 err:
5363 r = -1;
5365 done:
5366 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5367 smartlist_free(items);
5368 if (transport_list) {
5369 SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
5370 smartlist_free(transport_list);
5373 return r;
5376 /** Given a ServerTransportListenAddr <b>line</b>, return its
5377 * <address:port> string. Return NULL if the line was not
5378 * well-formed.
5380 * If <b>transport</b> is set, return NULL if the line is not
5381 * referring to <b>transport</b>.
5383 * The returned string is allocated on the heap and it's the
5384 * responsibility of the caller to free it. */
5385 static char *
5386 get_bindaddr_from_transport_listen_line(const char *line,const char *transport)
5388 smartlist_t *items = NULL;
5389 const char *parsed_transport = NULL;
5390 char *addrport = NULL;
5391 tor_addr_t addr;
5392 uint16_t port = 0;
5394 items = smartlist_new();
5395 smartlist_split_string(items, line, NULL,
5396 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5398 if (smartlist_len(items) < 2) {
5399 log_warn(LD_CONFIG,"Too few arguments on ServerTransportListenAddr line.");
5400 goto err;
5403 parsed_transport = smartlist_get(items, 0);
5404 addrport = tor_strdup(smartlist_get(items, 1));
5406 /* If 'transport' is given, check if it matches the one on the line */
5407 if (transport && strcmp(transport, parsed_transport))
5408 goto err;
5410 /* Validate addrport */
5411 if (tor_addr_port_parse(LOG_WARN, addrport, &addr, &port, -1)<0) {
5412 log_warn(LD_CONFIG, "Error parsing ServerTransportListenAddr "
5413 "address '%s'", addrport);
5414 goto err;
5417 goto done;
5419 err:
5420 tor_free(addrport);
5421 addrport = NULL;
5423 done:
5424 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5425 smartlist_free(items);
5427 return addrport;
5430 /** Given a ServerTransportOptions <b>line</b>, return a smartlist
5431 * with the options. Return NULL if the line was not well-formed.
5433 * If <b>transport</b> is set, return NULL if the line is not
5434 * referring to <b>transport</b>.
5436 * The returned smartlist and its strings are allocated on the heap
5437 * and it's the responsibility of the caller to free it. */
5438 smartlist_t *
5439 get_options_from_transport_options_line(const char *line,const char *transport)
5441 smartlist_t *items = smartlist_new();
5442 smartlist_t *options = smartlist_new();
5443 const char *parsed_transport = NULL;
5445 smartlist_split_string(items, line, NULL,
5446 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5448 if (smartlist_len(items) < 2) {
5449 log_warn(LD_CONFIG,"Too few arguments on ServerTransportOptions line.");
5450 goto err;
5453 parsed_transport = smartlist_get(items, 0);
5454 /* If 'transport' is given, check if it matches the one on the line */
5455 if (transport && strcmp(transport, parsed_transport))
5456 goto err;
5458 SMARTLIST_FOREACH_BEGIN(items, const char *, option) {
5459 if (option_sl_idx == 0) /* skip the transport field (first field)*/
5460 continue;
5462 /* validate that it's a k=v value */
5463 if (!string_is_key_value(LOG_WARN, option)) {
5464 log_warn(LD_CONFIG, "%s is not a k=v value.", escaped(option));
5465 goto err;
5468 /* add it to the options smartlist */
5469 smartlist_add(options, tor_strdup(option));
5470 log_debug(LD_CONFIG, "Added %s to the list of options", escaped(option));
5471 } SMARTLIST_FOREACH_END(option);
5473 goto done;
5475 err:
5476 SMARTLIST_FOREACH(options, char*, s, tor_free(s));
5477 smartlist_free(options);
5478 options = NULL;
5480 done:
5481 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5482 smartlist_free(items);
5484 return options;
5487 /** Given the name of a pluggable transport in <b>transport</b>, check
5488 * the configuration file to see if the user has explicitly asked for
5489 * it to listen on a specific port. Return a <address:port> string if
5490 * so, otherwise NULL. */
5491 char *
5492 get_transport_bindaddr_from_config(const char *transport)
5494 config_line_t *cl;
5495 const or_options_t *options = get_options();
5497 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
5498 char *bindaddr =
5499 get_bindaddr_from_transport_listen_line(cl->value, transport);
5500 if (bindaddr)
5501 return bindaddr;
5504 return NULL;
5507 /** Given the name of a pluggable transport in <b>transport</b>, check
5508 * the configuration file to see if the user has asked us to pass any
5509 * parameters to the pluggable transport. Return a smartlist
5510 * containing the parameters, otherwise NULL. */
5511 smartlist_t *
5512 get_options_for_server_transport(const char *transport)
5514 config_line_t *cl;
5515 const or_options_t *options = get_options();
5517 for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
5518 smartlist_t *options_sl =
5519 get_options_from_transport_options_line(cl->value, transport);
5520 if (options_sl)
5521 return options_sl;
5524 return NULL;
5527 /** Read the contents of a DirAuthority line from <b>line</b>. If
5528 * <b>validate_only</b> is 0, and the line is well-formed, and it
5529 * shares any bits with <b>required_type</b> or <b>required_type</b>
5530 * is NO_DIRINFO (zero), then add the dirserver described in the line
5531 * (minus whatever bits it's missing) as a valid authority.
5532 * Return 0 on success or filtering out by type,
5533 * or -1 if the line isn't well-formed or if we can't add it. */
5534 static int
5535 parse_dir_authority_line(const char *line, dirinfo_type_t required_type,
5536 int validate_only)
5538 smartlist_t *items = NULL;
5539 int r;
5540 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
5541 tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
5542 uint16_t dir_port = 0, or_port = 0;
5543 char digest[DIGEST_LEN];
5544 char v3_digest[DIGEST_LEN];
5545 dirinfo_type_t type = 0;
5546 double weight = 1.0;
5548 items = smartlist_new();
5549 smartlist_split_string(items, line, NULL,
5550 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5551 if (smartlist_len(items) < 1) {
5552 log_warn(LD_CONFIG, "No arguments on DirAuthority line.");
5553 goto err;
5556 if (is_legal_nickname(smartlist_get(items, 0))) {
5557 nickname = smartlist_get(items, 0);
5558 smartlist_del_keeporder(items, 0);
5561 while (smartlist_len(items)) {
5562 char *flag = smartlist_get(items, 0);
5563 if (TOR_ISDIGIT(flag[0]))
5564 break;
5565 if (!strcasecmp(flag, "hs") ||
5566 !strcasecmp(flag, "no-hs")) {
5567 log_warn(LD_CONFIG, "The DirAuthority options 'hs' and 'no-hs' are "
5568 "obsolete; you don't need them any more.");
5569 } else if (!strcasecmp(flag, "bridge")) {
5570 type |= BRIDGE_DIRINFO;
5571 } else if (!strcasecmp(flag, "no-v2")) {
5572 /* obsolete, but may still be contained in DirAuthority lines generated
5573 by various tools */;
5574 } else if (!strcasecmpstart(flag, "orport=")) {
5575 int ok;
5576 char *portstring = flag + strlen("orport=");
5577 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
5578 if (!ok)
5579 log_warn(LD_CONFIG, "Invalid orport '%s' on DirAuthority line.",
5580 portstring);
5581 } else if (!strcmpstart(flag, "weight=")) {
5582 int ok;
5583 const char *wstring = flag + strlen("weight=");
5584 weight = tor_parse_double(wstring, 0, UINT64_MAX, &ok, NULL);
5585 if (!ok) {
5586 log_warn(LD_CONFIG, "Invalid weight '%s' on DirAuthority line.",flag);
5587 weight=1.0;
5589 } else if (!strcasecmpstart(flag, "v3ident=")) {
5590 char *idstr = flag + strlen("v3ident=");
5591 if (strlen(idstr) != HEX_DIGEST_LEN ||
5592 base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
5593 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirAuthority line",
5594 flag);
5595 } else {
5596 type |= V3_DIRINFO|EXTRAINFO_DIRINFO|MICRODESC_DIRINFO;
5598 } else if (!strcasecmpstart(flag, "ipv6=")) {
5599 if (ipv6_addrport_ptr) {
5600 log_warn(LD_CONFIG, "Redundant ipv6 addr/port on DirAuthority line");
5601 } else {
5602 if (tor_addr_port_parse(LOG_WARN, flag+strlen("ipv6="),
5603 &ipv6_addrport.addr, &ipv6_addrport.port) < 0
5604 || tor_addr_family(&ipv6_addrport.addr) != AF_INET6) {
5605 log_warn(LD_CONFIG, "Bad ipv6 addr/port %s on DirAuthority line",
5606 escaped(flag));
5607 goto err;
5609 ipv6_addrport_ptr = &ipv6_addrport;
5611 } else {
5612 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirAuthority line",
5613 flag);
5615 tor_free(flag);
5616 smartlist_del_keeporder(items, 0);
5619 if (smartlist_len(items) < 2) {
5620 log_warn(LD_CONFIG, "Too few arguments to DirAuthority line.");
5621 goto err;
5623 addrport = smartlist_get(items, 0);
5624 smartlist_del_keeporder(items, 0);
5625 if (addr_port_lookup(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
5626 log_warn(LD_CONFIG, "Error parsing DirAuthority address '%s'", addrport);
5627 goto err;
5629 if (!dir_port) {
5630 log_warn(LD_CONFIG, "Missing port in DirAuthority address '%s'",addrport);
5631 goto err;
5634 fingerprint = smartlist_join_strings(items, "", 0, NULL);
5635 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
5636 log_warn(LD_CONFIG, "Key digest '%s' for DirAuthority is wrong length %d.",
5637 fingerprint, (int)strlen(fingerprint));
5638 goto err;
5640 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
5641 log_warn(LD_CONFIG, "Unable to decode DirAuthority key digest.");
5642 goto err;
5645 if (!validate_only && (!required_type || required_type & type)) {
5646 dir_server_t *ds;
5647 if (required_type)
5648 type &= required_type; /* pare down what we think of them as an
5649 * authority for. */
5650 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
5651 address, (int)dir_port, (char*)smartlist_get(items,0));
5652 if (!(ds = trusted_dir_server_new(nickname, address, dir_port, or_port,
5653 ipv6_addrport_ptr,
5654 digest, v3_digest, type, weight)))
5655 goto err;
5656 dir_server_add(ds);
5659 r = 0;
5660 goto done;
5662 err:
5663 r = -1;
5665 done:
5666 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5667 smartlist_free(items);
5668 tor_free(addrport);
5669 tor_free(address);
5670 tor_free(nickname);
5671 tor_free(fingerprint);
5672 return r;
5675 /** Read the contents of a FallbackDir line from <b>line</b>. If
5676 * <b>validate_only</b> is 0, and the line is well-formed, then add the
5677 * dirserver described in the line as a fallback directory. Return 0 on
5678 * success, or -1 if the line isn't well-formed or if we can't add it. */
5680 parse_dir_fallback_line(const char *line,
5681 int validate_only)
5683 int r = -1;
5684 smartlist_t *items = smartlist_new(), *positional = smartlist_new();
5685 int orport = -1;
5686 uint16_t dirport;
5687 tor_addr_t addr;
5688 int ok;
5689 char id[DIGEST_LEN];
5690 char *address=NULL;
5691 tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
5692 double weight=1.0;
5694 memset(id, 0, sizeof(id));
5695 smartlist_split_string(items, line, NULL,
5696 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5697 SMARTLIST_FOREACH_BEGIN(items, const char *, cp) {
5698 const char *eq = strchr(cp, '=');
5699 ok = 1;
5700 if (! eq) {
5701 smartlist_add(positional, (char*)cp);
5702 continue;
5704 if (!strcmpstart(cp, "orport=")) {
5705 orport = (int)tor_parse_long(cp+strlen("orport="), 10,
5706 1, 65535, &ok, NULL);
5707 } else if (!strcmpstart(cp, "id=")) {
5708 ok = !base16_decode(id, DIGEST_LEN,
5709 cp+strlen("id="), strlen(cp)-strlen("id="));
5710 } else if (!strcasecmpstart(cp, "ipv6=")) {
5711 if (ipv6_addrport_ptr) {
5712 log_warn(LD_CONFIG, "Redundant ipv6 addr/port on FallbackDir line");
5713 } else {
5714 if (tor_addr_port_parse(LOG_WARN, cp+strlen("ipv6="),
5715 &ipv6_addrport.addr, &ipv6_addrport.port) < 0
5716 || tor_addr_family(&ipv6_addrport.addr) != AF_INET6) {
5717 log_warn(LD_CONFIG, "Bad ipv6 addr/port %s on FallbackDir line",
5718 escaped(cp));
5719 goto end;
5721 ipv6_addrport_ptr = &ipv6_addrport;
5723 } else if (!strcmpstart(cp, "weight=")) {
5724 int ok;
5725 const char *wstring = cp + strlen("weight=");
5726 weight = tor_parse_double(wstring, 0, UINT64_MAX, &ok, NULL);
5727 if (!ok) {
5728 log_warn(LD_CONFIG, "Invalid weight '%s' on FallbackDir line.", cp);
5729 weight=1.0;
5733 if (!ok) {
5734 log_warn(LD_CONFIG, "Bad FallbackDir option %s", escaped(cp));
5735 goto end;
5737 } SMARTLIST_FOREACH_END(cp);
5739 if (smartlist_len(positional) != 1) {
5740 log_warn(LD_CONFIG, "Couldn't parse FallbackDir line %s", escaped(line));
5741 goto end;
5744 if (tor_digest_is_zero(id)) {
5745 log_warn(LD_CONFIG, "Missing identity on FallbackDir line");
5746 goto end;
5749 if (orport <= 0) {
5750 log_warn(LD_CONFIG, "Missing orport on FallbackDir line");
5751 goto end;
5754 if (tor_addr_port_split(LOG_INFO, smartlist_get(positional, 0),
5755 &address, &dirport) < 0 ||
5756 tor_addr_parse(&addr, address)<0) {
5757 log_warn(LD_CONFIG, "Couldn't parse address:port %s on FallbackDir line",
5758 (const char*)smartlist_get(positional, 0));
5759 goto end;
5762 if (!validate_only) {
5763 dir_server_t *ds;
5764 ds = fallback_dir_server_new(&addr, dirport, orport, ipv6_addrport_ptr,
5765 id, weight);
5766 if (!ds) {
5767 log_warn(LD_CONFIG, "Couldn't create FallbackDir %s", escaped(line));
5768 goto end;
5770 dir_server_add(ds);
5773 r = 0;
5775 end:
5776 SMARTLIST_FOREACH(items, char *, cp, tor_free(cp));
5777 smartlist_free(items);
5778 smartlist_free(positional);
5779 tor_free(address);
5780 return r;
5783 /** Allocate and return a new port_cfg_t with reasonable defaults. */
5784 STATIC port_cfg_t *
5785 port_cfg_new(size_t namelen)
5787 tor_assert(namelen <= SIZE_T_CEILING - sizeof(port_cfg_t) - 1);
5788 port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t) + namelen + 1);
5789 cfg->entry_cfg.ipv4_traffic = 1;
5790 cfg->entry_cfg.cache_ipv4_answers = 1;
5791 cfg->entry_cfg.prefer_ipv6_virtaddr = 1;
5792 return cfg;
5795 /** Free all storage held in <b>port</b> */
5796 STATIC void
5797 port_cfg_free(port_cfg_t *port)
5799 tor_free(port);
5802 /** Warn for every port in <b>ports</b> of type <b>listener_type</b> that is
5803 * on a publicly routable address. */
5804 static void
5805 warn_nonlocal_client_ports(const smartlist_t *ports, const char *portname,
5806 int listener_type)
5808 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
5809 if (port->type != listener_type)
5810 continue;
5811 if (port->is_unix_addr) {
5812 /* Unix sockets aren't accessible over a network. */
5813 } else if (!tor_addr_is_internal(&port->addr, 1)) {
5814 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
5815 "Other people on the Internet might find your computer and "
5816 "use it as an open proxy. Please don't allow this unless you "
5817 "have a good reason.",
5818 fmt_addrport(&port->addr, port->port), portname);
5819 } else if (!tor_addr_is_loopback(&port->addr)) {
5820 log_notice(LD_CONFIG, "You configured a non-loopback address '%s' "
5821 "for %sPort. This allows everybody on your local network to "
5822 "use your machine as a proxy. Make sure this is what you "
5823 "wanted.",
5824 fmt_addrport(&port->addr, port->port), portname);
5826 } SMARTLIST_FOREACH_END(port);
5829 /** Warn for every Extended ORPort port in <b>ports</b> that is on a
5830 * publicly routable address. */
5831 static void
5832 warn_nonlocal_ext_orports(const smartlist_t *ports, const char *portname)
5834 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
5835 if (port->type != CONN_TYPE_EXT_OR_LISTENER)
5836 continue;
5837 if (port->is_unix_addr)
5838 continue;
5839 /* XXX maybe warn even if address is RFC1918? */
5840 if (!tor_addr_is_internal(&port->addr, 1)) {
5841 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
5842 "This is not advised; this address is supposed to only be "
5843 "exposed on localhost so that your pluggable transport "
5844 "proxies can connect to it.",
5845 fmt_addrport(&port->addr, port->port), portname);
5847 } SMARTLIST_FOREACH_END(port);
5850 /** Given a list of port_cfg_t in <b>ports</b>, warn if any controller port
5851 * there is listening on any non-loopback address. If <b>forbid_nonlocal</b>
5852 * is true, then emit a stronger warning and remove the port from the list.
5854 static void
5855 warn_nonlocal_controller_ports(smartlist_t *ports, unsigned forbid_nonlocal)
5857 int warned = 0;
5858 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
5859 if (port->type != CONN_TYPE_CONTROL_LISTENER)
5860 continue;
5861 if (port->is_unix_addr)
5862 continue;
5863 if (!tor_addr_is_loopback(&port->addr)) {
5864 if (forbid_nonlocal) {
5865 if (!warned)
5866 log_warn(LD_CONFIG,
5867 "You have a ControlPort set to accept "
5868 "unauthenticated connections from a non-local address. "
5869 "This means that programs not running on your computer "
5870 "can reconfigure your Tor, without even having to guess a "
5871 "password. That's so bad that I'm closing your ControlPort "
5872 "for you. If you need to control your Tor remotely, try "
5873 "enabling authentication and using a tool like stunnel or "
5874 "ssh to encrypt remote access.");
5875 warned = 1;
5876 port_cfg_free(port);
5877 SMARTLIST_DEL_CURRENT(ports, port);
5878 } else {
5879 log_warn(LD_CONFIG, "You have a ControlPort set to accept "
5880 "connections from a non-local address. This means that "
5881 "programs not running on your computer can reconfigure your "
5882 "Tor. That's pretty bad, since the controller "
5883 "protocol isn't encrypted! Maybe you should just listen on "
5884 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
5885 "remote connections to your control port.");
5886 return; /* No point in checking the rest */
5889 } SMARTLIST_FOREACH_END(port);
5892 #define CL_PORT_NO_STREAM_OPTIONS (1u<<0)
5893 #define CL_PORT_WARN_NONLOCAL (1u<<1)
5894 #define CL_PORT_ALLOW_EXTRA_LISTENADDR (1u<<2)
5895 #define CL_PORT_SERVER_OPTIONS (1u<<3)
5896 #define CL_PORT_FORBID_NONLOCAL (1u<<4)
5897 #define CL_PORT_TAKES_HOSTNAMES (1u<<5)
5898 #define CL_PORT_IS_UNIXSOCKET (1u<<6)
5899 #define CL_PORT_DFLT_GROUP_WRITABLE (1u<<7)
5901 #ifdef HAVE_SYS_UN_H
5903 /** Parse the given <b>addrport</b> and set <b>path_out</b> if a Unix socket
5904 * path is found. Return 0 on success. On error, a negative value is
5905 * returned, -ENOENT if no Unix statement found, -EINVAL if the socket path
5906 * is empty and -ENOSYS if AF_UNIX is not supported (see function in the
5907 * #else statement below). */
5910 config_parse_unix_port(const char *addrport, char **path_out)
5912 tor_assert(path_out);
5913 tor_assert(addrport);
5915 if (strcmpstart(addrport, unix_socket_prefix)) {
5916 /* Not a Unix socket path. */
5917 return -ENOENT;
5920 if (strlen(addrport + strlen(unix_socket_prefix)) == 0) {
5921 /* Empty socket path, not very usable. */
5922 return -EINVAL;
5925 *path_out = tor_strdup(addrport + strlen(unix_socket_prefix));
5926 return 0;
5929 #else /* defined(HAVE_SYS_UN_H) */
5932 config_parse_unix_port(const char *addrport, char **path_out)
5934 tor_assert(path_out);
5935 tor_assert(addrport);
5937 if (strcmpstart(addrport, unix_socket_prefix)) {
5938 /* Not a Unix socket path. */
5939 return -ENOENT;
5942 log_warn(LD_CONFIG,
5943 "Port configuration %s is for an AF_UNIX socket, but we have no"
5944 "support available on this platform",
5945 escaped(addrport));
5946 return -ENOSYS;
5948 #endif /* defined(HAVE_SYS_UN_H) */
5951 * Parse port configuration for a single port type.
5953 * Read entries of the "FooPort" type from the list <b>ports</b>, and
5954 * entries of the "FooListenAddress" type from the list
5955 * <b>listenaddrs</b>. Two syntaxes are supported: a legacy syntax
5956 * where FooPort is at most a single entry containing a port number and
5957 * where FooListenAddress has any number of address:port combinations;
5958 * and a new syntax where there are no FooListenAddress entries and
5959 * where FooPort can have any number of entries of the format
5960 * "[Address:][Port] IsolationOptions".
5962 * In log messages, describe the port type as <b>portname</b>.
5964 * If no address is specified, default to <b>defaultaddr</b>. If no
5965 * FooPort is given, default to defaultport (if 0, there is no default).
5967 * If CL_PORT_NO_STREAM_OPTIONS is set in <b>flags</b>, do not allow stream
5968 * isolation options in the FooPort entries.
5970 * If CL_PORT_WARN_NONLOCAL is set in <b>flags</b>, warn if any of the
5971 * ports are not on a local address. If CL_PORT_FORBID_NONLOCAL is set,
5972 * this is a control port with no password set: don't even allow it.
5974 * Unless CL_PORT_ALLOW_EXTRA_LISTENADDR is set in <b>flags</b>, warn
5975 * if FooListenAddress is set but FooPort is 0.
5977 * If CL_PORT_SERVER_OPTIONS is set in <b>flags</b>, do not allow stream
5978 * isolation options in the FooPort entries; instead allow the
5979 * server-port option set.
5981 * If CL_PORT_TAKES_HOSTNAMES is set in <b>flags</b>, allow the options
5982 * {No,}IPv{4,6}Traffic.
5984 * On success, if <b>out</b> is given, add a new port_cfg_t entry to
5985 * <b>out</b> for every port that the client should listen on. Return 0
5986 * on success, -1 on failure.
5988 static int
5989 parse_port_config(smartlist_t *out,
5990 const config_line_t *ports,
5991 const config_line_t *listenaddrs,
5992 const char *portname,
5993 int listener_type,
5994 const char *defaultaddr,
5995 int defaultport,
5996 const unsigned flags)
5998 smartlist_t *elts;
5999 int retval = -1;
6000 const unsigned is_control = (listener_type == CONN_TYPE_CONTROL_LISTENER);
6001 const unsigned is_ext_orport = (listener_type == CONN_TYPE_EXT_OR_LISTENER);
6002 const unsigned allow_no_stream_options = flags & CL_PORT_NO_STREAM_OPTIONS;
6003 const unsigned use_server_options = flags & CL_PORT_SERVER_OPTIONS;
6004 const unsigned warn_nonlocal = flags & CL_PORT_WARN_NONLOCAL;
6005 const unsigned forbid_nonlocal = flags & CL_PORT_FORBID_NONLOCAL;
6006 const unsigned default_to_group_writable =
6007 flags & CL_PORT_DFLT_GROUP_WRITABLE;
6008 const unsigned allow_spurious_listenaddr =
6009 flags & CL_PORT_ALLOW_EXTRA_LISTENADDR;
6010 const unsigned takes_hostnames = flags & CL_PORT_TAKES_HOSTNAMES;
6011 const unsigned is_unix_socket = flags & CL_PORT_IS_UNIXSOCKET;
6012 int got_zero_port=0, got_nonzero_port=0;
6013 char *unix_socket_path = NULL;
6015 /* FooListenAddress is deprecated; let's make it work like it used to work,
6016 * though. */
6017 if (listenaddrs) {
6018 int mainport = defaultport;
6020 if (ports && ports->next) {
6021 log_warn(LD_CONFIG, "%sListenAddress can't be used when there are "
6022 "multiple %sPort lines", portname, portname);
6023 return -1;
6024 } else if (ports) {
6025 if (!strcmp(ports->value, "auto")) {
6026 mainport = CFG_AUTO_PORT;
6027 } else {
6028 int ok;
6029 mainport = (int)tor_parse_long(ports->value, 10, 0, 65535, &ok, NULL);
6030 if (!ok) {
6031 log_warn(LD_CONFIG, "%sListenAddress can only be used with a single "
6032 "%sPort with value \"auto\" or 1-65535 and no options set.",
6033 portname, portname);
6034 return -1;
6039 if (mainport == 0) {
6040 if (allow_spurious_listenaddr)
6041 return 1; /*DOCDOC*/
6042 log_warn(LD_CONFIG, "%sPort must be defined if %sListenAddress is used",
6043 portname, portname);
6044 return -1;
6047 if (use_server_options && out) {
6048 /* Add a no_listen port. */
6049 port_cfg_t *cfg = port_cfg_new(0);
6050 cfg->type = listener_type;
6051 cfg->port = mainport;
6052 tor_addr_make_unspec(&cfg->addr); /* Server ports default to 0.0.0.0 */
6053 cfg->server_cfg.no_listen = 1;
6054 cfg->server_cfg.bind_ipv4_only = 1;
6055 cfg->entry_cfg.ipv4_traffic = 1;
6056 cfg->entry_cfg.prefer_ipv6_virtaddr = 1;
6057 smartlist_add(out, cfg);
6060 for (; listenaddrs; listenaddrs = listenaddrs->next) {
6061 tor_addr_t addr;
6062 uint16_t port = 0;
6063 if (tor_addr_port_lookup(listenaddrs->value, &addr, &port) < 0) {
6064 log_warn(LD_CONFIG, "Unable to parse %sListenAddress '%s'",
6065 portname, listenaddrs->value);
6066 return -1;
6068 if (out) {
6069 port_cfg_t *cfg = port_cfg_new(0);
6070 cfg->type = listener_type;
6071 cfg->port = port ? port : mainport;
6072 tor_addr_copy(&cfg->addr, &addr);
6073 cfg->entry_cfg.session_group = SESSION_GROUP_UNSET;
6074 cfg->entry_cfg.isolation_flags = ISO_DEFAULT;
6075 cfg->server_cfg.no_advertise = 1;
6076 smartlist_add(out, cfg);
6080 if (warn_nonlocal && out) {
6081 if (is_control)
6082 warn_nonlocal_controller_ports(out, forbid_nonlocal);
6083 else if (is_ext_orport)
6084 warn_nonlocal_ext_orports(out, portname);
6085 else
6086 warn_nonlocal_client_ports(out, portname, listener_type);
6088 return 0;
6089 } /* end if (listenaddrs) */
6091 /* No ListenAddress lines. If there's no FooPort, then maybe make a default
6092 * one. */
6093 if (! ports) {
6094 if (defaultport && defaultaddr && out) {
6095 port_cfg_t *cfg = port_cfg_new(is_unix_socket ? strlen(defaultaddr) : 0);
6096 cfg->type = listener_type;
6097 if (is_unix_socket) {
6098 tor_addr_make_unspec(&cfg->addr);
6099 memcpy(cfg->unix_addr, defaultaddr, strlen(defaultaddr) + 1);
6100 cfg->is_unix_addr = 1;
6101 } else {
6102 cfg->port = defaultport;
6103 tor_addr_parse(&cfg->addr, defaultaddr);
6105 cfg->entry_cfg.session_group = SESSION_GROUP_UNSET;
6106 cfg->entry_cfg.isolation_flags = ISO_DEFAULT;
6107 smartlist_add(out, cfg);
6109 return 0;
6112 /* At last we can actually parse the FooPort lines. The syntax is:
6113 * [Addr:](Port|auto) [Options].*/
6114 elts = smartlist_new();
6116 for (; ports; ports = ports->next) {
6117 tor_addr_t addr;
6118 int port, ret;
6119 int sessiongroup = SESSION_GROUP_UNSET;
6120 unsigned isolation = ISO_DEFAULT;
6121 int prefer_no_auth = 0;
6122 int socks_iso_keep_alive = 0;
6124 char *addrport;
6125 uint16_t ptmp=0;
6126 int ok;
6127 int no_listen = 0, no_advertise = 0, all_addrs = 0,
6128 bind_ipv4_only = 0, bind_ipv6_only = 0,
6129 ipv4_traffic = 1, ipv6_traffic = 0, prefer_ipv6 = 0,
6130 cache_ipv4 = 1, use_cached_ipv4 = 0,
6131 cache_ipv6 = 0, use_cached_ipv6 = 0,
6132 prefer_ipv6_automap = 1, world_writable = 0, group_writable = 0;
6134 smartlist_split_string(elts, ports->value, NULL,
6135 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
6136 if (smartlist_len(elts) == 0) {
6137 log_warn(LD_CONFIG, "Invalid %sPort line with no value", portname);
6138 goto err;
6141 /* Now parse the addr/port value */
6142 addrport = smartlist_get(elts, 0);
6144 /* Let's start to check if it's a Unix socket path. */
6145 ret = config_parse_unix_port(addrport, &unix_socket_path);
6146 if (ret < 0 && ret != -ENOENT) {
6147 if (ret == -EINVAL) {
6148 log_warn(LD_CONFIG, "Empty Unix socket path.");
6150 goto err;
6153 if (unix_socket_path &&
6154 ! conn_listener_type_supports_af_unix(listener_type)) {
6155 log_warn(LD_CONFIG, "%sPort does not support unix sockets", portname);
6156 goto err;
6159 if (unix_socket_path) {
6160 port = 1;
6161 } else if (is_unix_socket) {
6162 unix_socket_path = tor_strdup(addrport);
6163 if (!strcmp(addrport, "0"))
6164 port = 0;
6165 else
6166 port = 1;
6167 } else if (!strcmp(addrport, "auto")) {
6168 port = CFG_AUTO_PORT;
6169 int af = tor_addr_parse(&addr, defaultaddr);
6170 tor_assert(af >= 0);
6171 } else if (!strcasecmpend(addrport, ":auto")) {
6172 char *addrtmp = tor_strndup(addrport, strlen(addrport)-5);
6173 port = CFG_AUTO_PORT;
6174 if (tor_addr_port_lookup(addrtmp, &addr, &ptmp)<0 || ptmp) {
6175 log_warn(LD_CONFIG, "Invalid address '%s' for %sPort",
6176 escaped(addrport), portname);
6177 tor_free(addrtmp);
6178 goto err;
6180 } else {
6181 /* Try parsing integer port before address, because, who knows?
6182 "9050" might be a valid address. */
6183 port = (int) tor_parse_long(addrport, 10, 0, 65535, &ok, NULL);
6184 if (ok) {
6185 int af = tor_addr_parse(&addr, defaultaddr);
6186 tor_assert(af >= 0);
6187 } else if (tor_addr_port_lookup(addrport, &addr, &ptmp) == 0) {
6188 if (ptmp == 0) {
6189 log_warn(LD_CONFIG, "%sPort line has address but no port", portname);
6190 goto err;
6192 port = ptmp;
6193 } else {
6194 log_warn(LD_CONFIG, "Couldn't parse address '%s' for %sPort",
6195 escaped(addrport), portname);
6196 goto err;
6200 if (unix_socket_path && default_to_group_writable)
6201 group_writable = 1;
6203 /* Now parse the rest of the options, if any. */
6204 if (use_server_options) {
6205 /* This is a server port; parse advertising options */
6206 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
6207 if (elt_sl_idx == 0)
6208 continue; /* Skip addr:port */
6210 if (!strcasecmp(elt, "NoAdvertise")) {
6211 no_advertise = 1;
6212 } else if (!strcasecmp(elt, "NoListen")) {
6213 no_listen = 1;
6214 #if 0
6215 /* not implemented yet. */
6216 } else if (!strcasecmp(elt, "AllAddrs")) {
6218 all_addrs = 1;
6219 #endif
6220 } else if (!strcasecmp(elt, "IPv4Only")) {
6221 bind_ipv4_only = 1;
6222 } else if (!strcasecmp(elt, "IPv6Only")) {
6223 bind_ipv6_only = 1;
6224 } else {
6225 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6226 portname, escaped(elt));
6228 } SMARTLIST_FOREACH_END(elt);
6230 if (no_advertise && no_listen) {
6231 log_warn(LD_CONFIG, "Tried to set both NoListen and NoAdvertise "
6232 "on %sPort line '%s'",
6233 portname, escaped(ports->value));
6234 goto err;
6236 if (bind_ipv4_only && bind_ipv6_only) {
6237 log_warn(LD_CONFIG, "Tried to set both IPv4Only and IPv6Only "
6238 "on %sPort line '%s'",
6239 portname, escaped(ports->value));
6240 goto err;
6242 if (bind_ipv4_only && tor_addr_family(&addr) == AF_INET6) {
6243 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv6",
6244 portname);
6245 goto err;
6247 if (bind_ipv6_only && tor_addr_family(&addr) == AF_INET) {
6248 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv4",
6249 portname);
6250 goto err;
6252 } else {
6253 /* This is a client port; parse isolation options */
6254 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
6255 int no = 0, isoflag = 0;
6256 const char *elt_orig = elt;
6257 if (elt_sl_idx == 0)
6258 continue; /* Skip addr:port */
6260 if (!strcasecmpstart(elt, "SessionGroup=")) {
6261 int group = (int)tor_parse_long(elt+strlen("SessionGroup="),
6262 10, 0, INT_MAX, &ok, NULL);
6263 if (!ok || !allow_no_stream_options) {
6264 log_warn(LD_CONFIG, "Invalid %sPort option '%s'",
6265 portname, escaped(elt));
6266 goto err;
6268 if (sessiongroup >= 0) {
6269 log_warn(LD_CONFIG, "Multiple SessionGroup options on %sPort",
6270 portname);
6271 goto err;
6273 sessiongroup = group;
6274 continue;
6277 if (!strcasecmpstart(elt, "No")) {
6278 no = 1;
6279 elt += 2;
6282 if (!strcasecmp(elt, "GroupWritable")) {
6283 group_writable = !no;
6284 continue;
6285 } else if (!strcasecmp(elt, "WorldWritable")) {
6286 world_writable = !no;
6287 continue;
6290 if (allow_no_stream_options) {
6291 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6292 portname, escaped(elt));
6293 continue;
6296 if (takes_hostnames) {
6297 if (!strcasecmp(elt, "IPv4Traffic")) {
6298 ipv4_traffic = ! no;
6299 continue;
6300 } else if (!strcasecmp(elt, "IPv6Traffic")) {
6301 ipv6_traffic = ! no;
6302 continue;
6303 } else if (!strcasecmp(elt, "PreferIPv6")) {
6304 prefer_ipv6 = ! no;
6305 continue;
6308 if (!strcasecmp(elt, "CacheIPv4DNS")) {
6309 cache_ipv4 = ! no;
6310 continue;
6311 } else if (!strcasecmp(elt, "CacheIPv6DNS")) {
6312 cache_ipv6 = ! no;
6313 continue;
6314 } else if (!strcasecmp(elt, "CacheDNS")) {
6315 cache_ipv4 = cache_ipv6 = ! no;
6316 continue;
6317 } else if (!strcasecmp(elt, "UseIPv4Cache")) {
6318 use_cached_ipv4 = ! no;
6319 continue;
6320 } else if (!strcasecmp(elt, "UseIPv6Cache")) {
6321 use_cached_ipv6 = ! no;
6322 continue;
6323 } else if (!strcasecmp(elt, "UseDNSCache")) {
6324 use_cached_ipv4 = use_cached_ipv6 = ! no;
6325 continue;
6326 } else if (!strcasecmp(elt, "PreferIPv6Automap")) {
6327 prefer_ipv6_automap = ! no;
6328 continue;
6329 } else if (!strcasecmp(elt, "PreferSOCKSNoAuth")) {
6330 prefer_no_auth = ! no;
6331 continue;
6332 } else if (!strcasecmp(elt, "KeepAliveIsolateSOCKSAuth")) {
6333 socks_iso_keep_alive = ! no;
6334 continue;
6337 if (!strcasecmpend(elt, "s"))
6338 elt[strlen(elt)-1] = '\0'; /* kill plurals. */
6340 if (!strcasecmp(elt, "IsolateDestPort")) {
6341 isoflag = ISO_DESTPORT;
6342 } else if (!strcasecmp(elt, "IsolateDestAddr")) {
6343 isoflag = ISO_DESTADDR;
6344 } else if (!strcasecmp(elt, "IsolateSOCKSAuth")) {
6345 isoflag = ISO_SOCKSAUTH;
6346 } else if (!strcasecmp(elt, "IsolateClientProtocol")) {
6347 isoflag = ISO_CLIENTPROTO;
6348 } else if (!strcasecmp(elt, "IsolateClientAddr")) {
6349 isoflag = ISO_CLIENTADDR;
6350 } else {
6351 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6352 portname, escaped(elt_orig));
6355 if (no) {
6356 isolation &= ~isoflag;
6357 } else {
6358 isolation |= isoflag;
6360 } SMARTLIST_FOREACH_END(elt);
6363 if (port)
6364 got_nonzero_port = 1;
6365 else
6366 got_zero_port = 1;
6368 if (ipv4_traffic == 0 && ipv6_traffic == 0) {
6369 log_warn(LD_CONFIG, "You have a %sPort entry with both IPv4 and "
6370 "IPv6 disabled; that won't work.", portname);
6371 goto err;
6374 if ( (world_writable || group_writable) && ! unix_socket_path) {
6375 log_warn(LD_CONFIG, "You have a %sPort entry with GroupWritable "
6376 "or WorldWritable set, but it is not a unix socket.", portname);
6377 goto err;
6380 if (!(isolation & ISO_SOCKSAUTH) && socks_iso_keep_alive) {
6381 log_warn(LD_CONFIG, "You have a %sPort entry with both "
6382 "NoIsolateSOCKSAuth and KeepAliveIsolateSOCKSAuth set.",
6383 portname);
6384 goto err;
6387 if (out && port) {
6388 size_t namelen = unix_socket_path ? strlen(unix_socket_path) : 0;
6389 port_cfg_t *cfg = port_cfg_new(namelen);
6390 if (unix_socket_path) {
6391 tor_addr_make_unspec(&cfg->addr);
6392 memcpy(cfg->unix_addr, unix_socket_path, namelen + 1);
6393 cfg->is_unix_addr = 1;
6394 tor_free(unix_socket_path);
6395 } else {
6396 tor_addr_copy(&cfg->addr, &addr);
6397 cfg->port = port;
6399 cfg->type = listener_type;
6400 cfg->is_world_writable = world_writable;
6401 cfg->is_group_writable = group_writable;
6402 cfg->entry_cfg.isolation_flags = isolation;
6403 cfg->entry_cfg.session_group = sessiongroup;
6404 cfg->server_cfg.no_advertise = no_advertise;
6405 cfg->server_cfg.no_listen = no_listen;
6406 cfg->server_cfg.all_addrs = all_addrs;
6407 cfg->server_cfg.bind_ipv4_only = bind_ipv4_only;
6408 cfg->server_cfg.bind_ipv6_only = bind_ipv6_only;
6409 cfg->entry_cfg.ipv4_traffic = ipv4_traffic;
6410 cfg->entry_cfg.ipv6_traffic = ipv6_traffic;
6411 cfg->entry_cfg.prefer_ipv6 = prefer_ipv6;
6412 cfg->entry_cfg.cache_ipv4_answers = cache_ipv4;
6413 cfg->entry_cfg.cache_ipv6_answers = cache_ipv6;
6414 cfg->entry_cfg.use_cached_ipv4_answers = use_cached_ipv4;
6415 cfg->entry_cfg.use_cached_ipv6_answers = use_cached_ipv6;
6416 cfg->entry_cfg.prefer_ipv6_virtaddr = prefer_ipv6_automap;
6417 cfg->entry_cfg.socks_prefer_no_auth = prefer_no_auth;
6418 if (! (isolation & ISO_SOCKSAUTH))
6419 cfg->entry_cfg.socks_prefer_no_auth = 1;
6420 cfg->entry_cfg.socks_iso_keep_alive = socks_iso_keep_alive;
6422 smartlist_add(out, cfg);
6424 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
6425 smartlist_clear(elts);
6428 if (warn_nonlocal && out) {
6429 if (is_control)
6430 warn_nonlocal_controller_ports(out, forbid_nonlocal);
6431 else if (is_ext_orport)
6432 warn_nonlocal_ext_orports(out, portname);
6433 else
6434 warn_nonlocal_client_ports(out, portname, listener_type);
6437 if (got_zero_port && got_nonzero_port) {
6438 log_warn(LD_CONFIG, "You specified a nonzero %sPort along with '%sPort 0' "
6439 "in the same configuration. Did you mean to disable %sPort or "
6440 "not?", portname, portname, portname);
6441 goto err;
6444 retval = 0;
6445 err:
6446 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
6447 smartlist_free(elts);
6448 tor_free(unix_socket_path);
6449 return retval;
6452 /** Return the number of ports which are actually going to listen with type
6453 * <b>listenertype</b>. Do not count no_listen ports. Do not count unix
6454 * sockets. */
6455 static int
6456 count_real_listeners(const smartlist_t *ports, int listenertype)
6458 int n = 0;
6459 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
6460 if (port->server_cfg.no_listen || port->is_unix_addr)
6461 continue;
6462 if (port->type != listenertype)
6463 continue;
6464 ++n;
6465 } SMARTLIST_FOREACH_END(port);
6466 return n;
6469 /** Parse all client port types (Socks, DNS, Trans, NATD) from
6470 * <b>options</b>. On success, set *<b>n_ports_out</b> to the number
6471 * of ports that are listed, update the *Port_set values in
6472 * <b>options</b>, and return 0. On failure, set *<b>msg</b> to a
6473 * description of the problem and return -1.
6475 * If <b>validate_only</b> is false, set configured_client_ports to the
6476 * new list of ports parsed from <b>options</b>.
6478 static int
6479 parse_ports(or_options_t *options, int validate_only,
6480 char **msg, int *n_ports_out,
6481 int *world_writable_control_socket)
6483 smartlist_t *ports;
6484 int retval = -1;
6486 ports = smartlist_new();
6488 *n_ports_out = 0;
6490 const unsigned gw_flag = options->SocksSocketsGroupWritable ?
6491 CL_PORT_DFLT_GROUP_WRITABLE : 0;
6492 if (parse_port_config(ports,
6493 options->SocksPort_lines, options->SocksListenAddress,
6494 "Socks", CONN_TYPE_AP_LISTENER,
6495 "127.0.0.1", 9050,
6496 CL_PORT_WARN_NONLOCAL|CL_PORT_ALLOW_EXTRA_LISTENADDR|
6497 CL_PORT_TAKES_HOSTNAMES|gw_flag) < 0) {
6498 *msg = tor_strdup("Invalid SocksPort/SocksListenAddress configuration");
6499 goto err;
6501 if (parse_port_config(ports,
6502 options->DNSPort_lines, options->DNSListenAddress,
6503 "DNS", CONN_TYPE_AP_DNS_LISTENER,
6504 "127.0.0.1", 0,
6505 CL_PORT_WARN_NONLOCAL|CL_PORT_TAKES_HOSTNAMES) < 0) {
6506 *msg = tor_strdup("Invalid DNSPort/DNSListenAddress configuration");
6507 goto err;
6509 if (parse_port_config(ports,
6510 options->TransPort_lines, options->TransListenAddress,
6511 "Trans", CONN_TYPE_AP_TRANS_LISTENER,
6512 "127.0.0.1", 0,
6513 CL_PORT_WARN_NONLOCAL) < 0) {
6514 *msg = tor_strdup("Invalid TransPort/TransListenAddress configuration");
6515 goto err;
6517 if (parse_port_config(ports,
6518 options->NATDPort_lines, options->NATDListenAddress,
6519 "NATD", CONN_TYPE_AP_NATD_LISTENER,
6520 "127.0.0.1", 0,
6521 CL_PORT_WARN_NONLOCAL) < 0) {
6522 *msg = tor_strdup("Invalid NatdPort/NatdListenAddress configuration");
6523 goto err;
6526 unsigned control_port_flags = CL_PORT_NO_STREAM_OPTIONS |
6527 CL_PORT_WARN_NONLOCAL;
6528 const int any_passwords = (options->HashedControlPassword ||
6529 options->HashedControlSessionPassword ||
6530 options->CookieAuthentication);
6531 if (! any_passwords)
6532 control_port_flags |= CL_PORT_FORBID_NONLOCAL;
6533 if (options->ControlSocketsGroupWritable)
6534 control_port_flags |= CL_PORT_DFLT_GROUP_WRITABLE;
6536 if (parse_port_config(ports,
6537 options->ControlPort_lines,
6538 options->ControlListenAddress,
6539 "Control", CONN_TYPE_CONTROL_LISTENER,
6540 "127.0.0.1", 0,
6541 control_port_flags) < 0) {
6542 *msg = tor_strdup("Invalid ControlPort/ControlListenAddress "
6543 "configuration");
6544 goto err;
6547 if (parse_port_config(ports, options->ControlSocket, NULL,
6548 "ControlSocket",
6549 CONN_TYPE_CONTROL_LISTENER, NULL, 0,
6550 control_port_flags | CL_PORT_IS_UNIXSOCKET) < 0) {
6551 *msg = tor_strdup("Invalid ControlSocket configuration");
6552 goto err;
6555 if (! options->ClientOnly) {
6556 if (parse_port_config(ports,
6557 options->ORPort_lines, options->ORListenAddress,
6558 "OR", CONN_TYPE_OR_LISTENER,
6559 "0.0.0.0", 0,
6560 CL_PORT_SERVER_OPTIONS) < 0) {
6561 *msg = tor_strdup("Invalid ORPort/ORListenAddress configuration");
6562 goto err;
6564 if (parse_port_config(ports,
6565 options->ExtORPort_lines, NULL,
6566 "ExtOR", CONN_TYPE_EXT_OR_LISTENER,
6567 "127.0.0.1", 0,
6568 CL_PORT_SERVER_OPTIONS|CL_PORT_WARN_NONLOCAL) < 0) {
6569 *msg = tor_strdup("Invalid ExtORPort configuration");
6570 goto err;
6572 if (parse_port_config(ports,
6573 options->DirPort_lines, options->DirListenAddress,
6574 "Dir", CONN_TYPE_DIR_LISTENER,
6575 "0.0.0.0", 0,
6576 CL_PORT_SERVER_OPTIONS) < 0) {
6577 *msg = tor_strdup("Invalid DirPort/DirListenAddress configuration");
6578 goto err;
6582 if (check_server_ports(ports, options) < 0) {
6583 *msg = tor_strdup("Misconfigured server ports");
6584 goto err;
6587 *n_ports_out = smartlist_len(ports);
6589 retval = 0;
6591 /* Update the *Port_set options. The !! here is to force a boolean out of
6592 an integer. */
6593 options->ORPort_set =
6594 !! count_real_listeners(ports, CONN_TYPE_OR_LISTENER);
6595 options->SocksPort_set =
6596 !! count_real_listeners(ports, CONN_TYPE_AP_LISTENER);
6597 options->TransPort_set =
6598 !! count_real_listeners(ports, CONN_TYPE_AP_TRANS_LISTENER);
6599 options->NATDPort_set =
6600 !! count_real_listeners(ports, CONN_TYPE_AP_NATD_LISTENER);
6601 options->ControlPort_set =
6602 !! count_real_listeners(ports, CONN_TYPE_CONTROL_LISTENER);
6603 options->DirPort_set =
6604 !! count_real_listeners(ports, CONN_TYPE_DIR_LISTENER);
6605 options->DNSPort_set =
6606 !! count_real_listeners(ports, CONN_TYPE_AP_DNS_LISTENER);
6607 options->ExtORPort_set =
6608 !! count_real_listeners(ports, CONN_TYPE_EXT_OR_LISTENER);
6610 if (world_writable_control_socket) {
6611 SMARTLIST_FOREACH(ports, port_cfg_t *, p,
6612 if (p->type == CONN_TYPE_CONTROL_LISTENER &&
6613 p->is_unix_addr &&
6614 p->is_world_writable) {
6615 *world_writable_control_socket = 1;
6616 break;
6620 if (!validate_only) {
6621 if (configured_ports) {
6622 SMARTLIST_FOREACH(configured_ports,
6623 port_cfg_t *, p, port_cfg_free(p));
6624 smartlist_free(configured_ports);
6626 configured_ports = ports;
6627 ports = NULL; /* prevent free below. */
6630 err:
6631 if (ports) {
6632 SMARTLIST_FOREACH(ports, port_cfg_t *, p, port_cfg_free(p));
6633 smartlist_free(ports);
6635 return retval;
6638 /** Given a list of <b>port_cfg_t</b> in <b>ports</b>, check them for internal
6639 * consistency and warn as appropriate. */
6640 static int
6641 check_server_ports(const smartlist_t *ports,
6642 const or_options_t *options)
6644 int n_orport_advertised = 0;
6645 int n_orport_advertised_ipv4 = 0;
6646 int n_orport_listeners = 0;
6647 int n_dirport_advertised = 0;
6648 int n_dirport_listeners = 0;
6649 int n_low_port = 0;
6650 int r = 0;
6652 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
6653 if (port->type == CONN_TYPE_DIR_LISTENER) {
6654 if (! port->server_cfg.no_advertise)
6655 ++n_dirport_advertised;
6656 if (! port->server_cfg.no_listen)
6657 ++n_dirport_listeners;
6658 } else if (port->type == CONN_TYPE_OR_LISTENER) {
6659 if (! port->server_cfg.no_advertise) {
6660 ++n_orport_advertised;
6661 if (tor_addr_family(&port->addr) == AF_INET ||
6662 (tor_addr_family(&port->addr) == AF_UNSPEC &&
6663 !port->server_cfg.bind_ipv6_only))
6664 ++n_orport_advertised_ipv4;
6666 if (! port->server_cfg.no_listen)
6667 ++n_orport_listeners;
6668 } else {
6669 continue;
6671 #ifndef _WIN32
6672 if (!port->server_cfg.no_listen && port->port < 1024)
6673 ++n_low_port;
6674 #endif
6675 } SMARTLIST_FOREACH_END(port);
6677 if (n_orport_advertised && !n_orport_listeners) {
6678 log_warn(LD_CONFIG, "We are advertising an ORPort, but not actually "
6679 "listening on one.");
6680 r = -1;
6682 if (n_orport_listeners && !n_orport_advertised) {
6683 log_warn(LD_CONFIG, "We are listening on an ORPort, but not advertising "
6684 "any ORPorts. This will keep us from building a %s "
6685 "descriptor, and make us impossible to use.",
6686 options->BridgeRelay ? "bridge" : "router");
6687 r = -1;
6689 if (n_dirport_advertised && !n_dirport_listeners) {
6690 log_warn(LD_CONFIG, "We are advertising a DirPort, but not actually "
6691 "listening on one.");
6692 r = -1;
6694 if (n_dirport_advertised > 1) {
6695 log_warn(LD_CONFIG, "Can't advertise more than one DirPort.");
6696 r = -1;
6698 if (n_orport_advertised && !n_orport_advertised_ipv4 &&
6699 !options->BridgeRelay) {
6700 log_warn(LD_CONFIG, "Configured non-bridge only to listen on an IPv6 "
6701 "address.");
6702 r = -1;
6705 if (n_low_port && options->AccountingMax) {
6706 log_warn(LD_CONFIG,
6707 "You have set AccountingMax to use hibernation. You have also "
6708 "chosen a low DirPort or OrPort. This combination can make Tor stop "
6709 "working when it tries to re-attach the port after a period of "
6710 "hibernation. Please choose a different port or turn off "
6711 "hibernation unless you know this combination will work on your "
6712 "platform.");
6715 return r;
6718 /** Return a list of port_cfg_t for client ports parsed from the
6719 * options. */
6720 MOCK_IMPL(const smartlist_t *,
6721 get_configured_ports,(void))
6723 if (!configured_ports)
6724 configured_ports = smartlist_new();
6725 return configured_ports;
6728 /** Return an address:port string representation of the address
6729 * where the first <b>listener_type</b> listener waits for
6730 * connections. Return NULL if we couldn't find a listener. The
6731 * string is allocated on the heap and it's the responsibility of the
6732 * caller to free it after use.
6734 * This function is meant to be used by the pluggable transport proxy
6735 * spawning code, please make sure that it fits your purposes before
6736 * using it. */
6737 char *
6738 get_first_listener_addrport_string(int listener_type)
6740 static const char *ipv4_localhost = "127.0.0.1";
6741 static const char *ipv6_localhost = "[::1]";
6742 const char *address;
6743 uint16_t port;
6744 char *string = NULL;
6746 if (!configured_ports)
6747 return NULL;
6749 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
6750 if (cfg->server_cfg.no_listen)
6751 continue;
6753 if (cfg->type == listener_type &&
6754 tor_addr_family(&cfg->addr) != AF_UNSPEC) {
6756 /* We found the first listener of the type we are interested in! */
6758 /* If a listener is listening on INADDR_ANY, assume that it's
6759 also listening on 127.0.0.1, and point the transport proxy
6760 there: */
6761 if (tor_addr_is_null(&cfg->addr))
6762 address = tor_addr_is_v4(&cfg->addr) ? ipv4_localhost : ipv6_localhost;
6763 else
6764 address = fmt_and_decorate_addr(&cfg->addr);
6766 /* If a listener is configured with port 'auto', we are forced
6767 to iterate all listener connections and find out in which
6768 port it ended up listening: */
6769 if (cfg->port == CFG_AUTO_PORT) {
6770 port = router_get_active_listener_port_by_type_af(listener_type,
6771 tor_addr_family(&cfg->addr));
6772 if (!port)
6773 return NULL;
6774 } else {
6775 port = cfg->port;
6778 tor_asprintf(&string, "%s:%u", address, port);
6780 return string;
6783 } SMARTLIST_FOREACH_END(cfg);
6785 return NULL;
6788 /** Return the first advertised port of type <b>listener_type</b> in
6789 <b>address_family</b>. */
6791 get_first_advertised_port_by_type_af(int listener_type, int address_family)
6793 if (!configured_ports)
6794 return 0;
6795 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
6796 if (cfg->type == listener_type &&
6797 !cfg->server_cfg.no_advertise &&
6798 (tor_addr_family(&cfg->addr) == address_family ||
6799 tor_addr_family(&cfg->addr) == AF_UNSPEC)) {
6800 if (tor_addr_family(&cfg->addr) != AF_UNSPEC ||
6801 (address_family == AF_INET && !cfg->server_cfg.bind_ipv6_only) ||
6802 (address_family == AF_INET6 && !cfg->server_cfg.bind_ipv4_only)) {
6803 return cfg->port;
6806 } SMARTLIST_FOREACH_END(cfg);
6807 return 0;
6810 /** Adjust the value of options->DataDirectory, or fill it in if it's
6811 * absent. Return 0 on success, -1 on failure. */
6812 static int
6813 normalize_data_directory(or_options_t *options)
6815 #ifdef _WIN32
6816 char *p;
6817 if (options->DataDirectory)
6818 return 0; /* all set */
6819 p = tor_malloc(MAX_PATH);
6820 strlcpy(p,get_windows_conf_root(),MAX_PATH);
6821 options->DataDirectory = p;
6822 return 0;
6823 #else
6824 const char *d = options->DataDirectory;
6825 if (!d)
6826 d = "~/.tor";
6828 if (strncmp(d,"~/",2) == 0) {
6829 char *fn = expand_filename(d);
6830 if (!fn) {
6831 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
6832 return -1;
6834 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
6835 /* If our homedir is /, we probably don't want to use it. */
6836 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
6837 * want. */
6838 log_warn(LD_CONFIG,
6839 "Default DataDirectory is \"~/.tor\". This expands to "
6840 "\"%s\", which is probably not what you want. Using "
6841 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
6842 tor_free(fn);
6843 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
6845 tor_free(options->DataDirectory);
6846 options->DataDirectory = fn;
6848 return 0;
6849 #endif
6852 /** Check and normalize the value of options->DataDirectory; return 0 if it
6853 * is sane, -1 otherwise. */
6854 static int
6855 validate_data_directory(or_options_t *options)
6857 if (normalize_data_directory(options) < 0)
6858 return -1;
6859 tor_assert(options->DataDirectory);
6860 if (strlen(options->DataDirectory) > (512-128)) {
6861 log_warn(LD_CONFIG, "DataDirectory is too long.");
6862 return -1;
6864 return 0;
6867 /** This string must remain the same forevermore. It is how we
6868 * recognize that the torrc file doesn't need to be backed up. */
6869 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
6870 "if you edit it, comments will not be preserved"
6871 /** This string can change; it tries to give the reader an idea
6872 * that editing this file by hand is not a good plan. */
6873 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
6874 "to torrc.orig.1 or similar, and Tor will ignore it"
6876 /** Save a configuration file for the configuration in <b>options</b>
6877 * into the file <b>fname</b>. If the file already exists, and
6878 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
6879 * replace it. Return 0 on success, -1 on failure. */
6880 static int
6881 write_configuration_file(const char *fname, const or_options_t *options)
6883 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
6884 int rename_old = 0, r;
6886 if (!fname)
6887 return -1;
6889 switch (file_status(fname)) {
6890 /* create backups of old config files, even if they're empty */
6891 case FN_FILE:
6892 case FN_EMPTY:
6893 old_val = read_file_to_str(fname, 0, NULL);
6894 if (!old_val || strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
6895 rename_old = 1;
6897 tor_free(old_val);
6898 break;
6899 case FN_NOENT:
6900 break;
6901 case FN_ERROR:
6902 case FN_DIR:
6903 default:
6904 log_warn(LD_CONFIG,
6905 "Config file \"%s\" is not a file? Failing.", fname);
6906 return -1;
6909 if (!(new_conf = options_dump(options, OPTIONS_DUMP_MINIMAL))) {
6910 log_warn(LD_BUG, "Couldn't get configuration string");
6911 goto err;
6914 tor_asprintf(&new_val, "%s\n%s\n\n%s",
6915 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
6917 if (rename_old) {
6918 int i = 1;
6919 char *fn_tmp = NULL;
6920 while (1) {
6921 tor_asprintf(&fn_tmp, "%s.orig.%d", fname, i);
6922 if (file_status(fn_tmp) == FN_NOENT)
6923 break;
6924 tor_free(fn_tmp);
6925 ++i;
6927 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
6928 if (tor_rename(fname, fn_tmp) < 0) {//XXXX sandbox doesn't allow
6929 log_warn(LD_FS,
6930 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
6931 fname, fn_tmp, strerror(errno));
6932 tor_free(fn_tmp);
6933 goto err;
6935 tor_free(fn_tmp);
6938 if (write_str_to_file(fname, new_val, 0) < 0)
6939 goto err;
6941 r = 0;
6942 goto done;
6943 err:
6944 r = -1;
6945 done:
6946 tor_free(new_val);
6947 tor_free(new_conf);
6948 return r;
6952 * Save the current configuration file value to disk. Return 0 on
6953 * success, -1 on failure.
6956 options_save_current(void)
6958 /* This fails if we can't write to our configuration file.
6960 * If we try falling back to datadirectory or something, we have a better
6961 * chance of saving the configuration, but a better chance of doing
6962 * something the user never expected. */
6963 return write_configuration_file(get_torrc_fname(0), get_options());
6966 /** Return the number of cpus configured in <b>options</b>. If we are
6967 * told to auto-detect the number of cpus, return the auto-detected number. */
6969 get_num_cpus(const or_options_t *options)
6971 if (options->NumCPUs == 0) {
6972 int n = compute_num_cpus();
6973 return (n >= 1) ? n : 1;
6974 } else {
6975 return options->NumCPUs;
6980 * Initialize the libevent library.
6982 static void
6983 init_libevent(const or_options_t *options)
6985 tor_libevent_cfg cfg;
6987 tor_assert(options);
6989 configure_libevent_logging();
6990 /* If the kernel complains that some method (say, epoll) doesn't
6991 * exist, we don't care about it, since libevent will cope.
6993 suppress_libevent_log_msg("Function not implemented");
6995 tor_check_libevent_header_compatibility();
6997 memset(&cfg, 0, sizeof(cfg));
6998 cfg.disable_iocp = options->DisableIOCP;
6999 cfg.num_cpus = get_num_cpus(options);
7000 cfg.msec_per_tick = options->TokenBucketRefillInterval;
7002 tor_libevent_initialize(&cfg);
7004 suppress_libevent_log_msg(NULL);
7007 /** Return a newly allocated string holding a filename relative to the data
7008 * directory. If <b>sub1</b> is present, it is the first path component after
7009 * the data directory. If <b>sub2</b> is also present, it is the second path
7010 * component after the data directory. If <b>suffix</b> is present, it
7011 * is appended to the filename.
7013 * Examples:
7014 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
7015 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
7016 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
7017 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
7019 * Note: Consider using the get_datadir_fname* macros in or.h.
7021 char *
7022 options_get_datadir_fname2_suffix(const or_options_t *options,
7023 const char *sub1, const char *sub2,
7024 const char *suffix)
7026 char *fname = NULL;
7027 size_t len;
7028 tor_assert(options);
7029 tor_assert(options->DataDirectory);
7030 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
7031 len = strlen(options->DataDirectory);
7032 if (sub1) {
7033 len += strlen(sub1)+1;
7034 if (sub2)
7035 len += strlen(sub2)+1;
7037 if (suffix)
7038 len += strlen(suffix);
7039 len++;
7040 fname = tor_malloc(len);
7041 if (sub1) {
7042 if (sub2) {
7043 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
7044 options->DataDirectory, sub1, sub2);
7045 } else {
7046 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
7047 options->DataDirectory, sub1);
7049 } else {
7050 strlcpy(fname, options->DataDirectory, len);
7052 if (suffix)
7053 strlcat(fname, suffix, len);
7054 return fname;
7057 /** Check wether the data directory has a private subdirectory
7058 * <b>subdir</b>. If not, try to create it. Return 0 on success,
7059 * -1 otherwise. */
7061 check_or_create_data_subdir(const char *subdir)
7063 char *statsdir = get_datadir_fname(subdir);
7064 int return_val = 0;
7066 if (check_private_dir(statsdir, CPD_CREATE, get_options()->User) < 0) {
7067 log_warn(LD_HIST, "Unable to create %s/ directory!", subdir);
7068 return_val = -1;
7070 tor_free(statsdir);
7071 return return_val;
7074 /** Create a file named <b>fname</b> with contents <b>str</b> in the
7075 * subdirectory <b>subdir</b> of the data directory. <b>descr</b>
7076 * should be a short description of the file's content and will be
7077 * used for the warning message, if it's present and the write process
7078 * fails. Return 0 on success, -1 otherwise.*/
7080 write_to_data_subdir(const char* subdir, const char* fname,
7081 const char* str, const char* descr)
7083 char *filename = get_datadir_fname2(subdir, fname);
7084 int return_val = 0;
7086 if (write_str_to_file(filename, str, 0) < 0) {
7087 log_warn(LD_HIST, "Unable to write %s to disk!", descr ? descr : fname);
7088 return_val = -1;
7090 tor_free(filename);
7091 return return_val;
7094 /** Given a file name check to see whether the file exists but has not been
7095 * modified for a very long time. If so, remove it. */
7096 void
7097 remove_file_if_very_old(const char *fname, time_t now)
7099 #define VERY_OLD_FILE_AGE (28*24*60*60)
7100 struct stat st;
7102 log_debug(LD_FS, "stat()ing %s", fname);
7103 if (stat(sandbox_intern_string(fname), &st)==0 &&
7104 st.st_mtime < now-VERY_OLD_FILE_AGE) {
7105 char buf[ISO_TIME_LEN+1];
7106 format_local_iso_time(buf, st.st_mtime);
7107 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
7108 "Removing it.", fname, buf);
7109 if (unlink(fname) != 0) {
7110 log_warn(LD_FS, "Failed to unlink %s: %s",
7111 fname, strerror(errno));
7116 /** Return a smartlist of ports that must be forwarded by
7117 * tor-fw-helper. The smartlist contains the ports in a string format
7118 * that is understandable by tor-fw-helper. */
7119 smartlist_t *
7120 get_list_of_ports_to_forward(void)
7122 smartlist_t *ports_to_forward = smartlist_new();
7123 int port = 0;
7125 /** XXX TODO tor-fw-helper does not support forwarding ports to
7126 other hosts than the local one. If the user is binding to a
7127 different IP address, tor-fw-helper won't work. */
7128 port = router_get_advertised_or_port(get_options()); /* Get ORPort */
7129 if (port)
7130 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
7132 port = router_get_advertised_dir_port(get_options(), 0); /* Get DirPort */
7133 if (port)
7134 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
7136 /* Get ports of transport proxies */
7138 smartlist_t *transport_ports = get_transport_proxy_ports();
7139 if (transport_ports) {
7140 smartlist_add_all(ports_to_forward, transport_ports);
7141 smartlist_free(transport_ports);
7145 if (!smartlist_len(ports_to_forward)) {
7146 smartlist_free(ports_to_forward);
7147 ports_to_forward = NULL;
7150 return ports_to_forward;
7153 /** Helper to implement GETINFO functions about configuration variables (not
7154 * their values). Given a "config/names" question, set *<b>answer</b> to a
7155 * new string describing the supported configuration variables and their
7156 * types. */
7158 getinfo_helper_config(control_connection_t *conn,
7159 const char *question, char **answer,
7160 const char **errmsg)
7162 (void) conn;
7163 (void) errmsg;
7164 if (!strcmp(question, "config/names")) {
7165 smartlist_t *sl = smartlist_new();
7166 int i;
7167 for (i = 0; option_vars_[i].name; ++i) {
7168 const config_var_t *var = &option_vars_[i];
7169 const char *type;
7170 /* don't tell controller about triple-underscore options */
7171 if (!strncmp(option_vars_[i].name, "___", 3))
7172 continue;
7173 switch (var->type) {
7174 case CONFIG_TYPE_STRING: type = "String"; break;
7175 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
7176 case CONFIG_TYPE_UINT: type = "Integer"; break;
7177 case CONFIG_TYPE_INT: type = "SignedInteger"; break;
7178 case CONFIG_TYPE_PORT: type = "Port"; break;
7179 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
7180 case CONFIG_TYPE_MSEC_INTERVAL: type = "TimeMsecInterval"; break;
7181 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
7182 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
7183 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
7184 case CONFIG_TYPE_AUTOBOOL: type = "Boolean+Auto"; break;
7185 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
7186 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
7187 case CONFIG_TYPE_CSV: type = "CommaList"; break;
7188 case CONFIG_TYPE_CSV_INTERVAL: type = "TimeIntervalCommaList"; break;
7189 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
7190 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
7191 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
7192 default:
7193 case CONFIG_TYPE_OBSOLETE:
7194 type = NULL; break;
7196 if (!type)
7197 continue;
7198 smartlist_add_asprintf(sl, "%s %s\n",var->name,type);
7200 *answer = smartlist_join_strings(sl, "", 0, NULL);
7201 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
7202 smartlist_free(sl);
7203 } else if (!strcmp(question, "config/defaults")) {
7204 smartlist_t *sl = smartlist_new();
7205 int i, dirauth_lines_seen = 0;
7206 for (i = 0; option_vars_[i].name; ++i) {
7207 const config_var_t *var = &option_vars_[i];
7208 if (var->initvalue != NULL) {
7209 if (strcmp(option_vars_[i].name, "DirAuthority") == 0) {
7211 * Count dirauth lines we have a default for; we'll use the
7212 * count later to decide whether to add the defaults manually
7214 ++dirauth_lines_seen;
7216 char *val = esc_for_log(var->initvalue);
7217 smartlist_add_asprintf(sl, "%s %s\n",var->name,val);
7218 tor_free(val);
7222 if (dirauth_lines_seen == 0) {
7224 * We didn't see any directory authorities with default values,
7225 * so add the list of default authorities manually.
7227 const char **i;
7230 * default_authorities is defined earlier in this file and
7231 * is a const char ** NULL-terminated array of dirauth config
7232 * lines.
7234 for (i = default_authorities; *i != NULL; ++i) {
7235 char *val = esc_for_log(*i);
7236 smartlist_add_asprintf(sl, "DirAuthority %s\n", val);
7237 tor_free(val);
7241 *answer = smartlist_join_strings(sl, "", 0, NULL);
7242 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
7243 smartlist_free(sl);
7245 return 0;
7248 /** Parse outbound bind address option lines. If <b>validate_only</b>
7249 * is not 0 update OutboundBindAddressIPv4_ and
7250 * OutboundBindAddressIPv6_ in <b>options</b>. On failure, set
7251 * <b>msg</b> (if provided) to a newly allocated string containing a
7252 * description of the problem and return -1. */
7253 static int
7254 parse_outbound_addresses(or_options_t *options, int validate_only, char **msg)
7256 const config_line_t *lines = options->OutboundBindAddress;
7257 int found_v4 = 0, found_v6 = 0;
7259 if (!validate_only) {
7260 memset(&options->OutboundBindAddressIPv4_, 0,
7261 sizeof(options->OutboundBindAddressIPv4_));
7262 memset(&options->OutboundBindAddressIPv6_, 0,
7263 sizeof(options->OutboundBindAddressIPv6_));
7265 while (lines) {
7266 tor_addr_t addr, *dst_addr = NULL;
7267 int af = tor_addr_parse(&addr, lines->value);
7268 switch (af) {
7269 case AF_INET:
7270 if (found_v4) {
7271 if (msg)
7272 tor_asprintf(msg, "Multiple IPv4 outbound bind addresses "
7273 "configured: %s", lines->value);
7274 return -1;
7276 found_v4 = 1;
7277 dst_addr = &options->OutboundBindAddressIPv4_;
7278 break;
7279 case AF_INET6:
7280 if (found_v6) {
7281 if (msg)
7282 tor_asprintf(msg, "Multiple IPv6 outbound bind addresses "
7283 "configured: %s", lines->value);
7284 return -1;
7286 found_v6 = 1;
7287 dst_addr = &options->OutboundBindAddressIPv6_;
7288 break;
7289 default:
7290 if (msg)
7291 tor_asprintf(msg, "Outbound bind address '%s' didn't parse.",
7292 lines->value);
7293 return -1;
7295 if (!validate_only)
7296 tor_addr_copy(dst_addr, &addr);
7297 lines = lines->next;
7299 return 0;
7302 /** Load one of the geoip files, <a>family</a> determining which
7303 * one. <a>default_fname</a> is used if on Windows and
7304 * <a>fname</a> equals "<default>". */
7305 static void
7306 config_load_geoip_file_(sa_family_t family,
7307 const char *fname,
7308 const char *default_fname)
7310 #ifdef _WIN32
7311 char *free_fname = NULL; /* Used to hold any temporary-allocated value */
7312 /* XXXX Don't use this "<default>" junk; make our filename options
7313 * understand prefixes somehow. -NM */
7314 if (!strcmp(fname, "<default>")) {
7315 const char *conf_root = get_windows_conf_root();
7316 tor_asprintf(&free_fname, "%s\\%s", conf_root, default_fname);
7317 fname = free_fname;
7319 geoip_load_file(family, fname);
7320 tor_free(free_fname);
7321 #else
7322 (void)default_fname;
7323 geoip_load_file(family, fname);
7324 #endif
7327 /** Load geoip files for IPv4 and IPv6 if <a>options</a> and
7328 * <a>old_options</a> indicate we should. */
7329 static void
7330 config_maybe_load_geoip_files_(const or_options_t *options,
7331 const or_options_t *old_options)
7333 /* XXXX024 Reload GeoIPFile on SIGHUP. -NM */
7335 if (options->GeoIPFile &&
7336 ((!old_options || !opt_streq(old_options->GeoIPFile,
7337 options->GeoIPFile))
7338 || !geoip_is_loaded(AF_INET)))
7339 config_load_geoip_file_(AF_INET, options->GeoIPFile, "geoip");
7340 if (options->GeoIPv6File &&
7341 ((!old_options || !opt_streq(old_options->GeoIPv6File,
7342 options->GeoIPv6File))
7343 || !geoip_is_loaded(AF_INET6)))
7344 config_load_geoip_file_(AF_INET6, options->GeoIPv6File, "geoip6");
7347 /** Initialize cookie authentication (used so far by the ControlPort
7348 * and Extended ORPort).
7350 * Allocate memory and create a cookie (of length <b>cookie_len</b>)
7351 * in <b>cookie_out</b>.
7352 * Then write it down to <b>fname</b> and prepend it with <b>header</b>.
7354 * If <b>group_readable</b> is set, set <b>fname</b> to be readable
7355 * by the default GID.
7357 * If the whole procedure was successful, set
7358 * <b>cookie_is_set_out</b> to True. */
7360 init_cookie_authentication(const char *fname, const char *header,
7361 int cookie_len, int group_readable,
7362 uint8_t **cookie_out, int *cookie_is_set_out)
7364 char cookie_file_str_len = strlen(header) + cookie_len;
7365 char *cookie_file_str = tor_malloc(cookie_file_str_len);
7366 int retval = -1;
7368 /* We don't want to generate a new cookie every time we call
7369 * options_act(). One should be enough. */
7370 if (*cookie_is_set_out) {
7371 retval = 0; /* we are all set */
7372 goto done;
7375 /* If we've already set the cookie, free it before re-setting
7376 it. This can happen if we previously generated a cookie, but
7377 couldn't write it to a disk. */
7378 if (*cookie_out)
7379 tor_free(*cookie_out);
7381 /* Generate the cookie */
7382 *cookie_out = tor_malloc(cookie_len);
7383 crypto_rand((char *)*cookie_out, cookie_len);
7385 /* Create the string that should be written on the file. */
7386 memcpy(cookie_file_str, header, strlen(header));
7387 memcpy(cookie_file_str+strlen(header), *cookie_out, cookie_len);
7388 if (write_bytes_to_file(fname, cookie_file_str, cookie_file_str_len, 1)) {
7389 log_warn(LD_FS,"Error writing auth cookie to %s.", escaped(fname));
7390 goto done;
7393 #ifndef _WIN32
7394 if (group_readable) {
7395 if (chmod(fname, 0640)) {
7396 log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
7399 #else
7400 (void) group_readable;
7401 #endif
7403 /* Success! */
7404 log_info(LD_GENERAL, "Generated auth cookie file in '%s'.", escaped(fname));
7405 *cookie_is_set_out = 1;
7406 retval = 0;
7408 done:
7409 memwipe(cookie_file_str, 0, cookie_file_str_len);
7410 tor_free(cookie_file_str);
7411 return retval;