Implement proposal 221: Stop sending CREATE_FAST
[tor.git] / src / or / config.c
blob1de91878b70d8988f8b6064b575c54ea8d5ce314
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-2013, 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
14 #include "or.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 "util.h"
44 #include "routerlist.h"
45 #include "routerset.h"
46 #include "statefile.h"
47 #include "transports.h"
48 #ifdef _WIN32
49 #include <shlobj.h>
50 #endif
52 #include "procmon.h"
54 /* From main.c */
55 extern int quiet_level;
57 /** A list of abbreviations and aliases to map command-line options, obsolete
58 * option names, or alternative option names, to their current values. */
59 static config_abbrev_t option_abbrevs_[] = {
60 PLURAL(AuthDirBadDirCC),
61 PLURAL(AuthDirBadExitCC),
62 PLURAL(AuthDirInvalidCC),
63 PLURAL(AuthDirRejectCC),
64 PLURAL(ExitNode),
65 PLURAL(EntryNode),
66 PLURAL(ExcludeNode),
67 PLURAL(FirewallPort),
68 PLURAL(LongLivedPort),
69 PLURAL(HiddenServiceNode),
70 PLURAL(HiddenServiceExcludeNode),
71 PLURAL(NumCPU),
72 PLURAL(RendNode),
73 PLURAL(RendExcludeNode),
74 PLURAL(StrictEntryNode),
75 PLURAL(StrictExitNode),
76 PLURAL(StrictNode),
77 { "l", "Log", 1, 0},
78 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
79 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
80 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
81 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
82 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
83 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
84 { "DirServer", "DirAuthority", 0, 0}, /* XXXX024 later, make this warn? */
85 { "MaxConn", "ConnLimit", 0, 1},
86 { "ORBindAddress", "ORListenAddress", 0, 0},
87 { "DirBindAddress", "DirListenAddress", 0, 0},
88 { "SocksBindAddress", "SocksListenAddress", 0, 0},
89 { "UseHelperNodes", "UseEntryGuards", 0, 0},
90 { "NumHelperNodes", "NumEntryGuards", 0, 0},
91 { "UseEntryNodes", "UseEntryGuards", 0, 0},
92 { "NumEntryNodes", "NumEntryGuards", 0, 0},
93 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
94 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
95 { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0},
96 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
97 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
98 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
99 { "StrictEntryNodes", "StrictNodes", 0, 1},
100 { "StrictExitNodes", "StrictNodes", 0, 1},
101 { "VirtualAddrNetwork", "VirtualAddrNetworkIPv4", 0, 0},
102 { "_UseFilteringSSLBufferevents", "UseFilteringSSLBufferevents", 0, 1},
103 { NULL, NULL, 0, 0},
106 /** An entry for config_vars: "The option <b>name</b> has type
107 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
108 * or_options_t.<b>member</b>"
110 #define VAR(name,conftype,member,initvalue) \
111 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
112 initvalue }
113 /** As VAR, but the option name and member name are the same. */
114 #define V(member,conftype,initvalue) \
115 VAR(#member, conftype, member, initvalue)
116 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
117 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
119 #define VPORT(member,conftype,initvalue) \
120 VAR(#member, conftype, member ## _lines, initvalue)
122 /** Array of configuration options. Until we disallow nonstandard
123 * abbreviations, order is significant, since the first matching option will
124 * be chosen first.
126 static config_var_t option_vars_[] = {
127 OBSOLETE("AccountingMaxKB"),
128 V(AccountingMax, MEMUNIT, "0 bytes"),
129 V(AccountingStart, STRING, NULL),
130 V(Address, STRING, NULL),
131 V(AllowDotExit, BOOL, "0"),
132 V(AllowInvalidNodes, CSV, "middle,rendezvous"),
133 V(AllowNonRFC953Hostnames, BOOL, "0"),
134 V(AllowSingleHopCircuits, BOOL, "0"),
135 V(AllowSingleHopExits, BOOL, "0"),
136 V(AlternateBridgeAuthority, LINELIST, NULL),
137 V(AlternateDirAuthority, LINELIST, NULL),
138 V(AlternateHSAuthority, LINELIST, NULL),
139 V(AssumeReachable, BOOL, "0"),
140 V(AuthDirBadDir, LINELIST, NULL),
141 V(AuthDirBadDirCCs, CSV, ""),
142 V(AuthDirBadExit, LINELIST, NULL),
143 V(AuthDirBadExitCCs, CSV, ""),
144 V(AuthDirInvalid, LINELIST, NULL),
145 V(AuthDirInvalidCCs, CSV, ""),
146 V(AuthDirFastGuarantee, MEMUNIT, "100 KB"),
147 V(AuthDirGuardBWGuarantee, MEMUNIT, "250 KB"),
148 V(AuthDirReject, LINELIST, NULL),
149 V(AuthDirRejectCCs, CSV, ""),
150 V(AuthDirRejectUnlisted, BOOL, "0"),
151 V(AuthDirListBadDirs, BOOL, "0"),
152 V(AuthDirListBadExits, BOOL, "0"),
153 V(AuthDirMaxServersPerAddr, UINT, "2"),
154 V(AuthDirMaxServersPerAuthAddr,UINT, "5"),
155 V(AuthDirHasIPv6Connectivity, BOOL, "0"),
156 VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
157 V(AutomapHostsOnResolve, BOOL, "0"),
158 V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
159 V(AvoidDiskWrites, BOOL, "0"),
160 V(BandwidthBurst, MEMUNIT, "1 GB"),
161 V(BandwidthRate, MEMUNIT, "1 GB"),
162 V(BridgeAuthoritativeDir, BOOL, "0"),
163 VAR("Bridge", LINELIST, Bridges, NULL),
164 V(BridgePassword, STRING, NULL),
165 V(BridgeRecordUsageByCountry, BOOL, "1"),
166 V(BridgeRelay, BOOL, "0"),
167 V(CellStatistics, BOOL, "0"),
168 V(LearnCircuitBuildTimeout, BOOL, "1"),
169 V(CircuitBuildTimeout, INTERVAL, "0"),
170 V(CircuitIdleTimeout, INTERVAL, "1 hour"),
171 V(CircuitStreamTimeout, INTERVAL, "0"),
172 V(CircuitPriorityHalflife, DOUBLE, "-100.0"), /*negative:'Use default'*/
173 V(ClientDNSRejectInternalAddresses, BOOL,"1"),
174 V(ClientOnly, BOOL, "0"),
175 V(ClientPreferIPv6ORPort, BOOL, "0"),
176 V(ClientRejectInternalAddresses, BOOL, "1"),
177 V(ClientTransportPlugin, LINELIST, NULL),
178 V(ClientUseIPv6, BOOL, "0"),
179 V(ConsensusParams, STRING, NULL),
180 V(ConnLimit, UINT, "1000"),
181 V(ConnDirectionStatistics, BOOL, "0"),
182 V(ConstrainedSockets, BOOL, "0"),
183 V(ConstrainedSockSize, MEMUNIT, "8192"),
184 V(ContactInfo, STRING, NULL),
185 V(ControlListenAddress, LINELIST, NULL),
186 VPORT(ControlPort, LINELIST, NULL),
187 V(ControlPortFileGroupReadable,BOOL, "0"),
188 V(ControlPortWriteToFile, FILENAME, NULL),
189 V(ControlSocket, LINELIST, NULL),
190 V(ControlSocketsGroupWritable, BOOL, "0"),
191 V(CookieAuthentication, BOOL, "0"),
192 V(CookieAuthFileGroupReadable, BOOL, "0"),
193 V(CookieAuthFile, STRING, NULL),
194 V(CountPrivateBandwidth, BOOL, "0"),
195 V(DataDirectory, FILENAME, NULL),
196 OBSOLETE("DebugLogFile"),
197 V(DisableNetwork, BOOL, "0"),
198 V(DirAllowPrivateAddresses, BOOL, "0"),
199 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
200 V(DirListenAddress, LINELIST, NULL),
201 OBSOLETE("DirFetchPeriod"),
202 V(DirPolicy, LINELIST, NULL),
203 VPORT(DirPort, LINELIST, NULL),
204 V(DirPortFrontPage, FILENAME, NULL),
205 OBSOLETE("DirPostPeriod"),
206 OBSOLETE("DirRecordUsageByCountry"),
207 OBSOLETE("DirRecordUsageGranularity"),
208 OBSOLETE("DirRecordUsageRetainIPs"),
209 OBSOLETE("DirRecordUsageSaveInterval"),
210 V(DirReqStatistics, BOOL, "1"),
211 VAR("DirAuthority", LINELIST, DirAuthorities, NULL),
212 V(DirAuthorityFallbackRate, DOUBLE, "1.0"),
213 V(DisableAllSwap, BOOL, "0"),
214 V(DisableDebuggerAttachment, BOOL, "1"),
215 V(DisableIOCP, BOOL, "1"),
216 V(DisableV2DirectoryInfo_, BOOL, "0"),
217 V(DynamicDHGroups, BOOL, "0"),
218 VPORT(DNSPort, LINELIST, NULL),
219 V(DNSListenAddress, LINELIST, NULL),
220 V(DownloadExtraInfo, BOOL, "0"),
221 V(EnforceDistinctSubnets, BOOL, "1"),
222 V(EntryNodes, ROUTERSET, NULL),
223 V(EntryStatistics, BOOL, "0"),
224 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
225 V(ExcludeNodes, ROUTERSET, NULL),
226 V(ExcludeExitNodes, ROUTERSET, NULL),
227 V(ExcludeSingleHopRelays, BOOL, "1"),
228 V(ExitNodes, ROUTERSET, NULL),
229 V(ExitPolicy, LINELIST, NULL),
230 V(ExitPolicyRejectPrivate, BOOL, "1"),
231 V(ExitPortStatistics, BOOL, "0"),
232 V(ExtendAllowPrivateAddresses, BOOL, "0"),
233 V(ExtraInfoStatistics, BOOL, "1"),
234 V(FallbackDir, LINELIST, NULL),
236 OBSOLETE("FallbackNetworkstatusFile"),
237 V(FascistFirewall, BOOL, "0"),
238 V(FirewallPorts, CSV, ""),
239 V(FastFirstHopPK, AUTOBOOL, "auto"),
240 V(FetchDirInfoEarly, BOOL, "0"),
241 V(FetchDirInfoExtraEarly, BOOL, "0"),
242 V(FetchServerDescriptors, BOOL, "1"),
243 V(FetchHidServDescriptors, BOOL, "1"),
244 V(FetchUselessDescriptors, BOOL, "0"),
245 V(FetchV2Networkstatus, BOOL, "0"),
246 V(GeoIPExcludeUnknown, AUTOBOOL, "auto"),
247 #ifdef _WIN32
248 V(GeoIPFile, FILENAME, "<default>"),
249 V(GeoIPv6File, FILENAME, "<default>"),
250 #else
251 V(GeoIPFile, FILENAME,
252 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
253 V(GeoIPv6File, FILENAME,
254 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip6"),
255 #endif
256 OBSOLETE("GiveGuardFlagTo_CVE_2011_2768_VulnerableRelays"),
257 OBSOLETE("Group"),
258 V(GuardLifetime, INTERVAL, "0 minutes"),
259 V(HardwareAccel, BOOL, "0"),
260 V(HeartbeatPeriod, INTERVAL, "6 hours"),
261 V(AccelName, STRING, NULL),
262 V(AccelDir, FILENAME, NULL),
263 V(HashedControlPassword, LINELIST, NULL),
264 V(HidServDirectoryV2, BOOL, "1"),
265 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
266 OBSOLETE("HiddenServiceExcludeNodes"),
267 OBSOLETE("HiddenServiceNodes"),
268 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
269 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
270 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
271 VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
272 V(HidServAuth, LINELIST, NULL),
273 V(HSAuthoritativeDir, BOOL, "0"),
274 OBSOLETE("HSAuthorityRecordStats"),
275 V(CloseHSClientCircuitsImmediatelyOnTimeout, BOOL, "0"),
276 V(CloseHSServiceRendCircuitsImmediatelyOnTimeout, BOOL, "0"),
277 V(HTTPProxy, STRING, NULL),
278 V(HTTPProxyAuthenticator, STRING, NULL),
279 V(HTTPSProxy, STRING, NULL),
280 V(HTTPSProxyAuthenticator, STRING, NULL),
281 V(IPv6Exit, BOOL, "0"),
282 VAR("ServerTransportPlugin", LINELIST, ServerTransportPlugin, NULL),
283 V(ServerTransportListenAddr, LINELIST, NULL),
284 V(Socks4Proxy, STRING, NULL),
285 V(Socks5Proxy, STRING, NULL),
286 V(Socks5ProxyUsername, STRING, NULL),
287 V(Socks5ProxyPassword, STRING, NULL),
288 OBSOLETE("IgnoreVersion"),
289 V(KeepalivePeriod, INTERVAL, "5 minutes"),
290 VAR("Log", LINELIST, Logs, NULL),
291 V(LogMessageDomains, BOOL, "0"),
292 OBSOLETE("LinkPadding"),
293 OBSOLETE("LogLevel"),
294 OBSOLETE("LogFile"),
295 V(LogTimeGranularity, MSEC_INTERVAL, "1 second"),
296 V(LongLivedPorts, CSV,
297 "21,22,706,1863,5050,5190,5222,5223,6523,6667,6697,8300"),
298 VAR("MapAddress", LINELIST, AddressMap, NULL),
299 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
300 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
301 V(MaxClientCircuitsPending, UINT, "32"),
302 V(MaxMemInCellQueues, MEMUNIT, "8 GB"),
303 OBSOLETE("MaxOnionsPending"),
304 V(MaxOnionQueueDelay, MSEC_INTERVAL, "1750 msec"),
305 V(MinMeasuredBWsForAuthToIgnoreAdvertised, INT, "500"),
306 OBSOLETE("MonthlyAccountingStart"),
307 V(MyFamily, STRING, NULL),
308 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
309 VAR("NamingAuthoritativeDirectory",BOOL, NamingAuthoritativeDir, "0"),
310 V(NATDListenAddress, LINELIST, NULL),
311 VPORT(NATDPort, LINELIST, NULL),
312 V(Nickname, STRING, NULL),
313 V(WarnUnsafeSocks, BOOL, "1"),
314 OBSOLETE("NoPublish"),
315 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
316 V(NumCPUs, UINT, "0"),
317 V(NumDirectoryGuards, UINT, "0"),
318 V(NumEntryGuards, UINT, "0"),
319 V(ORListenAddress, LINELIST, NULL),
320 VPORT(ORPort, LINELIST, NULL),
321 V(OutboundBindAddress, LINELIST, NULL),
323 OBSOLETE("PathBiasDisableRate"),
324 V(PathBiasCircThreshold, INT, "-1"),
325 V(PathBiasNoticeRate, DOUBLE, "-1"),
326 V(PathBiasWarnRate, DOUBLE, "-1"),
327 V(PathBiasExtremeRate, DOUBLE, "-1"),
328 V(PathBiasScaleThreshold, INT, "-1"),
329 OBSOLETE("PathBiasScaleFactor"),
330 OBSOLETE("PathBiasMultFactor"),
331 V(PathBiasDropGuards, AUTOBOOL, "0"),
332 OBSOLETE("PathBiasUseCloseCounts"),
334 V(PathBiasUseThreshold, INT, "-1"),
335 V(PathBiasNoticeUseRate, DOUBLE, "-1"),
336 V(PathBiasExtremeUseRate, DOUBLE, "-1"),
337 V(PathBiasScaleUseThreshold, INT, "-1"),
339 V(PathsNeededToBuildCircuits, DOUBLE, "-1"),
340 OBSOLETE("PathlenCoinWeight"),
341 V(PerConnBWBurst, MEMUNIT, "0"),
342 V(PerConnBWRate, MEMUNIT, "0"),
343 V(PidFile, STRING, NULL),
344 V(TestingTorNetwork, BOOL, "0"),
345 V(TestingMinExitFlagThreshold, MEMUNIT, "0"),
346 V(TestingMinFastFlagThreshold, MEMUNIT, "0"),
347 V(OptimisticData, AUTOBOOL, "auto"),
348 V(PortForwarding, BOOL, "0"),
349 V(PortForwardingHelper, FILENAME, "tor-fw-helper"),
350 V(PreferTunneledDirConns, BOOL, "1"),
351 V(ProtocolWarnings, BOOL, "0"),
352 V(PublishServerDescriptor, CSV, "1"),
353 V(PublishHidServDescriptors, BOOL, "1"),
354 V(ReachableAddresses, LINELIST, NULL),
355 V(ReachableDirAddresses, LINELIST, NULL),
356 V(ReachableORAddresses, LINELIST, NULL),
357 V(RecommendedVersions, LINELIST, NULL),
358 V(RecommendedClientVersions, LINELIST, NULL),
359 V(RecommendedServerVersions, LINELIST, NULL),
360 OBSOLETE("RedirectExit"),
361 V(RefuseUnknownExits, AUTOBOOL, "auto"),
362 V(RejectPlaintextPorts, CSV, ""),
363 V(RelayBandwidthBurst, MEMUNIT, "0"),
364 V(RelayBandwidthRate, MEMUNIT, "0"),
365 OBSOLETE("RendExcludeNodes"),
366 OBSOLETE("RendNodes"),
367 V(RendPostPeriod, INTERVAL, "1 hour"),
368 V(RephistTrackTime, INTERVAL, "24 hours"),
369 OBSOLETE("RouterFile"),
370 V(RunAsDaemon, BOOL, "0"),
371 // V(RunTesting, BOOL, "0"),
372 OBSOLETE("RunTesting"), // currently unused
373 V(SafeLogging, STRING, "1"),
374 V(SafeSocks, BOOL, "0"),
375 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
376 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
377 V(ServerDNSDetectHijacking, BOOL, "1"),
378 V(ServerDNSRandomizeCase, BOOL, "1"),
379 V(ServerDNSResolvConfFile, STRING, NULL),
380 V(ServerDNSSearchDomains, BOOL, "0"),
381 V(ServerDNSTestAddresses, CSV,
382 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
383 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
384 V(SocksListenAddress, LINELIST, NULL),
385 V(SocksPolicy, LINELIST, NULL),
386 VPORT(SocksPort, LINELIST, NULL),
387 V(SocksTimeout, INTERVAL, "2 minutes"),
388 V(SSLKeyLifetime, INTERVAL, "0"),
389 OBSOLETE("StatusFetchPeriod"),
390 V(StrictNodes, BOOL, "0"),
391 V(Support022HiddenServices, AUTOBOOL, "auto"),
392 OBSOLETE("SysLog"),
393 V(TestSocks, BOOL, "0"),
394 OBSOLETE("TestVia"),
395 V(TokenBucketRefillInterval, MSEC_INTERVAL, "100 msec"),
396 V(Tor2webMode, BOOL, "0"),
397 V(TLSECGroup, STRING, NULL),
398 V(TrackHostExits, CSV, NULL),
399 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
400 OBSOLETE("TrafficShaping"),
401 V(TransListenAddress, LINELIST, NULL),
402 VPORT(TransPort, LINELIST, NULL),
403 V(TunnelDirConns, BOOL, "1"),
404 V(UpdateBridgesFromAuthority, BOOL, "0"),
405 V(UseBridges, BOOL, "0"),
406 V(UseEntryGuards, BOOL, "1"),
407 V(UseEntryGuardsAsDirGuards, BOOL, "1"),
408 V(UseMicrodescriptors, AUTOBOOL, "auto"),
409 V(UseNTorHandshake, AUTOBOOL, "auto"),
410 V(User, STRING, NULL),
411 V(UserspaceIOCPBuffers, BOOL, "0"),
412 VAR("V1AuthoritativeDirectory",BOOL, V1AuthoritativeDir, "0"),
413 VAR("V2AuthoritativeDirectory",BOOL, V2AuthoritativeDir, "0"),
414 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
415 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
416 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
417 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
418 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
419 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
420 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
421 V(V3AuthNIntervalsValid, UINT, "3"),
422 V(V3AuthUseLegacyKey, BOOL, "0"),
423 V(V3BandwidthsFile, FILENAME, NULL),
424 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
425 V(VirtualAddrNetworkIPv4, STRING, "127.192.0.0/10"),
426 V(VirtualAddrNetworkIPv6, STRING, "[FE80::]/10"),
427 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
428 V(UseFilteringSSLBufferevents, BOOL, "0"),
429 VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
430 VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
431 VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
432 VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
433 VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
434 NULL),
435 VAR("__OwningControllerProcess",STRING,OwningControllerProcess, NULL),
436 V(MinUptimeHidServDirectoryV2, INTERVAL, "25 hours"),
437 V(VoteOnHidServDirectoriesV2, BOOL, "1"),
438 VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "0"),
440 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
443 /** Override default values with these if the user sets the TestingTorNetwork
444 * option. */
445 static const config_var_t testing_tor_network_defaults[] = {
446 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
447 V(DirAllowPrivateAddresses, BOOL, "1"),
448 V(EnforceDistinctSubnets, BOOL, "0"),
449 V(AssumeReachable, BOOL, "1"),
450 V(AuthDirMaxServersPerAddr, UINT, "0"),
451 V(AuthDirMaxServersPerAuthAddr,UINT, "0"),
452 V(ClientDNSRejectInternalAddresses, BOOL,"0"),
453 V(ClientRejectInternalAddresses, BOOL, "0"),
454 V(CountPrivateBandwidth, BOOL, "1"),
455 V(ExitPolicyRejectPrivate, BOOL, "0"),
456 V(ExtendAllowPrivateAddresses, BOOL, "1"),
457 V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
458 V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
459 V(V3AuthDistDelay, INTERVAL, "20 seconds"),
460 V(TestingV3AuthInitialVotingInterval, INTERVAL, "5 minutes"),
461 V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
462 V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
463 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
464 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
465 V(MinUptimeHidServDirectoryV2, INTERVAL, "0 minutes"),
466 VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "1"),
468 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
471 #undef VAR
472 #undef V
473 #undef OBSOLETE
475 #ifdef _WIN32
476 static char *get_windows_conf_root(void);
477 #endif
478 static int options_validate(or_options_t *old_options,
479 or_options_t *options,
480 int from_setconf, char **msg);
481 static int options_act_reversible(const or_options_t *old_options, char **msg);
482 static int options_act(const or_options_t *old_options);
483 static int options_transition_allowed(const or_options_t *old,
484 const or_options_t *new,
485 char **msg);
486 static int options_transition_affects_workers(
487 const or_options_t *old_options, const or_options_t *new_options);
488 static int options_transition_affects_descriptor(
489 const or_options_t *old_options, const or_options_t *new_options);
490 static int check_nickname_list(const char *lst, const char *name, char **msg);
492 static int parse_bridge_line(const char *line, int validate_only);
493 static int parse_client_transport_line(const char *line, int validate_only);
495 static int parse_server_transport_line(const char *line, int validate_only);
496 static char *get_bindaddr_from_transport_listen_line(const char *line,
497 const char *transport);
498 static int parse_dir_authority_line(const char *line,
499 dirinfo_type_t required_type,
500 int validate_only);
501 static int parse_dir_fallback_line(const char *line,
502 int validate_only);
503 static void port_cfg_free(port_cfg_t *port);
504 static int parse_ports(or_options_t *options, int validate_only,
505 char **msg_out, int *n_ports_out);
506 static int check_server_ports(const smartlist_t *ports,
507 const or_options_t *options);
509 static int validate_data_directory(or_options_t *options);
510 static int write_configuration_file(const char *fname,
511 const or_options_t *options);
512 static int options_init_logs(or_options_t *options, int validate_only);
514 static void init_libevent(const or_options_t *options);
515 static int opt_streq(const char *s1, const char *s2);
516 static int parse_outbound_addresses(or_options_t *options, int validate_only,
517 char **msg);
518 static void config_maybe_load_geoip_files_(const or_options_t *options,
519 const or_options_t *old_options);
521 /** Magic value for or_options_t. */
522 #define OR_OPTIONS_MAGIC 9090909
524 /** Configuration format for or_options_t. */
525 static config_format_t options_format = {
526 sizeof(or_options_t),
527 OR_OPTIONS_MAGIC,
528 STRUCT_OFFSET(or_options_t, magic_),
529 option_abbrevs_,
530 option_vars_,
531 (validate_fn_t)options_validate,
532 NULL
536 * Functions to read and write the global options pointer.
539 /** Command-line and config-file options. */
540 static or_options_t *global_options = NULL;
541 /** The fallback options_t object; this is where we look for options not
542 * in torrc before we fall back to Tor's defaults. */
543 static or_options_t *global_default_options = NULL;
544 /** Name of most recently read torrc file. */
545 static char *torrc_fname = NULL;
546 /** Name of the most recently read torrc-defaults file.*/
547 static char *torrc_defaults_fname;
548 /** Configuration Options set by command line. */
549 static config_line_t *global_cmdline_options = NULL;
550 /** Contents of most recently read DirPortFrontPage file. */
551 static char *global_dirfrontpagecontents = NULL;
552 /** List of port_cfg_t for all configured ports. */
553 static smartlist_t *configured_ports = NULL;
555 /** Return the contents of our frontpage string, or NULL if not configured. */
556 const char *
557 get_dirportfrontpage(void)
559 return global_dirfrontpagecontents;
562 /** Return the currently configured options. */
563 or_options_t *
564 get_options_mutable(void)
566 tor_assert(global_options);
567 return global_options;
570 /** Returns the currently configured options */
571 const or_options_t *
572 get_options(void)
574 return get_options_mutable();
577 /** Change the current global options to contain <b>new_val</b> instead of
578 * their current value; take action based on the new value; free the old value
579 * as necessary. Returns 0 on success, -1 on failure.
582 set_options(or_options_t *new_val, char **msg)
584 int i;
585 smartlist_t *elements;
586 config_line_t *line;
587 or_options_t *old_options = global_options;
588 global_options = new_val;
589 /* Note that we pass the *old* options below, for comparison. It
590 * pulls the new options directly out of global_options. */
591 if (options_act_reversible(old_options, msg)<0) {
592 tor_assert(*msg);
593 global_options = old_options;
594 return -1;
596 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
597 log_err(LD_BUG,
598 "Acting on config options left us in a broken state. Dying.");
599 exit(1);
601 /* Issues a CONF_CHANGED event to notify controller of the change. If Tor is
602 * just starting up then the old_options will be undefined. */
603 if (old_options && old_options != global_options) {
604 elements = smartlist_new();
605 for (i=0; options_format.vars[i].name; ++i) {
606 const config_var_t *var = &options_format.vars[i];
607 const char *var_name = var->name;
608 if (var->type == CONFIG_TYPE_LINELIST_S ||
609 var->type == CONFIG_TYPE_OBSOLETE) {
610 continue;
612 if (!config_is_same(&options_format, new_val, old_options, var_name)) {
613 line = config_get_assigned_option(&options_format, new_val,
614 var_name, 1);
616 if (line) {
617 config_line_t *next;
618 for (; line; line = next) {
619 next = line->next;
620 smartlist_add(elements, line->key);
621 smartlist_add(elements, line->value);
622 tor_free(line);
624 } else {
625 smartlist_add(elements, tor_strdup(options_format.vars[i].name));
626 smartlist_add(elements, NULL);
630 control_event_conf_changed(elements);
631 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
632 smartlist_free(elements);
635 if (old_options != global_options)
636 config_free(&options_format, old_options);
638 return 0;
641 extern const char tor_git_revision[]; /* from tor_main.c */
643 /** The version of this Tor process, as parsed. */
644 static char *the_tor_version = NULL;
645 /** A shorter version of this Tor process's version, for export in our router
646 * descriptor. (Does not include the git version, if any.) */
647 static char *the_short_tor_version = NULL;
649 /** Return the current Tor version. */
650 const char *
651 get_version(void)
653 if (the_tor_version == NULL) {
654 if (strlen(tor_git_revision)) {
655 tor_asprintf(&the_tor_version, "%s (git-%s)", get_short_version(),
656 tor_git_revision);
657 } else {
658 the_tor_version = tor_strdup(get_short_version());
661 return the_tor_version;
664 /** Return the current Tor version, without any git tag. */
665 const char *
666 get_short_version(void)
669 if (the_short_tor_version == NULL) {
670 #ifdef TOR_BUILD_TAG
671 tor_asprintf(&the_short_tor_version, "%s (%s)", VERSION, TOR_BUILD_TAG);
672 #else
673 the_short_tor_version = tor_strdup(VERSION);
674 #endif
676 return the_short_tor_version;
679 /** Release additional memory allocated in options
681 static void
682 or_options_free(or_options_t *options)
684 if (!options)
685 return;
687 routerset_free(options->ExcludeExitNodesUnion_);
688 if (options->NodeFamilySets) {
689 SMARTLIST_FOREACH(options->NodeFamilySets, routerset_t *,
690 rs, routerset_free(rs));
691 smartlist_free(options->NodeFamilySets);
693 tor_free(options->BridgePassword_AuthDigest_);
694 config_free(&options_format, options);
697 /** Release all memory and resources held by global configuration structures.
699 void
700 config_free_all(void)
702 or_options_free(global_options);
703 global_options = NULL;
704 or_options_free(global_default_options);
705 global_default_options = NULL;
707 config_free_lines(global_cmdline_options);
708 global_cmdline_options = NULL;
710 if (configured_ports) {
711 SMARTLIST_FOREACH(configured_ports,
712 port_cfg_t *, p, port_cfg_free(p));
713 smartlist_free(configured_ports);
714 configured_ports = NULL;
717 tor_free(torrc_fname);
718 tor_free(torrc_defaults_fname);
719 tor_free(the_tor_version);
720 tor_free(global_dirfrontpagecontents);
722 tor_free(the_short_tor_version);
723 tor_free(the_tor_version);
726 /** Make <b>address</b> -- a piece of information related to our operation as
727 * a client -- safe to log according to the settings in options->SafeLogging,
728 * and return it.
730 * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
732 const char *
733 safe_str_client(const char *address)
735 tor_assert(address);
736 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
737 return "[scrubbed]";
738 else
739 return address;
742 /** Make <b>address</b> -- a piece of information of unspecified sensitivity
743 * -- safe to log according to the settings in options->SafeLogging, and
744 * return it.
746 * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
747 * otherwise.)
749 const char *
750 safe_str(const char *address)
752 tor_assert(address);
753 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
754 return "[scrubbed]";
755 else
756 return address;
759 /** Equivalent to escaped(safe_str_client(address)). See reentrancy note on
760 * escaped(): don't use this outside the main thread, or twice in the same
761 * log statement. */
762 const char *
763 escaped_safe_str_client(const char *address)
765 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
766 return "[scrubbed]";
767 else
768 return escaped(address);
771 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
772 * escaped(): don't use this outside the main thread, or twice in the same
773 * log statement. */
774 const char *
775 escaped_safe_str(const char *address)
777 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
778 return "[scrubbed]";
779 else
780 return escaped(address);
783 /** Add the default directory authorities directly into the trusted dir list,
784 * but only add them insofar as they share bits with <b>type</b>. */
785 static void
786 add_default_trusted_dir_authorities(dirinfo_type_t type)
788 int i;
789 const char *authorities[] = {
790 "moria1 orport=9101 no-v2 "
791 "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
792 "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
793 "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
794 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
795 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
796 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
797 "Tonga orport=443 bridge no-v2 82.94.251.203:80 "
798 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
799 "turtles orport=9090 no-v2 "
800 "v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
801 "76.73.17.194:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
802 "gabelmoo orport=443 no-v2 "
803 "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
804 "212.112.245.170:80 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
805 "dannenberg orport=443 no-v2 "
806 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
807 "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
808 "urras orport=80 no-v2 v3ident=80550987E1D626E3EBA5E5E75A458DE0626D088C "
809 "208.83.223.34:443 0AD3 FA88 4D18 F89E EA2D 89C0 1937 9E0E 7FD9 4417",
810 "maatuska orport=80 no-v2 "
811 "v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
812 "171.25.193.9:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
813 "Faravahar orport=443 no-v2 "
814 "v3ident=EFCBE720AB3A82B99F9E953CD5BF50F7EEFC7B97 "
815 "154.35.32.5:80 CF6D 0AAF B385 BE71 B8E1 11FC 5CFF 4B47 9237 33BC",
816 NULL
818 for (i=0; authorities[i]; i++) {
819 if (parse_dir_authority_line(authorities[i], type, 0)<0) {
820 log_err(LD_BUG, "Couldn't parse internal DirAuthority line %s",
821 authorities[i]);
826 /** Add the default fallback directory servers into the fallback directory
827 * server list. */
828 static void
829 add_default_fallback_dir_servers(void)
831 int i;
832 const char *fallback[] = {
833 NULL
835 for (i=0; fallback[i]; i++) {
836 if (parse_dir_fallback_line(fallback[i], 0)<0) {
837 log_err(LD_BUG, "Couldn't parse internal FallbackDir line %s",
838 fallback[i]);
843 /** Look at all the config options for using alternate directory
844 * authorities, and make sure none of them are broken. Also, warn the
845 * user if we changed any dangerous ones.
847 static int
848 validate_dir_servers(or_options_t *options, or_options_t *old_options)
850 config_line_t *cl;
852 if (options->DirAuthorities &&
853 (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
854 options->AlternateHSAuthority)) {
855 log_warn(LD_CONFIG,
856 "You cannot set both DirAuthority and Alternate*Authority.");
857 return -1;
860 /* do we want to complain to the user about being partitionable? */
861 if ((options->DirAuthorities &&
862 (!old_options ||
863 !config_lines_eq(options->DirAuthorities,
864 old_options->DirAuthorities))) ||
865 (options->AlternateDirAuthority &&
866 (!old_options ||
867 !config_lines_eq(options->AlternateDirAuthority,
868 old_options->AlternateDirAuthority)))) {
869 log_warn(LD_CONFIG,
870 "You have used DirAuthority or AlternateDirAuthority to "
871 "specify alternate directory authorities in "
872 "your configuration. This is potentially dangerous: it can "
873 "make you look different from all other Tor users, and hurt "
874 "your anonymity. Even if you've specified the same "
875 "authorities as Tor uses by default, the defaults could "
876 "change in the future. Be sure you know what you're doing.");
879 /* Now go through the four ways you can configure an alternate
880 * set of directory authorities, and make sure none are broken. */
881 for (cl = options->DirAuthorities; cl; cl = cl->next)
882 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
883 return -1;
884 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
885 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
886 return -1;
887 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
888 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
889 return -1;
890 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
891 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
892 return -1;
893 for (cl = options->FallbackDir; cl; cl = cl->next)
894 if (parse_dir_fallback_line(cl->value, 1)<0)
895 return -1;
896 return 0;
899 /** Look at all the config options and assign new dir authorities
900 * as appropriate.
902 static int
903 consider_adding_dir_servers(const or_options_t *options,
904 const or_options_t *old_options)
906 config_line_t *cl;
907 int need_to_update =
908 !smartlist_len(router_get_trusted_dir_servers()) ||
909 !smartlist_len(router_get_fallback_dir_servers()) || !old_options ||
910 !config_lines_eq(options->DirAuthorities, old_options->DirAuthorities) ||
911 !config_lines_eq(options->FallbackDir, old_options->FallbackDir) ||
912 !config_lines_eq(options->AlternateBridgeAuthority,
913 old_options->AlternateBridgeAuthority) ||
914 !config_lines_eq(options->AlternateDirAuthority,
915 old_options->AlternateDirAuthority) ||
916 !config_lines_eq(options->AlternateHSAuthority,
917 old_options->AlternateHSAuthority);
919 if (!need_to_update)
920 return 0; /* all done */
922 /* Start from a clean slate. */
923 clear_dir_servers();
925 if (!options->DirAuthorities) {
926 /* then we may want some of the defaults */
927 dirinfo_type_t type = NO_DIRINFO;
928 if (!options->AlternateBridgeAuthority)
929 type |= BRIDGE_DIRINFO;
930 if (!options->AlternateDirAuthority)
931 type |= V1_DIRINFO | V2_DIRINFO | V3_DIRINFO | EXTRAINFO_DIRINFO |
932 MICRODESC_DIRINFO;
933 if (!options->AlternateHSAuthority)
934 type |= HIDSERV_DIRINFO;
935 add_default_trusted_dir_authorities(type);
937 if (!options->FallbackDir)
938 add_default_fallback_dir_servers();
940 for (cl = options->DirAuthorities; cl; cl = cl->next)
941 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
942 return -1;
943 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
944 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
945 return -1;
946 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
947 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
948 return -1;
949 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
950 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
951 return -1;
952 for (cl = options->FallbackDir; cl; cl = cl->next)
953 if (parse_dir_fallback_line(cl->value, 0)<0)
954 return -1;
955 return 0;
958 /** Fetch the active option list, and take actions based on it. All of the
959 * things we do should survive being done repeatedly. If present,
960 * <b>old_options</b> contains the previous value of the options.
962 * Return 0 if all goes well, return -1 if things went badly.
964 static int
965 options_act_reversible(const or_options_t *old_options, char **msg)
967 smartlist_t *new_listeners = smartlist_new();
968 smartlist_t *replaced_listeners = smartlist_new();
969 static int libevent_initialized = 0;
970 or_options_t *options = get_options_mutable();
971 int running_tor = options->command == CMD_RUN_TOR;
972 int set_conn_limit = 0;
973 int r = -1;
974 int logs_marked = 0;
976 /* Daemonize _first_, since we only want to open most of this stuff in
977 * the subprocess. Libevent bases can't be reliably inherited across
978 * processes. */
979 if (running_tor && options->RunAsDaemon) {
980 /* No need to roll back, since you can't change the value. */
981 start_daemon();
984 #ifndef HAVE_SYS_UN_H
985 if (options->ControlSocket || options->ControlSocketsGroupWritable) {
986 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported "
987 "on this OS/with this build.");
988 goto rollback;
990 #else
991 if (options->ControlSocketsGroupWritable && !options->ControlSocket) {
992 *msg = tor_strdup("Setting ControlSocketGroupWritable without setting"
993 "a ControlSocket makes no sense.");
994 goto rollback;
996 #endif
998 if (running_tor) {
999 int n_ports=0;
1000 /* We need to set the connection limit before we can open the listeners. */
1001 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1002 &options->ConnLimit_) < 0) {
1003 *msg = tor_strdup("Problem with ConnLimit value. See logs for details.");
1004 goto rollback;
1006 set_conn_limit = 1;
1008 /* Set up libevent. (We need to do this before we can register the
1009 * listeners as listeners.) */
1010 if (running_tor && !libevent_initialized) {
1011 init_libevent(options);
1012 libevent_initialized = 1;
1015 /* Adjust the port configuration so we can launch listeners. */
1016 if (parse_ports(options, 0, msg, &n_ports)) {
1017 if (!*msg)
1018 *msg = tor_strdup("Unexpected problem parsing port config");
1019 goto rollback;
1022 /* Set the hibernation state appropriately.*/
1023 consider_hibernation(time(NULL));
1025 /* Launch the listeners. (We do this before we setuid, so we can bind to
1026 * ports under 1024.) We don't want to rebind if we're hibernating. If
1027 * networking is disabled, this will close all but the control listeners,
1028 * but disable those. */
1029 if (!we_are_hibernating()) {
1030 if (retry_all_listeners(replaced_listeners, new_listeners,
1031 options->DisableNetwork) < 0) {
1032 *msg = tor_strdup("Failed to bind one of the listener ports.");
1033 goto rollback;
1036 if (options->DisableNetwork) {
1037 /* Aggressively close non-controller stuff, NOW */
1038 log_notice(LD_NET, "DisableNetwork is set. Tor will not make or accept "
1039 "non-control network connections. Shutting down all existing "
1040 "connections.");
1041 connection_mark_all_noncontrol_connections();
1045 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1046 /* Open /dev/pf before dropping privileges. */
1047 if (options->TransPort_set) {
1048 if (get_pf_socket() < 0) {
1049 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1050 goto rollback;
1053 #endif
1055 /* Attempt to lock all current and future memory with mlockall() only once */
1056 if (options->DisableAllSwap) {
1057 if (tor_mlockall() == -1) {
1058 *msg = tor_strdup("DisableAllSwap failure. Do you have proper "
1059 "permissions?");
1060 goto done;
1064 /* Setuid/setgid as appropriate */
1065 if (options->User) {
1066 if (switch_id(options->User) != 0) {
1067 /* No need to roll back, since you can't change the value. */
1068 *msg = tor_strdup("Problem with User value. See logs for details.");
1069 goto done;
1073 /* Ensure data directory is private; create if possible. */
1074 if (check_private_dir(options->DataDirectory,
1075 running_tor ? CPD_CREATE : CPD_CHECK,
1076 options->User)<0) {
1077 tor_asprintf(msg,
1078 "Couldn't access/create private data directory \"%s\"",
1079 options->DataDirectory);
1080 goto done;
1081 /* No need to roll back, since you can't change the value. */
1084 /* Write control ports to disk as appropriate */
1085 control_ports_write_to_file();
1087 if (directory_caches_v2_dir_info(options)) {
1088 char *fn = NULL;
1089 tor_asprintf(&fn, "%s"PATH_SEPARATOR"cached-status",
1090 options->DataDirectory);
1091 if (check_private_dir(fn, running_tor ? CPD_CREATE : CPD_CHECK,
1092 options->User) < 0) {
1093 tor_asprintf(msg,
1094 "Couldn't access/create private data directory \"%s\"", fn);
1095 tor_free(fn);
1096 goto done;
1098 tor_free(fn);
1101 /* Bail out at this point if we're not going to be a client or server:
1102 * we don't run Tor itself. */
1103 if (!running_tor)
1104 goto commit;
1106 mark_logs_temp(); /* Close current logs once new logs are open. */
1107 logs_marked = 1;
1108 if (options_init_logs(options, 0)<0) { /* Configure the tor_log(s) */
1109 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1110 goto rollback;
1113 commit:
1114 r = 0;
1115 if (logs_marked) {
1116 log_severity_list_t *severity =
1117 tor_malloc_zero(sizeof(log_severity_list_t));
1118 close_temp_logs();
1119 add_callback_log(severity, control_event_logmsg);
1120 control_adjust_event_log_severity();
1121 tor_free(severity);
1123 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1125 log_notice(LD_NET, "Closing old %s on %s:%d",
1126 conn_type_to_string(conn->type), conn->address, conn->port);
1127 connection_close_immediate(conn);
1128 connection_mark_for_close(conn);
1130 goto done;
1132 rollback:
1133 r = -1;
1134 tor_assert(*msg);
1136 if (logs_marked) {
1137 rollback_log_changes();
1138 control_adjust_event_log_severity();
1141 if (set_conn_limit && old_options)
1142 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1143 &options->ConnLimit_);
1145 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1147 log_notice(LD_NET, "Closing partially-constructed %s on %s:%d",
1148 conn_type_to_string(conn->type), conn->address, conn->port);
1149 connection_close_immediate(conn);
1150 connection_mark_for_close(conn);
1153 done:
1154 smartlist_free(new_listeners);
1155 smartlist_free(replaced_listeners);
1156 return r;
1159 /** If we need to have a GEOIP ip-to-country map to run with our configured
1160 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1162 options_need_geoip_info(const or_options_t *options, const char **reason_out)
1164 int bridge_usage =
1165 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1166 int routerset_usage =
1167 routerset_needs_geoip(options->EntryNodes) ||
1168 routerset_needs_geoip(options->ExitNodes) ||
1169 routerset_needs_geoip(options->ExcludeExitNodes) ||
1170 routerset_needs_geoip(options->ExcludeNodes);
1172 if (routerset_usage && reason_out) {
1173 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1174 "countries, and we need GEOIP information to figure out which ones they "
1175 "are.";
1176 } else if (bridge_usage && reason_out) {
1177 *reason_out = "We've been configured to see which countries can access "
1178 "us as a bridge, and we need GEOIP information to tell which countries "
1179 "clients are in.";
1181 return bridge_usage || routerset_usage;
1184 /** Return the bandwidthrate that we are going to report to the authorities
1185 * based on the config options. */
1186 uint32_t
1187 get_effective_bwrate(const or_options_t *options)
1189 uint64_t bw = options->BandwidthRate;
1190 if (bw > options->MaxAdvertisedBandwidth)
1191 bw = options->MaxAdvertisedBandwidth;
1192 if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1193 bw = options->RelayBandwidthRate;
1194 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1195 return (uint32_t)bw;
1198 /** Return the bandwidthburst that we are going to report to the authorities
1199 * based on the config options. */
1200 uint32_t
1201 get_effective_bwburst(const or_options_t *options)
1203 uint64_t bw = options->BandwidthBurst;
1204 if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1205 bw = options->RelayBandwidthBurst;
1206 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1207 return (uint32_t)bw;
1210 /** Return True if any changes from <b>old_options</b> to
1211 * <b>new_options</b> needs us to refresh our TLS context. */
1212 static int
1213 options_transition_requires_fresh_tls_context(const or_options_t *old_options,
1214 const or_options_t *new_options)
1216 tor_assert(new_options);
1218 if (!old_options)
1219 return 0;
1221 if ((old_options->DynamicDHGroups != new_options->DynamicDHGroups)) {
1222 return 1;
1225 if (!opt_streq(old_options->TLSECGroup, new_options->TLSECGroup))
1226 return 1;
1228 return 0;
1231 /** Fetch the active option list, and take actions based on it. All of the
1232 * things we do should survive being done repeatedly. If present,
1233 * <b>old_options</b> contains the previous value of the options.
1235 * Return 0 if all goes well, return -1 if it's time to die.
1237 * Note: We haven't moved all the "act on new configuration" logic
1238 * here yet. Some is still in do_hup() and other places.
1240 static int
1241 options_act(const or_options_t *old_options)
1243 config_line_t *cl;
1244 or_options_t *options = get_options_mutable();
1245 int running_tor = options->command == CMD_RUN_TOR;
1246 char *msg=NULL;
1247 const int transition_affects_workers =
1248 old_options && options_transition_affects_workers(old_options, options);
1249 int old_ewma_enabled;
1251 /* disable ptrace and later, other basic debugging techniques */
1253 /* Remember if we already disabled debugger attachment */
1254 static int disabled_debugger_attach = 0;
1255 /* Remember if we already warned about being configured not to disable
1256 * debugger attachment */
1257 static int warned_debugger_attach = 0;
1258 /* Don't disable debugger attachment when we're running the unit tests. */
1259 if (options->DisableDebuggerAttachment && !disabled_debugger_attach &&
1260 running_tor) {
1261 int ok = tor_disable_debugger_attach();
1262 if (warned_debugger_attach && ok == 1) {
1263 log_notice(LD_CONFIG, "Disabled attaching debuggers for unprivileged "
1264 "users.");
1266 disabled_debugger_attach = (ok == 1);
1267 } else if (!options->DisableDebuggerAttachment &&
1268 !warned_debugger_attach) {
1269 log_notice(LD_CONFIG, "Not disabling debugger attaching for "
1270 "unprivileged users.");
1271 warned_debugger_attach = 1;
1275 if (running_tor && !have_lockfile()) {
1276 if (try_locking(options, 1) < 0)
1277 return -1;
1280 if (consider_adding_dir_servers(options, old_options) < 0)
1281 return -1;
1283 #ifdef NON_ANONYMOUS_MODE_ENABLED
1284 log_warn(LD_GENERAL, "This copy of Tor was compiled to run in a "
1285 "non-anonymous mode. It will provide NO ANONYMITY.");
1286 #endif
1288 #ifdef ENABLE_TOR2WEB_MODE
1289 if (!options->Tor2webMode) {
1290 log_err(LD_CONFIG, "This copy of Tor was compiled to run in "
1291 "'tor2web mode'. It can only be run with the Tor2webMode torrc "
1292 "option enabled.");
1293 return -1;
1295 #else
1296 if (options->Tor2webMode) {
1297 log_err(LD_CONFIG, "This copy of Tor was not compiled to run in "
1298 "'tor2web mode'. It cannot be run with the Tor2webMode torrc "
1299 "option enabled. To enable Tor2webMode recompile with the "
1300 "--enable-tor2webmode option.");
1301 return -1;
1303 #endif
1305 if (options->Bridges) {
1306 mark_bridge_list();
1307 for (cl = options->Bridges; cl; cl = cl->next) {
1308 if (parse_bridge_line(cl->value, 0)<0) {
1309 log_warn(LD_BUG,
1310 "Previously validated Bridge line could not be added!");
1311 return -1;
1314 sweep_bridge_list();
1317 if (running_tor && rend_config_services(options, 0)<0) {
1318 log_warn(LD_BUG,
1319 "Previously validated hidden services line could not be added!");
1320 return -1;
1323 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1324 log_warn(LD_BUG, "Previously validated client authorization for "
1325 "hidden services could not be added!");
1326 return -1;
1329 /* Load state */
1330 if (! or_state_loaded() && running_tor) {
1331 if (or_state_load())
1332 return -1;
1333 rep_hist_load_mtbf_data(time(NULL));
1336 mark_transport_list();
1337 pt_prepare_proxy_list_for_config_read();
1338 if (options->ClientTransportPlugin) {
1339 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
1340 if (parse_client_transport_line(cl->value, 0)<0) {
1341 log_warn(LD_BUG,
1342 "Previously validated ClientTransportPlugin line "
1343 "could not be added!");
1344 return -1;
1349 if (options->ServerTransportPlugin && server_mode(options)) {
1350 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
1351 if (parse_server_transport_line(cl->value, 0)<0) {
1352 log_warn(LD_BUG,
1353 "Previously validated ServerTransportPlugin line "
1354 "could not be added!");
1355 return -1;
1359 sweep_transport_list();
1360 sweep_proxy_list();
1362 /* Bail out at this point if we're not going to be a client or server:
1363 * we want to not fork, and to log stuff to stderr. */
1364 if (!running_tor)
1365 return 0;
1367 /* Finish backgrounding the process */
1368 if (options->RunAsDaemon) {
1369 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1370 finish_daemon(options->DataDirectory);
1373 /* If needed, generate a new TLS DH prime according to the current torrc. */
1374 if (server_mode(options) && options->DynamicDHGroups) {
1375 char *keydir = get_datadir_fname("keys");
1376 if (check_private_dir(keydir, CPD_CREATE, options->User)) {
1377 tor_free(keydir);
1378 return -1;
1380 tor_free(keydir);
1382 if (!old_options || !old_options->DynamicDHGroups) {
1383 char *fname = get_datadir_fname2("keys", "dynamic_dh_params");
1384 crypto_set_tls_dh_prime(fname);
1385 tor_free(fname);
1387 } else { /* clients don't need a dynamic DH prime. */
1388 crypto_set_tls_dh_prime(NULL);
1391 /* We want to reinit keys as needed before we do much of anything else:
1392 keys are important, and other things can depend on them. */
1393 if (transition_affects_workers ||
1394 (options->V3AuthoritativeDir && (!old_options ||
1395 !old_options->V3AuthoritativeDir))) {
1396 if (init_keys() < 0) {
1397 log_warn(LD_BUG,"Error initializing keys; exiting");
1398 return -1;
1400 } else if (old_options &&
1401 options_transition_requires_fresh_tls_context(old_options,
1402 options)) {
1403 if (router_initialize_tls_context() < 0) {
1404 log_warn(LD_BUG,"Error initializing TLS context.");
1405 return -1;
1409 /* Write our PID to the PID file. If we do not have write permissions we
1410 * will log a warning */
1411 if (options->PidFile)
1412 write_pidfile(options->PidFile);
1414 /* Register addressmap directives */
1415 config_register_addressmaps(options);
1416 parse_virtual_addr_network(options->VirtualAddrNetworkIPv4, AF_INET,0,NULL);
1417 parse_virtual_addr_network(options->VirtualAddrNetworkIPv6, AF_INET6,0,NULL);
1419 /* Update address policies. */
1420 if (policies_parse_from_options(options) < 0) {
1421 /* This should be impossible, but let's be sure. */
1422 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1423 return -1;
1426 if (init_cookie_authentication(options->CookieAuthentication) < 0) {
1427 log_warn(LD_CONFIG,"Error creating cookie authentication file.");
1428 return -1;
1431 monitor_owning_controller_process(options->OwningControllerProcess);
1433 /* reload keys as needed for rendezvous services. */
1434 if (rend_service_load_all_keys()<0) {
1435 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1436 return -1;
1439 /* Set up accounting */
1440 if (accounting_parse_options(options, 0)<0) {
1441 log_warn(LD_CONFIG,"Error in accounting options");
1442 return -1;
1444 if (accounting_is_enabled(options))
1445 configure_accounting(time(NULL));
1447 #ifdef USE_BUFFEREVENTS
1448 /* If we're using the bufferevents implementation and our rate limits
1449 * changed, we need to tell the rate-limiting system about it. */
1450 if (!old_options ||
1451 old_options->BandwidthRate != options->BandwidthRate ||
1452 old_options->BandwidthBurst != options->BandwidthBurst ||
1453 old_options->RelayBandwidthRate != options->RelayBandwidthRate ||
1454 old_options->RelayBandwidthBurst != options->RelayBandwidthBurst)
1455 connection_bucket_init();
1456 #endif
1458 old_ewma_enabled = cell_ewma_enabled();
1459 /* Change the cell EWMA settings */
1460 cell_ewma_set_scale_factor(options, networkstatus_get_latest_consensus());
1461 /* If we just enabled ewma, set the cmux policy on all active channels */
1462 if (cell_ewma_enabled() && !old_ewma_enabled) {
1463 channel_set_cmux_policy_everywhere(&ewma_policy);
1464 } else if (!cell_ewma_enabled() && old_ewma_enabled) {
1465 /* Turn it off everywhere */
1466 channel_set_cmux_policy_everywhere(NULL);
1469 /* Update the BridgePassword's hashed version as needed. We store this as a
1470 * digest so that we can do side-channel-proof comparisons on it.
1472 if (options->BridgePassword) {
1473 char *http_authenticator;
1474 http_authenticator = alloc_http_authenticator(options->BridgePassword);
1475 if (!http_authenticator) {
1476 log_warn(LD_BUG, "Unable to allocate HTTP authenticator. Not setting "
1477 "BridgePassword.");
1478 return -1;
1480 options->BridgePassword_AuthDigest_ = tor_malloc(DIGEST256_LEN);
1481 crypto_digest256(options->BridgePassword_AuthDigest_,
1482 http_authenticator, strlen(http_authenticator),
1483 DIGEST_SHA256);
1484 tor_free(http_authenticator);
1487 if (parse_outbound_addresses(options, 0, &msg) < 0) {
1488 log_warn(LD_BUG, "Failed parsing oubound bind addresses: %s", msg);
1489 tor_free(msg);
1490 return -1;
1493 /* Check for transitions that need action. */
1494 if (old_options) {
1495 int revise_trackexithosts = 0;
1496 int revise_automap_entries = 0;
1497 if ((options->UseEntryGuards && !old_options->UseEntryGuards) ||
1498 options->UseBridges != old_options->UseBridges ||
1499 (options->UseBridges &&
1500 !config_lines_eq(options->Bridges, old_options->Bridges)) ||
1501 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes) ||
1502 !routerset_equal(old_options->ExcludeExitNodes,
1503 options->ExcludeExitNodes) ||
1504 !routerset_equal(old_options->EntryNodes, options->EntryNodes) ||
1505 !routerset_equal(old_options->ExitNodes, options->ExitNodes) ||
1506 options->StrictNodes != old_options->StrictNodes) {
1507 log_info(LD_CIRC,
1508 "Changed to using entry guards or bridges, or changed "
1509 "preferred or excluded node lists. "
1510 "Abandoning previous circuits.");
1511 circuit_mark_all_unused_circs();
1512 circuit_mark_all_dirty_circs_as_unusable();
1513 revise_trackexithosts = 1;
1516 if (!smartlist_strings_eq(old_options->TrackHostExits,
1517 options->TrackHostExits))
1518 revise_trackexithosts = 1;
1520 if (revise_trackexithosts)
1521 addressmap_clear_excluded_trackexithosts(options);
1523 if (!options->AutomapHostsOnResolve) {
1524 if (old_options->AutomapHostsOnResolve)
1525 revise_automap_entries = 1;
1526 } else {
1527 if (!smartlist_strings_eq(old_options->AutomapHostsSuffixes,
1528 options->AutomapHostsSuffixes))
1529 revise_automap_entries = 1;
1530 else if (!opt_streq(old_options->VirtualAddrNetworkIPv4,
1531 options->VirtualAddrNetworkIPv4) ||
1532 !opt_streq(old_options->VirtualAddrNetworkIPv6,
1533 options->VirtualAddrNetworkIPv6))
1534 revise_automap_entries = 1;
1537 if (revise_automap_entries)
1538 addressmap_clear_invalid_automaps(options);
1540 /* How long should we delay counting bridge stats after becoming a bridge?
1541 * We use this so we don't count people who used our bridge thinking it is
1542 * a relay. If you change this, don't forget to change the log message
1543 * below. It's 4 hours (the time it takes to stop being used by clients)
1544 * plus some extra time for clock skew. */
1545 #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
1547 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
1548 int was_relay = 0;
1549 if (options->BridgeRelay) {
1550 time_t int_start = time(NULL);
1551 if (config_lines_eq(old_options->ORPort_lines,options->ORPort_lines)) {
1552 int_start += RELAY_BRIDGE_STATS_DELAY;
1553 was_relay = 1;
1555 geoip_bridge_stats_init(int_start);
1556 log_info(LD_CONFIG, "We are acting as a bridge now. Starting new "
1557 "GeoIP stats interval%s.", was_relay ? " in 6 "
1558 "hours from now" : "");
1559 } else {
1560 geoip_bridge_stats_term();
1561 log_info(LD_GENERAL, "We are no longer acting as a bridge. "
1562 "Forgetting GeoIP stats.");
1566 if (transition_affects_workers) {
1567 log_info(LD_GENERAL,
1568 "Worker-related options changed. Rotating workers.");
1570 if (server_mode(options) && !server_mode(old_options)) {
1571 ip_address_changed(0);
1572 if (can_complete_circuit || !any_predicted_circuits(time(NULL)))
1573 inform_testing_reachability();
1575 cpuworkers_rotate();
1576 if (dns_reset())
1577 return -1;
1578 } else {
1579 if (dns_reset())
1580 return -1;
1583 if (options->PerConnBWRate != old_options->PerConnBWRate ||
1584 options->PerConnBWBurst != old_options->PerConnBWBurst)
1585 connection_or_update_token_buckets(get_connection_array(), options);
1588 config_maybe_load_geoip_files_(options, old_options);
1590 if (geoip_is_loaded(AF_INET) && options->GeoIPExcludeUnknown) {
1591 /* ExcludeUnknown is true or "auto" */
1592 const int is_auto = options->GeoIPExcludeUnknown == -1;
1593 int changed;
1595 changed = routerset_add_unknown_ccs(&options->ExcludeNodes, is_auto);
1596 changed += routerset_add_unknown_ccs(&options->ExcludeExitNodes, is_auto);
1598 if (changed)
1599 routerset_add_unknown_ccs(&options->ExcludeExitNodesUnion_, is_auto);
1602 if (options->CellStatistics || options->DirReqStatistics ||
1603 options->EntryStatistics || options->ExitPortStatistics ||
1604 options->ConnDirectionStatistics ||
1605 options->BridgeAuthoritativeDir) {
1606 time_t now = time(NULL);
1607 int print_notice = 0;
1609 /* If we aren't acting as a server, we can't collect stats anyway. */
1610 if (!server_mode(options)) {
1611 options->CellStatistics = 0;
1612 options->DirReqStatistics = 0;
1613 options->EntryStatistics = 0;
1614 options->ExitPortStatistics = 0;
1617 if ((!old_options || !old_options->CellStatistics) &&
1618 options->CellStatistics) {
1619 rep_hist_buffer_stats_init(now);
1620 print_notice = 1;
1622 if ((!old_options || !old_options->DirReqStatistics) &&
1623 options->DirReqStatistics) {
1624 if (geoip_is_loaded(AF_INET)) {
1625 geoip_dirreq_stats_init(now);
1626 print_notice = 1;
1627 } else {
1628 options->DirReqStatistics = 0;
1629 /* Don't warn Tor clients, they don't use statistics */
1630 if (options->ORPort_set)
1631 log_notice(LD_CONFIG, "Configured to measure directory request "
1632 "statistics, but no GeoIP database found. "
1633 "Please specify a GeoIP database using the "
1634 "GeoIPFile option.");
1637 if ((!old_options || !old_options->EntryStatistics) &&
1638 options->EntryStatistics && !should_record_bridge_info(options)) {
1639 if (geoip_is_loaded(AF_INET) || geoip_is_loaded(AF_INET6)) {
1640 geoip_entry_stats_init(now);
1641 print_notice = 1;
1642 } else {
1643 options->EntryStatistics = 0;
1644 log_notice(LD_CONFIG, "Configured to measure entry node "
1645 "statistics, but no GeoIP database found. "
1646 "Please specify a GeoIP database using the "
1647 "GeoIPFile option.");
1650 if ((!old_options || !old_options->ExitPortStatistics) &&
1651 options->ExitPortStatistics) {
1652 rep_hist_exit_stats_init(now);
1653 print_notice = 1;
1655 if ((!old_options || !old_options->ConnDirectionStatistics) &&
1656 options->ConnDirectionStatistics) {
1657 rep_hist_conn_stats_init(now);
1659 if ((!old_options || !old_options->BridgeAuthoritativeDir) &&
1660 options->BridgeAuthoritativeDir) {
1661 rep_hist_desc_stats_init(now);
1662 print_notice = 1;
1664 if (print_notice)
1665 log_notice(LD_CONFIG, "Configured to measure statistics. Look for "
1666 "the *-stats files that will first be written to the "
1667 "data directory in 24 hours from now.");
1670 if (old_options && old_options->CellStatistics &&
1671 !options->CellStatistics)
1672 rep_hist_buffer_stats_term();
1673 if (old_options && old_options->DirReqStatistics &&
1674 !options->DirReqStatistics)
1675 geoip_dirreq_stats_term();
1676 if (old_options && old_options->EntryStatistics &&
1677 !options->EntryStatistics)
1678 geoip_entry_stats_term();
1679 if (old_options && old_options->ExitPortStatistics &&
1680 !options->ExitPortStatistics)
1681 rep_hist_exit_stats_term();
1682 if (old_options && old_options->ConnDirectionStatistics &&
1683 !options->ConnDirectionStatistics)
1684 rep_hist_conn_stats_term();
1685 if (old_options && old_options->BridgeAuthoritativeDir &&
1686 !options->BridgeAuthoritativeDir)
1687 rep_hist_desc_stats_term();
1689 /* Check if we need to parse and add the EntryNodes config option. */
1690 if (options->EntryNodes &&
1691 (!old_options ||
1692 !routerset_equal(old_options->EntryNodes,options->EntryNodes) ||
1693 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes)))
1694 entry_nodes_should_be_added();
1696 /* Since our options changed, we might need to regenerate and upload our
1697 * server descriptor.
1699 if (!old_options ||
1700 options_transition_affects_descriptor(old_options, options))
1701 mark_my_descriptor_dirty("config change");
1703 /* We may need to reschedule some directory stuff if our status changed. */
1704 if (old_options) {
1705 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1706 dirvote_recalculate_timing(options, time(NULL));
1707 if (!bool_eq(directory_fetches_dir_info_early(options),
1708 directory_fetches_dir_info_early(old_options)) ||
1709 !bool_eq(directory_fetches_dir_info_later(options),
1710 directory_fetches_dir_info_later(old_options))) {
1711 /* Make sure update_router_have_min_dir_info gets called. */
1712 router_dir_info_changed();
1713 /* We might need to download a new consensus status later or sooner than
1714 * we had expected. */
1715 update_consensus_networkstatus_fetch_time(time(NULL));
1719 /* Load the webpage we're going to serve every time someone asks for '/' on
1720 our DirPort. */
1721 tor_free(global_dirfrontpagecontents);
1722 if (options->DirPortFrontPage) {
1723 global_dirfrontpagecontents =
1724 read_file_to_str(options->DirPortFrontPage, 0, NULL);
1725 if (!global_dirfrontpagecontents) {
1726 log_warn(LD_CONFIG,
1727 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1728 options->DirPortFrontPage);
1732 return 0;
1735 /** Helper: Read a list of configuration options from the command line.
1736 * If successful, put them in *<b>result</b> and return 0, and return
1737 * -1 and leave *<b>result</b> alone. */
1738 static int
1739 config_get_commandlines(int argc, char **argv, config_line_t **result)
1741 config_line_t *front = NULL;
1742 config_line_t **new = &front;
1743 char *s;
1744 int i = 1;
1746 while (i < argc) {
1747 unsigned command = CONFIG_LINE_NORMAL;
1748 int want_arg = 1;
1750 if (!strcmp(argv[i],"-f") ||
1751 !strcmp(argv[i],"--defaults-torrc") ||
1752 !strcmp(argv[i],"--hash-password")) {
1753 i += 2; /* command-line option with argument. ignore them. */
1754 continue;
1755 } else if (!strcmp(argv[i],"--list-fingerprint") ||
1756 !strcmp(argv[i],"--verify-config") ||
1757 !strcmp(argv[i],"--ignore-missing-torrc") ||
1758 !strcmp(argv[i],"--quiet") ||
1759 !strcmp(argv[i],"--hush")) {
1760 i += 1; /* command-line option. ignore it. */
1761 continue;
1762 } else if (!strcmp(argv[i],"--nt-service") ||
1763 !strcmp(argv[i],"-nt-service")) {
1764 i += 1;
1765 continue;
1768 *new = tor_malloc_zero(sizeof(config_line_t));
1769 s = argv[i];
1771 /* Each keyword may be prefixed with one or two dashes. */
1772 if (*s == '-')
1773 s++;
1774 if (*s == '-')
1775 s++;
1776 /* Figure out the command, if any. */
1777 if (*s == '+') {
1778 s++;
1779 command = CONFIG_LINE_APPEND;
1780 } else if (*s == '/') {
1781 s++;
1782 command = CONFIG_LINE_CLEAR;
1783 /* A 'clear' command has no argument. */
1784 want_arg = 0;
1787 if (want_arg && i == argc-1) {
1788 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1789 argv[i]);
1790 config_free_lines(front);
1791 return -1;
1794 (*new)->key = tor_strdup(config_expand_abbrev(&options_format, s, 1, 1));
1795 (*new)->value = want_arg ? tor_strdup(argv[i+1]) : tor_strdup("");
1796 (*new)->command = command;
1797 (*new)->next = NULL;
1798 log_debug(LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
1799 (*new)->key, (*new)->value);
1801 new = &((*new)->next);
1802 i += want_arg ? 2 : 1;
1804 *result = front;
1805 return 0;
1808 /** Return true iff key is a valid configuration option. */
1810 option_is_recognized(const char *key)
1812 const config_var_t *var = config_find_option(&options_format, key);
1813 return (var != NULL);
1816 /** Return the canonical name of a configuration option, or NULL
1817 * if no such option exists. */
1818 const char *
1819 option_get_canonical_name(const char *key)
1821 const config_var_t *var = config_find_option(&options_format, key);
1822 return var ? var->name : NULL;
1825 /** Return a canonical list of the options assigned for key.
1827 config_line_t *
1828 option_get_assignment(const or_options_t *options, const char *key)
1830 return config_get_assigned_option(&options_format, options, key, 1);
1833 /** Try assigning <b>list</b> to the global options. You do this by duping
1834 * options, assigning list to the new one, then validating it. If it's
1835 * ok, then throw out the old one and stick with the new one. Else,
1836 * revert to old and return failure. Return SETOPT_OK on success, or
1837 * a setopt_err_t on failure.
1839 * If not success, point *<b>msg</b> to a newly allocated string describing
1840 * what went wrong.
1842 setopt_err_t
1843 options_trial_assign(config_line_t *list, int use_defaults,
1844 int clear_first, char **msg)
1846 int r;
1847 or_options_t *trial_options = config_dup(&options_format, get_options());
1849 if ((r=config_assign(&options_format, trial_options,
1850 list, use_defaults, clear_first, msg)) < 0) {
1851 config_free(&options_format, trial_options);
1852 return r;
1855 if (options_validate(get_options_mutable(), trial_options, 1, msg) < 0) {
1856 config_free(&options_format, trial_options);
1857 return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
1860 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
1861 config_free(&options_format, trial_options);
1862 return SETOPT_ERR_TRANSITION;
1865 if (set_options(trial_options, msg)<0) {
1866 config_free(&options_format, trial_options);
1867 return SETOPT_ERR_SETTING;
1870 /* we liked it. put it in place. */
1871 return SETOPT_OK;
1874 /** Print a usage message for tor. */
1875 static void
1876 print_usage(void)
1878 printf(
1879 "Copyright (c) 2001-2004, Roger Dingledine\n"
1880 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
1881 "Copyright (c) 2007-2013, The Tor Project, Inc.\n\n"
1882 "tor -f <torrc> [args]\n"
1883 "See man page for options, or https://www.torproject.org/ for "
1884 "documentation.\n");
1887 /** Print all non-obsolete torrc options. */
1888 static void
1889 list_torrc_options(void)
1891 int i;
1892 smartlist_t *lines = smartlist_new();
1893 for (i = 0; option_vars_[i].name; ++i) {
1894 const config_var_t *var = &option_vars_[i];
1895 if (var->type == CONFIG_TYPE_OBSOLETE ||
1896 var->type == CONFIG_TYPE_LINELIST_V)
1897 continue;
1898 printf("%s\n", var->name);
1900 smartlist_free(lines);
1903 /** Last value actually set by resolve_my_address. */
1904 static uint32_t last_resolved_addr = 0;
1906 /** Accessor for last_resolved_addr from outside this file. */
1907 uint32_t
1908 get_last_resolved_addr(void)
1910 return last_resolved_addr;
1914 * Use <b>options-\>Address</b> to guess our public IP address.
1916 * Return 0 if all is well, or -1 if we can't find a suitable
1917 * public IP address.
1919 * If we are returning 0:
1920 * - Put our public IP address (in host order) into *<b>addr_out</b>.
1921 * - If <b>method_out</b> is non-NULL, set *<b>method_out</b> to a static
1922 * string describing how we arrived at our answer.
1923 * - If <b>hostname_out</b> is non-NULL, and we resolved a hostname to
1924 * get our address, set *<b>hostname_out</b> to a newly allocated string
1925 * holding that hostname. (If we didn't get our address by resolving a
1926 * hostname, set *<b>hostname_out</b> to NULL.)
1928 * XXXX ipv6
1931 resolve_my_address(int warn_severity, const or_options_t *options,
1932 uint32_t *addr_out,
1933 const char **method_out, char **hostname_out)
1935 struct in_addr in;
1936 uint32_t addr; /* host order */
1937 char hostname[256];
1938 const char *method_used;
1939 const char *hostname_used;
1940 int explicit_ip=1;
1941 int explicit_hostname=1;
1942 int from_interface=0;
1943 char *addr_string = NULL;
1944 const char *address = options->Address;
1945 int notice_severity = warn_severity <= LOG_NOTICE ?
1946 LOG_NOTICE : warn_severity;
1948 tor_assert(addr_out);
1951 * Step one: Fill in 'hostname' to be our best guess.
1954 if (address && *address) {
1955 strlcpy(hostname, address, sizeof(hostname));
1956 } else { /* then we need to guess our address */
1957 explicit_ip = 0; /* it's implicit */
1958 explicit_hostname = 0; /* it's implicit */
1960 if (gethostname(hostname, sizeof(hostname)) < 0) {
1961 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
1962 return -1;
1964 log_debug(LD_CONFIG, "Guessed local host name as '%s'", hostname);
1968 * Step two: Now that we know 'hostname', parse it or resolve it. If
1969 * it doesn't parse or resolve, look at the interface address. Set 'addr'
1970 * to be our (host-order) 32-bit answer.
1973 if (tor_inet_aton(hostname, &in) == 0) {
1974 /* then we have to resolve it */
1975 explicit_ip = 0;
1976 if (tor_lookup_hostname(hostname, &addr)) { /* failed to resolve */
1977 uint32_t interface_ip; /* host order */
1979 if (explicit_hostname) {
1980 log_fn(warn_severity, LD_CONFIG,
1981 "Could not resolve local Address '%s'. Failing.", hostname);
1982 return -1;
1984 log_fn(notice_severity, LD_CONFIG,
1985 "Could not resolve guessed local hostname '%s'. "
1986 "Trying something else.", hostname);
1987 if (get_interface_address(warn_severity, &interface_ip)) {
1988 log_fn(warn_severity, LD_CONFIG,
1989 "Could not get local interface IP address. Failing.");
1990 return -1;
1992 from_interface = 1;
1993 addr = interface_ip;
1994 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
1995 "local interface. Using that.", fmt_addr32(addr));
1996 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
1997 } else { /* resolved hostname into addr */
1998 if (!explicit_hostname &&
1999 is_internal_IP(addr, 0)) {
2000 uint32_t interface_ip;
2002 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2003 "resolves to a private IP address (%s). Trying something "
2004 "else.", hostname, fmt_addr32(addr));
2006 if (get_interface_address(warn_severity, &interface_ip)) {
2007 log_fn(warn_severity, LD_CONFIG,
2008 "Could not get local interface IP address. Too bad.");
2009 } else if (is_internal_IP(interface_ip, 0)) {
2010 log_fn(notice_severity, LD_CONFIG,
2011 "Interface IP address '%s' is a private address too. "
2012 "Ignoring.", fmt_addr32(interface_ip));
2013 } else {
2014 from_interface = 1;
2015 addr = interface_ip;
2016 log_fn(notice_severity, LD_CONFIG,
2017 "Learned IP address '%s' for local interface."
2018 " Using that.", fmt_addr32(addr));
2019 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2023 } else {
2024 addr = ntohl(in.s_addr); /* set addr so that addr_string is not
2025 * illformed */
2029 * Step three: Check whether 'addr' is an internal IP address, and error
2030 * out if it is and we don't want that.
2033 addr_string = tor_dup_ip(addr);
2034 if (is_internal_IP(addr, 0)) {
2035 /* make sure we're ok with publishing an internal IP */
2036 if (!options->DirAuthorities && !options->AlternateDirAuthority) {
2037 /* if they are using the default authorities, disallow internal IPs
2038 * always. */
2039 log_fn(warn_severity, LD_CONFIG,
2040 "Address '%s' resolves to private IP address '%s'. "
2041 "Tor servers that use the default DirAuthorities must have "
2042 "public IP addresses.", hostname, addr_string);
2043 tor_free(addr_string);
2044 return -1;
2046 if (!explicit_ip) {
2047 /* even if they've set their own authorities, require an explicit IP if
2048 * they're using an internal address. */
2049 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2050 "IP address '%s'. Please set the Address config option to be "
2051 "the IP address you want to use.", hostname, addr_string);
2052 tor_free(addr_string);
2053 return -1;
2058 * Step four: We have a winner! 'addr' is our answer for sure, and
2059 * 'addr_string' is its string form. Fill out the various fields to
2060 * say how we decided it.
2063 log_debug(LD_CONFIG, "Resolved Address to '%s'.", addr_string);
2065 if (explicit_ip) {
2066 method_used = "CONFIGURED";
2067 hostname_used = NULL;
2068 } else if (explicit_hostname) {
2069 method_used = "RESOLVED";
2070 hostname_used = hostname;
2071 } else if (from_interface) {
2072 method_used = "INTERFACE";
2073 hostname_used = NULL;
2074 } else {
2075 method_used = "GETHOSTNAME";
2076 hostname_used = hostname;
2079 *addr_out = addr;
2080 if (method_out)
2081 *method_out = method_used;
2082 if (hostname_out)
2083 *hostname_out = hostname_used ? tor_strdup(hostname_used) : NULL;
2086 * Step five: Check if the answer has changed since last time (or if
2087 * there was no last time), and if so call various functions to keep
2088 * us up-to-date.
2091 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2092 /* Leave this as a notice, regardless of the requested severity,
2093 * at least until dynamic IP address support becomes bulletproof. */
2094 log_notice(LD_NET,
2095 "Your IP address seems to have changed to %s "
2096 "(METHOD=%s%s%s). Updating.",
2097 addr_string, method_used,
2098 hostname_used ? " HOSTNAME=" : "",
2099 hostname_used ? hostname_used : "");
2100 ip_address_changed(0);
2103 if (last_resolved_addr != *addr_out) {
2104 control_event_server_status(LOG_NOTICE,
2105 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s%s%s",
2106 addr_string, method_used,
2107 hostname_used ? " HOSTNAME=" : "",
2108 hostname_used ? hostname_used : "");
2110 last_resolved_addr = *addr_out;
2113 * And finally, clean up and return success.
2116 tor_free(addr_string);
2117 return 0;
2120 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2121 * on a private network.
2124 is_local_addr(const tor_addr_t *addr)
2126 if (tor_addr_is_internal(addr, 0))
2127 return 1;
2128 /* Check whether ip is on the same /24 as we are. */
2129 if (get_options()->EnforceDistinctSubnets == 0)
2130 return 0;
2131 if (tor_addr_family(addr) == AF_INET) {
2132 /*XXXX023 IP6 what corresponds to an /24? */
2133 uint32_t ip = tor_addr_to_ipv4h(addr);
2135 /* It's possible that this next check will hit before the first time
2136 * resolve_my_address actually succeeds. (For clients, it is likely that
2137 * resolve_my_address will never be called at all). In those cases,
2138 * last_resolved_addr will be 0, and so checking to see whether ip is on
2139 * the same /24 as last_resolved_addr will be the same as checking whether
2140 * it was on net 0, which is already done by is_internal_IP.
2142 if ((last_resolved_addr & (uint32_t)0xffffff00ul)
2143 == (ip & (uint32_t)0xffffff00ul))
2144 return 1;
2146 return 0;
2149 /** Return a new empty or_options_t. Used for testing. */
2150 or_options_t *
2151 options_new(void)
2153 return config_new(&options_format);
2156 /** Set <b>options</b> to hold reasonable defaults for most options.
2157 * Each option defaults to zero. */
2158 void
2159 options_init(or_options_t *options)
2161 config_init(&options_format, options);
2164 /** Return a string containing a possible configuration file that would give
2165 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2166 * include options that are the same as Tor's defaults.
2168 char *
2169 options_dump(const or_options_t *options, int minimal)
2171 return config_dump(&options_format, global_default_options,
2172 options, minimal, 0);
2175 /** Return 0 if every element of sl is a string holding a decimal
2176 * representation of a port number, or if sl is NULL.
2177 * Otherwise set *msg and return -1. */
2178 static int
2179 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2181 int i;
2182 tor_assert(name);
2184 if (!sl)
2185 return 0;
2187 SMARTLIST_FOREACH(sl, const char *, cp,
2189 i = atoi(cp);
2190 if (i < 1 || i > 65535) {
2191 tor_asprintf(msg, "Port '%s' out of range in %s", cp, name);
2192 return -1;
2195 return 0;
2198 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2199 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2200 * Else return 0.
2202 static int
2203 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2205 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2206 /* This handles an understandable special case where somebody says "2gb"
2207 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2208 --*value;
2210 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2211 tor_asprintf(msg, "%s ("U64_FORMAT") must be at most %d",
2212 desc, U64_PRINTF_ARG(*value),
2213 ROUTER_MAX_DECLARED_BANDWIDTH);
2214 return -1;
2216 return 0;
2219 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2220 * and write it to <b>options</b>-\>PublishServerDescriptor_. Treat "1"
2221 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2222 * Treat "0" as "".
2223 * Return 0 on success or -1 if not a recognized authority type (in which
2224 * case the value of PublishServerDescriptor_ is undefined). */
2225 static int
2226 compute_publishserverdescriptor(or_options_t *options)
2228 smartlist_t *list = options->PublishServerDescriptor;
2229 dirinfo_type_t *auth = &options->PublishServerDescriptor_;
2230 *auth = NO_DIRINFO;
2231 if (!list) /* empty list, answer is none */
2232 return 0;
2233 SMARTLIST_FOREACH_BEGIN(list, const char *, string) {
2234 if (!strcasecmp(string, "v1"))
2235 *auth |= V1_DIRINFO;
2236 else if (!strcmp(string, "1"))
2237 if (options->BridgeRelay)
2238 *auth |= BRIDGE_DIRINFO;
2239 else
2240 *auth |= V2_DIRINFO | V3_DIRINFO;
2241 else if (!strcasecmp(string, "v2"))
2242 *auth |= V2_DIRINFO;
2243 else if (!strcasecmp(string, "v3"))
2244 *auth |= V3_DIRINFO;
2245 else if (!strcasecmp(string, "bridge"))
2246 *auth |= BRIDGE_DIRINFO;
2247 else if (!strcasecmp(string, "hidserv"))
2248 log_warn(LD_CONFIG,
2249 "PublishServerDescriptor hidserv is invalid. See "
2250 "PublishHidServDescriptors.");
2251 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2252 /* no authority */;
2253 else
2254 return -1;
2255 } SMARTLIST_FOREACH_END(string);
2256 return 0;
2259 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2260 * services can overload the directory system. */
2261 #define MIN_REND_POST_PERIOD (10*60)
2263 /** Highest allowable value for RendPostPeriod. */
2264 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2266 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2267 * will generate too many circuits and potentially overload the network. */
2268 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2270 /** Highest allowable value for MaxCircuitDirtiness: prevents time_t
2271 * overflows. */
2272 #define MAX_MAX_CIRCUIT_DIRTINESS (30*24*60*60)
2274 /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
2275 * will generate too many circuits and potentially overload the network. */
2276 #define MIN_CIRCUIT_STREAM_TIMEOUT 10
2278 /** Lowest allowable value for HeartbeatPeriod; if this is too low, we might
2279 * expose more information than we're comfortable with. */
2280 #define MIN_HEARTBEAT_PERIOD (30*60)
2282 /** Lowest recommended value for CircuitBuildTimeout; if it is set too low
2283 * and LearnCircuitBuildTimeout is off, the failure rate for circuit
2284 * construction may be very high. In that case, if it is set below this
2285 * threshold emit a warning.
2286 * */
2287 #define RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT (10)
2289 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2290 * permissible transition from <b>old_options</b>. Else return -1.
2291 * Should have no side effects, except for normalizing the contents of
2292 * <b>options</b>.
2294 * On error, tor_strdup an error explanation into *<b>msg</b>.
2296 * XXX
2297 * If <b>from_setconf</b>, we were called by the controller, and our
2298 * Log line should stay empty. If it's 0, then give us a default log
2299 * if there are no logs defined.
2301 static int
2302 options_validate(or_options_t *old_options, or_options_t *options,
2303 int from_setconf, char **msg)
2305 int i;
2306 config_line_t *cl;
2307 const char *uname = get_uname();
2308 int n_ports=0;
2309 #define REJECT(arg) \
2310 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2311 #define COMPLAIN(arg) STMT_BEGIN log_warn(LD_CONFIG, arg); STMT_END
2313 tor_assert(msg);
2314 *msg = NULL;
2316 if (server_mode(options) &&
2317 (!strcmpstart(uname, "Windows 95") ||
2318 !strcmpstart(uname, "Windows 98") ||
2319 !strcmpstart(uname, "Windows Me"))) {
2320 log_warn(LD_CONFIG, "Tor is running as a server, but you are "
2321 "running %s; this probably won't work. See "
2322 "https://www.torproject.org/docs/faq.html#BestOSForRelay "
2323 "for details.", uname);
2326 if (parse_ports(options, 1, msg, &n_ports) < 0)
2327 return -1;
2329 if (parse_outbound_addresses(options, 1, msg) < 0)
2330 return -1;
2332 if (validate_data_directory(options)<0)
2333 REJECT("Invalid DataDirectory");
2335 if (options->Nickname == NULL) {
2336 if (server_mode(options)) {
2337 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
2339 } else {
2340 if (!is_legal_nickname(options->Nickname)) {
2341 tor_asprintf(msg,
2342 "Nickname '%s' is wrong length or contains illegal characters.",
2343 options->Nickname);
2344 return -1;
2348 if (server_mode(options) && !options->ContactInfo)
2349 log_notice(LD_CONFIG, "Your ContactInfo config option is not set. "
2350 "Please consider setting it, so we can contact you if your server is "
2351 "misconfigured or something else goes wrong.");
2353 /* Special case on first boot if no Log options are given. */
2354 if (!options->Logs && !options->RunAsDaemon && !from_setconf) {
2355 if (quiet_level == 0)
2356 config_line_append(&options->Logs, "Log", "notice stdout");
2357 else if (quiet_level == 1)
2358 config_line_append(&options->Logs, "Log", "warn stdout");
2361 if (options_init_logs(options, 1)<0) /* Validate the tor_log(s) */
2362 REJECT("Failed to validate Log options. See logs for details.");
2364 if (authdir_mode(options)) {
2365 /* confirm that our address isn't broken, so we can complain now */
2366 uint32_t tmp;
2367 if (resolve_my_address(LOG_WARN, options, &tmp, NULL, NULL) < 0)
2368 REJECT("Failed to resolve/guess local address. See logs for details.");
2371 #ifndef _WIN32
2372 if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
2373 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
2374 #endif
2376 /* XXXX require that the only port not be DirPort? */
2377 /* XXXX require that at least one port be listened-upon. */
2378 if (n_ports == 0 && !options->RendConfigLines)
2379 log_warn(LD_CONFIG,
2380 "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
2381 "undefined, and there aren't any hidden services configured. "
2382 "Tor will still run, but probably won't do anything.");
2384 #ifndef USE_TRANSPARENT
2385 /* XXXX024 I think we can remove this TransListenAddress */
2386 if (options->TransPort_set || options->TransListenAddress)
2387 REJECT("TransPort and TransListenAddress are disabled in this build.");
2388 #endif
2390 if (options->TokenBucketRefillInterval <= 0
2391 || options->TokenBucketRefillInterval > 1000) {
2392 REJECT("TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
2395 if (options->DisableV2DirectoryInfo_ && ! authdir_mode(options)) {
2396 REJECT("DisableV2DirectoryInfo_ set, but we aren't an authority.");
2399 if (options->ExcludeExitNodes || options->ExcludeNodes) {
2400 options->ExcludeExitNodesUnion_ = routerset_new();
2401 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeExitNodes);
2402 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeNodes);
2405 if (options->NodeFamilies) {
2406 options->NodeFamilySets = smartlist_new();
2407 for (cl = options->NodeFamilies; cl; cl = cl->next) {
2408 routerset_t *rs = routerset_new();
2409 if (routerset_parse(rs, cl->value, cl->key) == 0) {
2410 smartlist_add(options->NodeFamilySets, rs);
2411 } else {
2412 routerset_free(rs);
2417 if (options->TLSECGroup && (strcasecmp(options->TLSECGroup, "P256") &&
2418 strcasecmp(options->TLSECGroup, "P224"))) {
2419 COMPLAIN("Unrecognized TLSECGroup: Falling back to the default.");
2420 tor_free(options->TLSECGroup);
2423 if (options->ExcludeNodes && options->StrictNodes) {
2424 COMPLAIN("You have asked to exclude certain relays from all positions "
2425 "in your circuits. Expect hidden services and other Tor "
2426 "features to be broken in unpredictable ways.");
2429 if (options->AuthoritativeDir) {
2430 if (!options->ContactInfo && !options->TestingTorNetwork)
2431 REJECT("Authoritative directory servers must set ContactInfo");
2432 if (options->V1AuthoritativeDir && !options->RecommendedVersions)
2433 REJECT("V1 authoritative dir servers must set RecommendedVersions.");
2434 if (!options->RecommendedClientVersions)
2435 options->RecommendedClientVersions =
2436 config_lines_dup(options->RecommendedVersions);
2437 if (!options->RecommendedServerVersions)
2438 options->RecommendedServerVersions =
2439 config_lines_dup(options->RecommendedVersions);
2440 if (options->VersioningAuthoritativeDir &&
2441 (!options->RecommendedClientVersions ||
2442 !options->RecommendedServerVersions))
2443 REJECT("Versioning authoritative dir servers must set "
2444 "Recommended*Versions.");
2445 if (options->UseEntryGuards) {
2446 log_info(LD_CONFIG, "Authoritative directory servers can't set "
2447 "UseEntryGuards. Disabling.");
2448 options->UseEntryGuards = 0;
2450 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
2451 log_info(LD_CONFIG, "Authoritative directories always try to download "
2452 "extra-info documents. Setting DownloadExtraInfo.");
2453 options->DownloadExtraInfo = 1;
2455 if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
2456 options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
2457 options->V3AuthoritativeDir))
2458 REJECT("AuthoritativeDir is set, but none of "
2459 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
2460 /* If we have a v3bandwidthsfile and it's broken, complain on startup */
2461 if (options->V3BandwidthsFile && !old_options) {
2462 dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
2466 if (options->AuthoritativeDir && !options->DirPort_set)
2467 REJECT("Running as authoritative directory, but no DirPort set.");
2469 if (options->AuthoritativeDir && !options->ORPort_set)
2470 REJECT("Running as authoritative directory, but no ORPort set.");
2472 if (options->AuthoritativeDir && options->ClientOnly)
2473 REJECT("Running as authoritative directory, but ClientOnly also set.");
2475 if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
2476 REJECT("FetchDirInfoExtraEarly requires that you also set "
2477 "FetchDirInfoEarly");
2479 if (options->HSAuthoritativeDir && proxy_mode(options))
2480 REJECT("Running as authoritative v0 HS directory, but also configured "
2481 "as a client.");
2483 if (options->ConnLimit <= 0) {
2484 tor_asprintf(msg,
2485 "ConnLimit must be greater than 0, but was set to %d",
2486 options->ConnLimit);
2487 return -1;
2490 if (options->PathsNeededToBuildCircuits >= 0.0) {
2491 if (options->PathsNeededToBuildCircuits < 0.25) {
2492 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too low. Increasing "
2493 "to 0.25");
2494 options->PathsNeededToBuildCircuits = 0.25;
2495 } else if (options->PathsNeededToBuildCircuits > 0.95) {
2496 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too high. Decreasing "
2497 "to 0.95");
2498 options->PathsNeededToBuildCircuits = 0.95;
2502 if (options->MaxClientCircuitsPending <= 0 ||
2503 options->MaxClientCircuitsPending > MAX_MAX_CLIENT_CIRCUITS_PENDING) {
2504 tor_asprintf(msg,
2505 "MaxClientCircuitsPending must be between 1 and %d, but "
2506 "was set to %d", MAX_MAX_CLIENT_CIRCUITS_PENDING,
2507 options->MaxClientCircuitsPending);
2508 return -1;
2511 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
2512 return -1;
2514 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
2515 return -1;
2517 if (validate_ports_csv(options->RejectPlaintextPorts,
2518 "RejectPlaintextPorts", msg) < 0)
2519 return -1;
2521 if (validate_ports_csv(options->WarnPlaintextPorts,
2522 "WarnPlaintextPorts", msg) < 0)
2523 return -1;
2525 if (options->FascistFirewall && !options->ReachableAddresses) {
2526 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
2527 /* We already have firewall ports set, so migrate them to
2528 * ReachableAddresses, which will set ReachableORAddresses and
2529 * ReachableDirAddresses if they aren't set explicitly. */
2530 smartlist_t *instead = smartlist_new();
2531 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
2532 new_line->key = tor_strdup("ReachableAddresses");
2533 /* If we're configured with the old format, we need to prepend some
2534 * open ports. */
2535 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
2537 int p = atoi(portno);
2538 if (p<0) continue;
2539 smartlist_add_asprintf(instead, "*:%d", p);
2541 new_line->value = smartlist_join_strings(instead,",",0,NULL);
2542 /* These have been deprecated since 0.1.1.5-alpha-cvs */
2543 log_notice(LD_CONFIG,
2544 "Converting FascistFirewall and FirewallPorts "
2545 "config options to new format: \"ReachableAddresses %s\"",
2546 new_line->value);
2547 options->ReachableAddresses = new_line;
2548 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
2549 smartlist_free(instead);
2550 } else {
2551 /* We do not have FirewallPorts set, so add 80 to
2552 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
2553 if (!options->ReachableDirAddresses) {
2554 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
2555 new_line->key = tor_strdup("ReachableDirAddresses");
2556 new_line->value = tor_strdup("*:80");
2557 options->ReachableDirAddresses = new_line;
2558 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
2559 "to new format: \"ReachableDirAddresses *:80\"");
2561 if (!options->ReachableORAddresses) {
2562 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
2563 new_line->key = tor_strdup("ReachableORAddresses");
2564 new_line->value = tor_strdup("*:443");
2565 options->ReachableORAddresses = new_line;
2566 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
2567 "to new format: \"ReachableORAddresses *:443\"");
2572 for (i=0; i<3; i++) {
2573 config_line_t **linep =
2574 (i==0) ? &options->ReachableAddresses :
2575 (i==1) ? &options->ReachableORAddresses :
2576 &options->ReachableDirAddresses;
2577 if (!*linep)
2578 continue;
2579 /* We need to end with a reject *:*, not an implicit accept *:* */
2580 for (;;) {
2581 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
2582 break;
2583 linep = &((*linep)->next);
2584 if (!*linep) {
2585 *linep = tor_malloc_zero(sizeof(config_line_t));
2586 (*linep)->key = tor_strdup(
2587 (i==0) ? "ReachableAddresses" :
2588 (i==1) ? "ReachableORAddresses" :
2589 "ReachableDirAddresses");
2590 (*linep)->value = tor_strdup("reject *:*");
2591 break;
2596 if ((options->ReachableAddresses ||
2597 options->ReachableORAddresses ||
2598 options->ReachableDirAddresses) &&
2599 server_mode(options))
2600 REJECT("Servers must be able to freely connect to the rest "
2601 "of the Internet, so they must not set Reachable*Addresses "
2602 "or FascistFirewall.");
2604 if (options->UseBridges &&
2605 server_mode(options))
2606 REJECT("Servers must be able to freely connect to the rest "
2607 "of the Internet, so they must not set UseBridges.");
2609 /* If both of these are set, we'll end up with funny behavior where we
2610 * demand enough entrynodes be up and running else we won't build
2611 * circuits, yet we never actually use them. */
2612 if (options->UseBridges && options->EntryNodes)
2613 REJECT("You cannot set both UseBridges and EntryNodes.");
2615 if (options->EntryNodes && !options->UseEntryGuards) {
2616 REJECT("If EntryNodes is set, UseEntryGuards must be enabled.");
2619 if (options->MaxMemInCellQueues < (256 << 20)) {
2620 log_warn(LD_CONFIG, "MaxMemInCellQueues must be at least 256 MB for now. "
2621 "Ideally, have it as large as you can afford.");
2622 options->MaxMemInCellQueues = (256 << 20);
2625 options->AllowInvalid_ = 0;
2627 if (options->AllowInvalidNodes) {
2628 SMARTLIST_FOREACH_BEGIN(options->AllowInvalidNodes, const char *, cp) {
2629 if (!strcasecmp(cp, "entry"))
2630 options->AllowInvalid_ |= ALLOW_INVALID_ENTRY;
2631 else if (!strcasecmp(cp, "exit"))
2632 options->AllowInvalid_ |= ALLOW_INVALID_EXIT;
2633 else if (!strcasecmp(cp, "middle"))
2634 options->AllowInvalid_ |= ALLOW_INVALID_MIDDLE;
2635 else if (!strcasecmp(cp, "introduction"))
2636 options->AllowInvalid_ |= ALLOW_INVALID_INTRODUCTION;
2637 else if (!strcasecmp(cp, "rendezvous"))
2638 options->AllowInvalid_ |= ALLOW_INVALID_RENDEZVOUS;
2639 else {
2640 tor_asprintf(msg,
2641 "Unrecognized value '%s' in AllowInvalidNodes", cp);
2642 return -1;
2644 } SMARTLIST_FOREACH_END(cp);
2647 if (!options->SafeLogging ||
2648 !strcasecmp(options->SafeLogging, "0")) {
2649 options->SafeLogging_ = SAFELOG_SCRUB_NONE;
2650 } else if (!strcasecmp(options->SafeLogging, "relay")) {
2651 options->SafeLogging_ = SAFELOG_SCRUB_RELAY;
2652 } else if (!strcasecmp(options->SafeLogging, "1")) {
2653 options->SafeLogging_ = SAFELOG_SCRUB_ALL;
2654 } else {
2655 tor_asprintf(msg,
2656 "Unrecognized value '%s' in SafeLogging",
2657 escaped(options->SafeLogging));
2658 return -1;
2661 if (compute_publishserverdescriptor(options) < 0) {
2662 tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
2663 return -1;
2666 if ((options->BridgeRelay
2667 || options->PublishServerDescriptor_ & BRIDGE_DIRINFO)
2668 && (options->PublishServerDescriptor_
2669 & (V1_DIRINFO|V2_DIRINFO|V3_DIRINFO))) {
2670 REJECT("Bridges are not supposed to publish router descriptors to the "
2671 "directory authorities. Please correct your "
2672 "PublishServerDescriptor line.");
2675 if (options->BridgeRelay && options->DirPort_set) {
2676 log_warn(LD_CONFIG, "Can't set a DirPort on a bridge relay; disabling "
2677 "DirPort");
2678 config_free_lines(options->DirPort_lines);
2679 options->DirPort_lines = NULL;
2680 options->DirPort_set = 0;
2683 if (options->MinUptimeHidServDirectoryV2 < 0) {
2684 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
2685 "least 0 seconds. Changing to 0.");
2686 options->MinUptimeHidServDirectoryV2 = 0;
2689 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
2690 log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
2691 "raising to %d seconds.", MIN_REND_POST_PERIOD);
2692 options->RendPostPeriod = MIN_REND_POST_PERIOD;
2695 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
2696 log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
2697 MAX_DIR_PERIOD);
2698 options->RendPostPeriod = MAX_DIR_PERIOD;
2701 if (options->Tor2webMode && options->LearnCircuitBuildTimeout) {
2702 /* LearnCircuitBuildTimeout and Tor2webMode are incompatible in
2703 * two ways:
2705 * - LearnCircuitBuildTimeout results in a low CBT, which
2706 * Tor2webMode's use of one-hop rendezvous circuits lowers
2707 * much further, producing *far* too many timeouts.
2709 * - The adaptive CBT code does not update its timeout estimate
2710 * using build times for single-hop circuits.
2712 * If we fix both of these issues someday, we should test
2713 * Tor2webMode with LearnCircuitBuildTimeout on again. */
2714 log_notice(LD_CONFIG,"Tor2webMode is enabled; turning "
2715 "LearnCircuitBuildTimeout off.");
2716 options->LearnCircuitBuildTimeout = 0;
2719 if (options->Tor2webMode && options->UseEntryGuards) {
2720 /* tor2web mode clients do not (and should not) use entry guards
2721 * in any meaningful way. Further, tor2web mode causes the hidden
2722 * service client code to do things which break the path bias
2723 * detector, and it's far easier to turn off entry guards (and
2724 * thus the path bias detector with it) than to figure out how to
2725 * make a piece of code which cannot possibly help tor2web mode
2726 * users compatible with tor2web mode.
2728 log_notice(LD_CONFIG,
2729 "Tor2WebMode is enabled; disabling UseEntryGuards.");
2730 options->UseEntryGuards = 0;
2733 if (!(options->UseEntryGuards) &&
2734 (options->RendConfigLines != NULL)) {
2735 log_warn(LD_CONFIG,
2736 "UseEntryGuards is disabled, but you have configured one or more "
2737 "hidden services on this Tor instance. Your hidden services "
2738 "will be very easy to locate using a well-known attack -- see "
2739 "http://freehaven.net/anonbib/#hs-attack06 for details.");
2742 if (!options->LearnCircuitBuildTimeout && options->CircuitBuildTimeout &&
2743 options->CircuitBuildTimeout < RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT) {
2744 log_warn(LD_CONFIG,
2745 "CircuitBuildTimeout is shorter (%d seconds) than the recommended "
2746 "minimum (%d seconds), and LearnCircuitBuildTimeout is disabled. "
2747 "If tor isn't working, raise this value or enable "
2748 "LearnCircuitBuildTimeout.",
2749 options->CircuitBuildTimeout,
2750 RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT );
2751 } else if (!options->LearnCircuitBuildTimeout &&
2752 !options->CircuitBuildTimeout) {
2753 log_notice(LD_CONFIG, "You disabled LearnCircuitBuildTimeout, but didn't "
2754 "a CircuitBuildTimeout. I'll pick a plausible default.");
2757 if (options->PathBiasNoticeRate > 1.0) {
2758 tor_asprintf(msg,
2759 "PathBiasNoticeRate is too high. "
2760 "It must be between 0 and 1.0");
2761 return -1;
2763 if (options->PathBiasWarnRate > 1.0) {
2764 tor_asprintf(msg,
2765 "PathBiasWarnRate is too high. "
2766 "It must be between 0 and 1.0");
2767 return -1;
2769 if (options->PathBiasExtremeRate > 1.0) {
2770 tor_asprintf(msg,
2771 "PathBiasExtremeRate is too high. "
2772 "It must be between 0 and 1.0");
2773 return -1;
2775 if (options->PathBiasNoticeUseRate > 1.0) {
2776 tor_asprintf(msg,
2777 "PathBiasNoticeUseRate is too high. "
2778 "It must be between 0 and 1.0");
2779 return -1;
2781 if (options->PathBiasExtremeUseRate > 1.0) {
2782 tor_asprintf(msg,
2783 "PathBiasExtremeUseRate is too high. "
2784 "It must be between 0 and 1.0");
2785 return -1;
2788 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
2789 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
2790 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
2791 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
2794 if (options->MaxCircuitDirtiness > MAX_MAX_CIRCUIT_DIRTINESS) {
2795 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too high; "
2796 "setting to %d days.", MAX_MAX_CIRCUIT_DIRTINESS/86400);
2797 options->MaxCircuitDirtiness = MAX_MAX_CIRCUIT_DIRTINESS;
2800 if (options->CircuitStreamTimeout &&
2801 options->CircuitStreamTimeout < MIN_CIRCUIT_STREAM_TIMEOUT) {
2802 log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
2803 "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
2804 options->CircuitStreamTimeout = MIN_CIRCUIT_STREAM_TIMEOUT;
2807 if (options->HeartbeatPeriod &&
2808 options->HeartbeatPeriod < MIN_HEARTBEAT_PERIOD) {
2809 log_warn(LD_CONFIG, "HeartbeatPeriod option is too short; "
2810 "raising to %d seconds.", MIN_HEARTBEAT_PERIOD);
2811 options->HeartbeatPeriod = MIN_HEARTBEAT_PERIOD;
2814 if (options->KeepalivePeriod < 1)
2815 REJECT("KeepalivePeriod option must be positive.");
2817 if (ensure_bandwidth_cap(&options->BandwidthRate,
2818 "BandwidthRate", msg) < 0)
2819 return -1;
2820 if (ensure_bandwidth_cap(&options->BandwidthBurst,
2821 "BandwidthBurst", msg) < 0)
2822 return -1;
2823 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
2824 "MaxAdvertisedBandwidth", msg) < 0)
2825 return -1;
2826 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
2827 "RelayBandwidthRate", msg) < 0)
2828 return -1;
2829 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
2830 "RelayBandwidthBurst", msg) < 0)
2831 return -1;
2832 if (ensure_bandwidth_cap(&options->PerConnBWRate,
2833 "PerConnBWRate", msg) < 0)
2834 return -1;
2835 if (ensure_bandwidth_cap(&options->PerConnBWBurst,
2836 "PerConnBWBurst", msg) < 0)
2837 return -1;
2838 if (ensure_bandwidth_cap(&options->AuthDirFastGuarantee,
2839 "AuthDirFastGuarantee", msg) < 0)
2840 return -1;
2841 if (ensure_bandwidth_cap(&options->AuthDirGuardBWGuarantee,
2842 "AuthDirGuardBWGuarantee", msg) < 0)
2843 return -1;
2845 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
2846 options->RelayBandwidthBurst = options->RelayBandwidthRate;
2847 if (options->RelayBandwidthBurst && !options->RelayBandwidthRate)
2848 options->RelayBandwidthRate = options->RelayBandwidthBurst;
2850 if (server_mode(options)) {
2851 if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
2852 tor_asprintf(msg,
2853 "BandwidthRate is set to %d bytes/second. "
2854 "For servers, it must be at least %d.",
2855 (int)options->BandwidthRate,
2856 ROUTER_REQUIRED_MIN_BANDWIDTH);
2857 return -1;
2858 } else if (options->MaxAdvertisedBandwidth <
2859 ROUTER_REQUIRED_MIN_BANDWIDTH/2) {
2860 tor_asprintf(msg,
2861 "MaxAdvertisedBandwidth is set to %d bytes/second. "
2862 "For servers, it must be at least %d.",
2863 (int)options->MaxAdvertisedBandwidth,
2864 ROUTER_REQUIRED_MIN_BANDWIDTH/2);
2865 return -1;
2867 if (options->RelayBandwidthRate &&
2868 options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
2869 tor_asprintf(msg,
2870 "RelayBandwidthRate is set to %d bytes/second. "
2871 "For servers, it must be at least %d.",
2872 (int)options->RelayBandwidthRate,
2873 ROUTER_REQUIRED_MIN_BANDWIDTH);
2874 return -1;
2878 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
2879 REJECT("RelayBandwidthBurst must be at least equal "
2880 "to RelayBandwidthRate.");
2882 if (options->BandwidthRate > options->BandwidthBurst)
2883 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
2885 /* if they set relaybandwidth* really high but left bandwidth*
2886 * at the default, raise the defaults. */
2887 if (options->RelayBandwidthRate > options->BandwidthRate)
2888 options->BandwidthRate = options->RelayBandwidthRate;
2889 if (options->RelayBandwidthBurst > options->BandwidthBurst)
2890 options->BandwidthBurst = options->RelayBandwidthBurst;
2892 if (accounting_parse_options(options, 1)<0)
2893 REJECT("Failed to parse accounting options. See logs for details.");
2895 if (options->AccountingMax) {
2896 if (options->RendConfigLines && server_mode(options)) {
2897 log_warn(LD_CONFIG, "Using accounting with a hidden service and an "
2898 "ORPort is risky: your hidden service(s) and your public "
2899 "address will all turn off at the same time, which may alert "
2900 "observers that they are being run by the same party.");
2901 } else if (config_count_key(options->RendConfigLines,
2902 "HiddenServiceDir") > 1) {
2903 log_warn(LD_CONFIG, "Using accounting with multiple hidden services is "
2904 "risky: they will all turn off at the same time, which may "
2905 "alert observers that they are being run by the same party.");
2909 if (options->HTTPProxy) { /* parse it now */
2910 if (tor_addr_port_lookup(options->HTTPProxy,
2911 &options->HTTPProxyAddr, &options->HTTPProxyPort) < 0)
2912 REJECT("HTTPProxy failed to parse or resolve. Please fix.");
2913 if (options->HTTPProxyPort == 0) { /* give it a default */
2914 options->HTTPProxyPort = 80;
2918 if (options->HTTPProxyAuthenticator) {
2919 if (strlen(options->HTTPProxyAuthenticator) >= 512)
2920 REJECT("HTTPProxyAuthenticator is too long (>= 512 chars).");
2923 if (options->HTTPSProxy) { /* parse it now */
2924 if (tor_addr_port_lookup(options->HTTPSProxy,
2925 &options->HTTPSProxyAddr, &options->HTTPSProxyPort) <0)
2926 REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
2927 if (options->HTTPSProxyPort == 0) { /* give it a default */
2928 options->HTTPSProxyPort = 443;
2932 if (options->HTTPSProxyAuthenticator) {
2933 if (strlen(options->HTTPSProxyAuthenticator) >= 512)
2934 REJECT("HTTPSProxyAuthenticator is too long (>= 512 chars).");
2937 if (options->Socks4Proxy) { /* parse it now */
2938 if (tor_addr_port_lookup(options->Socks4Proxy,
2939 &options->Socks4ProxyAddr,
2940 &options->Socks4ProxyPort) <0)
2941 REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
2942 if (options->Socks4ProxyPort == 0) { /* give it a default */
2943 options->Socks4ProxyPort = 1080;
2947 if (options->Socks5Proxy) { /* parse it now */
2948 if (tor_addr_port_lookup(options->Socks5Proxy,
2949 &options->Socks5ProxyAddr,
2950 &options->Socks5ProxyPort) <0)
2951 REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
2952 if (options->Socks5ProxyPort == 0) { /* give it a default */
2953 options->Socks5ProxyPort = 1080;
2957 /* Check if more than one proxy type has been enabled. */
2958 if (!!options->Socks4Proxy + !!options->Socks5Proxy +
2959 !!options->HTTPSProxy + !!options->ClientTransportPlugin > 1)
2960 REJECT("You have configured more than one proxy type. "
2961 "(Socks4Proxy|Socks5Proxy|HTTPSProxy|ClientTransportPlugin)");
2963 /* Check if the proxies will give surprising behavior. */
2964 if (options->HTTPProxy && !(options->Socks4Proxy ||
2965 options->Socks5Proxy ||
2966 options->HTTPSProxy)) {
2967 log_warn(LD_CONFIG, "HTTPProxy configured, but no SOCKS proxy or "
2968 "HTTPS proxy configured. Watch out: this configuration will "
2969 "proxy unencrypted directory connections only.");
2972 if (options->Socks5ProxyUsername) {
2973 size_t len;
2975 len = strlen(options->Socks5ProxyUsername);
2976 if (len < 1 || len > 255)
2977 REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
2979 if (!options->Socks5ProxyPassword)
2980 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
2982 len = strlen(options->Socks5ProxyPassword);
2983 if (len < 1 || len > 255)
2984 REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
2985 } else if (options->Socks5ProxyPassword)
2986 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
2988 if (options->HashedControlPassword) {
2989 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
2990 if (!sl) {
2991 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
2992 } else {
2993 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
2994 smartlist_free(sl);
2998 if (options->HashedControlSessionPassword) {
2999 smartlist_t *sl = decode_hashed_passwords(
3000 options->HashedControlSessionPassword);
3001 if (!sl) {
3002 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3003 } else {
3004 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3005 smartlist_free(sl);
3009 if (options->OwningControllerProcess) {
3010 const char *validate_pspec_msg = NULL;
3011 if (tor_validate_process_specifier(options->OwningControllerProcess,
3012 &validate_pspec_msg)) {
3013 tor_asprintf(msg, "Bad OwningControllerProcess: %s",
3014 validate_pspec_msg);
3015 return -1;
3019 if (options->ControlPort_set && !options->HashedControlPassword &&
3020 !options->HashedControlSessionPassword &&
3021 !options->CookieAuthentication) {
3022 log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
3023 "has been configured. This means that any program on your "
3024 "computer can reconfigure your Tor. That's bad! You should "
3025 "upgrade your Tor controller as soon as possible.");
3028 if (options->CookieAuthFileGroupReadable && !options->CookieAuthFile) {
3029 log_warn(LD_CONFIG, "CookieAuthFileGroupReadable is set, but will have "
3030 "no effect: you must specify an explicit CookieAuthFile to "
3031 "have it group-readable.");
3034 if (options->MyFamily && options->BridgeRelay) {
3035 log_warn(LD_CONFIG, "Listing a family for a bridge relay is not "
3036 "supported: it can reveal bridge fingerprints to censors. "
3037 "You should also make sure you aren't listing this bridge's "
3038 "fingerprint in any other MyFamily.");
3040 if (check_nickname_list(options->MyFamily, "MyFamily", msg))
3041 return -1;
3042 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3043 routerset_t *rs = routerset_new();
3044 if (routerset_parse(rs, cl->value, cl->key)) {
3045 routerset_free(rs);
3046 return -1;
3048 routerset_free(rs);
3051 if (validate_addr_policies(options, msg) < 0)
3052 return -1;
3054 if (validate_dir_servers(options, old_options) < 0)
3055 REJECT("Directory authority/fallback line did not parse. See logs "
3056 "for details.");
3058 if (options->UseBridges && !options->Bridges)
3059 REJECT("If you set UseBridges, you must specify at least one bridge.");
3060 if (options->UseBridges && !options->TunnelDirConns)
3061 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3062 if (options->RendConfigLines &&
3063 (!options->TunnelDirConns || !options->PreferTunneledDirConns))
3064 REJECT("If you are running a hidden service, you must set TunnelDirConns "
3065 "and PreferTunneledDirConns");
3067 for (cl = options->Bridges; cl; cl = cl->next) {
3068 if (parse_bridge_line(cl->value, 1)<0)
3069 REJECT("Bridge line did not parse. See logs for details.");
3072 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
3073 if (parse_client_transport_line(cl->value, 1)<0)
3074 REJECT("Transport line did not parse. See logs for details.");
3077 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
3078 if (parse_server_transport_line(cl->value, 1)<0)
3079 REJECT("Server transport line did not parse. See logs for details.");
3082 if (options->ServerTransportPlugin && !server_mode(options)) {
3083 log_notice(LD_GENERAL, "Tor is not configured as a relay but you specified"
3084 " a ServerTransportPlugin line (%s). The ServerTransportPlugin "
3085 "line will be ignored.",
3086 escaped(options->ServerTransportPlugin->value));
3089 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
3090 /** If get_bindaddr_from_transport_listen_line() fails with
3091 'transport' being NULL, it means that something went wrong
3092 while parsing the ServerTransportListenAddr line. */
3093 char *bindaddr = get_bindaddr_from_transport_listen_line(cl->value, NULL);
3094 if (!bindaddr)
3095 REJECT("ServerTransportListenAddr did not parse. See logs for details.");
3096 tor_free(bindaddr);
3099 if (options->ServerTransportListenAddr && !options->ServerTransportPlugin) {
3100 log_notice(LD_GENERAL, "You need at least a single managed-proxy to "
3101 "specify a transport listen address. The "
3102 "ServerTransportListenAddr line will be ignored.");
3105 if (options->ConstrainedSockets) {
3106 /* If the user wants to constrain socket buffer use, make sure the desired
3107 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3108 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3109 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3110 options->ConstrainedSockSize % 1024) {
3111 tor_asprintf(msg,
3112 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3113 "in 1024 byte increments.",
3114 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3115 return -1;
3117 if (options->DirPort_set) {
3118 /* Providing cached directory entries while system TCP buffers are scarce
3119 * will exacerbate the socket errors. Suggest that this be disabled. */
3120 COMPLAIN("You have requested constrained socket buffers while also "
3121 "serving directory entries via DirPort. It is strongly "
3122 "suggested that you disable serving directory requests when "
3123 "system TCP buffer resources are scarce.");
3127 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3128 options->V3AuthVotingInterval/2) {
3129 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3130 "V3AuthVotingInterval");
3132 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
3133 REJECT("V3AuthVoteDelay is way too low.");
3134 if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
3135 REJECT("V3AuthDistDelay is way too low.");
3137 if (options->V3AuthNIntervalsValid < 2)
3138 REJECT("V3AuthNIntervalsValid must be at least 2.");
3140 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3141 REJECT("V3AuthVotingInterval is insanely low.");
3142 } else if (options->V3AuthVotingInterval > 24*60*60) {
3143 REJECT("V3AuthVotingInterval is insanely high.");
3144 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3145 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3148 if (rend_config_services(options, 1) < 0)
3149 REJECT("Failed to configure rendezvous options. See logs for details.");
3151 /* Parse client-side authorization for hidden services. */
3152 if (rend_parse_service_authorization(options, 1) < 0)
3153 REJECT("Failed to configure client authorization for hidden services. "
3154 "See logs for details.");
3156 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv4,
3157 AF_INET, 1, msg)<0)
3158 return -1;
3159 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv6,
3160 AF_INET6, 1, msg)<0)
3161 return -1;
3163 if (options->PreferTunneledDirConns && !options->TunnelDirConns)
3164 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3166 if ((options->Socks4Proxy || options->Socks5Proxy) &&
3167 !options->HTTPProxy && !options->PreferTunneledDirConns)
3168 REJECT("When Socks4Proxy or Socks5Proxy is configured, "
3169 "PreferTunneledDirConns and TunnelDirConns must both be "
3170 "set to 1, or HTTPProxy must be configured.");
3172 if (options->AutomapHostsSuffixes) {
3173 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
3175 size_t len = strlen(suf);
3176 if (len && suf[len-1] == '.')
3177 suf[len-1] = '\0';
3181 if (options->TestingTorNetwork &&
3182 !(options->DirAuthorities ||
3183 (options->AlternateDirAuthority &&
3184 options->AlternateBridgeAuthority))) {
3185 REJECT("TestingTorNetwork may only be configured in combination with "
3186 "a non-default set of DirAuthority or both of "
3187 "AlternateDirAuthority and AlternateBridgeAuthority configured.");
3190 if (options->AllowSingleHopExits && !options->DirAuthorities) {
3191 COMPLAIN("You have set AllowSingleHopExits; now your relay will allow "
3192 "others to make one-hop exits. However, since by default most "
3193 "clients avoid relays that set this option, most clients will "
3194 "ignore you.");
3197 /*XXXX checking for defaults manually like this is a bit fragile.*/
3199 /* Keep changes to hard-coded values synchronous to man page and default
3200 * values table. */
3201 if (options->TestingV3AuthInitialVotingInterval != 30*60 &&
3202 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
3203 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
3204 "Tor networks!");
3205 } else if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
3206 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3207 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
3208 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3209 "30 minutes.");
3212 if (options->TestingV3AuthInitialVoteDelay != 5*60 &&
3213 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
3215 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
3216 "Tor networks!");
3217 } else if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
3218 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3221 if (options->TestingV3AuthInitialDistDelay != 5*60 &&
3222 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
3223 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
3224 "Tor networks!");
3225 } else if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
3226 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3229 if (options->TestingV3AuthInitialVoteDelay +
3230 options->TestingV3AuthInitialDistDelay >=
3231 options->TestingV3AuthInitialVotingInterval/2) {
3232 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3233 "must be less than half TestingV3AuthInitialVotingInterval");
3236 if (options->TestingAuthDirTimeToLearnReachability != 30*60 &&
3237 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
3238 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
3239 "testing Tor networks!");
3240 } else if (options->TestingAuthDirTimeToLearnReachability < 0) {
3241 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3242 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
3243 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3246 if (options->TestingEstimatedDescriptorPropagationTime != 10*60 &&
3247 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
3248 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
3249 "testing Tor networks!");
3250 } else if (options->TestingEstimatedDescriptorPropagationTime < 0) {
3251 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3252 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
3253 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3256 if (options->TestingTorNetwork) {
3257 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
3258 "almost unusable in the public Tor network, and is "
3259 "therefore only advised if you are building a "
3260 "testing Tor network!");
3263 if (options->AccelName && !options->HardwareAccel)
3264 options->HardwareAccel = 1;
3265 if (options->AccelDir && !options->AccelName)
3266 REJECT("Can't use hardware crypto accelerator dir without engine name.");
3268 if (options->PublishServerDescriptor)
3269 SMARTLIST_FOREACH(options->PublishServerDescriptor, const char *, pubdes, {
3270 if (!strcmp(pubdes, "1") || !strcmp(pubdes, "0"))
3271 if (smartlist_len(options->PublishServerDescriptor) > 1) {
3272 COMPLAIN("You have passed a list of multiple arguments to the "
3273 "PublishServerDescriptor option that includes 0 or 1. "
3274 "0 or 1 should only be used as the sole argument. "
3275 "This configuration will be rejected in a future release.");
3276 break;
3280 if (options->BridgeRelay == 1 && ! options->ORPort_set)
3281 REJECT("BridgeRelay is 1, ORPort is not set. This is an invalid "
3282 "combination.");
3284 return 0;
3285 #undef REJECT
3286 #undef COMPLAIN
3289 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3290 * equal strings. */
3291 static int
3292 opt_streq(const char *s1, const char *s2)
3294 return 0 == strcmp_opt(s1, s2);
3297 /** Check if any of the previous options have changed but aren't allowed to. */
3298 static int
3299 options_transition_allowed(const or_options_t *old,
3300 const or_options_t *new_val,
3301 char **msg)
3303 if (!old)
3304 return 0;
3306 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3307 *msg = tor_strdup("PidFile is not allowed to change.");
3308 return -1;
3311 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3312 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3313 "is not allowed.");
3314 return -1;
3317 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
3318 tor_asprintf(msg,
3319 "While Tor is running, changing DataDirectory "
3320 "(\"%s\"->\"%s\") is not allowed.",
3321 old->DataDirectory, new_val->DataDirectory);
3322 return -1;
3325 if (!opt_streq(old->User, new_val->User)) {
3326 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
3327 return -1;
3330 if ((old->HardwareAccel != new_val->HardwareAccel)
3331 || !opt_streq(old->AccelName, new_val->AccelName)
3332 || !opt_streq(old->AccelDir, new_val->AccelDir)) {
3333 *msg = tor_strdup("While Tor is running, changing OpenSSL hardware "
3334 "acceleration engine is not allowed.");
3335 return -1;
3338 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
3339 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
3340 "is not allowed.");
3341 return -1;
3344 if (old->DisableAllSwap != new_val->DisableAllSwap) {
3345 *msg = tor_strdup("While Tor is running, changing DisableAllSwap "
3346 "is not allowed.");
3347 return -1;
3350 if (old->TokenBucketRefillInterval != new_val->TokenBucketRefillInterval) {
3351 *msg = tor_strdup("While Tor is running, changing TokenBucketRefill"
3352 "Interval is not allowed");
3353 return -1;
3356 if (old->DisableIOCP != new_val->DisableIOCP) {
3357 *msg = tor_strdup("While Tor is running, changing DisableIOCP "
3358 "is not allowed.");
3359 return -1;
3362 if (old->DisableDebuggerAttachment &&
3363 !new_val->DisableDebuggerAttachment) {
3364 *msg = tor_strdup("While Tor is running, disabling "
3365 "DisableDebuggerAttachment is not allowed.");
3366 return -1;
3369 return 0;
3372 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3373 * will require us to rotate the CPU and DNS workers; else return 0. */
3374 static int
3375 options_transition_affects_workers(const or_options_t *old_options,
3376 const or_options_t *new_options)
3378 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3379 old_options->NumCPUs != new_options->NumCPUs ||
3380 !config_lines_eq(old_options->ORPort_lines, new_options->ORPort_lines) ||
3381 old_options->ServerDNSSearchDomains !=
3382 new_options->ServerDNSSearchDomains ||
3383 old_options->SafeLogging_ != new_options->SafeLogging_ ||
3384 old_options->ClientOnly != new_options->ClientOnly ||
3385 public_server_mode(old_options) != public_server_mode(new_options) ||
3386 !config_lines_eq(old_options->Logs, new_options->Logs) ||
3387 old_options->LogMessageDomains != new_options->LogMessageDomains)
3388 return 1;
3390 /* Check whether log options match. */
3392 /* Nothing that changed matters. */
3393 return 0;
3396 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3397 * will require us to generate a new descriptor; else return 0. */
3398 static int
3399 options_transition_affects_descriptor(const or_options_t *old_options,
3400 const or_options_t *new_options)
3402 /* XXX We can be smarter here. If your DirPort isn't being
3403 * published and you just turned it off, no need to republish. Etc. */
3404 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3405 !opt_streq(old_options->Nickname,new_options->Nickname) ||
3406 !opt_streq(old_options->Address,new_options->Address) ||
3407 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
3408 old_options->ExitPolicyRejectPrivate !=
3409 new_options->ExitPolicyRejectPrivate ||
3410 old_options->IPv6Exit != new_options->IPv6Exit ||
3411 !config_lines_eq(old_options->ORPort_lines,
3412 new_options->ORPort_lines) ||
3413 !config_lines_eq(old_options->DirPort_lines,
3414 new_options->DirPort_lines) ||
3415 old_options->ClientOnly != new_options->ClientOnly ||
3416 old_options->DisableNetwork != new_options->DisableNetwork ||
3417 old_options->PublishServerDescriptor_ !=
3418 new_options->PublishServerDescriptor_ ||
3419 get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
3420 get_effective_bwburst(old_options) !=
3421 get_effective_bwburst(new_options) ||
3422 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
3423 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
3424 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
3425 old_options->AccountingMax != new_options->AccountingMax ||
3426 public_server_mode(old_options) != public_server_mode(new_options))
3427 return 1;
3429 return 0;
3432 #ifdef _WIN32
3433 /** Return the directory on windows where we expect to find our application
3434 * data. */
3435 static char *
3436 get_windows_conf_root(void)
3438 static int is_set = 0;
3439 static char path[MAX_PATH*2+1];
3440 TCHAR tpath[MAX_PATH] = {0};
3442 LPITEMIDLIST idl;
3443 IMalloc *m;
3444 HRESULT result;
3446 if (is_set)
3447 return path;
3449 /* Find X:\documents and settings\username\application data\ .
3450 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3452 #ifdef ENABLE_LOCAL_APPDATA
3453 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
3454 #else
3455 #define APPDATA_PATH CSIDL_APPDATA
3456 #endif
3457 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
3458 getcwd(path,MAX_PATH);
3459 is_set = 1;
3460 log_warn(LD_CONFIG,
3461 "I couldn't find your application data folder: are you "
3462 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3463 path);
3464 return path;
3466 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3467 result = SHGetPathFromIDList(idl, tpath);
3468 #ifdef UNICODE
3469 wcstombs(path,tpath,sizeof(path));
3470 path[sizeof(path)-1] = '\0';
3471 #else
3472 strlcpy(path,tpath,sizeof(path));
3473 #endif
3475 /* Now we need to free the memory that the path-idl was stored in. In
3476 * typical Windows fashion, we can't just call 'free()' on it. */
3477 SHGetMalloc(&m);
3478 if (m) {
3479 m->lpVtbl->Free(m, idl);
3480 m->lpVtbl->Release(m);
3482 if (!SUCCEEDED(result)) {
3483 return NULL;
3485 strlcat(path,"\\tor",MAX_PATH);
3486 is_set = 1;
3487 return path;
3489 #endif
3491 /** Return the default location for our torrc file (if <b>defaults_file</b> is
3492 * false), or for the torrc-defaults file (if <b>defaults_file</b> is true). */
3493 static const char *
3494 get_default_conf_file(int defaults_file)
3496 #ifdef _WIN32
3497 if (defaults_file) {
3498 static char defaults_path[MAX_PATH+1];
3499 tor_snprintf(defaults_path, MAX_PATH, "%s\\torrc-defaults",
3500 get_windows_conf_root());
3501 return defaults_path;
3502 } else {
3503 static char path[MAX_PATH+1];
3504 tor_snprintf(path, MAX_PATH, "%s\\torrc",
3505 get_windows_conf_root());
3506 return path;
3508 #else
3509 return defaults_file ? CONFDIR "/torrc-defaults" : CONFDIR "/torrc";
3510 #endif
3513 /** Verify whether lst is a string containing valid-looking comma-separated
3514 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3516 static int
3517 check_nickname_list(const char *lst, const char *name, char **msg)
3519 int r = 0;
3520 smartlist_t *sl;
3522 if (!lst)
3523 return 0;
3524 sl = smartlist_new();
3526 smartlist_split_string(sl, lst, ",",
3527 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
3529 SMARTLIST_FOREACH(sl, const char *, s,
3531 if (!is_legal_nickname_or_hexdigest(s)) {
3532 tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
3533 r = -1;
3534 break;
3537 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
3538 smartlist_free(sl);
3539 return r;
3542 /** Learn config file name from command line arguments, or use the default.
3544 * If <b>defaults_file</b> is true, we're looking for torrc-defaults;
3545 * otherwise, we're looking for the regular torrc_file.
3547 * Set *<b>using_default_fname</b> to true if we're using the default
3548 * configuration file name; or false if we've set it from the command line.
3550 * Set *<b>ignore_missing_torrc</b> to true if we should ignore the resulting
3551 * filename if it doesn't exist.
3553 static char *
3554 find_torrc_filename(int argc, char **argv,
3555 int defaults_file,
3556 int *using_default_fname, int *ignore_missing_torrc)
3558 char *fname=NULL;
3559 int i;
3560 const char *fname_opt = defaults_file ? "--defaults-torrc" : "-f";
3561 const char *ignore_opt = defaults_file ? NULL : "--ignore-missing-torrc";
3563 if (defaults_file)
3564 *ignore_missing_torrc = 1;
3566 for (i = 1; i < argc; ++i) {
3567 if (i < argc-1 && !strcmp(argv[i],fname_opt)) {
3568 if (fname) {
3569 log_warn(LD_CONFIG, "Duplicate %s options on command line.",
3570 fname_opt);
3571 tor_free(fname);
3573 fname = expand_filename(argv[i+1]);
3576 char *absfname;
3577 absfname = make_path_absolute(fname);
3578 tor_free(fname);
3579 fname = absfname;
3582 *using_default_fname = 0;
3583 ++i;
3584 } else if (ignore_opt && !strcmp(argv[i],ignore_opt)) {
3585 *ignore_missing_torrc = 1;
3589 if (*using_default_fname) {
3590 /* didn't find one, try CONFDIR */
3591 const char *dflt = get_default_conf_file(defaults_file);
3592 if (dflt && file_status(dflt) == FN_FILE) {
3593 fname = tor_strdup(dflt);
3594 } else {
3595 #ifndef _WIN32
3596 char *fn = NULL;
3597 if (!defaults_file)
3598 fn = expand_filename("~/.torrc");
3599 if (fn && file_status(fn) == FN_FILE) {
3600 fname = fn;
3601 } else {
3602 tor_free(fn);
3603 fname = tor_strdup(dflt);
3605 #else
3606 fname = tor_strdup(dflt);
3607 #endif
3610 return fname;
3613 /** Load a configuration file from disk, setting torrc_fname or
3614 * torrc_defaults_fname if successful.
3616 * If <b>defaults_file</b> is true, load torrc-defaults; otherwise load torrc.
3618 * Return the contents of the file on success, and NULL on failure.
3620 static char *
3621 load_torrc_from_disk(int argc, char **argv, int defaults_file)
3623 char *fname=NULL;
3624 char *cf = NULL;
3625 int using_default_torrc = 1;
3626 int ignore_missing_torrc = 0;
3627 char **fname_var = defaults_file ? &torrc_defaults_fname : &torrc_fname;
3629 fname = find_torrc_filename(argc, argv, defaults_file,
3630 &using_default_torrc, &ignore_missing_torrc);
3631 tor_assert(fname);
3632 log_debug(LD_CONFIG, "Opening config file \"%s\"", fname);
3634 tor_free(*fname_var);
3635 *fname_var = fname;
3637 /* Open config file */
3638 if (file_status(fname) != FN_FILE ||
3639 !(cf = read_file_to_str(fname,0,NULL))) {
3640 if (using_default_torrc == 1 || ignore_missing_torrc) {
3641 if (!defaults_file)
3642 log_notice(LD_CONFIG, "Configuration file \"%s\" not present, "
3643 "using reasonable defaults.", fname);
3644 tor_free(fname); /* sets fname to NULL */
3645 *fname_var = NULL;
3646 cf = tor_strdup("");
3647 } else {
3648 log_warn(LD_CONFIG,
3649 "Unable to open configuration file \"%s\".", fname);
3650 goto err;
3652 } else {
3653 log_notice(LD_CONFIG, "Read configuration file \"%s\".", fname);
3656 return cf;
3657 err:
3658 tor_free(fname);
3659 *fname_var = NULL;
3660 return NULL;
3663 /** Read a configuration file into <b>options</b>, finding the configuration
3664 * file location based on the command line. After loading the file
3665 * call options_init_from_string() to load the config.
3666 * Return 0 if success, -1 if failure. */
3668 options_init_from_torrc(int argc, char **argv)
3670 char *cf=NULL, *cf_defaults=NULL;
3671 int i, command;
3672 int retval = -1;
3673 static char **backup_argv;
3674 static int backup_argc;
3675 char *command_arg = NULL;
3676 char *errmsg=NULL;
3678 if (argv) { /* first time we're called. save command line args */
3679 backup_argv = argv;
3680 backup_argc = argc;
3681 } else { /* we're reloading. need to clean up old options first. */
3682 argv = backup_argv;
3683 argc = backup_argc;
3685 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
3686 print_usage();
3687 exit(0);
3689 if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
3690 /* For documenting validating whether we've documented everything. */
3691 list_torrc_options();
3692 exit(0);
3695 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
3696 printf("Tor version %s.\n",get_version());
3697 exit(0);
3699 if (argc > 1 && (!strcmp(argv[1],"--digests"))) {
3700 printf("Tor version %s.\n",get_version());
3701 printf("%s", libor_get_digests());
3702 printf("%s", tor_get_digests());
3703 exit(0);
3706 /* Go through command-line variables */
3707 if (!global_cmdline_options) {
3708 /* Or we could redo the list every time we pass this place.
3709 * It does not really matter */
3710 if (config_get_commandlines(argc, argv, &global_cmdline_options) < 0) {
3711 goto err;
3715 command = CMD_RUN_TOR;
3716 for (i = 1; i < argc; ++i) {
3717 if (!strcmp(argv[i],"--list-fingerprint")) {
3718 command = CMD_LIST_FINGERPRINT;
3719 } else if (!strcmp(argv[i],"--hash-password")) {
3720 command = CMD_HASH_PASSWORD;
3721 command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
3722 ++i;
3723 } else if (!strcmp(argv[i],"--verify-config")) {
3724 command = CMD_VERIFY_CONFIG;
3728 if (command == CMD_HASH_PASSWORD) {
3729 cf_defaults = tor_strdup("");
3730 cf = tor_strdup("");
3731 } else {
3732 cf_defaults = load_torrc_from_disk(argc, argv, 1);
3733 cf = load_torrc_from_disk(argc, argv, 0);
3734 if (!cf)
3735 goto err;
3738 retval = options_init_from_string(cf_defaults, cf, command, command_arg,
3739 &errmsg);
3741 err:
3743 tor_free(cf);
3744 tor_free(cf_defaults);
3745 if (errmsg) {
3746 log_warn(LD_CONFIG,"%s", errmsg);
3747 tor_free(errmsg);
3749 return retval < 0 ? -1 : 0;
3752 /** Load the options from the configuration in <b>cf</b>, validate
3753 * them for consistency and take actions based on them.
3755 * Return 0 if success, negative on error:
3756 * * -1 for general errors.
3757 * * -2 for failure to parse/validate,
3758 * * -3 for transition not allowed
3759 * * -4 for error while setting the new options
3761 setopt_err_t
3762 options_init_from_string(const char *cf_defaults, const char *cf,
3763 int command, const char *command_arg,
3764 char **msg)
3766 or_options_t *oldoptions, *newoptions, *newdefaultoptions=NULL;
3767 config_line_t *cl;
3768 int retval, i;
3769 setopt_err_t err = SETOPT_ERR_MISC;
3770 tor_assert(msg);
3772 oldoptions = global_options; /* get_options unfortunately asserts if
3773 this is the first time we run*/
3775 newoptions = tor_malloc_zero(sizeof(or_options_t));
3776 newoptions->magic_ = OR_OPTIONS_MAGIC;
3777 options_init(newoptions);
3778 newoptions->command = command;
3779 newoptions->command_arg = command_arg;
3781 for (i = 0; i < 2; ++i) {
3782 const char *body = i==0 ? cf_defaults : cf;
3783 if (!body)
3784 continue;
3785 /* get config lines, assign them */
3786 retval = config_get_lines(body, &cl, 1);
3787 if (retval < 0) {
3788 err = SETOPT_ERR_PARSE;
3789 goto err;
3791 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
3792 config_free_lines(cl);
3793 if (retval < 0) {
3794 err = SETOPT_ERR_PARSE;
3795 goto err;
3797 if (i==0)
3798 newdefaultoptions = config_dup(&options_format, newoptions);
3801 if (newdefaultoptions == NULL) {
3802 newdefaultoptions = config_dup(&options_format, global_default_options);
3805 /* Go through command-line variables too */
3806 retval = config_assign(&options_format, newoptions,
3807 global_cmdline_options, 0, 0, msg);
3808 if (retval < 0) {
3809 err = SETOPT_ERR_PARSE;
3810 goto err;
3813 /* If this is a testing network configuration, change defaults
3814 * for a list of dependent config options, re-initialize newoptions
3815 * with the new defaults, and assign all options to it second time. */
3816 if (newoptions->TestingTorNetwork) {
3817 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
3818 * this? We could, for example, make the parsing algorithm do two passes
3819 * over the configuration. If it finds any "suite" options like
3820 * TestingTorNetwork, it could change the defaults before its second pass.
3821 * Not urgent so long as this seems to work, but at any sign of trouble,
3822 * let's clean it up. -NM */
3824 /* Change defaults. */
3825 int i;
3826 for (i = 0; testing_tor_network_defaults[i].name; ++i) {
3827 const config_var_t *new_var = &testing_tor_network_defaults[i];
3828 config_var_t *old_var =
3829 config_find_option_mutable(&options_format, new_var->name);
3830 tor_assert(new_var);
3831 tor_assert(old_var);
3832 old_var->initvalue = new_var->initvalue;
3835 /* Clear newoptions and re-initialize them with new defaults. */
3836 config_free(&options_format, newoptions);
3837 config_free(&options_format, newdefaultoptions);
3838 newdefaultoptions = NULL;
3839 newoptions = tor_malloc_zero(sizeof(or_options_t));
3840 newoptions->magic_ = OR_OPTIONS_MAGIC;
3841 options_init(newoptions);
3842 newoptions->command = command;
3843 newoptions->command_arg = command_arg;
3845 /* Assign all options a second time. */
3846 for (i = 0; i < 2; ++i) {
3847 const char *body = i==0 ? cf_defaults : cf;
3848 if (!body)
3849 continue;
3850 /* get config lines, assign them */
3851 retval = config_get_lines(body, &cl, 1);
3852 if (retval < 0) {
3853 err = SETOPT_ERR_PARSE;
3854 goto err;
3856 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
3857 config_free_lines(cl);
3858 if (retval < 0) {
3859 err = SETOPT_ERR_PARSE;
3860 goto err;
3862 if (i==0)
3863 newdefaultoptions = config_dup(&options_format, newoptions);
3865 /* Assign command-line variables a second time too */
3866 retval = config_assign(&options_format, newoptions,
3867 global_cmdline_options, 0, 0, msg);
3868 if (retval < 0) {
3869 err = SETOPT_ERR_PARSE;
3870 goto err;
3874 /* Validate newoptions */
3875 if (options_validate(oldoptions, newoptions, 0, msg) < 0) {
3876 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
3877 goto err;
3880 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
3881 err = SETOPT_ERR_TRANSITION;
3882 goto err;
3885 if (set_options(newoptions, msg)) {
3886 err = SETOPT_ERR_SETTING;
3887 goto err; /* frees and replaces old options */
3889 config_free(&options_format, global_default_options);
3890 global_default_options = newdefaultoptions;
3892 return SETOPT_OK;
3894 err:
3895 config_free(&options_format, newoptions);
3896 config_free(&options_format, newdefaultoptions);
3897 if (*msg) {
3898 char *old_msg = *msg;
3899 tor_asprintf(msg, "Failed to parse/validate config: %s", old_msg);
3900 tor_free(old_msg);
3902 return err;
3905 /** Return the location for our configuration file.
3907 const char *
3908 get_torrc_fname(int defaults_fname)
3910 const char *fname = defaults_fname ? torrc_defaults_fname : torrc_fname;
3912 if (fname)
3913 return fname;
3914 else
3915 return get_default_conf_file(defaults_fname);
3918 /** Adjust the address map based on the MapAddress elements in the
3919 * configuration <b>options</b>
3921 void
3922 config_register_addressmaps(const or_options_t *options)
3924 smartlist_t *elts;
3925 config_line_t *opt;
3926 const char *from, *to, *msg;
3928 addressmap_clear_configured();
3929 elts = smartlist_new();
3930 for (opt = options->AddressMap; opt; opt = opt->next) {
3931 smartlist_split_string(elts, opt->value, NULL,
3932 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
3933 if (smartlist_len(elts) < 2) {
3934 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
3935 opt->value);
3936 goto cleanup;
3939 from = smartlist_get(elts,0);
3940 to = smartlist_get(elts,1);
3942 if (to[0] == '.' || from[0] == '.') {
3943 log_warn(LD_CONFIG,"MapAddress '%s' is ambiguous - address starts with a"
3944 "'.'. Ignoring.",opt->value);
3945 goto cleanup;
3948 if (addressmap_register_auto(from, to, 0, ADDRMAPSRC_TORRC, &msg) < 0) {
3949 log_warn(LD_CONFIG,"MapAddress '%s' failed: %s. Ignoring.", opt->value,
3950 msg);
3951 goto cleanup;
3954 if (smartlist_len(elts) > 2)
3955 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
3957 cleanup:
3958 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
3959 smartlist_clear(elts);
3961 smartlist_free(elts);
3964 /** As addressmap_register(), but detect the wildcarded status of "from" and
3965 * "to", and do not steal a reference to <b>to</b>. */
3966 /* XXXX024 move to connection_edge.c */
3968 addressmap_register_auto(const char *from, const char *to,
3969 time_t expires,
3970 addressmap_entry_source_t addrmap_source,
3971 const char **msg)
3973 int from_wildcard = 0, to_wildcard = 0;
3975 *msg = "whoops, forgot the error message";
3976 if (1) {
3977 if (!strcmp(to, "*") || !strcmp(from, "*")) {
3978 *msg = "can't remap from or to *";
3979 return -1;
3981 /* Detect asterisks in expressions of type: '*.example.com' */
3982 if (!strncmp(from,"*.",2)) {
3983 from += 2;
3984 from_wildcard = 1;
3986 if (!strncmp(to,"*.",2)) {
3987 to += 2;
3988 to_wildcard = 1;
3991 if (to_wildcard && !from_wildcard) {
3992 *msg = "can only use wildcard (i.e. '*.') if 'from' address "
3993 "uses wildcard also";
3994 return -1;
3997 if (address_is_invalid_destination(to, 1)) {
3998 *msg = "destination is invalid";
3999 return -1;
4002 addressmap_register(from, tor_strdup(to), expires, addrmap_source,
4003 from_wildcard, to_wildcard);
4005 return 0;
4009 * Initialize the logs based on the configuration file.
4011 static int
4012 options_init_logs(or_options_t *options, int validate_only)
4014 config_line_t *opt;
4015 int ok;
4016 smartlist_t *elts;
4017 int daemon =
4018 #ifdef _WIN32
4020 #else
4021 options->RunAsDaemon;
4022 #endif
4024 if (options->LogTimeGranularity <= 0) {
4025 log_warn(LD_CONFIG, "Log time granularity '%d' has to be positive.",
4026 options->LogTimeGranularity);
4027 return -1;
4028 } else if (1000 % options->LogTimeGranularity != 0 &&
4029 options->LogTimeGranularity % 1000 != 0) {
4030 int granularity = options->LogTimeGranularity;
4031 if (granularity < 40) {
4032 do granularity++;
4033 while (1000 % granularity != 0);
4034 } else if (granularity < 1000) {
4035 granularity = 1000 / granularity;
4036 while (1000 % granularity != 0)
4037 granularity--;
4038 granularity = 1000 / granularity;
4039 } else {
4040 granularity = 1000 * ((granularity / 1000) + 1);
4042 log_warn(LD_CONFIG, "Log time granularity '%d' has to be either a "
4043 "divisor or a multiple of 1 second. Changing to "
4044 "'%d'.",
4045 options->LogTimeGranularity, granularity);
4046 if (!validate_only)
4047 set_log_time_granularity(granularity);
4048 } else {
4049 if (!validate_only)
4050 set_log_time_granularity(options->LogTimeGranularity);
4053 ok = 1;
4054 elts = smartlist_new();
4056 for (opt = options->Logs; opt; opt = opt->next) {
4057 log_severity_list_t *severity;
4058 const char *cfg = opt->value;
4059 severity = tor_malloc_zero(sizeof(log_severity_list_t));
4060 if (parse_log_severity_config(&cfg, severity) < 0) {
4061 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
4062 opt->value);
4063 ok = 0; goto cleanup;
4066 smartlist_split_string(elts, cfg, NULL,
4067 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4069 if (smartlist_len(elts) == 0)
4070 smartlist_add(elts, tor_strdup("stdout"));
4072 if (smartlist_len(elts) == 1 &&
4073 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
4074 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
4075 int err = smartlist_len(elts) &&
4076 !strcasecmp(smartlist_get(elts,0), "stderr");
4077 if (!validate_only) {
4078 if (daemon) {
4079 log_warn(LD_CONFIG,
4080 "Can't log to %s with RunAsDaemon set; skipping stdout",
4081 err?"stderr":"stdout");
4082 } else {
4083 add_stream_log(severity, err?"<stderr>":"<stdout>",
4084 fileno(err?stderr:stdout));
4087 goto cleanup;
4089 if (smartlist_len(elts) == 1 &&
4090 !strcasecmp(smartlist_get(elts,0), "syslog")) {
4091 #ifdef HAVE_SYSLOG_H
4092 if (!validate_only) {
4093 add_syslog_log(severity);
4095 #else
4096 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
4097 #endif
4098 goto cleanup;
4101 if (smartlist_len(elts) == 2 &&
4102 !strcasecmp(smartlist_get(elts,0), "file")) {
4103 if (!validate_only) {
4104 char *fname = expand_filename(smartlist_get(elts, 1));
4105 if (add_file_log(severity, fname) < 0) {
4106 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
4107 opt->value, strerror(errno));
4108 ok = 0;
4110 tor_free(fname);
4112 goto cleanup;
4115 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
4116 opt->value);
4117 ok = 0; goto cleanup;
4119 cleanup:
4120 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4121 smartlist_clear(elts);
4122 tor_free(severity);
4124 smartlist_free(elts);
4126 if (ok && !validate_only)
4127 logs_set_domain_logging(options->LogMessageDomains);
4129 return ok?0:-1;
4132 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4133 * if the line is well-formed, and -1 if it isn't. If
4134 * <b>validate_only</b> is 0, and the line is well-formed, then add
4135 * the bridge described in the line to our internal bridge list. */
4136 static int
4137 parse_bridge_line(const char *line, int validate_only)
4139 smartlist_t *items = NULL;
4140 int r;
4141 char *addrport=NULL, *fingerprint=NULL;
4142 char *transport_name=NULL;
4143 char *field1=NULL;
4144 tor_addr_t addr;
4145 uint16_t port = 0;
4146 char digest[DIGEST_LEN];
4148 items = smartlist_new();
4149 smartlist_split_string(items, line, NULL,
4150 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4151 if (smartlist_len(items) < 1) {
4152 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
4153 goto err;
4156 /* field1 is either a transport name or addrport */
4157 field1 = smartlist_get(items, 0);
4158 smartlist_del_keeporder(items, 0);
4160 if (!(strstr(field1, ".") || strstr(field1, ":"))) {
4161 /* new-style bridge line */
4162 transport_name = field1;
4163 if (smartlist_len(items) < 1) {
4164 log_warn(LD_CONFIG, "Too few items to Bridge line.");
4165 goto err;
4167 addrport = smartlist_get(items, 0);
4168 smartlist_del_keeporder(items, 0);
4169 } else {
4170 addrport = field1;
4173 if (tor_addr_port_lookup(addrport, &addr, &port)<0) {
4174 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
4175 goto err;
4177 if (!port) {
4178 log_info(LD_CONFIG,
4179 "Bridge address '%s' has no port; using default port 443.",
4180 addrport);
4181 port = 443;
4184 if (smartlist_len(items)) {
4185 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4186 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4187 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
4188 goto err;
4190 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4191 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
4192 goto err;
4196 if (!validate_only) {
4197 log_debug(LD_DIR, "Bridge at %s (transport: %s) (%s)",
4198 fmt_addrport(&addr, port),
4199 transport_name ? transport_name : "no transport",
4200 fingerprint ? fingerprint : "no key listed");
4201 bridge_add_from_config(&addr, port,
4202 fingerprint ? digest : NULL, transport_name);
4205 r = 0;
4206 goto done;
4208 err:
4209 r = -1;
4211 done:
4212 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4213 smartlist_free(items);
4214 tor_free(addrport);
4215 tor_free(transport_name);
4216 tor_free(fingerprint);
4217 return r;
4220 /** Read the contents of a ClientTransportPlugin line from
4221 * <b>line</b>. Return 0 if the line is well-formed, and -1 if it
4222 * isn't.
4224 * If <b>validate_only</b> is 0, and the line is well-formed:
4225 * - If it's an external proxy line, add the transport described in the line to
4226 * our internal transport list.
4227 * - If it's a managed proxy line, launch the managed proxy. */
4228 static int
4229 parse_client_transport_line(const char *line, int validate_only)
4231 smartlist_t *items = NULL;
4232 int r;
4233 char *field2=NULL;
4235 const char *transports=NULL;
4236 smartlist_t *transport_list=NULL;
4237 char *addrport=NULL;
4238 tor_addr_t addr;
4239 uint16_t port = 0;
4240 int socks_ver=PROXY_NONE;
4242 /* managed proxy options */
4243 int is_managed=0;
4244 char **proxy_argv=NULL;
4245 char **tmp=NULL;
4246 int proxy_argc,i;
4248 int line_length;
4250 items = smartlist_new();
4251 smartlist_split_string(items, line, NULL,
4252 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4254 line_length = smartlist_len(items);
4255 if (line_length < 3) {
4256 log_warn(LD_CONFIG, "Too few arguments on ClientTransportPlugin line.");
4257 goto err;
4260 /* Get the first line element, split it to commas into
4261 transport_list (in case it's multiple transports) and validate
4262 the transport names. */
4263 transports = smartlist_get(items, 0);
4264 transport_list = smartlist_new();
4265 smartlist_split_string(transport_list, transports, ",",
4266 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
4267 SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
4268 if (!string_is_C_identifier(transport_name)) {
4269 log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
4270 transport_name);
4271 goto err;
4273 } SMARTLIST_FOREACH_END(transport_name);
4275 /* field2 is either a SOCKS version or "exec" */
4276 field2 = smartlist_get(items, 1);
4278 if (!strcmp(field2,"socks4")) {
4279 socks_ver = PROXY_SOCKS4;
4280 } else if (!strcmp(field2,"socks5")) {
4281 socks_ver = PROXY_SOCKS5;
4282 } else if (!strcmp(field2,"exec")) {
4283 is_managed=1;
4284 } else {
4285 log_warn(LD_CONFIG, "Strange ClientTransportPlugin field '%s'.",
4286 field2);
4287 goto err;
4290 if (is_managed) { /* managed */
4291 if (!validate_only) { /* if we are not just validating, use the
4292 rest of the line as the argv of the proxy
4293 to be launched */
4294 proxy_argc = line_length-2;
4295 tor_assert(proxy_argc > 0);
4296 proxy_argv = tor_malloc_zero(sizeof(char*)*(proxy_argc+1));
4297 tmp = proxy_argv;
4298 for (i=0;i<proxy_argc;i++) { /* store arguments */
4299 *tmp++ = smartlist_get(items, 2);
4300 smartlist_del_keeporder(items, 2);
4302 *tmp = NULL; /*terminated with NULL, just like execve() likes it*/
4304 /* kickstart the thing */
4305 pt_kickstart_client_proxy(transport_list, proxy_argv);
4307 } else { /* external */
4308 if (smartlist_len(transport_list) != 1) {
4309 log_warn(LD_CONFIG, "You can't have an external proxy with "
4310 "more than one transports.");
4311 goto err;
4314 addrport = smartlist_get(items, 2);
4316 if (tor_addr_port_lookup(addrport, &addr, &port)<0) {
4317 log_warn(LD_CONFIG, "Error parsing transport "
4318 "address '%s'", addrport);
4319 goto err;
4321 if (!port) {
4322 log_warn(LD_CONFIG,
4323 "Transport address '%s' has no port.", addrport);
4324 goto err;
4327 if (!validate_only) {
4328 transport_add_from_config(&addr, port, smartlist_get(transport_list, 0),
4329 socks_ver);
4331 log_info(LD_DIR, "Transport '%s' found at %s",
4332 transports, fmt_addrport(&addr, port));
4336 r = 0;
4337 goto done;
4339 err:
4340 r = -1;
4342 done:
4343 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4344 smartlist_free(items);
4345 if (transport_list) {
4346 SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
4347 smartlist_free(transport_list);
4350 return r;
4353 /** Given a ServerTransportListenAddr <b>line</b>, return its
4354 * <address:port> string. Return NULL if the line was not
4355 * well-formed.
4357 * If <b>transport</b> is set, return NULL if the line is not
4358 * referring to <b>transport</b>.
4360 * The returned string is allocated on the heap and it's the
4361 * responsibility of the caller to free it. */
4362 static char *
4363 get_bindaddr_from_transport_listen_line(const char *line,const char *transport)
4365 smartlist_t *items = NULL;
4366 const char *parsed_transport = NULL;
4367 char *addrport = NULL;
4368 tor_addr_t addr;
4369 uint16_t port = 0;
4371 items = smartlist_new();
4372 smartlist_split_string(items, line, NULL,
4373 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4375 if (smartlist_len(items) < 2) {
4376 log_warn(LD_CONFIG,"Too few arguments on ServerTransportListenAddr line.");
4377 goto err;
4380 parsed_transport = smartlist_get(items, 0);
4381 addrport = tor_strdup(smartlist_get(items, 1));
4383 /* If 'transport' is given, check if it matches the one on the line */
4384 if (transport && strcmp(transport, parsed_transport))
4385 goto err;
4387 /* Validate addrport */
4388 if (tor_addr_port_parse(LOG_WARN, addrport, &addr, &port)<0) {
4389 log_warn(LD_CONFIG, "Error parsing ServerTransportListenAddr "
4390 "address '%s'", addrport);
4391 goto err;
4394 goto done;
4396 err:
4397 tor_free(addrport);
4398 addrport = NULL;
4400 done:
4401 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4402 smartlist_free(items);
4404 return addrport;
4407 /** Given the name of a pluggable transport in <b>transport</b>, check
4408 * the configuration file to see if the user has explicitly asked for
4409 * it to listen on a specific port. Return a <address:port> string if
4410 * so, otherwise NULL. */
4411 char *
4412 get_transport_bindaddr_from_config(const char *transport)
4414 config_line_t *cl;
4415 const or_options_t *options = get_options();
4417 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
4418 char *bindaddr =
4419 get_bindaddr_from_transport_listen_line(cl->value, transport);
4420 if (bindaddr)
4421 return bindaddr;
4424 return NULL;
4427 /** Read the contents of a ServerTransportPlugin line from
4428 * <b>line</b>. Return 0 if the line is well-formed, and -1 if it
4429 * isn't.
4430 * If <b>validate_only</b> is 0, the line is well-formed, and it's a
4431 * managed proxy line, launch the managed proxy. */
4432 static int
4433 parse_server_transport_line(const char *line, int validate_only)
4435 smartlist_t *items = NULL;
4436 int r;
4437 const char *transports=NULL;
4438 smartlist_t *transport_list=NULL;
4439 char *type=NULL;
4440 char *addrport=NULL;
4441 tor_addr_t addr;
4442 uint16_t port = 0;
4444 /* managed proxy options */
4445 int is_managed=0;
4446 char **proxy_argv=NULL;
4447 char **tmp=NULL;
4448 int proxy_argc,i;
4450 int line_length;
4452 items = smartlist_new();
4453 smartlist_split_string(items, line, NULL,
4454 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4456 line_length = smartlist_len(items);
4457 if (line_length < 3) {
4458 log_warn(LD_CONFIG, "Too few arguments on ServerTransportPlugin line.");
4459 goto err;
4462 /* Get the first line element, split it to commas into
4463 transport_list (in case it's multiple transports) and validate
4464 the transport names. */
4465 transports = smartlist_get(items, 0);
4466 transport_list = smartlist_new();
4467 smartlist_split_string(transport_list, transports, ",",
4468 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
4469 SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
4470 if (!string_is_C_identifier(transport_name)) {
4471 log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
4472 transport_name);
4473 goto err;
4475 } SMARTLIST_FOREACH_END(transport_name);
4477 type = smartlist_get(items, 1);
4479 if (!strcmp(type, "exec")) {
4480 is_managed=1;
4481 } else if (!strcmp(type, "proxy")) {
4482 is_managed=0;
4483 } else {
4484 log_warn(LD_CONFIG, "Strange ServerTransportPlugin type '%s'", type);
4485 goto err;
4488 if (is_managed) { /* managed */
4489 if (!validate_only) {
4490 proxy_argc = line_length-2;
4491 tor_assert(proxy_argc > 0);
4492 proxy_argv = tor_malloc_zero(sizeof(char*)*(proxy_argc+1));
4493 tmp = proxy_argv;
4495 for (i=0;i<proxy_argc;i++) { /* store arguments */
4496 *tmp++ = smartlist_get(items, 2);
4497 smartlist_del_keeporder(items, 2);
4499 *tmp = NULL; /*terminated with NULL, just like execve() likes it*/
4501 /* kickstart the thing */
4502 pt_kickstart_server_proxy(transport_list, proxy_argv);
4504 } else { /* external */
4505 if (smartlist_len(transport_list) != 1) {
4506 log_warn(LD_CONFIG, "You can't have an external proxy with "
4507 "more than one transports.");
4508 goto err;
4511 addrport = smartlist_get(items, 2);
4513 if (tor_addr_port_lookup(addrport, &addr, &port)<0) {
4514 log_warn(LD_CONFIG, "Error parsing transport "
4515 "address '%s'", addrport);
4516 goto err;
4518 if (!port) {
4519 log_warn(LD_CONFIG,
4520 "Transport address '%s' has no port.", addrport);
4521 goto err;
4524 if (!validate_only) {
4525 log_info(LD_DIR, "Server transport '%s' at %s.",
4526 transports, fmt_addrport(&addr, port));
4530 r = 0;
4531 goto done;
4533 err:
4534 r = -1;
4536 done:
4537 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4538 smartlist_free(items);
4539 if (transport_list) {
4540 SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
4541 smartlist_free(transport_list);
4544 return r;
4547 /** Read the contents of a DirAuthority line from <b>line</b>. If
4548 * <b>validate_only</b> is 0, and the line is well-formed, and it
4549 * shares any bits with <b>required_type</b> or <b>required_type</b>
4550 * is 0, then add the dirserver described in the line (minus whatever
4551 * bits it's missing) as a valid authority. Return 0 on success,
4552 * or -1 if the line isn't well-formed or if we can't add it. */
4553 static int
4554 parse_dir_authority_line(const char *line, dirinfo_type_t required_type,
4555 int validate_only)
4557 smartlist_t *items = NULL;
4558 int r;
4559 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
4560 uint16_t dir_port = 0, or_port = 0;
4561 char digest[DIGEST_LEN];
4562 char v3_digest[DIGEST_LEN];
4563 dirinfo_type_t type = V2_DIRINFO;
4564 int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
4565 double weight = 1.0;
4567 items = smartlist_new();
4568 smartlist_split_string(items, line, NULL,
4569 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4570 if (smartlist_len(items) < 1) {
4571 log_warn(LD_CONFIG, "No arguments on DirAuthority line.");
4572 goto err;
4575 if (is_legal_nickname(smartlist_get(items, 0))) {
4576 nickname = smartlist_get(items, 0);
4577 smartlist_del_keeporder(items, 0);
4580 while (smartlist_len(items)) {
4581 char *flag = smartlist_get(items, 0);
4582 if (TOR_ISDIGIT(flag[0]))
4583 break;
4584 if (!strcasecmp(flag, "v1")) {
4585 type |= (V1_DIRINFO | HIDSERV_DIRINFO);
4586 } else if (!strcasecmp(flag, "hs")) {
4587 type |= HIDSERV_DIRINFO;
4588 } else if (!strcasecmp(flag, "no-hs")) {
4589 is_not_hidserv_authority = 1;
4590 } else if (!strcasecmp(flag, "bridge")) {
4591 type |= BRIDGE_DIRINFO;
4592 } else if (!strcasecmp(flag, "no-v2")) {
4593 is_not_v2_authority = 1;
4594 } else if (!strcasecmpstart(flag, "orport=")) {
4595 int ok;
4596 char *portstring = flag + strlen("orport=");
4597 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
4598 if (!ok)
4599 log_warn(LD_CONFIG, "Invalid orport '%s' on DirAuthority line.",
4600 portstring);
4601 } else if (!strcmpstart(flag, "weight=")) {
4602 int ok;
4603 const char *wstring = flag + strlen("weight=");
4604 weight = tor_parse_double(wstring, 0, UINT64_MAX, &ok, NULL);
4605 if (!ok) {
4606 log_warn(LD_CONFIG, "Invalid weight '%s' on DirAuthority line.",flag);
4607 weight=1.0;
4609 } else if (!strcasecmpstart(flag, "v3ident=")) {
4610 char *idstr = flag + strlen("v3ident=");
4611 if (strlen(idstr) != HEX_DIGEST_LEN ||
4612 base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
4613 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirAuthority line",
4614 flag);
4615 } else {
4616 type |= V3_DIRINFO|EXTRAINFO_DIRINFO|MICRODESC_DIRINFO;
4618 } else {
4619 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirAuthority line",
4620 flag);
4622 tor_free(flag);
4623 smartlist_del_keeporder(items, 0);
4625 if (is_not_hidserv_authority)
4626 type &= ~HIDSERV_DIRINFO;
4627 if (is_not_v2_authority)
4628 type &= ~V2_DIRINFO;
4630 if (smartlist_len(items) < 2) {
4631 log_warn(LD_CONFIG, "Too few arguments to DirAuthority line.");
4632 goto err;
4634 addrport = smartlist_get(items, 0);
4635 smartlist_del_keeporder(items, 0);
4636 if (addr_port_lookup(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
4637 log_warn(LD_CONFIG, "Error parsing DirAuthority address '%s'", addrport);
4638 goto err;
4640 if (!dir_port) {
4641 log_warn(LD_CONFIG, "Missing port in DirAuthority address '%s'",addrport);
4642 goto err;
4645 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4646 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4647 log_warn(LD_CONFIG, "Key digest '%s' for DirAuthority is wrong length %d.",
4648 fingerprint, (int)strlen(fingerprint));
4649 goto err;
4651 if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4652 /* a known bad fingerprint. refuse to use it. We can remove this
4653 * clause once Tor 0.1.2.17 is obsolete. */
4654 log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
4655 "torrc file (%s), or reinstall Tor and use the default torrc.",
4656 get_torrc_fname(0));
4657 goto err;
4659 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4660 log_warn(LD_CONFIG, "Unable to decode DirAuthority key digest.");
4661 goto err;
4664 if (!validate_only && (!required_type || required_type & type)) {
4665 dir_server_t *ds;
4666 if (required_type)
4667 type &= required_type; /* pare down what we think of them as an
4668 * authority for. */
4669 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
4670 address, (int)dir_port, (char*)smartlist_get(items,0));
4671 if (!(ds = trusted_dir_server_new(nickname, address, dir_port, or_port,
4672 digest, v3_digest, type, weight)))
4673 goto err;
4674 dir_server_add(ds);
4677 r = 0;
4678 goto done;
4680 err:
4681 r = -1;
4683 done:
4684 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4685 smartlist_free(items);
4686 tor_free(addrport);
4687 tor_free(address);
4688 tor_free(nickname);
4689 tor_free(fingerprint);
4690 return r;
4693 /** Read the contents of a FallbackDir line from <b>line</b>. If
4694 * <b>validate_only</b> is 0, and the line is well-formed, then add the
4695 * dirserver described in the line as a fallback directory. Return 0 on
4696 * success, or -1 if the line isn't well-formed or if we can't add it. */
4697 static int
4698 parse_dir_fallback_line(const char *line,
4699 int validate_only)
4701 int r = -1;
4702 smartlist_t *items = smartlist_new(), *positional = smartlist_new();
4703 int orport = -1;
4704 uint16_t dirport;
4705 tor_addr_t addr;
4706 int ok;
4707 char id[DIGEST_LEN];
4708 char *address=NULL;
4709 double weight=1.0;
4711 memset(id, 0, sizeof(id));
4712 smartlist_split_string(items, line, NULL,
4713 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4714 SMARTLIST_FOREACH_BEGIN(items, const char *, cp) {
4715 const char *eq = strchr(cp, '=');
4716 ok = 1;
4717 if (! eq) {
4718 smartlist_add(positional, (char*)cp);
4719 continue;
4721 if (!strcmpstart(cp, "orport=")) {
4722 orport = (int)tor_parse_long(cp+strlen("orport="), 10,
4723 1, 65535, &ok, NULL);
4724 } else if (!strcmpstart(cp, "id=")) {
4725 ok = !base16_decode(id, DIGEST_LEN,
4726 cp+strlen("id="), strlen(cp)-strlen("id="));
4727 } else if (!strcmpstart(cp, "weight=")) {
4728 int ok;
4729 const char *wstring = cp + strlen("weight=");
4730 weight = tor_parse_double(wstring, 0, UINT64_MAX, &ok, NULL);
4731 if (!ok) {
4732 log_warn(LD_CONFIG, "Invalid weight '%s' on FallbackDir line.", cp);
4733 weight=1.0;
4737 if (!ok) {
4738 log_warn(LD_CONFIG, "Bad FallbackDir option %s", escaped(cp));
4739 goto end;
4741 } SMARTLIST_FOREACH_END(cp);
4743 if (smartlist_len(positional) != 1) {
4744 log_warn(LD_CONFIG, "Couldn't parse FallbackDir line %s", escaped(line));
4745 goto end;
4748 if (tor_digest_is_zero(id)) {
4749 log_warn(LD_CONFIG, "Missing identity on FallbackDir line");
4750 goto end;
4753 if (orport <= 0) {
4754 log_warn(LD_CONFIG, "Missing orport on FallbackDir line");
4755 goto end;
4758 if (tor_addr_port_split(LOG_INFO, smartlist_get(positional, 0),
4759 &address, &dirport) < 0 ||
4760 tor_addr_parse(&addr, address)<0) {
4761 log_warn(LD_CONFIG, "Couldn't parse address:port %s on FallbackDir line",
4762 (const char*)smartlist_get(positional, 0));
4763 goto end;
4766 if (!validate_only) {
4767 dir_server_t *ds;
4768 ds = fallback_dir_server_new(&addr, dirport, orport, id, weight);
4769 if (!ds) {
4770 log_warn(LD_CONFIG, "Couldn't create FallbackDir %s", escaped(line));
4771 goto end;
4773 dir_server_add(ds);
4776 r = 0;
4778 end:
4779 SMARTLIST_FOREACH(items, char *, cp, tor_free(cp));
4780 smartlist_free(items);
4781 smartlist_free(positional);
4782 tor_free(address);
4783 return r;
4786 /** Allocate and return a new port_cfg_t with reasonable defaults. */
4787 static port_cfg_t *
4788 port_cfg_new(void)
4790 port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t));
4791 cfg->ipv4_traffic = 1;
4792 cfg->cache_ipv4_answers = 1;
4793 cfg->prefer_ipv6_virtaddr = 1;
4794 return cfg;
4797 /** Free all storage held in <b>port</b> */
4798 static void
4799 port_cfg_free(port_cfg_t *port)
4801 tor_free(port);
4804 /** Warn for every port in <b>ports</b> of type <b>listener_type</b> that is
4805 * on a publicly routable address. */
4806 static void
4807 warn_nonlocal_client_ports(const smartlist_t *ports, const char *portname,
4808 int listener_type)
4810 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
4811 if (port->type != listener_type)
4812 continue;
4813 if (port->is_unix_addr) {
4814 /* Unix sockets aren't accessible over a network. */
4815 } else if (!tor_addr_is_internal(&port->addr, 1)) {
4816 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
4817 "Other people on the Internet might find your computer and "
4818 "use it as an open proxy. Please don't allow this unless you "
4819 "have a good reason.",
4820 fmt_addrport(&port->addr, port->port), portname);
4821 } else if (!tor_addr_is_loopback(&port->addr)) {
4822 log_notice(LD_CONFIG, "You configured a non-loopback address '%s' "
4823 "for %sPort. This allows everybody on your local network to "
4824 "use your machine as a proxy. Make sure this is what you "
4825 "wanted.",
4826 fmt_addrport(&port->addr, port->port), portname);
4828 } SMARTLIST_FOREACH_END(port);
4831 /** Given a list of port_cfg_t in <b>ports</b>, warn any controller port there
4832 * is listening on any non-loopback address. If <b>forbid</b> is true,
4833 * then emit a stronger warning and remove the port from the list.
4835 static void
4836 warn_nonlocal_controller_ports(smartlist_t *ports, unsigned forbid)
4838 int warned = 0;
4839 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
4840 if (port->type != CONN_TYPE_CONTROL_LISTENER)
4841 continue;
4842 if (port->is_unix_addr)
4843 continue;
4844 if (!tor_addr_is_loopback(&port->addr)) {
4845 if (forbid) {
4846 if (!warned)
4847 log_warn(LD_CONFIG,
4848 "You have a ControlPort set to accept "
4849 "unauthenticated connections from a non-local address. "
4850 "This means that programs not running on your computer "
4851 "can reconfigure your Tor, without even having to guess a "
4852 "password. That's so bad that I'm closing your ControlPort "
4853 "for you. If you need to control your Tor remotely, try "
4854 "enabling authentication and using a tool like stunnel or "
4855 "ssh to encrypt remote access.");
4856 warned = 1;
4857 port_cfg_free(port);
4858 SMARTLIST_DEL_CURRENT(ports, port);
4859 } else {
4860 log_warn(LD_CONFIG, "You have a ControlPort set to accept "
4861 "connections from a non-local address. This means that "
4862 "programs not running on your computer can reconfigure your "
4863 "Tor. That's pretty bad, since the controller "
4864 "protocol isn't encrypted! Maybe you should just listen on "
4865 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
4866 "remote connections to your control port.");
4867 return; /* No point in checking the rest */
4870 } SMARTLIST_FOREACH_END(port);
4873 #define CL_PORT_NO_OPTIONS (1u<<0)
4874 #define CL_PORT_WARN_NONLOCAL (1u<<1)
4875 #define CL_PORT_ALLOW_EXTRA_LISTENADDR (1u<<2)
4876 #define CL_PORT_SERVER_OPTIONS (1u<<3)
4877 #define CL_PORT_FORBID_NONLOCAL (1u<<4)
4878 #define CL_PORT_TAKES_HOSTNAMES (1u<<5)
4881 * Parse port configuration for a single port type.
4883 * Read entries of the "FooPort" type from the list <b>ports</b>, and
4884 * entries of the "FooListenAddress" type from the list
4885 * <b>listenaddrs</b>. Two syntaxes are supported: a legacy syntax
4886 * where FooPort is at most a single entry containing a port number and
4887 * where FooListenAddress has any number of address:port combinations;
4888 * and a new syntax where there are no FooListenAddress entries and
4889 * where FooPort can have any number of entries of the format
4890 * "[Address:][Port] IsolationOptions".
4892 * In log messages, describe the port type as <b>portname</b>.
4894 * If no address is specified, default to <b>defaultaddr</b>. If no
4895 * FooPort is given, default to defaultport (if 0, there is no default).
4897 * If CL_PORT_NO_OPTIONS is set in <b>flags</b>, do not allow stream
4898 * isolation options in the FooPort entries.
4900 * If CL_PORT_WARN_NONLOCAL is set in <b>flags</b>, warn if any of the
4901 * ports are not on a local address. If CL_PORT_FORBID_NONLOCAL is set,
4902 * this is a contrl port with no password set: don't even allow it.
4904 * Unless CL_PORT_ALLOW_EXTRA_LISTENADDR is set in <b>flags</b>, warn
4905 * if FooListenAddress is set but FooPort is 0.
4907 * If CL_PORT_SERVER_OPTIONS is set in <b>flags</b>, do not allow stream
4908 * isolation options in the FooPort entries; instead allow the
4909 * server-port option set.
4911 * If CL_PORT_TAKES_HOSTNAMES is set in <b>flags</b>, allow the options
4912 * {No,}IPv{4,6}Traffic.
4914 * On success, if <b>out</b> is given, add a new port_cfg_t entry to
4915 * <b>out</b> for every port that the client should listen on. Return 0
4916 * on success, -1 on failure.
4918 static int
4919 parse_port_config(smartlist_t *out,
4920 const config_line_t *ports,
4921 const config_line_t *listenaddrs,
4922 const char *portname,
4923 int listener_type,
4924 const char *defaultaddr,
4925 int defaultport,
4926 unsigned flags)
4928 smartlist_t *elts;
4929 int retval = -1;
4930 const unsigned is_control = (listener_type == CONN_TYPE_CONTROL_LISTENER);
4931 const unsigned allow_no_options = flags & CL_PORT_NO_OPTIONS;
4932 const unsigned use_server_options = flags & CL_PORT_SERVER_OPTIONS;
4933 const unsigned warn_nonlocal = flags & CL_PORT_WARN_NONLOCAL;
4934 const unsigned forbid_nonlocal = flags & CL_PORT_FORBID_NONLOCAL;
4935 const unsigned allow_spurious_listenaddr =
4936 flags & CL_PORT_ALLOW_EXTRA_LISTENADDR;
4937 const unsigned takes_hostnames = flags & CL_PORT_TAKES_HOSTNAMES;
4938 int got_zero_port=0, got_nonzero_port=0;
4940 /* FooListenAddress is deprecated; let's make it work like it used to work,
4941 * though. */
4942 if (listenaddrs) {
4943 int mainport = defaultport;
4945 if (ports && ports->next) {
4946 log_warn(LD_CONFIG, "%sListenAddress can't be used when there are "
4947 "multiple %sPort lines", portname, portname);
4948 return -1;
4949 } else if (ports) {
4950 if (!strcmp(ports->value, "auto")) {
4951 mainport = CFG_AUTO_PORT;
4952 } else {
4953 int ok;
4954 mainport = (int)tor_parse_long(ports->value, 10, 0, 65535, &ok, NULL);
4955 if (!ok) {
4956 log_warn(LD_CONFIG, "%sListenAddress can only be used with a single "
4957 "%sPort with value \"auto\" or 1-65535 and no options set.",
4958 portname, portname);
4959 return -1;
4964 if (mainport == 0) {
4965 if (allow_spurious_listenaddr)
4966 return 1; /*DOCDOC*/
4967 log_warn(LD_CONFIG, "%sPort must be defined if %sListenAddress is used",
4968 portname, portname);
4969 return -1;
4972 if (use_server_options && out) {
4973 /* Add a no_listen port. */
4974 port_cfg_t *cfg = port_cfg_new();
4975 cfg->type = listener_type;
4976 cfg->port = mainport;
4977 tor_addr_make_unspec(&cfg->addr); /* Server ports default to 0.0.0.0 */
4978 cfg->no_listen = 1;
4979 cfg->bind_ipv4_only = 1;
4980 cfg->ipv4_traffic = 1;
4981 cfg->prefer_ipv6_virtaddr = 1;
4982 smartlist_add(out, cfg);
4985 for (; listenaddrs; listenaddrs = listenaddrs->next) {
4986 tor_addr_t addr;
4987 uint16_t port = 0;
4988 if (tor_addr_port_lookup(listenaddrs->value, &addr, &port) < 0) {
4989 log_warn(LD_CONFIG, "Unable to parse %sListenAddress '%s'",
4990 portname, listenaddrs->value);
4991 return -1;
4993 if (out) {
4994 port_cfg_t *cfg = port_cfg_new();
4995 cfg->type = listener_type;
4996 cfg->port = port ? port : mainport;
4997 tor_addr_copy(&cfg->addr, &addr);
4998 cfg->session_group = SESSION_GROUP_UNSET;
4999 cfg->isolation_flags = ISO_DEFAULT;
5000 cfg->no_advertise = 1;
5001 smartlist_add(out, cfg);
5005 if (warn_nonlocal && out) {
5006 if (is_control)
5007 warn_nonlocal_controller_ports(out, forbid_nonlocal);
5008 else
5009 warn_nonlocal_client_ports(out, portname, listener_type);
5011 return 0;
5012 } /* end if (listenaddrs) */
5014 /* No ListenAddress lines. If there's no FooPort, then maybe make a default
5015 * one. */
5016 if (! ports) {
5017 if (defaultport && out) {
5018 port_cfg_t *cfg = port_cfg_new();
5019 cfg->type = listener_type;
5020 cfg->port = defaultport;
5021 tor_addr_parse(&cfg->addr, defaultaddr);
5022 cfg->session_group = SESSION_GROUP_UNSET;
5023 cfg->isolation_flags = ISO_DEFAULT;
5024 smartlist_add(out, cfg);
5026 return 0;
5029 /* At last we can actually parse the FooPort lines. The syntax is:
5030 * [Addr:](Port|auto) [Options].*/
5031 elts = smartlist_new();
5033 for (; ports; ports = ports->next) {
5034 tor_addr_t addr;
5035 int port;
5036 int sessiongroup = SESSION_GROUP_UNSET;
5037 unsigned isolation = ISO_DEFAULT;
5038 int prefer_no_auth = 0;
5040 char *addrport;
5041 uint16_t ptmp=0;
5042 int ok;
5043 int no_listen = 0, no_advertise = 0, all_addrs = 0,
5044 bind_ipv4_only = 0, bind_ipv6_only = 0,
5045 ipv4_traffic = 1, ipv6_traffic = 0, prefer_ipv6 = 0,
5046 cache_ipv4 = 1, use_cached_ipv4 = 0,
5047 cache_ipv6 = 0, use_cached_ipv6 = 0,
5048 prefer_ipv6_automap = 1;
5050 smartlist_split_string(elts, ports->value, NULL,
5051 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
5052 if (smartlist_len(elts) == 0) {
5053 log_warn(LD_CONFIG, "Invalid %sPort line with no value", portname);
5054 goto err;
5057 if (allow_no_options && smartlist_len(elts) > 1) {
5058 log_warn(LD_CONFIG, "Too many options on %sPort line", portname);
5059 goto err;
5062 /* Now parse the addr/port value */
5063 addrport = smartlist_get(elts, 0);
5064 if (!strcmp(addrport, "auto")) {
5065 port = CFG_AUTO_PORT;
5066 tor_addr_parse(&addr, defaultaddr);
5067 } else if (!strcasecmpend(addrport, ":auto")) {
5068 char *addrtmp = tor_strndup(addrport, strlen(addrport)-5);
5069 port = CFG_AUTO_PORT;
5070 if (tor_addr_port_lookup(addrtmp, &addr, &ptmp)<0 || ptmp) {
5071 log_warn(LD_CONFIG, "Invalid address '%s' for %sPort",
5072 escaped(addrport), portname);
5073 tor_free(addrtmp);
5074 goto err;
5076 } else {
5077 /* Try parsing integer port before address, because, who knows?
5078 "9050" might be a valid address. */
5079 port = (int) tor_parse_long(addrport, 10, 0, 65535, &ok, NULL);
5080 if (ok) {
5081 tor_addr_parse(&addr, defaultaddr);
5082 } else if (tor_addr_port_lookup(addrport, &addr, &ptmp) == 0) {
5083 if (ptmp == 0) {
5084 log_warn(LD_CONFIG, "%sPort line has address but no port", portname);
5085 goto err;
5087 port = ptmp;
5088 } else {
5089 log_warn(LD_CONFIG, "Couldn't parse address '%s' for %sPort",
5090 escaped(addrport), portname);
5091 goto err;
5095 /* Now parse the rest of the options, if any. */
5096 if (use_server_options) {
5097 /* This is a server port; parse advertising options */
5098 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
5099 if (elt_sl_idx == 0)
5100 continue; /* Skip addr:port */
5102 if (!strcasecmp(elt, "NoAdvertise")) {
5103 no_advertise = 1;
5104 } else if (!strcasecmp(elt, "NoListen")) {
5105 no_listen = 1;
5106 #if 0
5107 /* not implemented yet. */
5108 } else if (!strcasecmp(elt, "AllAddrs")) {
5110 all_addrs = 1;
5111 #endif
5112 } else if (!strcasecmp(elt, "IPv4Only")) {
5113 bind_ipv4_only = 1;
5114 } else if (!strcasecmp(elt, "IPv6Only")) {
5115 bind_ipv6_only = 1;
5116 } else {
5117 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
5118 portname, escaped(elt));
5120 } SMARTLIST_FOREACH_END(elt);
5122 if (no_advertise && no_listen) {
5123 log_warn(LD_CONFIG, "Tried to set both NoListen and NoAdvertise "
5124 "on %sPort line '%s'",
5125 portname, escaped(ports->value));
5126 goto err;
5128 if (bind_ipv4_only && bind_ipv6_only) {
5129 log_warn(LD_CONFIG, "Tried to set both IPv4Only and IPv6Only "
5130 "on %sPort line '%s'",
5131 portname, escaped(ports->value));
5132 goto err;
5134 if (bind_ipv4_only && tor_addr_family(&addr) == AF_INET6) {
5135 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv6",
5136 portname);
5137 goto err;
5139 if (bind_ipv6_only && tor_addr_family(&addr) == AF_INET) {
5140 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv4",
5141 portname);
5142 goto err;
5144 } else {
5145 /* This is a client port; parse isolation options */
5146 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
5147 int no = 0, isoflag = 0;
5148 const char *elt_orig = elt;
5149 if (elt_sl_idx == 0)
5150 continue; /* Skip addr:port */
5151 if (!strcasecmpstart(elt, "SessionGroup=")) {
5152 int group = (int)tor_parse_long(elt+strlen("SessionGroup="),
5153 10, 0, INT_MAX, &ok, NULL);
5154 if (!ok) {
5155 log_warn(LD_CONFIG, "Invalid %sPort option '%s'",
5156 portname, escaped(elt));
5157 goto err;
5159 if (sessiongroup >= 0) {
5160 log_warn(LD_CONFIG, "Multiple SessionGroup options on %sPort",
5161 portname);
5162 goto err;
5164 sessiongroup = group;
5165 continue;
5168 if (!strcasecmpstart(elt, "No")) {
5169 no = 1;
5170 elt += 2;
5173 if (takes_hostnames) {
5174 if (!strcasecmp(elt, "IPv4Traffic")) {
5175 ipv4_traffic = ! no;
5176 continue;
5177 } else if (!strcasecmp(elt, "IPv6Traffic")) {
5178 ipv6_traffic = ! no;
5179 continue;
5180 } else if (!strcasecmp(elt, "PreferIPv6")) {
5181 prefer_ipv6 = ! no;
5182 continue;
5185 if (!strcasecmp(elt, "CacheIPv4DNS")) {
5186 cache_ipv4 = ! no;
5187 continue;
5188 } else if (!strcasecmp(elt, "CacheIPv6DNS")) {
5189 cache_ipv6 = ! no;
5190 continue;
5191 } else if (!strcasecmp(elt, "CacheDNS")) {
5192 cache_ipv4 = cache_ipv6 = ! no;
5193 continue;
5194 } else if (!strcasecmp(elt, "UseIPv4Cache")) {
5195 use_cached_ipv4 = ! no;
5196 continue;
5197 } else if (!strcasecmp(elt, "UseIPv6Cache")) {
5198 use_cached_ipv6 = ! no;
5199 continue;
5200 } else if (!strcasecmp(elt, "UseDNSCache")) {
5201 use_cached_ipv4 = use_cached_ipv6 = ! no;
5202 continue;
5203 } else if (!strcasecmp(elt, "PreferIPv6Automap")) {
5204 prefer_ipv6_automap = ! no;
5205 continue;
5206 } else if (!strcasecmp(elt, "PreferSOCKSNoAuth")) {
5207 prefer_no_auth = ! no;
5208 continue;
5211 if (!strcasecmpend(elt, "s"))
5212 elt[strlen(elt)-1] = '\0'; /* kill plurals. */
5214 if (!strcasecmp(elt, "IsolateDestPort")) {
5215 isoflag = ISO_DESTPORT;
5216 } else if (!strcasecmp(elt, "IsolateDestAddr")) {
5217 isoflag = ISO_DESTADDR;
5218 } else if (!strcasecmp(elt, "IsolateSOCKSAuth")) {
5219 isoflag = ISO_SOCKSAUTH;
5220 } else if (!strcasecmp(elt, "IsolateClientProtocol")) {
5221 isoflag = ISO_CLIENTPROTO;
5222 } else if (!strcasecmp(elt, "IsolateClientAddr")) {
5223 isoflag = ISO_CLIENTADDR;
5224 } else {
5225 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
5226 portname, escaped(elt_orig));
5229 if (no) {
5230 isolation &= ~isoflag;
5231 } else {
5232 isolation |= isoflag;
5234 } SMARTLIST_FOREACH_END(elt);
5237 if (port)
5238 got_nonzero_port = 1;
5239 else
5240 got_zero_port = 1;
5242 if (ipv4_traffic == 0 && ipv6_traffic == 0) {
5243 log_warn(LD_CONFIG, "You have a %sPort entry with both IPv4 and "
5244 "IPv6 disabled; that won't work.", portname);
5245 goto err;
5248 if (out && port) {
5249 port_cfg_t *cfg = port_cfg_new();
5250 tor_addr_copy(&cfg->addr, &addr);
5251 cfg->port = port;
5252 cfg->type = listener_type;
5253 cfg->isolation_flags = isolation;
5254 cfg->session_group = sessiongroup;
5255 cfg->no_advertise = no_advertise;
5256 cfg->no_listen = no_listen;
5257 cfg->all_addrs = all_addrs;
5258 cfg->bind_ipv4_only = bind_ipv4_only;
5259 cfg->bind_ipv6_only = bind_ipv6_only;
5260 cfg->ipv4_traffic = ipv4_traffic;
5261 cfg->ipv6_traffic = ipv6_traffic;
5262 cfg->prefer_ipv6 = prefer_ipv6;
5263 cfg->cache_ipv4_answers = cache_ipv4;
5264 cfg->cache_ipv6_answers = cache_ipv6;
5265 cfg->use_cached_ipv4_answers = use_cached_ipv4;
5266 cfg->use_cached_ipv6_answers = use_cached_ipv6;
5267 cfg->prefer_ipv6_virtaddr = prefer_ipv6_automap;
5268 cfg->socks_prefer_no_auth = prefer_no_auth;
5269 if (! (isolation & ISO_SOCKSAUTH))
5270 cfg->socks_prefer_no_auth = 1;
5272 smartlist_add(out, cfg);
5274 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
5275 smartlist_clear(elts);
5278 if (warn_nonlocal && out) {
5279 if (is_control)
5280 warn_nonlocal_controller_ports(out, forbid_nonlocal);
5281 else
5282 warn_nonlocal_client_ports(out, portname, listener_type);
5285 if (got_zero_port && got_nonzero_port) {
5286 log_warn(LD_CONFIG, "You specified a nonzero %sPort along with '%sPort 0' "
5287 "in the same configuration. Did you mean to disable %sPort or "
5288 "not?", portname, portname, portname);
5289 goto err;
5292 retval = 0;
5293 err:
5294 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
5295 smartlist_free(elts);
5296 return retval;
5299 /** Parse a list of config_line_t for an AF_UNIX unix socket listener option
5300 * from <b>cfg</b> and add them to <b>out</b>. No fancy options are
5301 * supported: the line contains nothing but the path to the AF_UNIX socket. */
5302 static int
5303 parse_unix_socket_config(smartlist_t *out, const config_line_t *cfg,
5304 int listener_type)
5307 if (!out)
5308 return 0;
5310 for ( ; cfg; cfg = cfg->next) {
5311 size_t len = strlen(cfg->value);
5312 port_cfg_t *port = tor_malloc_zero(sizeof(port_cfg_t) + len + 1);
5313 port->is_unix_addr = 1;
5314 memcpy(port->unix_addr, cfg->value, len+1);
5315 port->type = listener_type;
5316 smartlist_add(out, port);
5319 return 0;
5322 /** Return the number of ports which are actually going to listen with type
5323 * <b>listenertype</b>. Do not count no_listen ports. Do not count unix
5324 * sockets. */
5325 static int
5326 count_real_listeners(const smartlist_t *ports, int listenertype)
5328 int n = 0;
5329 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
5330 if (port->no_listen || port->is_unix_addr)
5331 continue;
5332 if (port->type != listenertype)
5333 continue;
5334 ++n;
5335 } SMARTLIST_FOREACH_END(port);
5336 return n;
5339 /** Parse all client port types (Socks, DNS, Trans, NATD) from
5340 * <b>options</b>. On success, set *<b>n_ports_out</b> to the number
5341 * of ports that are listed, update the *Port_set values in
5342 * <b>options</b>, and return 0. On failure, set *<b>msg</b> to a
5343 * description of the problem and return -1.
5345 * If <b>validate_only</b> is false, set configured_client_ports to the
5346 * new list of ports parsed from <b>options</b>.
5348 static int
5349 parse_ports(or_options_t *options, int validate_only,
5350 char **msg, int *n_ports_out)
5352 smartlist_t *ports;
5353 int retval = -1;
5355 ports = smartlist_new();
5357 *n_ports_out = 0;
5359 if (parse_port_config(ports,
5360 options->SocksPort_lines, options->SocksListenAddress,
5361 "Socks", CONN_TYPE_AP_LISTENER,
5362 "127.0.0.1", 9050,
5363 CL_PORT_WARN_NONLOCAL|CL_PORT_ALLOW_EXTRA_LISTENADDR|
5364 CL_PORT_TAKES_HOSTNAMES) < 0) {
5365 *msg = tor_strdup("Invalid SocksPort/SocksListenAddress configuration");
5366 goto err;
5368 if (parse_port_config(ports,
5369 options->DNSPort_lines, options->DNSListenAddress,
5370 "DNS", CONN_TYPE_AP_DNS_LISTENER,
5371 "127.0.0.1", 0,
5372 CL_PORT_WARN_NONLOCAL|CL_PORT_TAKES_HOSTNAMES) < 0) {
5373 *msg = tor_strdup("Invalid DNSPort/DNSListenAddress configuration");
5374 goto err;
5376 if (parse_port_config(ports,
5377 options->TransPort_lines, options->TransListenAddress,
5378 "Trans", CONN_TYPE_AP_TRANS_LISTENER,
5379 "127.0.0.1", 0,
5380 CL_PORT_WARN_NONLOCAL) < 0) {
5381 *msg = tor_strdup("Invalid TransPort/TransListenAddress configuration");
5382 goto err;
5384 if (parse_port_config(ports,
5385 options->NATDPort_lines, options->NATDListenAddress,
5386 "NATD", CONN_TYPE_AP_NATD_LISTENER,
5387 "127.0.0.1", 0,
5388 CL_PORT_WARN_NONLOCAL) < 0) {
5389 *msg = tor_strdup("Invalid NatdPort/NatdListenAddress configuration");
5390 goto err;
5393 unsigned control_port_flags = CL_PORT_NO_OPTIONS | CL_PORT_WARN_NONLOCAL;
5394 const int any_passwords = (options->HashedControlPassword ||
5395 options->HashedControlSessionPassword ||
5396 options->CookieAuthentication);
5397 if (! any_passwords)
5398 control_port_flags |= CL_PORT_FORBID_NONLOCAL;
5400 if (parse_port_config(ports,
5401 options->ControlPort_lines,
5402 options->ControlListenAddress,
5403 "Control", CONN_TYPE_CONTROL_LISTENER,
5404 "127.0.0.1", 0,
5405 control_port_flags) < 0) {
5406 *msg = tor_strdup("Invalid ControlPort/ControlListenAddress "
5407 "configuration");
5408 goto err;
5410 if (parse_unix_socket_config(ports,
5411 options->ControlSocket,
5412 CONN_TYPE_CONTROL_LISTENER) < 0) {
5413 *msg = tor_strdup("Invalid ControlSocket configuration");
5414 goto err;
5417 if (! options->ClientOnly) {
5418 if (parse_port_config(ports,
5419 options->ORPort_lines, options->ORListenAddress,
5420 "OR", CONN_TYPE_OR_LISTENER,
5421 "0.0.0.0", 0,
5422 CL_PORT_SERVER_OPTIONS) < 0) {
5423 *msg = tor_strdup("Invalid ORPort/ORListenAddress configuration");
5424 goto err;
5426 if (parse_port_config(ports,
5427 options->DirPort_lines, options->DirListenAddress,
5428 "Dir", CONN_TYPE_DIR_LISTENER,
5429 "0.0.0.0", 0,
5430 CL_PORT_SERVER_OPTIONS) < 0) {
5431 *msg = tor_strdup("Invalid DirPort/DirListenAddress configuration");
5432 goto err;
5436 if (check_server_ports(ports, options) < 0) {
5437 *msg = tor_strdup("Misconfigured server ports");
5438 goto err;
5441 *n_ports_out = smartlist_len(ports);
5443 retval = 0;
5445 /* Update the *Port_set options. The !! here is to force a boolean out of
5446 an integer. */
5447 options->ORPort_set =
5448 !! count_real_listeners(ports, CONN_TYPE_OR_LISTENER);
5449 options->SocksPort_set =
5450 !! count_real_listeners(ports, CONN_TYPE_AP_LISTENER);
5451 options->TransPort_set =
5452 !! count_real_listeners(ports, CONN_TYPE_AP_TRANS_LISTENER);
5453 options->NATDPort_set =
5454 !! count_real_listeners(ports, CONN_TYPE_AP_NATD_LISTENER);
5455 options->ControlPort_set =
5456 !! count_real_listeners(ports, CONN_TYPE_CONTROL_LISTENER);
5457 options->DirPort_set =
5458 !! count_real_listeners(ports, CONN_TYPE_DIR_LISTENER);
5459 options->DNSPort_set =
5460 !! count_real_listeners(ports, CONN_TYPE_AP_DNS_LISTENER);
5462 if (!validate_only) {
5463 if (configured_ports) {
5464 SMARTLIST_FOREACH(configured_ports,
5465 port_cfg_t *, p, port_cfg_free(p));
5466 smartlist_free(configured_ports);
5468 configured_ports = ports;
5469 ports = NULL; /* prevent free below. */
5472 err:
5473 if (ports) {
5474 SMARTLIST_FOREACH(ports, port_cfg_t *, p, port_cfg_free(p));
5475 smartlist_free(ports);
5477 return retval;
5480 /** Given a list of <b>port_cfg_t</b> in <b>ports</b>, check them for internal
5481 * consistency and warn as appropriate. */
5482 static int
5483 check_server_ports(const smartlist_t *ports,
5484 const or_options_t *options)
5486 int n_orport_advertised = 0;
5487 int n_orport_advertised_ipv4 = 0;
5488 int n_orport_listeners = 0;
5489 int n_dirport_advertised = 0;
5490 int n_dirport_listeners = 0;
5491 int n_low_port = 0;
5492 int r = 0;
5494 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
5495 if (port->type == CONN_TYPE_DIR_LISTENER) {
5496 if (! port->no_advertise)
5497 ++n_dirport_advertised;
5498 if (! port->no_listen)
5499 ++n_dirport_listeners;
5500 } else if (port->type == CONN_TYPE_OR_LISTENER) {
5501 if (! port->no_advertise) {
5502 ++n_orport_advertised;
5503 if (tor_addr_family(&port->addr) == AF_INET ||
5504 (tor_addr_family(&port->addr) == AF_UNSPEC &&
5505 !port->bind_ipv6_only))
5506 ++n_orport_advertised_ipv4;
5508 if (! port->no_listen)
5509 ++n_orport_listeners;
5510 } else {
5511 continue;
5513 #ifndef _WIN32
5514 if (!port->no_listen && port->port < 1024)
5515 ++n_low_port;
5516 #endif
5517 } SMARTLIST_FOREACH_END(port);
5519 if (n_orport_advertised && !n_orport_listeners) {
5520 log_warn(LD_CONFIG, "We are advertising an ORPort, but not actually "
5521 "listening on one.");
5522 r = -1;
5524 if (n_orport_listeners && !n_orport_advertised) {
5525 log_warn(LD_CONFIG, "We are listening on an ORPort, but not advertising "
5526 "any ORPorts. This will keep us from building a %s "
5527 "descriptor, and make us impossible to use.",
5528 options->BridgeRelay ? "bridge" : "router");
5529 r = -1;
5531 if (n_dirport_advertised && !n_dirport_listeners) {
5532 log_warn(LD_CONFIG, "We are advertising a DirPort, but not actually "
5533 "listening on one.");
5534 r = -1;
5536 if (n_dirport_advertised > 1) {
5537 log_warn(LD_CONFIG, "Can't advertise more than one DirPort.");
5538 r = -1;
5540 if (n_orport_advertised && !n_orport_advertised_ipv4 &&
5541 !options->BridgeRelay) {
5542 log_warn(LD_CONFIG, "Configured non-bridge only to listen on an IPv6 "
5543 "address.");
5544 r = -1;
5547 if (n_low_port && options->AccountingMax) {
5548 log_warn(LD_CONFIG,
5549 "You have set AccountingMax to use hibernation. You have also "
5550 "chosen a low DirPort or OrPort. This combination can make Tor stop "
5551 "working when it tries to re-attach the port after a period of "
5552 "hibernation. Please choose a different port or turn off "
5553 "hibernation unless you know this combination will work on your "
5554 "platform.");
5557 return r;
5560 /** Return a list of port_cfg_t for client ports parsed from the
5561 * options. */
5562 const smartlist_t *
5563 get_configured_ports(void)
5565 if (!configured_ports)
5566 configured_ports = smartlist_new();
5567 return configured_ports;
5570 /** Return an address:port string representation of the address
5571 * where the first <b>listener_type</b> listener waits for
5572 * connections. Return NULL if we couldn't find a listener. The
5573 * string is allocated on the heap and it's the responsibility of the
5574 * caller to free it after use.
5576 * This function is meant to be used by the pluggable transport proxy
5577 * spawning code, please make sure that it fits your purposes before
5578 * using it. */
5579 char *
5580 get_first_listener_addrport_string(int listener_type)
5582 static const char *ipv4_localhost = "127.0.0.1";
5583 static const char *ipv6_localhost = "[::1]";
5584 const char *address;
5585 uint16_t port;
5586 char *string = NULL;
5588 if (!configured_ports)
5589 return NULL;
5591 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
5592 if (cfg->no_listen)
5593 continue;
5595 if (cfg->type == listener_type &&
5596 tor_addr_family(&cfg->addr) != AF_UNSPEC) {
5598 /* We found the first listener of the type we are interested in! */
5600 /* If a listener is listening on INADDR_ANY, assume that it's
5601 also listening on 127.0.0.1, and point the transport proxy
5602 there: */
5603 if (tor_addr_is_null(&cfg->addr))
5604 address = tor_addr_is_v4(&cfg->addr) ? ipv4_localhost : ipv6_localhost;
5605 else
5606 address = fmt_and_decorate_addr(&cfg->addr);
5608 /* If a listener is configured with port 'auto', we are forced
5609 to iterate all listener connections and find out in which
5610 port it ended up listening: */
5611 if (cfg->port == CFG_AUTO_PORT) {
5612 port = router_get_active_listener_port_by_type_af(listener_type,
5613 tor_addr_family(&cfg->addr));
5614 if (!port)
5615 return NULL;
5616 } else {
5617 port = cfg->port;
5620 tor_asprintf(&string, "%s:%u", address, port);
5622 return string;
5625 } SMARTLIST_FOREACH_END(cfg);
5627 return NULL;
5630 /** Return the first advertised port of type <b>listener_type</b> in
5631 <b>address_family</b>. */
5633 get_first_advertised_port_by_type_af(int listener_type, int address_family)
5635 if (!configured_ports)
5636 return 0;
5637 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
5638 if (cfg->type == listener_type &&
5639 !cfg->no_advertise &&
5640 (tor_addr_family(&cfg->addr) == address_family ||
5641 tor_addr_family(&cfg->addr) == AF_UNSPEC)) {
5642 if (tor_addr_family(&cfg->addr) != AF_UNSPEC ||
5643 (address_family == AF_INET && !cfg->bind_ipv6_only) ||
5644 (address_family == AF_INET6 && !cfg->bind_ipv4_only)) {
5645 return cfg->port;
5648 } SMARTLIST_FOREACH_END(cfg);
5649 return 0;
5652 /** Adjust the value of options->DataDirectory, or fill it in if it's
5653 * absent. Return 0 on success, -1 on failure. */
5654 static int
5655 normalize_data_directory(or_options_t *options)
5657 #ifdef _WIN32
5658 char *p;
5659 if (options->DataDirectory)
5660 return 0; /* all set */
5661 p = tor_malloc(MAX_PATH);
5662 strlcpy(p,get_windows_conf_root(),MAX_PATH);
5663 options->DataDirectory = p;
5664 return 0;
5665 #else
5666 const char *d = options->DataDirectory;
5667 if (!d)
5668 d = "~/.tor";
5670 if (strncmp(d,"~/",2) == 0) {
5671 char *fn = expand_filename(d);
5672 if (!fn) {
5673 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
5674 return -1;
5676 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
5677 /* If our homedir is /, we probably don't want to use it. */
5678 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
5679 * want. */
5680 log_warn(LD_CONFIG,
5681 "Default DataDirectory is \"~/.tor\". This expands to "
5682 "\"%s\", which is probably not what you want. Using "
5683 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
5684 tor_free(fn);
5685 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
5687 tor_free(options->DataDirectory);
5688 options->DataDirectory = fn;
5690 return 0;
5691 #endif
5694 /** Check and normalize the value of options->DataDirectory; return 0 if it
5695 * is sane, -1 otherwise. */
5696 static int
5697 validate_data_directory(or_options_t *options)
5699 if (normalize_data_directory(options) < 0)
5700 return -1;
5701 tor_assert(options->DataDirectory);
5702 if (strlen(options->DataDirectory) > (512-128)) {
5703 log_warn(LD_CONFIG, "DataDirectory is too long.");
5704 return -1;
5706 return 0;
5709 /** This string must remain the same forevermore. It is how we
5710 * recognize that the torrc file doesn't need to be backed up. */
5711 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
5712 "if you edit it, comments will not be preserved"
5713 /** This string can change; it tries to give the reader an idea
5714 * that editing this file by hand is not a good plan. */
5715 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
5716 "to torrc.orig.1 or similar, and Tor will ignore it"
5718 /** Save a configuration file for the configuration in <b>options</b>
5719 * into the file <b>fname</b>. If the file already exists, and
5720 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
5721 * replace it. Return 0 on success, -1 on failure. */
5722 static int
5723 write_configuration_file(const char *fname, const or_options_t *options)
5725 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
5726 int rename_old = 0, r;
5728 tor_assert(fname);
5730 switch (file_status(fname)) {
5731 case FN_FILE:
5732 old_val = read_file_to_str(fname, 0, NULL);
5733 if (!old_val || strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
5734 rename_old = 1;
5736 tor_free(old_val);
5737 break;
5738 case FN_NOENT:
5739 break;
5740 case FN_ERROR:
5741 case FN_DIR:
5742 default:
5743 log_warn(LD_CONFIG,
5744 "Config file \"%s\" is not a file? Failing.", fname);
5745 return -1;
5748 if (!(new_conf = options_dump(options, 1))) {
5749 log_warn(LD_BUG, "Couldn't get configuration string");
5750 goto err;
5753 tor_asprintf(&new_val, "%s\n%s\n\n%s",
5754 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
5756 if (rename_old) {
5757 int i = 1;
5758 char *fn_tmp = NULL;
5759 while (1) {
5760 tor_asprintf(&fn_tmp, "%s.orig.%d", fname, i);
5761 if (file_status(fn_tmp) == FN_NOENT)
5762 break;
5763 tor_free(fn_tmp);
5764 ++i;
5766 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
5767 if (rename(fname, fn_tmp) < 0) {
5768 log_warn(LD_FS,
5769 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
5770 fname, fn_tmp, strerror(errno));
5771 tor_free(fn_tmp);
5772 goto err;
5774 tor_free(fn_tmp);
5777 if (write_str_to_file(fname, new_val, 0) < 0)
5778 goto err;
5780 r = 0;
5781 goto done;
5782 err:
5783 r = -1;
5784 done:
5785 tor_free(new_val);
5786 tor_free(new_conf);
5787 return r;
5791 * Save the current configuration file value to disk. Return 0 on
5792 * success, -1 on failure.
5795 options_save_current(void)
5797 /* This fails if we can't write to our configuration file.
5799 * If we try falling back to datadirectory or something, we have a better
5800 * chance of saving the configuration, but a better chance of doing
5801 * something the user never expected. */
5802 return write_configuration_file(get_torrc_fname(0), get_options());
5805 /** Return the number of cpus configured in <b>options</b>. If we are
5806 * told to auto-detect the number of cpus, return the auto-detected number. */
5808 get_num_cpus(const or_options_t *options)
5810 if (options->NumCPUs == 0) {
5811 int n = compute_num_cpus();
5812 return (n >= 1) ? n : 1;
5813 } else {
5814 return options->NumCPUs;
5819 * Initialize the libevent library.
5821 static void
5822 init_libevent(const or_options_t *options)
5824 const char *badness=NULL;
5825 tor_libevent_cfg cfg;
5827 tor_assert(options);
5829 configure_libevent_logging();
5830 /* If the kernel complains that some method (say, epoll) doesn't
5831 * exist, we don't care about it, since libevent will cope.
5833 suppress_libevent_log_msg("Function not implemented");
5835 tor_check_libevent_header_compatibility();
5837 memset(&cfg, 0, sizeof(cfg));
5838 cfg.disable_iocp = options->DisableIOCP;
5839 cfg.num_cpus = get_num_cpus(options);
5840 cfg.msec_per_tick = options->TokenBucketRefillInterval;
5842 tor_libevent_initialize(&cfg);
5844 suppress_libevent_log_msg(NULL);
5846 tor_check_libevent_version(tor_libevent_get_method(),
5847 server_mode(get_options()),
5848 &badness);
5849 if (badness) {
5850 const char *v = tor_libevent_get_version_str();
5851 const char *m = tor_libevent_get_method();
5852 control_event_general_status(LOG_WARN,
5853 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
5854 v, m, badness);
5858 /** Return a newly allocated string holding a filename relative to the data
5859 * directory. If <b>sub1</b> is present, it is the first path component after
5860 * the data directory. If <b>sub2</b> is also present, it is the second path
5861 * component after the data directory. If <b>suffix</b> is present, it
5862 * is appended to the filename.
5864 * Examples:
5865 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
5866 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
5867 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
5868 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
5870 * Note: Consider using the get_datadir_fname* macros in or.h.
5872 char *
5873 options_get_datadir_fname2_suffix(const or_options_t *options,
5874 const char *sub1, const char *sub2,
5875 const char *suffix)
5877 char *fname = NULL;
5878 size_t len;
5879 tor_assert(options);
5880 tor_assert(options->DataDirectory);
5881 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
5882 len = strlen(options->DataDirectory);
5883 if (sub1) {
5884 len += strlen(sub1)+1;
5885 if (sub2)
5886 len += strlen(sub2)+1;
5888 if (suffix)
5889 len += strlen(suffix);
5890 len++;
5891 fname = tor_malloc(len);
5892 if (sub1) {
5893 if (sub2) {
5894 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
5895 options->DataDirectory, sub1, sub2);
5896 } else {
5897 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
5898 options->DataDirectory, sub1);
5900 } else {
5901 strlcpy(fname, options->DataDirectory, len);
5903 if (suffix)
5904 strlcat(fname, suffix, len);
5905 return fname;
5908 /** Given a file name check to see whether the file exists but has not been
5909 * modified for a very long time. If so, remove it. */
5910 void
5911 remove_file_if_very_old(const char *fname, time_t now)
5913 #define VERY_OLD_FILE_AGE (28*24*60*60)
5914 struct stat st;
5916 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
5917 char buf[ISO_TIME_LEN+1];
5918 format_local_iso_time(buf, st.st_mtime);
5919 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
5920 "Removing it.", fname, buf);
5921 unlink(fname);
5925 /** Return a smartlist of ports that must be forwarded by
5926 * tor-fw-helper. The smartlist contains the ports in a string format
5927 * that is understandable by tor-fw-helper. */
5928 smartlist_t *
5929 get_list_of_ports_to_forward(void)
5931 smartlist_t *ports_to_forward = smartlist_new();
5932 int port = 0;
5934 /** XXX TODO tor-fw-helper does not support forwarding ports to
5935 other hosts than the local one. If the user is binding to a
5936 different IP address, tor-fw-helper won't work. */
5937 port = router_get_advertised_or_port(get_options()); /* Get ORPort */
5938 if (port)
5939 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
5941 port = router_get_advertised_dir_port(get_options(), 0); /* Get DirPort */
5942 if (port)
5943 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
5945 /* Get ports of transport proxies */
5947 smartlist_t *transport_ports = get_transport_proxy_ports();
5948 if (transport_ports) {
5949 smartlist_add_all(ports_to_forward, transport_ports);
5950 smartlist_free(transport_ports);
5954 if (!smartlist_len(ports_to_forward)) {
5955 smartlist_free(ports_to_forward);
5956 ports_to_forward = NULL;
5959 return ports_to_forward;
5962 /** Helper to implement GETINFO functions about configuration variables (not
5963 * their values). Given a "config/names" question, set *<b>answer</b> to a
5964 * new string describing the supported configuration variables and their
5965 * types. */
5967 getinfo_helper_config(control_connection_t *conn,
5968 const char *question, char **answer,
5969 const char **errmsg)
5971 (void) conn;
5972 (void) errmsg;
5973 if (!strcmp(question, "config/names")) {
5974 smartlist_t *sl = smartlist_new();
5975 int i;
5976 for (i = 0; option_vars_[i].name; ++i) {
5977 const config_var_t *var = &option_vars_[i];
5978 const char *type;
5979 /* don't tell controller about triple-underscore options */
5980 if (!strncmp(option_vars_[i].name, "___", 3))
5981 continue;
5982 switch (var->type) {
5983 case CONFIG_TYPE_STRING: type = "String"; break;
5984 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
5985 case CONFIG_TYPE_UINT: type = "Integer"; break;
5986 case CONFIG_TYPE_INT: type = "SignedInteger"; break;
5987 case CONFIG_TYPE_PORT: type = "Port"; break;
5988 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
5989 case CONFIG_TYPE_MSEC_INTERVAL: type = "TimeMsecInterval"; break;
5990 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
5991 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
5992 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
5993 case CONFIG_TYPE_AUTOBOOL: type = "Boolean+Auto"; break;
5994 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
5995 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
5996 case CONFIG_TYPE_CSV: type = "CommaList"; break;
5997 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
5998 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
5999 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
6000 default:
6001 case CONFIG_TYPE_OBSOLETE:
6002 type = NULL; break;
6004 if (!type)
6005 continue;
6006 smartlist_add_asprintf(sl, "%s %s\n",var->name,type);
6008 *answer = smartlist_join_strings(sl, "", 0, NULL);
6009 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
6010 smartlist_free(sl);
6011 } else if (!strcmp(question, "config/defaults")) {
6012 smartlist_t *sl = smartlist_new();
6013 int i;
6014 for (i = 0; option_vars_[i].name; ++i) {
6015 const config_var_t *var = &option_vars_[i];
6016 if (var->initvalue != NULL) {
6017 char *val = esc_for_log(var->initvalue);
6018 smartlist_add_asprintf(sl, "%s %s\n",var->name,val);
6019 tor_free(val);
6022 *answer = smartlist_join_strings(sl, "", 0, NULL);
6023 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
6024 smartlist_free(sl);
6026 return 0;
6029 /** Parse outbound bind address option lines. If <b>validate_only</b>
6030 * is not 0 update OutboundBindAddressIPv4_ and
6031 * OutboundBindAddressIPv6_ in <b>options</b>. On failure, set
6032 * <b>msg</b> (if provided) to a newly allocated string containing a
6033 * description of the problem and return -1. */
6034 static int
6035 parse_outbound_addresses(or_options_t *options, int validate_only, char **msg)
6037 const config_line_t *lines = options->OutboundBindAddress;
6038 int found_v4 = 0, found_v6 = 0;
6040 if (!validate_only) {
6041 memset(&options->OutboundBindAddressIPv4_, 0,
6042 sizeof(options->OutboundBindAddressIPv4_));
6043 memset(&options->OutboundBindAddressIPv6_, 0,
6044 sizeof(options->OutboundBindAddressIPv6_));
6046 while (lines) {
6047 tor_addr_t addr, *dst_addr = NULL;
6048 int af = tor_addr_parse(&addr, lines->value);
6049 switch (af) {
6050 case AF_INET:
6051 if (found_v4) {
6052 if (msg)
6053 tor_asprintf(msg, "Multiple IPv4 outbound bind addresses "
6054 "configured: %s", lines->value);
6055 return -1;
6057 found_v4 = 1;
6058 dst_addr = &options->OutboundBindAddressIPv4_;
6059 break;
6060 case AF_INET6:
6061 if (found_v6) {
6062 if (msg)
6063 tor_asprintf(msg, "Multiple IPv6 outbound bind addresses "
6064 "configured: %s", lines->value);
6065 return -1;
6067 found_v6 = 1;
6068 dst_addr = &options->OutboundBindAddressIPv6_;
6069 break;
6070 default:
6071 if (msg)
6072 tor_asprintf(msg, "Outbound bind address '%s' didn't parse.",
6073 lines->value);
6074 return -1;
6076 if (!validate_only)
6077 tor_addr_copy(dst_addr, &addr);
6078 lines = lines->next;
6080 return 0;
6083 /** Load one of the geoip files, <a>family</a> determining which
6084 * one. <a>default_fname</a> is used if on Windows and
6085 * <a>fname</a> equals "<default>". */
6086 static void
6087 config_load_geoip_file_(sa_family_t family,
6088 const char *fname,
6089 const char *default_fname)
6091 #ifdef _WIN32
6092 char *free_fname = NULL; /* Used to hold any temporary-allocated value */
6093 /* XXXX Don't use this "<default>" junk; make our filename options
6094 * understand prefixes somehow. -NM */
6095 if (!strcmp(fname, "<default>")) {
6096 const char *conf_root = get_windows_conf_root();
6097 tor_asprintf(&free_fname, "%s\\%s", conf_root, default_fname);
6098 fname = free_fname;
6100 geoip_load_file(family, fname);
6101 tor_free(free_fname);
6102 #else
6103 (void)default_fname;
6104 geoip_load_file(family, fname);
6105 #endif
6108 /** Load geoip files for IPv4 and IPv6 if <a>options</a> and
6109 * <a>old_options</a> indicate we should. */
6110 static void
6111 config_maybe_load_geoip_files_(const or_options_t *options,
6112 const or_options_t *old_options)
6114 /* XXXX024 Reload GeoIPFile on SIGHUP. -NM */
6116 if (options->GeoIPFile &&
6117 ((!old_options || !opt_streq(old_options->GeoIPFile,
6118 options->GeoIPFile))
6119 || !geoip_is_loaded(AF_INET)))
6120 config_load_geoip_file_(AF_INET, options->GeoIPFile, "geoip");
6121 if (options->GeoIPv6File &&
6122 ((!old_options || !opt_streq(old_options->GeoIPv6File,
6123 options->GeoIPv6File))
6124 || !geoip_is_loaded(AF_INET6)))
6125 config_load_geoip_file_(AF_INET6, options->GeoIPv6File, "geoip6");