Remove dirauth support for the BadDirectory flag
[tor.git] / src / or / config.c
blobba9c944f564266edbee5a7ba792f184ae4b678bd
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
13 #include "or.h"
14 #include "addressmap.h"
15 #include "channel.h"
16 #include "circuitbuild.h"
17 #include "circuitlist.h"
18 #include "circuitmux.h"
19 #include "circuitmux_ewma.h"
20 #include "config.h"
21 #include "connection.h"
22 #include "connection_edge.h"
23 #include "connection_or.h"
24 #include "control.h"
25 #include "confparse.h"
26 #include "cpuworker.h"
27 #include "dirserv.h"
28 #include "dirvote.h"
29 #include "dns.h"
30 #include "entrynodes.h"
31 #include "geoip.h"
32 #include "hibernate.h"
33 #include "main.h"
34 #include "networkstatus.h"
35 #include "nodelist.h"
36 #include "policies.h"
37 #include "relay.h"
38 #include "rendclient.h"
39 #include "rendservice.h"
40 #include "rephist.h"
41 #include "router.h"
42 #include "sandbox.h"
43 #include "util.h"
44 #include "routerlist.h"
45 #include "routerset.h"
46 #include "statefile.h"
47 #include "transports.h"
48 #include "ext_orport.h"
49 #include "torgzip.h"
50 #ifdef _WIN32
51 #include <shlobj.h>
52 #endif
54 #include "procmon.h"
56 /* From main.c */
57 extern int quiet_level;
59 /** A list of abbreviations and aliases to map command-line options, obsolete
60 * option names, or alternative option names, to their current values. */
61 static config_abbrev_t option_abbrevs_[] = {
62 PLURAL(AuthDirBadDirCC),
63 PLURAL(AuthDirBadExitCC),
64 PLURAL(AuthDirInvalidCC),
65 PLURAL(AuthDirRejectCC),
66 PLURAL(ExitNode),
67 PLURAL(EntryNode),
68 PLURAL(ExcludeNode),
69 PLURAL(FirewallPort),
70 PLURAL(LongLivedPort),
71 PLURAL(HiddenServiceNode),
72 PLURAL(HiddenServiceExcludeNode),
73 PLURAL(NumCPU),
74 PLURAL(RendNode),
75 PLURAL(RendExcludeNode),
76 PLURAL(StrictEntryNode),
77 PLURAL(StrictExitNode),
78 PLURAL(StrictNode),
79 { "l", "Log", 1, 0},
80 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
81 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
82 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
83 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
84 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
85 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
86 { "DirServer", "DirAuthority", 0, 0}, /* XXXX024 later, make this warn? */
87 { "MaxConn", "ConnLimit", 0, 1},
88 { "MaxMemInCellQueues", "MaxMemInQueues", 0, 0},
89 { "ORBindAddress", "ORListenAddress", 0, 0},
90 { "DirBindAddress", "DirListenAddress", 0, 0},
91 { "SocksBindAddress", "SocksListenAddress", 0, 0},
92 { "UseHelperNodes", "UseEntryGuards", 0, 0},
93 { "NumHelperNodes", "NumEntryGuards", 0, 0},
94 { "UseEntryNodes", "UseEntryGuards", 0, 0},
95 { "NumEntryNodes", "NumEntryGuards", 0, 0},
96 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
97 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
98 { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0},
99 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
100 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
101 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
102 { "StrictEntryNodes", "StrictNodes", 0, 1},
103 { "StrictExitNodes", "StrictNodes", 0, 1},
104 { "VirtualAddrNetwork", "VirtualAddrNetworkIPv4", 0, 0},
105 { "_UseFilteringSSLBufferevents", "UseFilteringSSLBufferevents", 0, 1},
106 { NULL, NULL, 0, 0},
109 /** An entry for config_vars: "The option <b>name</b> has type
110 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
111 * or_options_t.<b>member</b>"
113 #define VAR(name,conftype,member,initvalue) \
114 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
115 initvalue }
116 /** As VAR, but the option name and member name are the same. */
117 #define V(member,conftype,initvalue) \
118 VAR(#member, conftype, member, initvalue)
119 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
120 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
122 #define VPORT(member,conftype,initvalue) \
123 VAR(#member, conftype, member ## _lines, initvalue)
125 /** Array of configuration options. Until we disallow nonstandard
126 * abbreviations, order is significant, since the first matching option will
127 * be chosen first.
129 static config_var_t option_vars_[] = {
130 OBSOLETE("AccountingMaxKB"),
131 V(AccountingMax, MEMUNIT, "0 bytes"),
132 V(AccountingStart, STRING, NULL),
133 V(Address, STRING, NULL),
134 V(AllowDotExit, BOOL, "0"),
135 V(AllowInvalidNodes, CSV, "middle,rendezvous"),
136 V(AllowNonRFC953Hostnames, BOOL, "0"),
137 V(AllowSingleHopCircuits, BOOL, "0"),
138 V(AllowSingleHopExits, BOOL, "0"),
139 V(AlternateBridgeAuthority, LINELIST, NULL),
140 V(AlternateDirAuthority, LINELIST, NULL),
141 OBSOLETE("AlternateHSAuthority"),
142 V(AssumeReachable, BOOL, "0"),
143 OBSOLETE("AuthDirBadDir"),
144 OBSOLETE("AuthDirBadDirCCs"),
145 V(AuthDirBadExit, LINELIST, NULL),
146 V(AuthDirBadExitCCs, CSV, ""),
147 V(AuthDirInvalid, LINELIST, NULL),
148 V(AuthDirInvalidCCs, CSV, ""),
149 V(AuthDirFastGuarantee, MEMUNIT, "100 KB"),
150 V(AuthDirGuardBWGuarantee, MEMUNIT, "2 MB"),
151 V(AuthDirReject, LINELIST, NULL),
152 V(AuthDirRejectCCs, CSV, ""),
153 OBSOLETE("AuthDirRejectUnlisted"),
154 OBSOLETE("AuthDirListBadDirs"),
155 V(AuthDirListBadExits, BOOL, "0"),
156 V(AuthDirMaxServersPerAddr, UINT, "2"),
157 V(AuthDirMaxServersPerAuthAddr,UINT, "5"),
158 V(AuthDirHasIPv6Connectivity, BOOL, "0"),
159 VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
160 V(AutomapHostsOnResolve, BOOL, "0"),
161 V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
162 V(AvoidDiskWrites, BOOL, "0"),
163 V(BandwidthBurst, MEMUNIT, "1 GB"),
164 V(BandwidthRate, MEMUNIT, "1 GB"),
165 V(BridgeAuthoritativeDir, BOOL, "0"),
166 VAR("Bridge", LINELIST, Bridges, NULL),
167 V(BridgePassword, STRING, NULL),
168 V(BridgeRecordUsageByCountry, BOOL, "1"),
169 V(BridgeRelay, BOOL, "0"),
170 V(CellStatistics, BOOL, "0"),
171 V(LearnCircuitBuildTimeout, BOOL, "1"),
172 V(CircuitBuildTimeout, INTERVAL, "0"),
173 V(CircuitIdleTimeout, INTERVAL, "1 hour"),
174 V(CircuitStreamTimeout, INTERVAL, "0"),
175 V(CircuitPriorityHalflife, DOUBLE, "-100.0"), /*negative:'Use default'*/
176 V(ClientDNSRejectInternalAddresses, BOOL,"1"),
177 V(ClientOnly, BOOL, "0"),
178 V(ClientPreferIPv6ORPort, BOOL, "0"),
179 V(ClientRejectInternalAddresses, BOOL, "1"),
180 V(ClientTransportPlugin, LINELIST, NULL),
181 V(ClientUseIPv6, BOOL, "0"),
182 V(ConsensusParams, STRING, NULL),
183 V(ConnLimit, UINT, "1000"),
184 V(ConnDirectionStatistics, BOOL, "0"),
185 V(ConstrainedSockets, BOOL, "0"),
186 V(ConstrainedSockSize, MEMUNIT, "8192"),
187 V(ContactInfo, STRING, NULL),
188 V(ControlListenAddress, LINELIST, NULL),
189 VPORT(ControlPort, LINELIST, NULL),
190 V(ControlPortFileGroupReadable,BOOL, "0"),
191 V(ControlPortWriteToFile, FILENAME, NULL),
192 V(ControlSocket, LINELIST, NULL),
193 V(ControlSocketsGroupWritable, BOOL, "0"),
194 V(CookieAuthentication, BOOL, "0"),
195 V(CookieAuthFileGroupReadable, BOOL, "0"),
196 V(CookieAuthFile, STRING, NULL),
197 V(CountPrivateBandwidth, BOOL, "0"),
198 V(DataDirectory, FILENAME, NULL),
199 OBSOLETE("DebugLogFile"),
200 V(DisableNetwork, BOOL, "0"),
201 V(DirAllowPrivateAddresses, BOOL, "0"),
202 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
203 V(DirListenAddress, LINELIST, NULL),
204 OBSOLETE("DirFetchPeriod"),
205 V(DirPolicy, LINELIST, NULL),
206 VPORT(DirPort, LINELIST, NULL),
207 V(DirPortFrontPage, FILENAME, NULL),
208 OBSOLETE("DirPostPeriod"),
209 OBSOLETE("DirRecordUsageByCountry"),
210 OBSOLETE("DirRecordUsageGranularity"),
211 OBSOLETE("DirRecordUsageRetainIPs"),
212 OBSOLETE("DirRecordUsageSaveInterval"),
213 V(DirReqStatistics, BOOL, "1"),
214 VAR("DirAuthority", LINELIST, DirAuthorities, NULL),
215 V(DirAuthorityFallbackRate, DOUBLE, "1.0"),
216 V(DisableAllSwap, BOOL, "0"),
217 V(DisableDebuggerAttachment, BOOL, "1"),
218 V(DisableIOCP, BOOL, "1"),
219 OBSOLETE("DisableV2DirectoryInfo_"),
220 V(DynamicDHGroups, BOOL, "0"),
221 VPORT(DNSPort, LINELIST, NULL),
222 V(DNSListenAddress, LINELIST, NULL),
223 V(DownloadExtraInfo, BOOL, "0"),
224 V(TestingEnableConnBwEvent, BOOL, "0"),
225 V(TestingEnableCellStatsEvent, BOOL, "0"),
226 V(TestingEnableTbEmptyEvent, BOOL, "0"),
227 V(EnforceDistinctSubnets, BOOL, "1"),
228 V(EntryNodes, ROUTERSET, NULL),
229 V(EntryStatistics, BOOL, "0"),
230 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
231 V(ExcludeNodes, ROUTERSET, NULL),
232 V(ExcludeExitNodes, ROUTERSET, NULL),
233 V(ExcludeSingleHopRelays, BOOL, "1"),
234 V(ExitNodes, ROUTERSET, NULL),
235 V(ExitPolicy, LINELIST, NULL),
236 V(ExitPolicyRejectPrivate, BOOL, "1"),
237 V(ExitPortStatistics, BOOL, "0"),
238 V(ExtendAllowPrivateAddresses, BOOL, "0"),
239 VPORT(ExtORPort, LINELIST, NULL),
240 V(ExtORPortCookieAuthFile, STRING, NULL),
241 V(ExtORPortCookieAuthFileGroupReadable, BOOL, "0"),
242 V(ExtraInfoStatistics, BOOL, "1"),
243 V(FallbackDir, LINELIST, NULL),
245 OBSOLETE("FallbackNetworkstatusFile"),
246 V(FascistFirewall, BOOL, "0"),
247 V(FirewallPorts, CSV, ""),
248 V(FastFirstHopPK, AUTOBOOL, "auto"),
249 V(FetchDirInfoEarly, BOOL, "0"),
250 V(FetchDirInfoExtraEarly, BOOL, "0"),
251 V(FetchServerDescriptors, BOOL, "1"),
252 V(FetchHidServDescriptors, BOOL, "1"),
253 V(FetchUselessDescriptors, BOOL, "0"),
254 OBSOLETE("FetchV2Networkstatus"),
255 V(GeoIPExcludeUnknown, AUTOBOOL, "auto"),
256 #ifdef _WIN32
257 V(GeoIPFile, FILENAME, "<default>"),
258 V(GeoIPv6File, FILENAME, "<default>"),
259 #else
260 V(GeoIPFile, FILENAME,
261 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
262 V(GeoIPv6File, FILENAME,
263 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip6"),
264 #endif
265 OBSOLETE("GiveGuardFlagTo_CVE_2011_2768_VulnerableRelays"),
266 OBSOLETE("Group"),
267 V(GuardLifetime, INTERVAL, "0 minutes"),
268 V(HardwareAccel, BOOL, "0"),
269 V(HeartbeatPeriod, INTERVAL, "6 hours"),
270 V(AccelName, STRING, NULL),
271 V(AccelDir, FILENAME, NULL),
272 V(HashedControlPassword, LINELIST, NULL),
273 V(HidServDirectoryV2, BOOL, "1"),
274 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
275 OBSOLETE("HiddenServiceExcludeNodes"),
276 OBSOLETE("HiddenServiceNodes"),
277 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
278 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
279 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
280 VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
281 V(HidServAuth, LINELIST, NULL),
282 OBSOLETE("HSAuthoritativeDir"),
283 OBSOLETE("HSAuthorityRecordStats"),
284 V(CloseHSClientCircuitsImmediatelyOnTimeout, BOOL, "0"),
285 V(CloseHSServiceRendCircuitsImmediatelyOnTimeout, BOOL, "0"),
286 V(HTTPProxy, STRING, NULL),
287 V(HTTPProxyAuthenticator, STRING, NULL),
288 V(HTTPSProxy, STRING, NULL),
289 V(HTTPSProxyAuthenticator, STRING, NULL),
290 V(IPv6Exit, BOOL, "0"),
291 VAR("ServerTransportPlugin", LINELIST, ServerTransportPlugin, NULL),
292 V(ServerTransportListenAddr, LINELIST, NULL),
293 V(ServerTransportOptions, LINELIST, NULL),
294 V(Socks4Proxy, STRING, NULL),
295 V(Socks5Proxy, STRING, NULL),
296 V(Socks5ProxyUsername, STRING, NULL),
297 V(Socks5ProxyPassword, STRING, NULL),
298 OBSOLETE("IgnoreVersion"),
299 V(KeepalivePeriod, INTERVAL, "5 minutes"),
300 VAR("Log", LINELIST, Logs, NULL),
301 V(LogMessageDomains, BOOL, "0"),
302 OBSOLETE("LinkPadding"),
303 OBSOLETE("LogLevel"),
304 OBSOLETE("LogFile"),
305 V(LogTimeGranularity, MSEC_INTERVAL, "1 second"),
306 V(TruncateLogFile, BOOL, "0"),
307 V(LongLivedPorts, CSV,
308 "21,22,706,1863,5050,5190,5222,5223,6523,6667,6697,8300"),
309 VAR("MapAddress", LINELIST, AddressMap, NULL),
310 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
311 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
312 V(MaxClientCircuitsPending, UINT, "32"),
313 VAR("MaxMemInQueues", MEMUNIT, MaxMemInQueues_raw, "0"),
314 OBSOLETE("MaxOnionsPending"),
315 V(MaxOnionQueueDelay, MSEC_INTERVAL, "1750 msec"),
316 V(MinMeasuredBWsForAuthToIgnoreAdvertised, INT, "500"),
317 OBSOLETE("MonthlyAccountingStart"),
318 V(MyFamily, STRING, NULL),
319 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
320 OBSOLETE("NamingAuthoritativeDirectory"),
321 V(NATDListenAddress, LINELIST, NULL),
322 VPORT(NATDPort, LINELIST, NULL),
323 V(Nickname, STRING, NULL),
324 V(PredictedPortsRelevanceTime, INTERVAL, "1 hour"),
325 V(WarnUnsafeSocks, BOOL, "1"),
326 OBSOLETE("NoPublish"),
327 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
328 V(NumCPUs, UINT, "0"),
329 V(NumDirectoryGuards, UINT, "0"),
330 V(NumEntryGuards, UINT, "0"),
331 V(ORListenAddress, LINELIST, NULL),
332 VPORT(ORPort, LINELIST, NULL),
333 V(OutboundBindAddress, LINELIST, NULL),
335 OBSOLETE("PathBiasDisableRate"),
336 V(PathBiasCircThreshold, INT, "-1"),
337 V(PathBiasNoticeRate, DOUBLE, "-1"),
338 V(PathBiasWarnRate, DOUBLE, "-1"),
339 V(PathBiasExtremeRate, DOUBLE, "-1"),
340 V(PathBiasScaleThreshold, INT, "-1"),
341 OBSOLETE("PathBiasScaleFactor"),
342 OBSOLETE("PathBiasMultFactor"),
343 V(PathBiasDropGuards, AUTOBOOL, "0"),
344 OBSOLETE("PathBiasUseCloseCounts"),
346 V(PathBiasUseThreshold, INT, "-1"),
347 V(PathBiasNoticeUseRate, DOUBLE, "-1"),
348 V(PathBiasExtremeUseRate, DOUBLE, "-1"),
349 V(PathBiasScaleUseThreshold, INT, "-1"),
351 V(PathsNeededToBuildCircuits, DOUBLE, "-1"),
352 OBSOLETE("PathlenCoinWeight"),
353 V(PerConnBWBurst, MEMUNIT, "0"),
354 V(PerConnBWRate, MEMUNIT, "0"),
355 V(PidFile, STRING, NULL),
356 V(TestingTorNetwork, BOOL, "0"),
357 V(TestingMinExitFlagThreshold, MEMUNIT, "0"),
358 V(TestingMinFastFlagThreshold, MEMUNIT, "0"),
359 V(OptimisticData, AUTOBOOL, "auto"),
360 V(PortForwarding, BOOL, "0"),
361 V(PortForwardingHelper, FILENAME, "tor-fw-helper"),
362 OBSOLETE("PreferTunneledDirConns"),
363 V(ProtocolWarnings, BOOL, "0"),
364 V(PublishServerDescriptor, CSV, "1"),
365 V(PublishHidServDescriptors, BOOL, "1"),
366 V(ReachableAddresses, LINELIST, NULL),
367 V(ReachableDirAddresses, LINELIST, NULL),
368 V(ReachableORAddresses, LINELIST, NULL),
369 V(RecommendedVersions, LINELIST, NULL),
370 V(RecommendedClientVersions, LINELIST, NULL),
371 V(RecommendedServerVersions, LINELIST, NULL),
372 OBSOLETE("RedirectExit"),
373 V(RefuseUnknownExits, AUTOBOOL, "auto"),
374 V(RejectPlaintextPorts, CSV, ""),
375 V(RelayBandwidthBurst, MEMUNIT, "0"),
376 V(RelayBandwidthRate, MEMUNIT, "0"),
377 OBSOLETE("RendExcludeNodes"),
378 OBSOLETE("RendNodes"),
379 V(RendPostPeriod, INTERVAL, "1 hour"),
380 V(RephistTrackTime, INTERVAL, "24 hours"),
381 OBSOLETE("RouterFile"),
382 V(RunAsDaemon, BOOL, "0"),
383 // V(RunTesting, BOOL, "0"),
384 OBSOLETE("RunTesting"), // currently unused
385 V(Sandbox, BOOL, "0"),
386 V(SafeLogging, STRING, "1"),
387 V(SafeSocks, BOOL, "0"),
388 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
389 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
390 V(ServerDNSDetectHijacking, BOOL, "1"),
391 V(ServerDNSRandomizeCase, BOOL, "1"),
392 V(ServerDNSResolvConfFile, STRING, NULL),
393 V(ServerDNSSearchDomains, BOOL, "0"),
394 V(ServerDNSTestAddresses, CSV,
395 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
396 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
397 V(SocksListenAddress, LINELIST, NULL),
398 V(SocksPolicy, LINELIST, NULL),
399 VPORT(SocksPort, LINELIST, NULL),
400 V(SocksTimeout, INTERVAL, "2 minutes"),
401 V(SSLKeyLifetime, INTERVAL, "0"),
402 OBSOLETE("StatusFetchPeriod"),
403 V(StrictNodes, BOOL, "0"),
404 V(Support022HiddenServices, AUTOBOOL, "auto"),
405 OBSOLETE("SysLog"),
406 V(TestSocks, BOOL, "0"),
407 OBSOLETE("TestVia"),
408 V(TokenBucketRefillInterval, MSEC_INTERVAL, "100 msec"),
409 V(Tor2webMode, BOOL, "0"),
410 V(TLSECGroup, STRING, NULL),
411 V(TrackHostExits, CSV, NULL),
412 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
413 OBSOLETE("TrafficShaping"),
414 V(TransListenAddress, LINELIST, NULL),
415 VPORT(TransPort, LINELIST, NULL),
416 V(TransProxyType, STRING, "default"),
417 OBSOLETE("TunnelDirConns"),
418 V(UpdateBridgesFromAuthority, BOOL, "0"),
419 V(UseBridges, BOOL, "0"),
420 V(UseEntryGuards, BOOL, "1"),
421 V(UseEntryGuardsAsDirGuards, BOOL, "1"),
422 V(UseMicrodescriptors, AUTOBOOL, "auto"),
423 V(UseNTorHandshake, AUTOBOOL, "1"),
424 V(User, STRING, NULL),
425 V(UserspaceIOCPBuffers, BOOL, "0"),
426 OBSOLETE("V1AuthoritativeDirectory"),
427 OBSOLETE("V2AuthoritativeDirectory"),
428 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
429 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
430 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
431 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
432 V(TestingV3AuthVotingStartOffset, INTERVAL, "0"),
433 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
434 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
435 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
436 V(V3AuthNIntervalsValid, UINT, "3"),
437 V(V3AuthUseLegacyKey, BOOL, "0"),
438 V(V3BandwidthsFile, FILENAME, NULL),
439 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
440 V(VirtualAddrNetworkIPv4, STRING, "127.192.0.0/10"),
441 V(VirtualAddrNetworkIPv6, STRING, "[FE80::]/10"),
442 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
443 V(UseFilteringSSLBufferevents, BOOL, "0"),
444 VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
445 VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
446 VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
447 VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
448 VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
449 NULL),
450 VAR("__OwningControllerProcess",STRING,OwningControllerProcess, NULL),
451 V(MinUptimeHidServDirectoryV2, INTERVAL, "25 hours"),
452 V(VoteOnHidServDirectoriesV2, BOOL, "1"),
453 V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 60, 60, 120, "
454 "300, 900, 2147483647"),
455 V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 60, 300, 600, "
456 "2147483647"),
457 V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
458 "300, 600, 1800, 1800, 1800, 1800, "
459 "1800, 3600, 7200"),
460 V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
461 "300, 600, 1800, 3600, 3600, 3600, "
462 "10800, 21600, 43200"),
463 V(TestingBridgeDownloadSchedule, CSV_INTERVAL, "3600, 900, 900, 3600"),
464 V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "10 minutes"),
465 V(TestingDirConnectionMaxStall, INTERVAL, "5 minutes"),
466 V(TestingConsensusMaxDownloadTries, UINT, "8"),
467 V(TestingDescriptorMaxDownloadTries, UINT, "8"),
468 V(TestingMicrodescMaxDownloadTries, UINT, "8"),
469 V(TestingCertMaxDownloadTries, UINT, "8"),
470 V(TestingDirAuthVoteGuard, ROUTERSET, NULL),
471 VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "0"),
473 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
476 /** Override default values with these if the user sets the TestingTorNetwork
477 * option. */
478 static const config_var_t testing_tor_network_defaults[] = {
479 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
480 V(DirAllowPrivateAddresses, BOOL, "1"),
481 V(EnforceDistinctSubnets, BOOL, "0"),
482 V(AssumeReachable, BOOL, "1"),
483 V(AuthDirMaxServersPerAddr, UINT, "0"),
484 V(AuthDirMaxServersPerAuthAddr,UINT, "0"),
485 V(ClientDNSRejectInternalAddresses, BOOL,"0"),
486 V(ClientRejectInternalAddresses, BOOL, "0"),
487 V(CountPrivateBandwidth, BOOL, "1"),
488 V(ExitPolicyRejectPrivate, BOOL, "0"),
489 V(ExtendAllowPrivateAddresses, BOOL, "1"),
490 V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
491 V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
492 V(V3AuthDistDelay, INTERVAL, "20 seconds"),
493 V(TestingV3AuthInitialVotingInterval, INTERVAL, "5 minutes"),
494 V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
495 V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
496 V(TestingV3AuthVotingStartOffset, INTERVAL, "0"),
497 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
498 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
499 V(MinUptimeHidServDirectoryV2, INTERVAL, "0 minutes"),
500 V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 5, 10, 15, "
501 "20, 30, 60"),
502 V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, 15, 20, "
503 "30, 60"),
504 V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
505 "15, 20, 30, 60"),
506 V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
507 "15, 20, 30, 60"),
508 V(TestingBridgeDownloadSchedule, CSV_INTERVAL, "60, 30, 30, 60"),
509 V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "5 seconds"),
510 V(TestingDirConnectionMaxStall, INTERVAL, "30 seconds"),
511 V(TestingConsensusMaxDownloadTries, UINT, "80"),
512 V(TestingDescriptorMaxDownloadTries, UINT, "80"),
513 V(TestingMicrodescMaxDownloadTries, UINT, "80"),
514 V(TestingCertMaxDownloadTries, UINT, "80"),
515 V(TestingEnableConnBwEvent, BOOL, "1"),
516 V(TestingEnableCellStatsEvent, BOOL, "1"),
517 V(TestingEnableTbEmptyEvent, BOOL, "1"),
518 VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "1"),
520 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
523 #undef VAR
524 #undef V
525 #undef OBSOLETE
527 #ifdef _WIN32
528 static char *get_windows_conf_root(void);
529 #endif
530 static int options_act_reversible(const or_options_t *old_options, char **msg);
531 static int options_act(const or_options_t *old_options);
532 static int options_transition_allowed(const or_options_t *old,
533 const or_options_t *new,
534 char **msg);
535 static int options_transition_affects_workers(
536 const or_options_t *old_options, const or_options_t *new_options);
537 static int options_transition_affects_descriptor(
538 const or_options_t *old_options, const or_options_t *new_options);
539 static int check_nickname_list(char **lst, const char *name, char **msg);
541 static int parse_client_transport_line(const or_options_t *options,
542 const char *line, int validate_only);
544 static int parse_server_transport_line(const or_options_t *options,
545 const char *line, int validate_only);
546 static char *get_bindaddr_from_transport_listen_line(const char *line,
547 const char *transport);
548 static int parse_dir_authority_line(const char *line,
549 dirinfo_type_t required_type,
550 int validate_only);
551 static int parse_dir_fallback_line(const char *line,
552 int validate_only);
553 static void port_cfg_free(port_cfg_t *port);
554 static int parse_ports(or_options_t *options, int validate_only,
555 char **msg_out, int *n_ports_out);
556 static int check_server_ports(const smartlist_t *ports,
557 const or_options_t *options);
559 static int validate_data_directory(or_options_t *options);
560 static int write_configuration_file(const char *fname,
561 const or_options_t *options);
562 static int options_init_logs(const or_options_t *old_options,
563 or_options_t *options, int validate_only);
565 static void init_libevent(const or_options_t *options);
566 static int opt_streq(const char *s1, const char *s2);
567 static int parse_outbound_addresses(or_options_t *options, int validate_only,
568 char **msg);
569 static void config_maybe_load_geoip_files_(const or_options_t *options,
570 const or_options_t *old_options);
571 static int options_validate_cb(void *old_options, void *options,
572 void *default_options,
573 int from_setconf, char **msg);
574 static uint64_t compute_real_max_mem_in_queues(const uint64_t val,
575 int log_guess);
577 /** Magic value for or_options_t. */
578 #define OR_OPTIONS_MAGIC 9090909
580 /** Configuration format for or_options_t. */
581 STATIC config_format_t options_format = {
582 sizeof(or_options_t),
583 OR_OPTIONS_MAGIC,
584 STRUCT_OFFSET(or_options_t, magic_),
585 option_abbrevs_,
586 option_vars_,
587 options_validate_cb,
588 NULL
592 * Functions to read and write the global options pointer.
595 /** Command-line and config-file options. */
596 static or_options_t *global_options = NULL;
597 /** The fallback options_t object; this is where we look for options not
598 * in torrc before we fall back to Tor's defaults. */
599 static or_options_t *global_default_options = NULL;
600 /** Name of most recently read torrc file. */
601 static char *torrc_fname = NULL;
602 /** Name of the most recently read torrc-defaults file.*/
603 static char *torrc_defaults_fname;
604 /** Configuration options set by command line. */
605 static config_line_t *global_cmdline_options = NULL;
606 /** Non-configuration options set by the command line */
607 static config_line_t *global_cmdline_only_options = NULL;
608 /** Boolean: Have we parsed the command line? */
609 static int have_parsed_cmdline = 0;
610 /** Contents of most recently read DirPortFrontPage file. */
611 static char *global_dirfrontpagecontents = NULL;
612 /** List of port_cfg_t for all configured ports. */
613 static smartlist_t *configured_ports = NULL;
615 /** Return the contents of our frontpage string, or NULL if not configured. */
616 const char *
617 get_dirportfrontpage(void)
619 return global_dirfrontpagecontents;
622 /** Return the currently configured options. */
623 or_options_t *
624 get_options_mutable(void)
626 tor_assert(global_options);
627 return global_options;
630 /** Returns the currently configured options */
631 MOCK_IMPL(const or_options_t *,
632 get_options,(void))
634 return get_options_mutable();
637 /** Change the current global options to contain <b>new_val</b> instead of
638 * their current value; take action based on the new value; free the old value
639 * as necessary. Returns 0 on success, -1 on failure.
642 set_options(or_options_t *new_val, char **msg)
644 int i;
645 smartlist_t *elements;
646 config_line_t *line;
647 or_options_t *old_options = global_options;
648 global_options = new_val;
649 /* Note that we pass the *old* options below, for comparison. It
650 * pulls the new options directly out of global_options. */
651 if (options_act_reversible(old_options, msg)<0) {
652 tor_assert(*msg);
653 global_options = old_options;
654 return -1;
656 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
657 log_err(LD_BUG,
658 "Acting on config options left us in a broken state. Dying.");
659 exit(1);
661 /* Issues a CONF_CHANGED event to notify controller of the change. If Tor is
662 * just starting up then the old_options will be undefined. */
663 if (old_options && old_options != global_options) {
664 elements = smartlist_new();
665 for (i=0; options_format.vars[i].name; ++i) {
666 const config_var_t *var = &options_format.vars[i];
667 const char *var_name = var->name;
668 if (var->type == CONFIG_TYPE_LINELIST_S ||
669 var->type == CONFIG_TYPE_OBSOLETE) {
670 continue;
672 if (!config_is_same(&options_format, new_val, old_options, var_name)) {
673 line = config_get_assigned_option(&options_format, new_val,
674 var_name, 1);
676 if (line) {
677 config_line_t *next;
678 for (; line; line = next) {
679 next = line->next;
680 smartlist_add(elements, line->key);
681 smartlist_add(elements, line->value);
682 tor_free(line);
684 } else {
685 smartlist_add(elements, tor_strdup(options_format.vars[i].name));
686 smartlist_add(elements, NULL);
690 control_event_conf_changed(elements);
691 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
692 smartlist_free(elements);
695 if (old_options != global_options)
696 config_free(&options_format, old_options);
698 return 0;
701 extern const char tor_git_revision[]; /* from tor_main.c */
703 /** The version of this Tor process, as parsed. */
704 static char *the_tor_version = NULL;
705 /** A shorter version of this Tor process's version, for export in our router
706 * descriptor. (Does not include the git version, if any.) */
707 static char *the_short_tor_version = NULL;
709 /** Return the current Tor version. */
710 const char *
711 get_version(void)
713 if (the_tor_version == NULL) {
714 if (strlen(tor_git_revision)) {
715 tor_asprintf(&the_tor_version, "%s (git-%s)", get_short_version(),
716 tor_git_revision);
717 } else {
718 the_tor_version = tor_strdup(get_short_version());
721 return the_tor_version;
724 /** Return the current Tor version, without any git tag. */
725 const char *
726 get_short_version(void)
729 if (the_short_tor_version == NULL) {
730 #ifdef TOR_BUILD_TAG
731 tor_asprintf(&the_short_tor_version, "%s (%s)", VERSION, TOR_BUILD_TAG);
732 #else
733 the_short_tor_version = tor_strdup(VERSION);
734 #endif
736 return the_short_tor_version;
739 /** Release additional memory allocated in options
741 STATIC void
742 or_options_free(or_options_t *options)
744 if (!options)
745 return;
747 routerset_free(options->ExcludeExitNodesUnion_);
748 if (options->NodeFamilySets) {
749 SMARTLIST_FOREACH(options->NodeFamilySets, routerset_t *,
750 rs, routerset_free(rs));
751 smartlist_free(options->NodeFamilySets);
753 tor_free(options->BridgePassword_AuthDigest_);
754 tor_free(options->command_arg);
755 config_free(&options_format, options);
758 /** Release all memory and resources held by global configuration structures.
760 void
761 config_free_all(void)
763 or_options_free(global_options);
764 global_options = NULL;
765 or_options_free(global_default_options);
766 global_default_options = NULL;
768 config_free_lines(global_cmdline_options);
769 global_cmdline_options = NULL;
771 config_free_lines(global_cmdline_only_options);
772 global_cmdline_only_options = NULL;
774 if (configured_ports) {
775 SMARTLIST_FOREACH(configured_ports,
776 port_cfg_t *, p, port_cfg_free(p));
777 smartlist_free(configured_ports);
778 configured_ports = NULL;
781 tor_free(torrc_fname);
782 tor_free(torrc_defaults_fname);
783 tor_free(the_tor_version);
784 tor_free(global_dirfrontpagecontents);
786 tor_free(the_short_tor_version);
787 tor_free(the_tor_version);
790 /** Make <b>address</b> -- a piece of information related to our operation as
791 * a client -- safe to log according to the settings in options->SafeLogging,
792 * and return it.
794 * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
796 const char *
797 safe_str_client(const char *address)
799 tor_assert(address);
800 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
801 return "[scrubbed]";
802 else
803 return address;
806 /** Make <b>address</b> -- a piece of information of unspecified sensitivity
807 * -- safe to log according to the settings in options->SafeLogging, and
808 * return it.
810 * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
811 * otherwise.)
813 const char *
814 safe_str(const char *address)
816 tor_assert(address);
817 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
818 return "[scrubbed]";
819 else
820 return address;
823 /** Equivalent to escaped(safe_str_client(address)). See reentrancy note on
824 * escaped(): don't use this outside the main thread, or twice in the same
825 * log statement. */
826 const char *
827 escaped_safe_str_client(const char *address)
829 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
830 return "[scrubbed]";
831 else
832 return escaped(address);
835 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
836 * escaped(): don't use this outside the main thread, or twice in the same
837 * log statement. */
838 const char *
839 escaped_safe_str(const char *address)
841 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
842 return "[scrubbed]";
843 else
844 return escaped(address);
847 /** Add the default directory authorities directly into the trusted dir list,
848 * but only add them insofar as they share bits with <b>type</b>. */
849 static void
850 add_default_trusted_dir_authorities(dirinfo_type_t type)
852 int i;
853 const char *authorities[] = {
854 "moria1 orport=9101 "
855 "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
856 "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
857 "tor26 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
858 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
859 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
860 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
861 "Tonga orport=443 bridge 82.94.251.203:80 "
862 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
863 "turtles orport=9090 "
864 "v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
865 "76.73.17.194:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
866 "gabelmoo orport=443 "
867 "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
868 "212.112.245.170:80 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
869 "dannenberg orport=443 "
870 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
871 "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
872 "urras orport=80 v3ident=80550987E1D626E3EBA5E5E75A458DE0626D088C "
873 "208.83.223.34:443 0AD3 FA88 4D18 F89E EA2D 89C0 1937 9E0E 7FD9 4417",
874 "maatuska orport=80 "
875 "v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
876 "171.25.193.9:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
877 "Faravahar orport=443 "
878 "v3ident=EFCBE720AB3A82B99F9E953CD5BF50F7EEFC7B97 "
879 "154.35.32.5:80 CF6D 0AAF B385 BE71 B8E1 11FC 5CFF 4B47 9237 33BC",
880 NULL
882 for (i=0; authorities[i]; i++) {
883 if (parse_dir_authority_line(authorities[i], type, 0)<0) {
884 log_err(LD_BUG, "Couldn't parse internal DirAuthority line %s",
885 authorities[i]);
890 /** Add the default fallback directory servers into the fallback directory
891 * server list. */
892 static void
893 add_default_fallback_dir_servers(void)
895 int i;
896 const char *fallback[] = {
897 NULL
899 for (i=0; fallback[i]; i++) {
900 if (parse_dir_fallback_line(fallback[i], 0)<0) {
901 log_err(LD_BUG, "Couldn't parse internal FallbackDir line %s",
902 fallback[i]);
907 /** Look at all the config options for using alternate directory
908 * authorities, and make sure none of them are broken. Also, warn the
909 * user if we changed any dangerous ones.
911 static int
912 validate_dir_servers(or_options_t *options, or_options_t *old_options)
914 config_line_t *cl;
916 if (options->DirAuthorities &&
917 (options->AlternateDirAuthority || options->AlternateBridgeAuthority)) {
918 log_warn(LD_CONFIG,
919 "You cannot set both DirAuthority and Alternate*Authority.");
920 return -1;
923 /* do we want to complain to the user about being partitionable? */
924 if ((options->DirAuthorities &&
925 (!old_options ||
926 !config_lines_eq(options->DirAuthorities,
927 old_options->DirAuthorities))) ||
928 (options->AlternateDirAuthority &&
929 (!old_options ||
930 !config_lines_eq(options->AlternateDirAuthority,
931 old_options->AlternateDirAuthority)))) {
932 log_warn(LD_CONFIG,
933 "You have used DirAuthority or AlternateDirAuthority to "
934 "specify alternate directory authorities in "
935 "your configuration. This is potentially dangerous: it can "
936 "make you look different from all other Tor users, and hurt "
937 "your anonymity. Even if you've specified the same "
938 "authorities as Tor uses by default, the defaults could "
939 "change in the future. Be sure you know what you're doing.");
942 /* Now go through the four ways you can configure an alternate
943 * set of directory authorities, and make sure none are broken. */
944 for (cl = options->DirAuthorities; cl; cl = cl->next)
945 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
946 return -1;
947 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
948 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
949 return -1;
950 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
951 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
952 return -1;
953 for (cl = options->FallbackDir; cl; cl = cl->next)
954 if (parse_dir_fallback_line(cl->value, 1)<0)
955 return -1;
956 return 0;
959 /** Look at all the config options and assign new dir authorities
960 * as appropriate.
962 static int
963 consider_adding_dir_servers(const or_options_t *options,
964 const or_options_t *old_options)
966 config_line_t *cl;
967 int need_to_update =
968 !smartlist_len(router_get_trusted_dir_servers()) ||
969 !smartlist_len(router_get_fallback_dir_servers()) || !old_options ||
970 !config_lines_eq(options->DirAuthorities, old_options->DirAuthorities) ||
971 !config_lines_eq(options->FallbackDir, old_options->FallbackDir) ||
972 !config_lines_eq(options->AlternateBridgeAuthority,
973 old_options->AlternateBridgeAuthority) ||
974 !config_lines_eq(options->AlternateDirAuthority,
975 old_options->AlternateDirAuthority);
977 if (!need_to_update)
978 return 0; /* all done */
980 /* Start from a clean slate. */
981 clear_dir_servers();
983 if (!options->DirAuthorities) {
984 /* then we may want some of the defaults */
985 dirinfo_type_t type = NO_DIRINFO;
986 if (!options->AlternateBridgeAuthority)
987 type |= BRIDGE_DIRINFO;
988 if (!options->AlternateDirAuthority)
989 type |= V3_DIRINFO | EXTRAINFO_DIRINFO | MICRODESC_DIRINFO;
990 add_default_trusted_dir_authorities(type);
992 if (!options->FallbackDir)
993 add_default_fallback_dir_servers();
995 for (cl = options->DirAuthorities; cl; cl = cl->next)
996 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
997 return -1;
998 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
999 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1000 return -1;
1001 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1002 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1003 return -1;
1004 for (cl = options->FallbackDir; cl; cl = cl->next)
1005 if (parse_dir_fallback_line(cl->value, 0)<0)
1006 return -1;
1007 return 0;
1010 /** Fetch the active option list, and take actions based on it. All of the
1011 * things we do should survive being done repeatedly. If present,
1012 * <b>old_options</b> contains the previous value of the options.
1014 * Return 0 if all goes well, return -1 if things went badly.
1016 static int
1017 options_act_reversible(const or_options_t *old_options, char **msg)
1019 smartlist_t *new_listeners = smartlist_new();
1020 smartlist_t *replaced_listeners = smartlist_new();
1021 static int libevent_initialized = 0;
1022 or_options_t *options = get_options_mutable();
1023 int running_tor = options->command == CMD_RUN_TOR;
1024 int set_conn_limit = 0;
1025 int r = -1;
1026 int logs_marked = 0;
1027 int old_min_log_level = get_min_log_level();
1029 /* Daemonize _first_, since we only want to open most of this stuff in
1030 * the subprocess. Libevent bases can't be reliably inherited across
1031 * processes. */
1032 if (running_tor && options->RunAsDaemon) {
1033 /* No need to roll back, since you can't change the value. */
1034 start_daemon();
1037 #ifndef HAVE_SYS_UN_H
1038 if (options->ControlSocket || options->ControlSocketsGroupWritable) {
1039 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported "
1040 "on this OS/with this build.");
1041 goto rollback;
1043 #else
1044 if (options->ControlSocketsGroupWritable && !options->ControlSocket) {
1045 *msg = tor_strdup("Setting ControlSocketGroupWritable without setting"
1046 "a ControlSocket makes no sense.");
1047 goto rollback;
1049 #endif
1051 if (running_tor) {
1052 int n_ports=0;
1053 /* We need to set the connection limit before we can open the listeners. */
1054 if (! sandbox_is_active()) {
1055 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1056 &options->ConnLimit_) < 0) {
1057 *msg = tor_strdup("Problem with ConnLimit value. "
1058 "See logs for details.");
1059 goto rollback;
1061 set_conn_limit = 1;
1062 } else {
1063 tor_assert(old_options);
1064 options->ConnLimit_ = old_options->ConnLimit_;
1067 /* Set up libevent. (We need to do this before we can register the
1068 * listeners as listeners.) */
1069 if (running_tor && !libevent_initialized) {
1070 init_libevent(options);
1071 libevent_initialized = 1;
1074 /* Adjust the port configuration so we can launch listeners. */
1075 if (parse_ports(options, 0, msg, &n_ports)) {
1076 if (!*msg)
1077 *msg = tor_strdup("Unexpected problem parsing port config");
1078 goto rollback;
1081 /* Set the hibernation state appropriately.*/
1082 consider_hibernation(time(NULL));
1084 /* Launch the listeners. (We do this before we setuid, so we can bind to
1085 * ports under 1024.) We don't want to rebind if we're hibernating. If
1086 * networking is disabled, this will close all but the control listeners,
1087 * but disable those. */
1088 if (!we_are_hibernating()) {
1089 if (retry_all_listeners(replaced_listeners, new_listeners,
1090 options->DisableNetwork) < 0) {
1091 *msg = tor_strdup("Failed to bind one of the listener ports.");
1092 goto rollback;
1095 if (options->DisableNetwork) {
1096 /* Aggressively close non-controller stuff, NOW */
1097 log_notice(LD_NET, "DisableNetwork is set. Tor will not make or accept "
1098 "non-control network connections. Shutting down all existing "
1099 "connections.");
1100 connection_mark_all_noncontrol_connections();
1104 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1105 /* Open /dev/pf before dropping privileges. */
1106 if (options->TransPort_set &&
1107 options->TransProxyType_parsed == TPT_DEFAULT) {
1108 if (get_pf_socket() < 0) {
1109 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1110 goto rollback;
1113 #endif
1115 /* Attempt to lock all current and future memory with mlockall() only once */
1116 if (options->DisableAllSwap) {
1117 if (tor_mlockall() == -1) {
1118 *msg = tor_strdup("DisableAllSwap failure. Do you have proper "
1119 "permissions?");
1120 goto done;
1124 /* Setuid/setgid as appropriate */
1125 if (options->User) {
1126 if (switch_id(options->User) != 0) {
1127 /* No need to roll back, since you can't change the value. */
1128 *msg = tor_strdup("Problem with User value. See logs for details.");
1129 goto done;
1133 /* Ensure data directory is private; create if possible. */
1134 if (check_private_dir(options->DataDirectory,
1135 running_tor ? CPD_CREATE : CPD_CHECK,
1136 options->User)<0) {
1137 tor_asprintf(msg,
1138 "Couldn't access/create private data directory \"%s\"",
1139 options->DataDirectory);
1140 goto done;
1141 /* No need to roll back, since you can't change the value. */
1144 /* Bail out at this point if we're not going to be a client or server:
1145 * we don't run Tor itself. */
1146 if (!running_tor)
1147 goto commit;
1149 mark_logs_temp(); /* Close current logs once new logs are open. */
1150 logs_marked = 1;
1151 /* Configure the tor_log(s) */
1152 if (options_init_logs(old_options, options, 0)<0) {
1153 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1154 goto rollback;
1157 commit:
1158 r = 0;
1159 if (logs_marked) {
1160 log_severity_list_t *severity =
1161 tor_malloc_zero(sizeof(log_severity_list_t));
1162 close_temp_logs();
1163 add_callback_log(severity, control_event_logmsg);
1164 control_adjust_event_log_severity();
1165 tor_free(severity);
1166 tor_log_update_sigsafe_err_fds();
1170 const char *badness = NULL;
1171 int bad_safelog = 0, bad_severity = 0, new_badness = 0;
1172 if (options->SafeLogging_ != SAFELOG_SCRUB_ALL) {
1173 bad_safelog = 1;
1174 if (!old_options || old_options->SafeLogging_ != options->SafeLogging_)
1175 new_badness = 1;
1177 if (get_min_log_level() >= LOG_INFO) {
1178 bad_severity = 1;
1179 if (get_min_log_level() != old_min_log_level)
1180 new_badness = 1;
1182 if (bad_safelog && bad_severity)
1183 badness = "you disabled SafeLogging, and "
1184 "you're logging more than \"notice\"";
1185 else if (bad_safelog)
1186 badness = "you disabled SafeLogging";
1187 else
1188 badness = "you're logging more than \"notice\"";
1189 if (new_badness)
1190 log_warn(LD_GENERAL, "Your log may contain sensitive information - %s. "
1191 "Don't log unless it serves an important reason. "
1192 "Overwrite the log afterwards.", badness);
1195 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1197 int marked = conn->marked_for_close;
1198 log_notice(LD_NET, "Closing old %s on %s:%d",
1199 conn_type_to_string(conn->type), conn->address, conn->port);
1200 connection_close_immediate(conn);
1201 if (!marked) {
1202 connection_mark_for_close(conn);
1205 goto done;
1207 rollback:
1208 r = -1;
1209 tor_assert(*msg);
1211 if (logs_marked) {
1212 rollback_log_changes();
1213 control_adjust_event_log_severity();
1216 if (set_conn_limit && old_options)
1217 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1218 &options->ConnLimit_);
1220 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1222 log_notice(LD_NET, "Closing partially-constructed %s on %s:%d",
1223 conn_type_to_string(conn->type), conn->address, conn->port);
1224 connection_close_immediate(conn);
1225 connection_mark_for_close(conn);
1228 done:
1229 smartlist_free(new_listeners);
1230 smartlist_free(replaced_listeners);
1231 return r;
1234 /** If we need to have a GEOIP ip-to-country map to run with our configured
1235 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1237 options_need_geoip_info(const or_options_t *options, const char **reason_out)
1239 int bridge_usage =
1240 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1241 int routerset_usage =
1242 routerset_needs_geoip(options->EntryNodes) ||
1243 routerset_needs_geoip(options->ExitNodes) ||
1244 routerset_needs_geoip(options->ExcludeExitNodes) ||
1245 routerset_needs_geoip(options->ExcludeNodes);
1247 if (routerset_usage && reason_out) {
1248 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1249 "countries, and we need GEOIP information to figure out which ones they "
1250 "are.";
1251 } else if (bridge_usage && reason_out) {
1252 *reason_out = "We've been configured to see which countries can access "
1253 "us as a bridge, and we need GEOIP information to tell which countries "
1254 "clients are in.";
1256 return bridge_usage || routerset_usage;
1259 /** Return the bandwidthrate that we are going to report to the authorities
1260 * based on the config options. */
1261 uint32_t
1262 get_effective_bwrate(const or_options_t *options)
1264 uint64_t bw = options->BandwidthRate;
1265 if (bw > options->MaxAdvertisedBandwidth)
1266 bw = options->MaxAdvertisedBandwidth;
1267 if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1268 bw = options->RelayBandwidthRate;
1269 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1270 return (uint32_t)bw;
1273 /** Return the bandwidthburst that we are going to report to the authorities
1274 * based on the config options. */
1275 uint32_t
1276 get_effective_bwburst(const or_options_t *options)
1278 uint64_t bw = options->BandwidthBurst;
1279 if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1280 bw = options->RelayBandwidthBurst;
1281 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1282 return (uint32_t)bw;
1285 /** Return True if any changes from <b>old_options</b> to
1286 * <b>new_options</b> needs us to refresh our TLS context. */
1287 static int
1288 options_transition_requires_fresh_tls_context(const or_options_t *old_options,
1289 const or_options_t *new_options)
1291 tor_assert(new_options);
1293 if (!old_options)
1294 return 0;
1296 if ((old_options->DynamicDHGroups != new_options->DynamicDHGroups)) {
1297 return 1;
1300 if (!opt_streq(old_options->TLSECGroup, new_options->TLSECGroup))
1301 return 1;
1303 return 0;
1306 /** Fetch the active option list, and take actions based on it. All of the
1307 * things we do should survive being done repeatedly. If present,
1308 * <b>old_options</b> contains the previous value of the options.
1310 * Return 0 if all goes well, return -1 if it's time to die.
1312 * Note: We haven't moved all the "act on new configuration" logic
1313 * here yet. Some is still in do_hup() and other places.
1315 static int
1316 options_act(const or_options_t *old_options)
1318 config_line_t *cl;
1319 or_options_t *options = get_options_mutable();
1320 int running_tor = options->command == CMD_RUN_TOR;
1321 char *msg=NULL;
1322 const int transition_affects_workers =
1323 old_options && options_transition_affects_workers(old_options, options);
1324 int old_ewma_enabled;
1326 /* disable ptrace and later, other basic debugging techniques */
1328 /* Remember if we already disabled debugger attachment */
1329 static int disabled_debugger_attach = 0;
1330 /* Remember if we already warned about being configured not to disable
1331 * debugger attachment */
1332 static int warned_debugger_attach = 0;
1333 /* Don't disable debugger attachment when we're running the unit tests. */
1334 if (options->DisableDebuggerAttachment && !disabled_debugger_attach &&
1335 running_tor) {
1336 int ok = tor_disable_debugger_attach();
1337 if (warned_debugger_attach && ok == 1) {
1338 log_notice(LD_CONFIG, "Disabled attaching debuggers for unprivileged "
1339 "users.");
1341 disabled_debugger_attach = (ok == 1);
1342 } else if (!options->DisableDebuggerAttachment &&
1343 !warned_debugger_attach) {
1344 log_notice(LD_CONFIG, "Not disabling debugger attaching for "
1345 "unprivileged users.");
1346 warned_debugger_attach = 1;
1350 /* Write control ports to disk as appropriate */
1351 control_ports_write_to_file();
1353 if (running_tor && !have_lockfile()) {
1354 if (try_locking(options, 1) < 0)
1355 return -1;
1358 if (consider_adding_dir_servers(options, old_options) < 0)
1359 return -1;
1361 #ifdef NON_ANONYMOUS_MODE_ENABLED
1362 log_warn(LD_GENERAL, "This copy of Tor was compiled to run in a "
1363 "non-anonymous mode. It will provide NO ANONYMITY.");
1364 #endif
1366 #ifdef ENABLE_TOR2WEB_MODE
1367 if (!options->Tor2webMode) {
1368 log_err(LD_CONFIG, "This copy of Tor was compiled to run in "
1369 "'tor2web mode'. It can only be run with the Tor2webMode torrc "
1370 "option enabled.");
1371 return -1;
1373 #else
1374 if (options->Tor2webMode) {
1375 log_err(LD_CONFIG, "This copy of Tor was not compiled to run in "
1376 "'tor2web mode'. It cannot be run with the Tor2webMode torrc "
1377 "option enabled. To enable Tor2webMode recompile with the "
1378 "--enable-tor2webmode option.");
1379 return -1;
1381 #endif
1383 /* If we are a bridge with a pluggable transport proxy but no
1384 Extended ORPort, inform the user that she is missing out. */
1385 if (server_mode(options) && options->ServerTransportPlugin &&
1386 !options->ExtORPort_lines) {
1387 log_notice(LD_CONFIG, "We use pluggable transports but the Extended "
1388 "ORPort is disabled. Tor and your pluggable transports proxy "
1389 "communicate with each other via the Extended ORPort so it "
1390 "is suggested you enable it: it will also allow your Bridge "
1391 "to collect statistics about its clients that use pluggable "
1392 "transports. Please enable it using the ExtORPort torrc option "
1393 "(e.g. set 'ExtORPort auto').");
1396 if (options->Bridges) {
1397 mark_bridge_list();
1398 for (cl = options->Bridges; cl; cl = cl->next) {
1399 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
1400 if (!bridge_line) {
1401 log_warn(LD_BUG,
1402 "Previously validated Bridge line could not be added!");
1403 return -1;
1405 bridge_add_from_config(bridge_line);
1407 sweep_bridge_list();
1410 if (running_tor && rend_config_services(options, 0)<0) {
1411 log_warn(LD_BUG,
1412 "Previously validated hidden services line could not be added!");
1413 return -1;
1416 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1417 log_warn(LD_BUG, "Previously validated client authorization for "
1418 "hidden services could not be added!");
1419 return -1;
1422 /* Load state */
1423 if (! or_state_loaded() && running_tor) {
1424 if (or_state_load())
1425 return -1;
1426 rep_hist_load_mtbf_data(time(NULL));
1429 mark_transport_list();
1430 pt_prepare_proxy_list_for_config_read();
1431 if (options->ClientTransportPlugin) {
1432 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
1433 if (parse_client_transport_line(options, cl->value, 0)<0) {
1434 log_warn(LD_BUG,
1435 "Previously validated ClientTransportPlugin line "
1436 "could not be added!");
1437 return -1;
1442 if (options->ServerTransportPlugin && server_mode(options)) {
1443 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
1444 if (parse_server_transport_line(options, cl->value, 0)<0) {
1445 log_warn(LD_BUG,
1446 "Previously validated ServerTransportPlugin line "
1447 "could not be added!");
1448 return -1;
1452 sweep_transport_list();
1453 sweep_proxy_list();
1455 /* Start the PT proxy configuration. By doing this configuration
1456 here, we also figure out which proxies need to be restarted and
1457 which not. */
1458 if (pt_proxies_configuration_pending() && !net_is_disabled())
1459 pt_configure_remaining_proxies();
1461 /* Bail out at this point if we're not going to be a client or server:
1462 * we want to not fork, and to log stuff to stderr. */
1463 if (!running_tor)
1464 return 0;
1466 /* Finish backgrounding the process */
1467 if (options->RunAsDaemon) {
1468 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1469 finish_daemon(options->DataDirectory);
1472 /* If needed, generate a new TLS DH prime according to the current torrc. */
1473 if (server_mode(options) && options->DynamicDHGroups) {
1474 char *keydir = get_datadir_fname("keys");
1475 if (check_private_dir(keydir, CPD_CREATE, options->User)) {
1476 tor_free(keydir);
1477 return -1;
1479 tor_free(keydir);
1481 if (!old_options || !old_options->DynamicDHGroups) {
1482 char *fname = get_datadir_fname2("keys", "dynamic_dh_params");
1483 crypto_set_tls_dh_prime(fname);
1484 tor_free(fname);
1486 } else { /* clients don't need a dynamic DH prime. */
1487 crypto_set_tls_dh_prime(NULL);
1490 /* We want to reinit keys as needed before we do much of anything else:
1491 keys are important, and other things can depend on them. */
1492 if (transition_affects_workers ||
1493 (options->V3AuthoritativeDir && (!old_options ||
1494 !old_options->V3AuthoritativeDir))) {
1495 if (init_keys() < 0) {
1496 log_warn(LD_BUG,"Error initializing keys; exiting");
1497 return -1;
1499 } else if (old_options &&
1500 options_transition_requires_fresh_tls_context(old_options,
1501 options)) {
1502 if (router_initialize_tls_context() < 0) {
1503 log_warn(LD_BUG,"Error initializing TLS context.");
1504 return -1;
1508 /* Write our PID to the PID file. If we do not have write permissions we
1509 * will log a warning */
1510 if (options->PidFile && !sandbox_is_active()) {
1511 write_pidfile(options->PidFile);
1514 /* Register addressmap directives */
1515 config_register_addressmaps(options);
1516 parse_virtual_addr_network(options->VirtualAddrNetworkIPv4, AF_INET,0,NULL);
1517 parse_virtual_addr_network(options->VirtualAddrNetworkIPv6, AF_INET6,0,NULL);
1519 /* Update address policies. */
1520 if (policies_parse_from_options(options) < 0) {
1521 /* This should be impossible, but let's be sure. */
1522 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1523 return -1;
1526 if (init_control_cookie_authentication(options->CookieAuthentication) < 0) {
1527 log_warn(LD_CONFIG,"Error creating control cookie authentication file.");
1528 return -1;
1531 /* If we have an ExtORPort, initialize its auth cookie. */
1532 if (init_ext_or_cookie_authentication(!!options->ExtORPort_lines) < 0) {
1533 log_warn(LD_CONFIG,"Error creating Extended ORPort cookie file.");
1534 return -1;
1537 monitor_owning_controller_process(options->OwningControllerProcess);
1539 /* reload keys as needed for rendezvous services. */
1540 if (rend_service_load_all_keys()<0) {
1541 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1542 return -1;
1545 /* Set up accounting */
1546 if (accounting_parse_options(options, 0)<0) {
1547 log_warn(LD_CONFIG,"Error in accounting options");
1548 return -1;
1550 if (accounting_is_enabled(options))
1551 configure_accounting(time(NULL));
1553 #ifdef USE_BUFFEREVENTS
1554 /* If we're using the bufferevents implementation and our rate limits
1555 * changed, we need to tell the rate-limiting system about it. */
1556 if (!old_options ||
1557 old_options->BandwidthRate != options->BandwidthRate ||
1558 old_options->BandwidthBurst != options->BandwidthBurst ||
1559 old_options->RelayBandwidthRate != options->RelayBandwidthRate ||
1560 old_options->RelayBandwidthBurst != options->RelayBandwidthBurst)
1561 connection_bucket_init();
1562 #endif
1564 old_ewma_enabled = cell_ewma_enabled();
1565 /* Change the cell EWMA settings */
1566 cell_ewma_set_scale_factor(options, networkstatus_get_latest_consensus());
1567 /* If we just enabled ewma, set the cmux policy on all active channels */
1568 if (cell_ewma_enabled() && !old_ewma_enabled) {
1569 channel_set_cmux_policy_everywhere(&ewma_policy);
1570 } else if (!cell_ewma_enabled() && old_ewma_enabled) {
1571 /* Turn it off everywhere */
1572 channel_set_cmux_policy_everywhere(NULL);
1575 /* Update the BridgePassword's hashed version as needed. We store this as a
1576 * digest so that we can do side-channel-proof comparisons on it.
1578 if (options->BridgePassword) {
1579 char *http_authenticator;
1580 http_authenticator = alloc_http_authenticator(options->BridgePassword);
1581 if (!http_authenticator) {
1582 log_warn(LD_BUG, "Unable to allocate HTTP authenticator. Not setting "
1583 "BridgePassword.");
1584 return -1;
1586 options->BridgePassword_AuthDigest_ = tor_malloc(DIGEST256_LEN);
1587 crypto_digest256(options->BridgePassword_AuthDigest_,
1588 http_authenticator, strlen(http_authenticator),
1589 DIGEST_SHA256);
1590 tor_free(http_authenticator);
1593 if (parse_outbound_addresses(options, 0, &msg) < 0) {
1594 log_warn(LD_BUG, "Failed parsing oubound bind addresses: %s", msg);
1595 tor_free(msg);
1596 return -1;
1599 config_maybe_load_geoip_files_(options, old_options);
1601 if (geoip_is_loaded(AF_INET) && options->GeoIPExcludeUnknown) {
1602 /* ExcludeUnknown is true or "auto" */
1603 const int is_auto = options->GeoIPExcludeUnknown == -1;
1604 int changed;
1606 changed = routerset_add_unknown_ccs(&options->ExcludeNodes, is_auto);
1607 changed += routerset_add_unknown_ccs(&options->ExcludeExitNodes, is_auto);
1609 if (changed)
1610 routerset_add_unknown_ccs(&options->ExcludeExitNodesUnion_, is_auto);
1613 /* Check for transitions that need action. */
1614 if (old_options) {
1615 int revise_trackexithosts = 0;
1616 int revise_automap_entries = 0;
1617 if ((options->UseEntryGuards && !old_options->UseEntryGuards) ||
1618 options->UseBridges != old_options->UseBridges ||
1619 (options->UseBridges &&
1620 !config_lines_eq(options->Bridges, old_options->Bridges)) ||
1621 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes) ||
1622 !routerset_equal(old_options->ExcludeExitNodes,
1623 options->ExcludeExitNodes) ||
1624 !routerset_equal(old_options->EntryNodes, options->EntryNodes) ||
1625 !routerset_equal(old_options->ExitNodes, options->ExitNodes) ||
1626 options->StrictNodes != old_options->StrictNodes) {
1627 log_info(LD_CIRC,
1628 "Changed to using entry guards or bridges, or changed "
1629 "preferred or excluded node lists. "
1630 "Abandoning previous circuits.");
1631 circuit_mark_all_unused_circs();
1632 circuit_mark_all_dirty_circs_as_unusable();
1633 revise_trackexithosts = 1;
1636 if (!smartlist_strings_eq(old_options->TrackHostExits,
1637 options->TrackHostExits))
1638 revise_trackexithosts = 1;
1640 if (revise_trackexithosts)
1641 addressmap_clear_excluded_trackexithosts(options);
1643 if (!options->AutomapHostsOnResolve) {
1644 if (old_options->AutomapHostsOnResolve)
1645 revise_automap_entries = 1;
1646 } else {
1647 if (!smartlist_strings_eq(old_options->AutomapHostsSuffixes,
1648 options->AutomapHostsSuffixes))
1649 revise_automap_entries = 1;
1650 else if (!opt_streq(old_options->VirtualAddrNetworkIPv4,
1651 options->VirtualAddrNetworkIPv4) ||
1652 !opt_streq(old_options->VirtualAddrNetworkIPv6,
1653 options->VirtualAddrNetworkIPv6))
1654 revise_automap_entries = 1;
1657 if (revise_automap_entries)
1658 addressmap_clear_invalid_automaps(options);
1660 /* How long should we delay counting bridge stats after becoming a bridge?
1661 * We use this so we don't count people who used our bridge thinking it is
1662 * a relay. If you change this, don't forget to change the log message
1663 * below. It's 4 hours (the time it takes to stop being used by clients)
1664 * plus some extra time for clock skew. */
1665 #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
1667 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
1668 int was_relay = 0;
1669 if (options->BridgeRelay) {
1670 time_t int_start = time(NULL);
1671 if (config_lines_eq(old_options->ORPort_lines,options->ORPort_lines)) {
1672 int_start += RELAY_BRIDGE_STATS_DELAY;
1673 was_relay = 1;
1675 geoip_bridge_stats_init(int_start);
1676 log_info(LD_CONFIG, "We are acting as a bridge now. Starting new "
1677 "GeoIP stats interval%s.", was_relay ? " in 6 "
1678 "hours from now" : "");
1679 } else {
1680 geoip_bridge_stats_term();
1681 log_info(LD_GENERAL, "We are no longer acting as a bridge. "
1682 "Forgetting GeoIP stats.");
1686 if (transition_affects_workers) {
1687 log_info(LD_GENERAL,
1688 "Worker-related options changed. Rotating workers.");
1690 if (server_mode(options) && !server_mode(old_options)) {
1691 ip_address_changed(0);
1692 if (can_complete_circuit || !any_predicted_circuits(time(NULL)))
1693 inform_testing_reachability();
1695 cpuworkers_rotate();
1696 if (dns_reset())
1697 return -1;
1698 } else {
1699 if (dns_reset())
1700 return -1;
1703 if (options->PerConnBWRate != old_options->PerConnBWRate ||
1704 options->PerConnBWBurst != old_options->PerConnBWBurst)
1705 connection_or_update_token_buckets(get_connection_array(), options);
1708 if (options->CellStatistics || options->DirReqStatistics ||
1709 options->EntryStatistics || options->ExitPortStatistics ||
1710 options->ConnDirectionStatistics ||
1711 options->BridgeAuthoritativeDir) {
1712 time_t now = time(NULL);
1713 int print_notice = 0;
1715 /* Only collect directory-request statistics on relays and bridges. */
1716 if (!server_mode(options)) {
1717 options->DirReqStatistics = 0;
1720 /* Only collect other relay-only statistics on relays. */
1721 if (!public_server_mode(options)) {
1722 options->CellStatistics = 0;
1723 options->EntryStatistics = 0;
1724 options->ExitPortStatistics = 0;
1727 if ((!old_options || !old_options->CellStatistics) &&
1728 options->CellStatistics) {
1729 rep_hist_buffer_stats_init(now);
1730 print_notice = 1;
1732 if ((!old_options || !old_options->DirReqStatistics) &&
1733 options->DirReqStatistics) {
1734 if (geoip_is_loaded(AF_INET)) {
1735 geoip_dirreq_stats_init(now);
1736 print_notice = 1;
1737 } else {
1738 options->DirReqStatistics = 0;
1739 /* Don't warn Tor clients, they don't use statistics */
1740 if (options->ORPort_set)
1741 log_notice(LD_CONFIG, "Configured to measure directory request "
1742 "statistics, but no GeoIP database found. "
1743 "Please specify a GeoIP database using the "
1744 "GeoIPFile option.");
1747 if ((!old_options || !old_options->EntryStatistics) &&
1748 options->EntryStatistics && !should_record_bridge_info(options)) {
1749 if (geoip_is_loaded(AF_INET) || geoip_is_loaded(AF_INET6)) {
1750 geoip_entry_stats_init(now);
1751 print_notice = 1;
1752 } else {
1753 options->EntryStatistics = 0;
1754 log_notice(LD_CONFIG, "Configured to measure entry node "
1755 "statistics, but no GeoIP database found. "
1756 "Please specify a GeoIP database using the "
1757 "GeoIPFile option.");
1760 if ((!old_options || !old_options->ExitPortStatistics) &&
1761 options->ExitPortStatistics) {
1762 rep_hist_exit_stats_init(now);
1763 print_notice = 1;
1765 if ((!old_options || !old_options->ConnDirectionStatistics) &&
1766 options->ConnDirectionStatistics) {
1767 rep_hist_conn_stats_init(now);
1769 if ((!old_options || !old_options->BridgeAuthoritativeDir) &&
1770 options->BridgeAuthoritativeDir) {
1771 rep_hist_desc_stats_init(now);
1772 print_notice = 1;
1774 if (print_notice)
1775 log_notice(LD_CONFIG, "Configured to measure statistics. Look for "
1776 "the *-stats files that will first be written to the "
1777 "data directory in 24 hours from now.");
1780 if (old_options && old_options->CellStatistics &&
1781 !options->CellStatistics)
1782 rep_hist_buffer_stats_term();
1783 if (old_options && old_options->DirReqStatistics &&
1784 !options->DirReqStatistics)
1785 geoip_dirreq_stats_term();
1786 if (old_options && old_options->EntryStatistics &&
1787 !options->EntryStatistics)
1788 geoip_entry_stats_term();
1789 if (old_options && old_options->ExitPortStatistics &&
1790 !options->ExitPortStatistics)
1791 rep_hist_exit_stats_term();
1792 if (old_options && old_options->ConnDirectionStatistics &&
1793 !options->ConnDirectionStatistics)
1794 rep_hist_conn_stats_term();
1795 if (old_options && old_options->BridgeAuthoritativeDir &&
1796 !options->BridgeAuthoritativeDir)
1797 rep_hist_desc_stats_term();
1799 /* Check if we need to parse and add the EntryNodes config option. */
1800 if (options->EntryNodes &&
1801 (!old_options ||
1802 !routerset_equal(old_options->EntryNodes,options->EntryNodes) ||
1803 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes)))
1804 entry_nodes_should_be_added();
1806 /* Since our options changed, we might need to regenerate and upload our
1807 * server descriptor.
1809 if (!old_options ||
1810 options_transition_affects_descriptor(old_options, options))
1811 mark_my_descriptor_dirty("config change");
1813 /* We may need to reschedule some directory stuff if our status changed. */
1814 if (old_options) {
1815 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1816 dirvote_recalculate_timing(options, time(NULL));
1817 if (!bool_eq(directory_fetches_dir_info_early(options),
1818 directory_fetches_dir_info_early(old_options)) ||
1819 !bool_eq(directory_fetches_dir_info_later(options),
1820 directory_fetches_dir_info_later(old_options))) {
1821 /* Make sure update_router_have_min_dir_info gets called. */
1822 router_dir_info_changed();
1823 /* We might need to download a new consensus status later or sooner than
1824 * we had expected. */
1825 update_consensus_networkstatus_fetch_time(time(NULL));
1829 /* Load the webpage we're going to serve every time someone asks for '/' on
1830 our DirPort. */
1831 tor_free(global_dirfrontpagecontents);
1832 if (options->DirPortFrontPage) {
1833 global_dirfrontpagecontents =
1834 read_file_to_str(options->DirPortFrontPage, 0, NULL);
1835 if (!global_dirfrontpagecontents) {
1836 log_warn(LD_CONFIG,
1837 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1838 options->DirPortFrontPage);
1842 return 0;
1845 static const struct {
1846 const char *name;
1847 int takes_argument;
1848 } CMDLINE_ONLY_OPTIONS[] = {
1849 { "-f", 1 },
1850 { "--allow-missing-torrc", 0 },
1851 { "--defaults-torrc", 1 },
1852 { "--hash-password", 1 },
1853 { "--dump-config", 1 },
1854 { "--list-fingerprint", 0 },
1855 { "--verify-config", 0 },
1856 { "--ignore-missing-torrc", 0 },
1857 { "--quiet", 0 },
1858 { "--hush", 0 },
1859 { "--version", 0 },
1860 { "--library-versions", 0 },
1861 { "-h", 0 },
1862 { "--help", 0 },
1863 { "--list-torrc-options", 0 },
1864 { "--digests", 0 },
1865 { "--nt-service", 0 },
1866 { "-nt-service", 0 },
1867 { NULL, 0 },
1870 /** Helper: Read a list of configuration options from the command line. If
1871 * successful, or if ignore_errors is set, put them in *<b>result</b>, put the
1872 * commandline-only options in *<b>cmdline_result</b>, and return 0;
1873 * otherwise, return -1 and leave *<b>result</b> and <b>cmdline_result</b>
1874 * alone. */
1876 config_parse_commandline(int argc, char **argv, int ignore_errors,
1877 config_line_t **result,
1878 config_line_t **cmdline_result)
1880 config_line_t *param = NULL;
1882 config_line_t *front = NULL;
1883 config_line_t **new = &front;
1885 config_line_t *front_cmdline = NULL;
1886 config_line_t **new_cmdline = &front_cmdline;
1888 char *s, *arg;
1889 int i = 1;
1891 while (i < argc) {
1892 unsigned command = CONFIG_LINE_NORMAL;
1893 int want_arg = 1;
1894 int is_cmdline = 0;
1895 int j;
1897 for (j = 0; CMDLINE_ONLY_OPTIONS[j].name != NULL; ++j) {
1898 if (!strcmp(argv[i], CMDLINE_ONLY_OPTIONS[j].name)) {
1899 is_cmdline = 1;
1900 want_arg = CMDLINE_ONLY_OPTIONS[j].takes_argument;
1901 break;
1905 s = argv[i];
1907 /* Each keyword may be prefixed with one or two dashes. */
1908 if (*s == '-')
1909 s++;
1910 if (*s == '-')
1911 s++;
1912 /* Figure out the command, if any. */
1913 if (*s == '+') {
1914 s++;
1915 command = CONFIG_LINE_APPEND;
1916 } else if (*s == '/') {
1917 s++;
1918 command = CONFIG_LINE_CLEAR;
1919 /* A 'clear' command has no argument. */
1920 want_arg = 0;
1923 if (want_arg && i == argc-1) {
1924 if (ignore_errors) {
1925 arg = strdup("");
1926 } else {
1927 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1928 argv[i]);
1929 config_free_lines(front);
1930 config_free_lines(front_cmdline);
1931 return -1;
1933 } else {
1934 arg = want_arg ? tor_strdup(argv[i+1]) : strdup("");
1937 param = tor_malloc_zero(sizeof(config_line_t));
1938 param->key = is_cmdline ? tor_strdup(argv[i]) :
1939 tor_strdup(config_expand_abbrev(&options_format, s, 1, 1));
1940 param->value = arg;
1941 param->command = command;
1942 param->next = NULL;
1943 log_debug(LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
1944 param->key, param->value);
1946 if (is_cmdline) {
1947 *new_cmdline = param;
1948 new_cmdline = &((*new_cmdline)->next);
1949 } else {
1950 *new = param;
1951 new = &((*new)->next);
1954 i += want_arg ? 2 : 1;
1956 *cmdline_result = front_cmdline;
1957 *result = front;
1958 return 0;
1961 /** Return true iff key is a valid configuration option. */
1963 option_is_recognized(const char *key)
1965 const config_var_t *var = config_find_option(&options_format, key);
1966 return (var != NULL);
1969 /** Return the canonical name of a configuration option, or NULL
1970 * if no such option exists. */
1971 const char *
1972 option_get_canonical_name(const char *key)
1974 const config_var_t *var = config_find_option(&options_format, key);
1975 return var ? var->name : NULL;
1978 /** Return a canonical list of the options assigned for key.
1980 config_line_t *
1981 option_get_assignment(const or_options_t *options, const char *key)
1983 return config_get_assigned_option(&options_format, options, key, 1);
1986 /** Try assigning <b>list</b> to the global options. You do this by duping
1987 * options, assigning list to the new one, then validating it. If it's
1988 * ok, then throw out the old one and stick with the new one. Else,
1989 * revert to old and return failure. Return SETOPT_OK on success, or
1990 * a setopt_err_t on failure.
1992 * If not success, point *<b>msg</b> to a newly allocated string describing
1993 * what went wrong.
1995 setopt_err_t
1996 options_trial_assign(config_line_t *list, int use_defaults,
1997 int clear_first, char **msg)
1999 int r;
2000 or_options_t *trial_options = config_dup(&options_format, get_options());
2002 if ((r=config_assign(&options_format, trial_options,
2003 list, use_defaults, clear_first, msg)) < 0) {
2004 config_free(&options_format, trial_options);
2005 return r;
2008 if (options_validate(get_options_mutable(), trial_options,
2009 global_default_options, 1, msg) < 0) {
2010 config_free(&options_format, trial_options);
2011 return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2014 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2015 config_free(&options_format, trial_options);
2016 return SETOPT_ERR_TRANSITION;
2019 if (set_options(trial_options, msg)<0) {
2020 config_free(&options_format, trial_options);
2021 return SETOPT_ERR_SETTING;
2024 /* we liked it. put it in place. */
2025 return SETOPT_OK;
2028 /** Print a usage message for tor. */
2029 static void
2030 print_usage(void)
2032 printf(
2033 "Copyright (c) 2001-2004, Roger Dingledine\n"
2034 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2035 "Copyright (c) 2007-2013, The Tor Project, Inc.\n\n"
2036 "tor -f <torrc> [args]\n"
2037 "See man page for options, or https://www.torproject.org/ for "
2038 "documentation.\n");
2041 /** Print all non-obsolete torrc options. */
2042 static void
2043 list_torrc_options(void)
2045 int i;
2046 smartlist_t *lines = smartlist_new();
2047 for (i = 0; option_vars_[i].name; ++i) {
2048 const config_var_t *var = &option_vars_[i];
2049 if (var->type == CONFIG_TYPE_OBSOLETE ||
2050 var->type == CONFIG_TYPE_LINELIST_V)
2051 continue;
2052 printf("%s\n", var->name);
2054 smartlist_free(lines);
2057 /** Last value actually set by resolve_my_address. */
2058 static uint32_t last_resolved_addr = 0;
2060 /** Accessor for last_resolved_addr from outside this file. */
2061 uint32_t
2062 get_last_resolved_addr(void)
2064 return last_resolved_addr;
2068 * Use <b>options-\>Address</b> to guess our public IP address.
2070 * Return 0 if all is well, or -1 if we can't find a suitable
2071 * public IP address.
2073 * If we are returning 0:
2074 * - Put our public IP address (in host order) into *<b>addr_out</b>.
2075 * - If <b>method_out</b> is non-NULL, set *<b>method_out</b> to a static
2076 * string describing how we arrived at our answer.
2077 * - If <b>hostname_out</b> is non-NULL, and we resolved a hostname to
2078 * get our address, set *<b>hostname_out</b> to a newly allocated string
2079 * holding that hostname. (If we didn't get our address by resolving a
2080 * hostname, set *<b>hostname_out</b> to NULL.)
2082 * XXXX ipv6
2085 resolve_my_address(int warn_severity, const or_options_t *options,
2086 uint32_t *addr_out,
2087 const char **method_out, char **hostname_out)
2089 struct in_addr in;
2090 uint32_t addr; /* host order */
2091 char hostname[256];
2092 const char *method_used;
2093 const char *hostname_used;
2094 int explicit_ip=1;
2095 int explicit_hostname=1;
2096 int from_interface=0;
2097 char *addr_string = NULL;
2098 const char *address = options->Address;
2099 int notice_severity = warn_severity <= LOG_NOTICE ?
2100 LOG_NOTICE : warn_severity;
2102 tor_addr_t myaddr;
2103 tor_assert(addr_out);
2106 * Step one: Fill in 'hostname' to be our best guess.
2109 if (address && *address) {
2110 strlcpy(hostname, address, sizeof(hostname));
2111 } else { /* then we need to guess our address */
2112 explicit_ip = 0; /* it's implicit */
2113 explicit_hostname = 0; /* it's implicit */
2115 if (gethostname(hostname, sizeof(hostname)) < 0) {
2116 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2117 return -1;
2119 log_debug(LD_CONFIG, "Guessed local host name as '%s'", hostname);
2123 * Step two: Now that we know 'hostname', parse it or resolve it. If
2124 * it doesn't parse or resolve, look at the interface address. Set 'addr'
2125 * to be our (host-order) 32-bit answer.
2128 if (tor_inet_aton(hostname, &in) == 0) {
2129 /* then we have to resolve it */
2130 explicit_ip = 0;
2131 if (tor_lookup_hostname(hostname, &addr)) { /* failed to resolve */
2132 uint32_t interface_ip; /* host order */
2134 if (explicit_hostname) {
2135 log_fn(warn_severity, LD_CONFIG,
2136 "Could not resolve local Address '%s'. Failing.", hostname);
2137 return -1;
2139 log_fn(notice_severity, LD_CONFIG,
2140 "Could not resolve guessed local hostname '%s'. "
2141 "Trying something else.", hostname);
2142 if (get_interface_address(warn_severity, &interface_ip)) {
2143 log_fn(warn_severity, LD_CONFIG,
2144 "Could not get local interface IP address. Failing.");
2145 return -1;
2147 from_interface = 1;
2148 addr = interface_ip;
2149 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2150 "local interface. Using that.", fmt_addr32(addr));
2151 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2152 } else { /* resolved hostname into addr */
2153 tor_addr_from_ipv4h(&myaddr, addr);
2155 if (!explicit_hostname &&
2156 tor_addr_is_internal(&myaddr, 0)) {
2157 tor_addr_t interface_ip;
2159 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2160 "resolves to a private IP address (%s). Trying something "
2161 "else.", hostname, fmt_addr32(addr));
2163 if (get_interface_address6(warn_severity, AF_INET, &interface_ip)<0) {
2164 log_fn(warn_severity, LD_CONFIG,
2165 "Could not get local interface IP address. Too bad.");
2166 } else if (tor_addr_is_internal(&interface_ip, 0)) {
2167 log_fn(notice_severity, LD_CONFIG,
2168 "Interface IP address '%s' is a private address too. "
2169 "Ignoring.", fmt_addr(&interface_ip));
2170 } else {
2171 from_interface = 1;
2172 addr = tor_addr_to_ipv4h(&interface_ip);
2173 log_fn(notice_severity, LD_CONFIG,
2174 "Learned IP address '%s' for local interface."
2175 " Using that.", fmt_addr32(addr));
2176 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2180 } else {
2181 addr = ntohl(in.s_addr); /* set addr so that addr_string is not
2182 * illformed */
2186 * Step three: Check whether 'addr' is an internal IP address, and error
2187 * out if it is and we don't want that.
2190 tor_addr_from_ipv4h(&myaddr,addr);
2192 addr_string = tor_dup_ip(addr);
2193 if (tor_addr_is_internal(&myaddr, 0)) {
2194 /* make sure we're ok with publishing an internal IP */
2195 if (!options->DirAuthorities && !options->AlternateDirAuthority) {
2196 /* if they are using the default authorities, disallow internal IPs
2197 * always. */
2198 log_fn(warn_severity, LD_CONFIG,
2199 "Address '%s' resolves to private IP address '%s'. "
2200 "Tor servers that use the default DirAuthorities must have "
2201 "public IP addresses.", hostname, addr_string);
2202 tor_free(addr_string);
2203 return -1;
2205 if (!explicit_ip) {
2206 /* even if they've set their own authorities, require an explicit IP if
2207 * they're using an internal address. */
2208 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2209 "IP address '%s'. Please set the Address config option to be "
2210 "the IP address you want to use.", hostname, addr_string);
2211 tor_free(addr_string);
2212 return -1;
2217 * Step four: We have a winner! 'addr' is our answer for sure, and
2218 * 'addr_string' is its string form. Fill out the various fields to
2219 * say how we decided it.
2222 log_debug(LD_CONFIG, "Resolved Address to '%s'.", addr_string);
2224 if (explicit_ip) {
2225 method_used = "CONFIGURED";
2226 hostname_used = NULL;
2227 } else if (explicit_hostname) {
2228 method_used = "RESOLVED";
2229 hostname_used = hostname;
2230 } else if (from_interface) {
2231 method_used = "INTERFACE";
2232 hostname_used = NULL;
2233 } else {
2234 method_used = "GETHOSTNAME";
2235 hostname_used = hostname;
2238 *addr_out = addr;
2239 if (method_out)
2240 *method_out = method_used;
2241 if (hostname_out)
2242 *hostname_out = hostname_used ? tor_strdup(hostname_used) : NULL;
2245 * Step five: Check if the answer has changed since last time (or if
2246 * there was no last time), and if so call various functions to keep
2247 * us up-to-date.
2250 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2251 /* Leave this as a notice, regardless of the requested severity,
2252 * at least until dynamic IP address support becomes bulletproof. */
2253 log_notice(LD_NET,
2254 "Your IP address seems to have changed to %s "
2255 "(METHOD=%s%s%s). Updating.",
2256 addr_string, method_used,
2257 hostname_used ? " HOSTNAME=" : "",
2258 hostname_used ? hostname_used : "");
2259 ip_address_changed(0);
2262 if (last_resolved_addr != *addr_out) {
2263 control_event_server_status(LOG_NOTICE,
2264 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s%s%s",
2265 addr_string, method_used,
2266 hostname_used ? " HOSTNAME=" : "",
2267 hostname_used ? hostname_used : "");
2269 last_resolved_addr = *addr_out;
2272 * And finally, clean up and return success.
2275 tor_free(addr_string);
2276 return 0;
2279 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2280 * on a private network.
2283 is_local_addr(const tor_addr_t *addr)
2285 if (tor_addr_is_internal(addr, 0))
2286 return 1;
2287 /* Check whether ip is on the same /24 as we are. */
2288 if (get_options()->EnforceDistinctSubnets == 0)
2289 return 0;
2290 if (tor_addr_family(addr) == AF_INET) {
2291 /*XXXX023 IP6 what corresponds to an /24? */
2292 uint32_t ip = tor_addr_to_ipv4h(addr);
2294 /* It's possible that this next check will hit before the first time
2295 * resolve_my_address actually succeeds. (For clients, it is likely that
2296 * resolve_my_address will never be called at all). In those cases,
2297 * last_resolved_addr will be 0, and so checking to see whether ip is on
2298 * the same /24 as last_resolved_addr will be the same as checking whether
2299 * it was on net 0, which is already done by tor_addr_is_internal.
2301 if ((last_resolved_addr & (uint32_t)0xffffff00ul)
2302 == (ip & (uint32_t)0xffffff00ul))
2303 return 1;
2305 return 0;
2308 /** Return a new empty or_options_t. Used for testing. */
2309 or_options_t *
2310 options_new(void)
2312 return config_new(&options_format);
2315 /** Set <b>options</b> to hold reasonable defaults for most options.
2316 * Each option defaults to zero. */
2317 void
2318 options_init(or_options_t *options)
2320 config_init(&options_format, options);
2323 /** Return a string containing a possible configuration file that would give
2324 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2325 * include options that are the same as Tor's defaults.
2327 char *
2328 options_dump(const or_options_t *options, int how_to_dump)
2330 const or_options_t *use_defaults;
2331 int minimal;
2332 switch (how_to_dump) {
2333 case OPTIONS_DUMP_MINIMAL:
2334 use_defaults = global_default_options;
2335 minimal = 1;
2336 break;
2337 case OPTIONS_DUMP_DEFAULTS:
2338 use_defaults = NULL;
2339 minimal = 1;
2340 break;
2341 case OPTIONS_DUMP_ALL:
2342 use_defaults = NULL;
2343 minimal = 0;
2344 break;
2345 default:
2346 log_warn(LD_BUG, "Bogus value for how_to_dump==%d", how_to_dump);
2347 return NULL;
2350 return config_dump(&options_format, use_defaults, options, minimal, 0);
2353 /** Return 0 if every element of sl is a string holding a decimal
2354 * representation of a port number, or if sl is NULL.
2355 * Otherwise set *msg and return -1. */
2356 static int
2357 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2359 int i;
2360 tor_assert(name);
2362 if (!sl)
2363 return 0;
2365 SMARTLIST_FOREACH(sl, const char *, cp,
2367 i = atoi(cp);
2368 if (i < 1 || i > 65535) {
2369 tor_asprintf(msg, "Port '%s' out of range in %s", cp, name);
2370 return -1;
2373 return 0;
2376 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2377 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2378 * Else return 0.
2380 static int
2381 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2383 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2384 /* This handles an understandable special case where somebody says "2gb"
2385 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2386 --*value;
2388 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2389 tor_asprintf(msg, "%s ("U64_FORMAT") must be at most %d",
2390 desc, U64_PRINTF_ARG(*value),
2391 ROUTER_MAX_DECLARED_BANDWIDTH);
2392 return -1;
2394 return 0;
2397 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2398 * and write it to <b>options</b>-\>PublishServerDescriptor_. Treat "1"
2399 * as "v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2400 * Treat "0" as "".
2401 * Return 0 on success or -1 if not a recognized authority type (in which
2402 * case the value of PublishServerDescriptor_ is undefined). */
2403 static int
2404 compute_publishserverdescriptor(or_options_t *options)
2406 smartlist_t *list = options->PublishServerDescriptor;
2407 dirinfo_type_t *auth = &options->PublishServerDescriptor_;
2408 *auth = NO_DIRINFO;
2409 if (!list) /* empty list, answer is none */
2410 return 0;
2411 SMARTLIST_FOREACH_BEGIN(list, const char *, string) {
2412 if (!strcasecmp(string, "v1"))
2413 log_warn(LD_CONFIG, "PublishServerDescriptor v1 has no effect, because "
2414 "there are no v1 directory authorities anymore.");
2415 else if (!strcmp(string, "1"))
2416 if (options->BridgeRelay)
2417 *auth |= BRIDGE_DIRINFO;
2418 else
2419 *auth |= V3_DIRINFO;
2420 else if (!strcasecmp(string, "v2"))
2421 log_warn(LD_CONFIG, "PublishServerDescriptor v2 has no effect, because "
2422 "there are no v2 directory authorities anymore.");
2423 else if (!strcasecmp(string, "v3"))
2424 *auth |= V3_DIRINFO;
2425 else if (!strcasecmp(string, "bridge"))
2426 *auth |= BRIDGE_DIRINFO;
2427 else if (!strcasecmp(string, "hidserv"))
2428 log_warn(LD_CONFIG,
2429 "PublishServerDescriptor hidserv is invalid. See "
2430 "PublishHidServDescriptors.");
2431 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2432 /* no authority */;
2433 else
2434 return -1;
2435 } SMARTLIST_FOREACH_END(string);
2436 return 0;
2439 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2440 * services can overload the directory system. */
2441 #define MIN_REND_POST_PERIOD (10*60)
2443 /** Higest allowable value for PredictedPortsRelevanceTime; if this is
2444 * too high, our selection of exits will decrease for an extended
2445 * period of time to an uncomfortable level .*/
2446 #define MAX_PREDICTED_CIRCS_RELEVANCE (60*60)
2448 /** Highest allowable value for RendPostPeriod. */
2449 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2451 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2452 * will generate too many circuits and potentially overload the network. */
2453 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2455 /** Highest allowable value for MaxCircuitDirtiness: prevents time_t
2456 * overflows. */
2457 #define MAX_MAX_CIRCUIT_DIRTINESS (30*24*60*60)
2459 /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
2460 * will generate too many circuits and potentially overload the network. */
2461 #define MIN_CIRCUIT_STREAM_TIMEOUT 10
2463 /** Lowest allowable value for HeartbeatPeriod; if this is too low, we might
2464 * expose more information than we're comfortable with. */
2465 #define MIN_HEARTBEAT_PERIOD (30*60)
2467 /** Lowest recommended value for CircuitBuildTimeout; if it is set too low
2468 * and LearnCircuitBuildTimeout is off, the failure rate for circuit
2469 * construction may be very high. In that case, if it is set below this
2470 * threshold emit a warning.
2471 * */
2472 #define RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT (10)
2474 static int
2475 options_validate_cb(void *old_options, void *options, void *default_options,
2476 int from_setconf, char **msg)
2478 return options_validate(old_options, options, default_options,
2479 from_setconf, msg);
2482 /** Return 0 if every setting in <b>options</b> is reasonable, is a
2483 * permissible transition from <b>old_options</b>, and none of the
2484 * testing-only settings differ from <b>default_options</b> unless in
2485 * testing mode. Else return -1. Should have no side effects, except for
2486 * normalizing the contents of <b>options</b>.
2488 * On error, tor_strdup an error explanation into *<b>msg</b>.
2490 * XXX
2491 * If <b>from_setconf</b>, we were called by the controller, and our
2492 * Log line should stay empty. If it's 0, then give us a default log
2493 * if there are no logs defined.
2495 STATIC int
2496 options_validate(or_options_t *old_options, or_options_t *options,
2497 or_options_t *default_options, int from_setconf, char **msg)
2499 int i;
2500 config_line_t *cl;
2501 const char *uname = get_uname();
2502 int n_ports=0;
2503 #define REJECT(arg) \
2504 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2505 #define COMPLAIN(arg) STMT_BEGIN log_warn(LD_CONFIG, arg); STMT_END
2507 tor_assert(msg);
2508 *msg = NULL;
2510 if (server_mode(options) &&
2511 (!strcmpstart(uname, "Windows 95") ||
2512 !strcmpstart(uname, "Windows 98") ||
2513 !strcmpstart(uname, "Windows Me"))) {
2514 log_warn(LD_CONFIG, "Tor is running as a server, but you are "
2515 "running %s; this probably won't work. See "
2516 "https://www.torproject.org/docs/faq.html#BestOSForRelay "
2517 "for details.", uname);
2520 if (parse_ports(options, 1, msg, &n_ports) < 0)
2521 return -1;
2523 if (parse_outbound_addresses(options, 1, msg) < 0)
2524 return -1;
2526 if (validate_data_directory(options)<0)
2527 REJECT("Invalid DataDirectory");
2529 if (options->Nickname == NULL) {
2530 if (server_mode(options)) {
2531 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
2533 } else {
2534 if (!is_legal_nickname(options->Nickname)) {
2535 tor_asprintf(msg,
2536 "Nickname '%s' is wrong length or contains illegal characters.",
2537 options->Nickname);
2538 return -1;
2542 if (server_mode(options) && !options->ContactInfo)
2543 log_notice(LD_CONFIG, "Your ContactInfo config option is not set. "
2544 "Please consider setting it, so we can contact you if your server is "
2545 "misconfigured or something else goes wrong.");
2547 /* Special case on first boot if no Log options are given. */
2548 if (!options->Logs && !options->RunAsDaemon && !from_setconf) {
2549 if (quiet_level == 0)
2550 config_line_append(&options->Logs, "Log", "notice stdout");
2551 else if (quiet_level == 1)
2552 config_line_append(&options->Logs, "Log", "warn stdout");
2555 /* Validate the tor_log(s) */
2556 if (options_init_logs(old_options, options, 1)<0)
2557 REJECT("Failed to validate Log options. See logs for details.");
2559 if (authdir_mode(options)) {
2560 /* confirm that our address isn't broken, so we can complain now */
2561 uint32_t tmp;
2562 if (resolve_my_address(LOG_WARN, options, &tmp, NULL, NULL) < 0)
2563 REJECT("Failed to resolve/guess local address. See logs for details.");
2566 #ifndef _WIN32
2567 if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
2568 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
2569 #endif
2571 if (server_mode(options) && options->RendConfigLines)
2572 log_warn(LD_CONFIG,
2573 "Tor is currently configured as a relay and a hidden service. "
2574 "That's not very secure: you should probably run your hidden service "
2575 "in a separate Tor process, at least -- see "
2576 "https://trac.torproject.org/8742");
2578 /* XXXX require that the only port not be DirPort? */
2579 /* XXXX require that at least one port be listened-upon. */
2580 if (n_ports == 0 && !options->RendConfigLines)
2581 log_warn(LD_CONFIG,
2582 "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
2583 "undefined, and there aren't any hidden services configured. "
2584 "Tor will still run, but probably won't do anything.");
2586 options->TransProxyType_parsed = TPT_DEFAULT;
2587 #ifdef USE_TRANSPARENT
2588 if (options->TransProxyType) {
2589 if (!strcasecmp(options->TransProxyType, "default")) {
2590 options->TransProxyType_parsed = TPT_DEFAULT;
2591 } else if (!strcasecmp(options->TransProxyType, "pf-divert")) {
2592 #ifndef __OpenBSD__
2593 REJECT("pf-divert is a OpenBSD-specific feature.");
2594 #else
2595 options->TransProxyType_parsed = TPT_PF_DIVERT;
2596 #endif
2597 } else if (!strcasecmp(options->TransProxyType, "tproxy")) {
2598 #ifndef __linux__
2599 REJECT("TPROXY is a Linux-specific feature.");
2600 #else
2601 options->TransProxyType_parsed = TPT_TPROXY;
2602 #endif
2603 } else if (!strcasecmp(options->TransProxyType, "ipfw")) {
2604 #ifndef __FreeBSD__
2605 REJECT("ipfw is a FreeBSD-specific feature.");
2606 #else
2607 options->TransProxyType_parsed = TPT_IPFW;
2608 #endif
2609 } else {
2610 REJECT("Unrecognized value for TransProxyType");
2613 if (strcasecmp(options->TransProxyType, "default") &&
2614 !options->TransPort_set) {
2615 REJECT("Cannot use TransProxyType without any valid TransPort or "
2616 "TransListenAddress.");
2619 #else
2620 if (options->TransPort_set)
2621 REJECT("TransPort and TransListenAddress are disabled "
2622 "in this build.");
2623 #endif
2625 if (options->TokenBucketRefillInterval <= 0
2626 || options->TokenBucketRefillInterval > 1000) {
2627 REJECT("TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
2630 if (options->ExcludeExitNodes || options->ExcludeNodes) {
2631 options->ExcludeExitNodesUnion_ = routerset_new();
2632 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeExitNodes);
2633 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeNodes);
2636 if (options->NodeFamilies) {
2637 options->NodeFamilySets = smartlist_new();
2638 for (cl = options->NodeFamilies; cl; cl = cl->next) {
2639 routerset_t *rs = routerset_new();
2640 if (routerset_parse(rs, cl->value, cl->key) == 0) {
2641 smartlist_add(options->NodeFamilySets, rs);
2642 } else {
2643 routerset_free(rs);
2648 if (options->TLSECGroup && (strcasecmp(options->TLSECGroup, "P256") &&
2649 strcasecmp(options->TLSECGroup, "P224"))) {
2650 COMPLAIN("Unrecognized TLSECGroup: Falling back to the default.");
2651 tor_free(options->TLSECGroup);
2654 if (options->ExcludeNodes && options->StrictNodes) {
2655 COMPLAIN("You have asked to exclude certain relays from all positions "
2656 "in your circuits. Expect hidden services and other Tor "
2657 "features to be broken in unpredictable ways.");
2660 if (options->AuthoritativeDir) {
2661 if (!options->ContactInfo && !options->TestingTorNetwork)
2662 REJECT("Authoritative directory servers must set ContactInfo");
2663 if (!options->RecommendedClientVersions)
2664 options->RecommendedClientVersions =
2665 config_lines_dup(options->RecommendedVersions);
2666 if (!options->RecommendedServerVersions)
2667 options->RecommendedServerVersions =
2668 config_lines_dup(options->RecommendedVersions);
2669 if (options->VersioningAuthoritativeDir &&
2670 (!options->RecommendedClientVersions ||
2671 !options->RecommendedServerVersions))
2672 REJECT("Versioning authoritative dir servers must set "
2673 "Recommended*Versions.");
2674 if (options->UseEntryGuards) {
2675 log_info(LD_CONFIG, "Authoritative directory servers can't set "
2676 "UseEntryGuards. Disabling.");
2677 options->UseEntryGuards = 0;
2679 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
2680 log_info(LD_CONFIG, "Authoritative directories always try to download "
2681 "extra-info documents. Setting DownloadExtraInfo.");
2682 options->DownloadExtraInfo = 1;
2684 if (!(options->BridgeAuthoritativeDir ||
2685 options->V3AuthoritativeDir))
2686 REJECT("AuthoritativeDir is set, but none of "
2687 "(Bridge/V3)AuthoritativeDir is set.");
2688 /* If we have a v3bandwidthsfile and it's broken, complain on startup */
2689 if (options->V3BandwidthsFile && !old_options) {
2690 dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
2694 if (options->AuthoritativeDir && !options->DirPort_set)
2695 REJECT("Running as authoritative directory, but no DirPort set.");
2697 if (options->AuthoritativeDir && !options->ORPort_set)
2698 REJECT("Running as authoritative directory, but no ORPort set.");
2700 if (options->AuthoritativeDir && options->ClientOnly)
2701 REJECT("Running as authoritative directory, but ClientOnly also set.");
2703 if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
2704 REJECT("FetchDirInfoExtraEarly requires that you also set "
2705 "FetchDirInfoEarly");
2707 if (options->ConnLimit <= 0) {
2708 tor_asprintf(msg,
2709 "ConnLimit must be greater than 0, but was set to %d",
2710 options->ConnLimit);
2711 return -1;
2714 if (options->PathsNeededToBuildCircuits >= 0.0) {
2715 if (options->PathsNeededToBuildCircuits < 0.25) {
2716 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too low. Increasing "
2717 "to 0.25");
2718 options->PathsNeededToBuildCircuits = 0.25;
2719 } else if (options->PathsNeededToBuildCircuits > 0.95) {
2720 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too high. Decreasing "
2721 "to 0.95");
2722 options->PathsNeededToBuildCircuits = 0.95;
2726 if (options->MaxClientCircuitsPending <= 0 ||
2727 options->MaxClientCircuitsPending > MAX_MAX_CLIENT_CIRCUITS_PENDING) {
2728 tor_asprintf(msg,
2729 "MaxClientCircuitsPending must be between 1 and %d, but "
2730 "was set to %d", MAX_MAX_CLIENT_CIRCUITS_PENDING,
2731 options->MaxClientCircuitsPending);
2732 return -1;
2735 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
2736 return -1;
2738 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
2739 return -1;
2741 if (validate_ports_csv(options->RejectPlaintextPorts,
2742 "RejectPlaintextPorts", msg) < 0)
2743 return -1;
2745 if (validate_ports_csv(options->WarnPlaintextPorts,
2746 "WarnPlaintextPorts", msg) < 0)
2747 return -1;
2749 if (options->FascistFirewall && !options->ReachableAddresses) {
2750 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
2751 /* We already have firewall ports set, so migrate them to
2752 * ReachableAddresses, which will set ReachableORAddresses and
2753 * ReachableDirAddresses if they aren't set explicitly. */
2754 smartlist_t *instead = smartlist_new();
2755 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
2756 new_line->key = tor_strdup("ReachableAddresses");
2757 /* If we're configured with the old format, we need to prepend some
2758 * open ports. */
2759 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
2761 int p = atoi(portno);
2762 if (p<0) continue;
2763 smartlist_add_asprintf(instead, "*:%d", p);
2765 new_line->value = smartlist_join_strings(instead,",",0,NULL);
2766 /* These have been deprecated since 0.1.1.5-alpha-cvs */
2767 log_notice(LD_CONFIG,
2768 "Converting FascistFirewall and FirewallPorts "
2769 "config options to new format: \"ReachableAddresses %s\"",
2770 new_line->value);
2771 options->ReachableAddresses = new_line;
2772 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
2773 smartlist_free(instead);
2774 } else {
2775 /* We do not have FirewallPorts set, so add 80 to
2776 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
2777 if (!options->ReachableDirAddresses) {
2778 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
2779 new_line->key = tor_strdup("ReachableDirAddresses");
2780 new_line->value = tor_strdup("*:80");
2781 options->ReachableDirAddresses = new_line;
2782 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
2783 "to new format: \"ReachableDirAddresses *:80\"");
2785 if (!options->ReachableORAddresses) {
2786 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
2787 new_line->key = tor_strdup("ReachableORAddresses");
2788 new_line->value = tor_strdup("*:443");
2789 options->ReachableORAddresses = new_line;
2790 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
2791 "to new format: \"ReachableORAddresses *:443\"");
2796 for (i=0; i<3; i++) {
2797 config_line_t **linep =
2798 (i==0) ? &options->ReachableAddresses :
2799 (i==1) ? &options->ReachableORAddresses :
2800 &options->ReachableDirAddresses;
2801 if (!*linep)
2802 continue;
2803 /* We need to end with a reject *:*, not an implicit accept *:* */
2804 for (;;) {
2805 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
2806 break;
2807 linep = &((*linep)->next);
2808 if (!*linep) {
2809 *linep = tor_malloc_zero(sizeof(config_line_t));
2810 (*linep)->key = tor_strdup(
2811 (i==0) ? "ReachableAddresses" :
2812 (i==1) ? "ReachableORAddresses" :
2813 "ReachableDirAddresses");
2814 (*linep)->value = tor_strdup("reject *:*");
2815 break;
2820 if ((options->ReachableAddresses ||
2821 options->ReachableORAddresses ||
2822 options->ReachableDirAddresses) &&
2823 server_mode(options))
2824 REJECT("Servers must be able to freely connect to the rest "
2825 "of the Internet, so they must not set Reachable*Addresses "
2826 "or FascistFirewall.");
2828 if (options->UseBridges &&
2829 server_mode(options))
2830 REJECT("Servers must be able to freely connect to the rest "
2831 "of the Internet, so they must not set UseBridges.");
2833 /* If both of these are set, we'll end up with funny behavior where we
2834 * demand enough entrynodes be up and running else we won't build
2835 * circuits, yet we never actually use them. */
2836 if (options->UseBridges && options->EntryNodes)
2837 REJECT("You cannot set both UseBridges and EntryNodes.");
2839 if (options->EntryNodes && !options->UseEntryGuards) {
2840 REJECT("If EntryNodes is set, UseEntryGuards must be enabled.");
2843 options->MaxMemInQueues =
2844 compute_real_max_mem_in_queues(options->MaxMemInQueues_raw,
2845 server_mode(options));
2847 options->AllowInvalid_ = 0;
2849 if (options->AllowInvalidNodes) {
2850 SMARTLIST_FOREACH_BEGIN(options->AllowInvalidNodes, const char *, cp) {
2851 if (!strcasecmp(cp, "entry"))
2852 options->AllowInvalid_ |= ALLOW_INVALID_ENTRY;
2853 else if (!strcasecmp(cp, "exit"))
2854 options->AllowInvalid_ |= ALLOW_INVALID_EXIT;
2855 else if (!strcasecmp(cp, "middle"))
2856 options->AllowInvalid_ |= ALLOW_INVALID_MIDDLE;
2857 else if (!strcasecmp(cp, "introduction"))
2858 options->AllowInvalid_ |= ALLOW_INVALID_INTRODUCTION;
2859 else if (!strcasecmp(cp, "rendezvous"))
2860 options->AllowInvalid_ |= ALLOW_INVALID_RENDEZVOUS;
2861 else {
2862 tor_asprintf(msg,
2863 "Unrecognized value '%s' in AllowInvalidNodes", cp);
2864 return -1;
2866 } SMARTLIST_FOREACH_END(cp);
2869 if (!options->SafeLogging ||
2870 !strcasecmp(options->SafeLogging, "0")) {
2871 options->SafeLogging_ = SAFELOG_SCRUB_NONE;
2872 } else if (!strcasecmp(options->SafeLogging, "relay")) {
2873 options->SafeLogging_ = SAFELOG_SCRUB_RELAY;
2874 } else if (!strcasecmp(options->SafeLogging, "1")) {
2875 options->SafeLogging_ = SAFELOG_SCRUB_ALL;
2876 } else {
2877 tor_asprintf(msg,
2878 "Unrecognized value '%s' in SafeLogging",
2879 escaped(options->SafeLogging));
2880 return -1;
2883 if (compute_publishserverdescriptor(options) < 0) {
2884 tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
2885 return -1;
2888 if ((options->BridgeRelay
2889 || options->PublishServerDescriptor_ & BRIDGE_DIRINFO)
2890 && (options->PublishServerDescriptor_ & V3_DIRINFO)) {
2891 REJECT("Bridges are not supposed to publish router descriptors to the "
2892 "directory authorities. Please correct your "
2893 "PublishServerDescriptor line.");
2896 if (options->BridgeRelay && options->DirPort_set) {
2897 log_warn(LD_CONFIG, "Can't set a DirPort on a bridge relay; disabling "
2898 "DirPort");
2899 config_free_lines(options->DirPort_lines);
2900 options->DirPort_lines = NULL;
2901 options->DirPort_set = 0;
2904 if (options->MinUptimeHidServDirectoryV2 < 0) {
2905 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
2906 "least 0 seconds. Changing to 0.");
2907 options->MinUptimeHidServDirectoryV2 = 0;
2910 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
2911 log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
2912 "raising to %d seconds.", MIN_REND_POST_PERIOD);
2913 options->RendPostPeriod = MIN_REND_POST_PERIOD;
2916 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
2917 log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
2918 MAX_DIR_PERIOD);
2919 options->RendPostPeriod = MAX_DIR_PERIOD;
2922 if (options->PredictedPortsRelevanceTime >
2923 MAX_PREDICTED_CIRCS_RELEVANCE) {
2924 log_warn(LD_CONFIG, "PredictedPortsRelevanceTime is too large; "
2925 "clipping to %ds.", MAX_PREDICTED_CIRCS_RELEVANCE);
2926 options->PredictedPortsRelevanceTime = MAX_PREDICTED_CIRCS_RELEVANCE;
2929 if (options->Tor2webMode && options->LearnCircuitBuildTimeout) {
2930 /* LearnCircuitBuildTimeout and Tor2webMode are incompatible in
2931 * two ways:
2933 * - LearnCircuitBuildTimeout results in a low CBT, which
2934 * Tor2webMode's use of one-hop rendezvous circuits lowers
2935 * much further, producing *far* too many timeouts.
2937 * - The adaptive CBT code does not update its timeout estimate
2938 * using build times for single-hop circuits.
2940 * If we fix both of these issues someday, we should test
2941 * Tor2webMode with LearnCircuitBuildTimeout on again. */
2942 log_notice(LD_CONFIG,"Tor2webMode is enabled; turning "
2943 "LearnCircuitBuildTimeout off.");
2944 options->LearnCircuitBuildTimeout = 0;
2947 if (options->Tor2webMode && options->UseEntryGuards) {
2948 /* tor2web mode clients do not (and should not) use entry guards
2949 * in any meaningful way. Further, tor2web mode causes the hidden
2950 * service client code to do things which break the path bias
2951 * detector, and it's far easier to turn off entry guards (and
2952 * thus the path bias detector with it) than to figure out how to
2953 * make a piece of code which cannot possibly help tor2web mode
2954 * users compatible with tor2web mode.
2956 log_notice(LD_CONFIG,
2957 "Tor2WebMode is enabled; disabling UseEntryGuards.");
2958 options->UseEntryGuards = 0;
2961 if (!(options->UseEntryGuards) &&
2962 (options->RendConfigLines != NULL)) {
2963 log_warn(LD_CONFIG,
2964 "UseEntryGuards is disabled, but you have configured one or more "
2965 "hidden services on this Tor instance. Your hidden services "
2966 "will be very easy to locate using a well-known attack -- see "
2967 "http://freehaven.net/anonbib/#hs-attack06 for details.");
2970 if (!options->LearnCircuitBuildTimeout && options->CircuitBuildTimeout &&
2971 options->CircuitBuildTimeout < RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT) {
2972 log_warn(LD_CONFIG,
2973 "CircuitBuildTimeout is shorter (%d seconds) than the recommended "
2974 "minimum (%d seconds), and LearnCircuitBuildTimeout is disabled. "
2975 "If tor isn't working, raise this value or enable "
2976 "LearnCircuitBuildTimeout.",
2977 options->CircuitBuildTimeout,
2978 RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT );
2979 } else if (!options->LearnCircuitBuildTimeout &&
2980 !options->CircuitBuildTimeout) {
2981 log_notice(LD_CONFIG, "You disabled LearnCircuitBuildTimeout, but didn't "
2982 "a CircuitBuildTimeout. I'll pick a plausible default.");
2985 if (options->PathBiasNoticeRate > 1.0) {
2986 tor_asprintf(msg,
2987 "PathBiasNoticeRate is too high. "
2988 "It must be between 0 and 1.0");
2989 return -1;
2991 if (options->PathBiasWarnRate > 1.0) {
2992 tor_asprintf(msg,
2993 "PathBiasWarnRate is too high. "
2994 "It must be between 0 and 1.0");
2995 return -1;
2997 if (options->PathBiasExtremeRate > 1.0) {
2998 tor_asprintf(msg,
2999 "PathBiasExtremeRate is too high. "
3000 "It must be between 0 and 1.0");
3001 return -1;
3003 if (options->PathBiasNoticeUseRate > 1.0) {
3004 tor_asprintf(msg,
3005 "PathBiasNoticeUseRate is too high. "
3006 "It must be between 0 and 1.0");
3007 return -1;
3009 if (options->PathBiasExtremeUseRate > 1.0) {
3010 tor_asprintf(msg,
3011 "PathBiasExtremeUseRate is too high. "
3012 "It must be between 0 and 1.0");
3013 return -1;
3016 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3017 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3018 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3019 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3022 if (options->MaxCircuitDirtiness > MAX_MAX_CIRCUIT_DIRTINESS) {
3023 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too high; "
3024 "setting to %d days.", MAX_MAX_CIRCUIT_DIRTINESS/86400);
3025 options->MaxCircuitDirtiness = MAX_MAX_CIRCUIT_DIRTINESS;
3028 if (options->CircuitStreamTimeout &&
3029 options->CircuitStreamTimeout < MIN_CIRCUIT_STREAM_TIMEOUT) {
3030 log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
3031 "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
3032 options->CircuitStreamTimeout = MIN_CIRCUIT_STREAM_TIMEOUT;
3035 if (options->HeartbeatPeriod &&
3036 options->HeartbeatPeriod < MIN_HEARTBEAT_PERIOD) {
3037 log_warn(LD_CONFIG, "HeartbeatPeriod option is too short; "
3038 "raising to %d seconds.", MIN_HEARTBEAT_PERIOD);
3039 options->HeartbeatPeriod = MIN_HEARTBEAT_PERIOD;
3042 if (options->KeepalivePeriod < 1)
3043 REJECT("KeepalivePeriod option must be positive.");
3045 if (options->PortForwarding && options->Sandbox) {
3046 REJECT("PortForwarding is not compatible with Sandbox; at most one can "
3047 "be set");
3050 if (ensure_bandwidth_cap(&options->BandwidthRate,
3051 "BandwidthRate", msg) < 0)
3052 return -1;
3053 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3054 "BandwidthBurst", msg) < 0)
3055 return -1;
3056 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3057 "MaxAdvertisedBandwidth", msg) < 0)
3058 return -1;
3059 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3060 "RelayBandwidthRate", msg) < 0)
3061 return -1;
3062 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3063 "RelayBandwidthBurst", msg) < 0)
3064 return -1;
3065 if (ensure_bandwidth_cap(&options->PerConnBWRate,
3066 "PerConnBWRate", msg) < 0)
3067 return -1;
3068 if (ensure_bandwidth_cap(&options->PerConnBWBurst,
3069 "PerConnBWBurst", msg) < 0)
3070 return -1;
3071 if (ensure_bandwidth_cap(&options->AuthDirFastGuarantee,
3072 "AuthDirFastGuarantee", msg) < 0)
3073 return -1;
3074 if (ensure_bandwidth_cap(&options->AuthDirGuardBWGuarantee,
3075 "AuthDirGuardBWGuarantee", msg) < 0)
3076 return -1;
3078 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3079 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3080 if (options->RelayBandwidthBurst && !options->RelayBandwidthRate)
3081 options->RelayBandwidthRate = options->RelayBandwidthBurst;
3083 if (server_mode(options)) {
3084 if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3085 tor_asprintf(msg,
3086 "BandwidthRate is set to %d bytes/second. "
3087 "For servers, it must be at least %d.",
3088 (int)options->BandwidthRate,
3089 ROUTER_REQUIRED_MIN_BANDWIDTH);
3090 return -1;
3091 } else if (options->MaxAdvertisedBandwidth <
3092 ROUTER_REQUIRED_MIN_BANDWIDTH/2) {
3093 tor_asprintf(msg,
3094 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3095 "For servers, it must be at least %d.",
3096 (int)options->MaxAdvertisedBandwidth,
3097 ROUTER_REQUIRED_MIN_BANDWIDTH/2);
3098 return -1;
3100 if (options->RelayBandwidthRate &&
3101 options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3102 tor_asprintf(msg,
3103 "RelayBandwidthRate is set to %d bytes/second. "
3104 "For servers, it must be at least %d.",
3105 (int)options->RelayBandwidthRate,
3106 ROUTER_REQUIRED_MIN_BANDWIDTH);
3107 return -1;
3111 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3112 REJECT("RelayBandwidthBurst must be at least equal "
3113 "to RelayBandwidthRate.");
3115 if (options->BandwidthRate > options->BandwidthBurst)
3116 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3118 /* if they set relaybandwidth* really high but left bandwidth*
3119 * at the default, raise the defaults. */
3120 if (options->RelayBandwidthRate > options->BandwidthRate)
3121 options->BandwidthRate = options->RelayBandwidthRate;
3122 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3123 options->BandwidthBurst = options->RelayBandwidthBurst;
3125 if (accounting_parse_options(options, 1)<0)
3126 REJECT("Failed to parse accounting options. See logs for details.");
3128 if (options->AccountingMax) {
3129 if (options->RendConfigLines && server_mode(options)) {
3130 log_warn(LD_CONFIG, "Using accounting with a hidden service and an "
3131 "ORPort is risky: your hidden service(s) and your public "
3132 "address will all turn off at the same time, which may alert "
3133 "observers that they are being run by the same party.");
3134 } else if (config_count_key(options->RendConfigLines,
3135 "HiddenServiceDir") > 1) {
3136 log_warn(LD_CONFIG, "Using accounting with multiple hidden services is "
3137 "risky: they will all turn off at the same time, which may "
3138 "alert observers that they are being run by the same party.");
3142 if (options->HTTPProxy) { /* parse it now */
3143 if (tor_addr_port_lookup(options->HTTPProxy,
3144 &options->HTTPProxyAddr, &options->HTTPProxyPort) < 0)
3145 REJECT("HTTPProxy failed to parse or resolve. Please fix.");
3146 if (options->HTTPProxyPort == 0) { /* give it a default */
3147 options->HTTPProxyPort = 80;
3151 if (options->HTTPProxyAuthenticator) {
3152 if (strlen(options->HTTPProxyAuthenticator) >= 512)
3153 REJECT("HTTPProxyAuthenticator is too long (>= 512 chars).");
3156 if (options->HTTPSProxy) { /* parse it now */
3157 if (tor_addr_port_lookup(options->HTTPSProxy,
3158 &options->HTTPSProxyAddr, &options->HTTPSProxyPort) <0)
3159 REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
3160 if (options->HTTPSProxyPort == 0) { /* give it a default */
3161 options->HTTPSProxyPort = 443;
3165 if (options->HTTPSProxyAuthenticator) {
3166 if (strlen(options->HTTPSProxyAuthenticator) >= 512)
3167 REJECT("HTTPSProxyAuthenticator is too long (>= 512 chars).");
3170 if (options->Socks4Proxy) { /* parse it now */
3171 if (tor_addr_port_lookup(options->Socks4Proxy,
3172 &options->Socks4ProxyAddr,
3173 &options->Socks4ProxyPort) <0)
3174 REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
3175 if (options->Socks4ProxyPort == 0) { /* give it a default */
3176 options->Socks4ProxyPort = 1080;
3180 if (options->Socks5Proxy) { /* parse it now */
3181 if (tor_addr_port_lookup(options->Socks5Proxy,
3182 &options->Socks5ProxyAddr,
3183 &options->Socks5ProxyPort) <0)
3184 REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
3185 if (options->Socks5ProxyPort == 0) { /* give it a default */
3186 options->Socks5ProxyPort = 1080;
3190 /* Check if more than one proxy type has been enabled. */
3191 if (!!options->Socks4Proxy + !!options->Socks5Proxy +
3192 !!options->HTTPSProxy + !!options->ClientTransportPlugin > 1)
3193 REJECT("You have configured more than one proxy type. "
3194 "(Socks4Proxy|Socks5Proxy|HTTPSProxy|ClientTransportPlugin)");
3196 /* Check if the proxies will give surprising behavior. */
3197 if (options->HTTPProxy && !(options->Socks4Proxy ||
3198 options->Socks5Proxy ||
3199 options->HTTPSProxy)) {
3200 log_warn(LD_CONFIG, "HTTPProxy configured, but no SOCKS proxy or "
3201 "HTTPS proxy configured. Watch out: this configuration will "
3202 "proxy unencrypted directory connections only.");
3205 if (options->Socks5ProxyUsername) {
3206 size_t len;
3208 len = strlen(options->Socks5ProxyUsername);
3209 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
3210 REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
3212 if (!options->Socks5ProxyPassword)
3213 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3215 len = strlen(options->Socks5ProxyPassword);
3216 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
3217 REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
3218 } else if (options->Socks5ProxyPassword)
3219 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3221 if (options->HashedControlPassword) {
3222 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3223 if (!sl) {
3224 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3225 } else {
3226 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3227 smartlist_free(sl);
3231 if (options->HashedControlSessionPassword) {
3232 smartlist_t *sl = decode_hashed_passwords(
3233 options->HashedControlSessionPassword);
3234 if (!sl) {
3235 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3236 } else {
3237 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3238 smartlist_free(sl);
3242 if (options->OwningControllerProcess) {
3243 const char *validate_pspec_msg = NULL;
3244 if (tor_validate_process_specifier(options->OwningControllerProcess,
3245 &validate_pspec_msg)) {
3246 tor_asprintf(msg, "Bad OwningControllerProcess: %s",
3247 validate_pspec_msg);
3248 return -1;
3252 if (options->ControlPort_set && !options->HashedControlPassword &&
3253 !options->HashedControlSessionPassword &&
3254 !options->CookieAuthentication) {
3255 log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
3256 "has been configured. This means that any program on your "
3257 "computer can reconfigure your Tor. That's bad! You should "
3258 "upgrade your Tor controller as soon as possible.");
3261 if (options->CookieAuthFileGroupReadable && !options->CookieAuthFile) {
3262 log_warn(LD_CONFIG, "CookieAuthFileGroupReadable is set, but will have "
3263 "no effect: you must specify an explicit CookieAuthFile to "
3264 "have it group-readable.");
3267 if (options->MyFamily && options->BridgeRelay) {
3268 log_warn(LD_CONFIG, "Listing a family for a bridge relay is not "
3269 "supported: it can reveal bridge fingerprints to censors. "
3270 "You should also make sure you aren't listing this bridge's "
3271 "fingerprint in any other MyFamily.");
3273 if (check_nickname_list(&options->MyFamily, "MyFamily", msg))
3274 return -1;
3275 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3276 routerset_t *rs = routerset_new();
3277 if (routerset_parse(rs, cl->value, cl->key)) {
3278 routerset_free(rs);
3279 return -1;
3281 routerset_free(rs);
3284 if (validate_addr_policies(options, msg) < 0)
3285 return -1;
3287 if (validate_dir_servers(options, old_options) < 0)
3288 REJECT("Directory authority/fallback line did not parse. See logs "
3289 "for details.");
3291 if (options->UseBridges && !options->Bridges)
3292 REJECT("If you set UseBridges, you must specify at least one bridge.");
3294 for (cl = options->Bridges; cl; cl = cl->next) {
3295 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
3296 if (!bridge_line)
3297 REJECT("Bridge line did not parse. See logs for details.");
3298 bridge_line_free(bridge_line);
3301 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
3302 if (parse_client_transport_line(options, cl->value, 1)<0)
3303 REJECT("Invalid client transport line. See logs for details.");
3306 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
3307 if (parse_server_transport_line(options, cl->value, 1)<0)
3308 REJECT("Invalid server transport line. See logs for details.");
3311 if (options->ServerTransportPlugin && !server_mode(options)) {
3312 log_notice(LD_GENERAL, "Tor is not configured as a relay but you specified"
3313 " a ServerTransportPlugin line (%s). The ServerTransportPlugin "
3314 "line will be ignored.",
3315 escaped(options->ServerTransportPlugin->value));
3318 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
3319 /** If get_bindaddr_from_transport_listen_line() fails with
3320 'transport' being NULL, it means that something went wrong
3321 while parsing the ServerTransportListenAddr line. */
3322 char *bindaddr = get_bindaddr_from_transport_listen_line(cl->value, NULL);
3323 if (!bindaddr)
3324 REJECT("ServerTransportListenAddr did not parse. See logs for details.");
3325 tor_free(bindaddr);
3328 if (options->ServerTransportListenAddr && !options->ServerTransportPlugin) {
3329 log_notice(LD_GENERAL, "You need at least a single managed-proxy to "
3330 "specify a transport listen address. The "
3331 "ServerTransportListenAddr line will be ignored.");
3334 for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
3335 /** If get_options_from_transport_options_line() fails with
3336 'transport' being NULL, it means that something went wrong
3337 while parsing the ServerTransportOptions line. */
3338 smartlist_t *options_sl =
3339 get_options_from_transport_options_line(cl->value, NULL);
3340 if (!options_sl)
3341 REJECT("ServerTransportOptions did not parse. See logs for details.");
3343 SMARTLIST_FOREACH(options_sl, char *, cp, tor_free(cp));
3344 smartlist_free(options_sl);
3347 if (options->ConstrainedSockets) {
3348 /* If the user wants to constrain socket buffer use, make sure the desired
3349 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3350 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3351 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3352 options->ConstrainedSockSize % 1024) {
3353 tor_asprintf(msg,
3354 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3355 "in 1024 byte increments.",
3356 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3357 return -1;
3359 if (options->DirPort_set) {
3360 /* Providing cached directory entries while system TCP buffers are scarce
3361 * will exacerbate the socket errors. Suggest that this be disabled. */
3362 COMPLAIN("You have requested constrained socket buffers while also "
3363 "serving directory entries via DirPort. It is strongly "
3364 "suggested that you disable serving directory requests when "
3365 "system TCP buffer resources are scarce.");
3369 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3370 options->V3AuthVotingInterval/2) {
3371 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3372 "V3AuthVotingInterval");
3374 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
3375 REJECT("V3AuthVoteDelay is way too low.");
3376 if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
3377 REJECT("V3AuthDistDelay is way too low.");
3379 if (options->V3AuthNIntervalsValid < 2)
3380 REJECT("V3AuthNIntervalsValid must be at least 2.");
3382 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3383 REJECT("V3AuthVotingInterval is insanely low.");
3384 } else if (options->V3AuthVotingInterval > 24*60*60) {
3385 REJECT("V3AuthVotingInterval is insanely high.");
3386 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3387 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3390 if (rend_config_services(options, 1) < 0)
3391 REJECT("Failed to configure rendezvous options. See logs for details.");
3393 /* Parse client-side authorization for hidden services. */
3394 if (rend_parse_service_authorization(options, 1) < 0)
3395 REJECT("Failed to configure client authorization for hidden services. "
3396 "See logs for details.");
3398 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv4,
3399 AF_INET, 1, msg)<0)
3400 return -1;
3401 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv6,
3402 AF_INET6, 1, msg)<0)
3403 return -1;
3405 if (options->AutomapHostsSuffixes) {
3406 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
3408 size_t len = strlen(suf);
3409 if (len && suf[len-1] == '.')
3410 suf[len-1] = '\0';
3414 if (options->TestingTorNetwork &&
3415 !(options->DirAuthorities ||
3416 (options->AlternateDirAuthority &&
3417 options->AlternateBridgeAuthority))) {
3418 REJECT("TestingTorNetwork may only be configured in combination with "
3419 "a non-default set of DirAuthority or both of "
3420 "AlternateDirAuthority and AlternateBridgeAuthority configured.");
3423 if (options->AllowSingleHopExits && !options->DirAuthorities) {
3424 COMPLAIN("You have set AllowSingleHopExits; now your relay will allow "
3425 "others to make one-hop exits. However, since by default most "
3426 "clients avoid relays that set this option, most clients will "
3427 "ignore you.");
3430 #define CHECK_DEFAULT(arg) \
3431 STMT_BEGIN \
3432 if (!options->TestingTorNetwork && \
3433 !options->UsingTestNetworkDefaults_ && \
3434 !config_is_same(&options_format,options, \
3435 default_options,#arg)) { \
3436 REJECT(#arg " may only be changed in testing Tor " \
3437 "networks!"); \
3438 } STMT_END
3439 CHECK_DEFAULT(TestingV3AuthInitialVotingInterval);
3440 CHECK_DEFAULT(TestingV3AuthInitialVoteDelay);
3441 CHECK_DEFAULT(TestingV3AuthInitialDistDelay);
3442 CHECK_DEFAULT(TestingV3AuthVotingStartOffset);
3443 CHECK_DEFAULT(TestingAuthDirTimeToLearnReachability);
3444 CHECK_DEFAULT(TestingEstimatedDescriptorPropagationTime);
3445 CHECK_DEFAULT(TestingServerDownloadSchedule);
3446 CHECK_DEFAULT(TestingClientDownloadSchedule);
3447 CHECK_DEFAULT(TestingServerConsensusDownloadSchedule);
3448 CHECK_DEFAULT(TestingClientConsensusDownloadSchedule);
3449 CHECK_DEFAULT(TestingBridgeDownloadSchedule);
3450 CHECK_DEFAULT(TestingClientMaxIntervalWithoutRequest);
3451 CHECK_DEFAULT(TestingDirConnectionMaxStall);
3452 CHECK_DEFAULT(TestingConsensusMaxDownloadTries);
3453 CHECK_DEFAULT(TestingDescriptorMaxDownloadTries);
3454 CHECK_DEFAULT(TestingMicrodescMaxDownloadTries);
3455 CHECK_DEFAULT(TestingCertMaxDownloadTries);
3456 #undef CHECK_DEFAULT
3458 if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
3459 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3460 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
3461 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3462 "30 minutes.");
3465 if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
3466 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3469 if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
3470 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3473 if (options->TestingV3AuthInitialVoteDelay +
3474 options->TestingV3AuthInitialDistDelay >=
3475 options->TestingV3AuthInitialVotingInterval/2) {
3476 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3477 "must be less than half TestingV3AuthInitialVotingInterval");
3480 if (options->TestingV3AuthVotingStartOffset >
3481 MIN(options->TestingV3AuthInitialVotingInterval,
3482 options->V3AuthVotingInterval)) {
3483 REJECT("TestingV3AuthVotingStartOffset is higher than the voting "
3484 "interval.");
3487 if (options->TestingAuthDirTimeToLearnReachability < 0) {
3488 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3489 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
3490 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3493 if (options->TestingEstimatedDescriptorPropagationTime < 0) {
3494 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3495 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
3496 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3499 if (options->TestingClientMaxIntervalWithoutRequest < 1) {
3500 REJECT("TestingClientMaxIntervalWithoutRequest is way too low.");
3501 } else if (options->TestingClientMaxIntervalWithoutRequest > 3600) {
3502 COMPLAIN("TestingClientMaxIntervalWithoutRequest is insanely high.");
3505 if (options->TestingDirConnectionMaxStall < 5) {
3506 REJECT("TestingDirConnectionMaxStall is way too low.");
3507 } else if (options->TestingDirConnectionMaxStall > 3600) {
3508 COMPLAIN("TestingDirConnectionMaxStall is insanely high.");
3511 if (options->TestingConsensusMaxDownloadTries < 2) {
3512 REJECT("TestingConsensusMaxDownloadTries must be greater than 1.");
3513 } else if (options->TestingConsensusMaxDownloadTries > 800) {
3514 COMPLAIN("TestingConsensusMaxDownloadTries is insanely high.");
3517 if (options->TestingDescriptorMaxDownloadTries < 2) {
3518 REJECT("TestingDescriptorMaxDownloadTries must be greater than 1.");
3519 } else if (options->TestingDescriptorMaxDownloadTries > 800) {
3520 COMPLAIN("TestingDescriptorMaxDownloadTries is insanely high.");
3523 if (options->TestingMicrodescMaxDownloadTries < 2) {
3524 REJECT("TestingMicrodescMaxDownloadTries must be greater than 1.");
3525 } else if (options->TestingMicrodescMaxDownloadTries > 800) {
3526 COMPLAIN("TestingMicrodescMaxDownloadTries is insanely high.");
3529 if (options->TestingCertMaxDownloadTries < 2) {
3530 REJECT("TestingCertMaxDownloadTries must be greater than 1.");
3531 } else if (options->TestingCertMaxDownloadTries > 800) {
3532 COMPLAIN("TestingCertMaxDownloadTries is insanely high.");
3535 if (options->TestingEnableConnBwEvent &&
3536 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
3537 REJECT("TestingEnableConnBwEvent may only be changed in testing "
3538 "Tor networks!");
3541 if (options->TestingEnableCellStatsEvent &&
3542 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
3543 REJECT("TestingEnableCellStatsEvent may only be changed in testing "
3544 "Tor networks!");
3547 if (options->TestingEnableTbEmptyEvent &&
3548 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
3549 REJECT("TestingEnableTbEmptyEvent may only be changed in testing "
3550 "Tor networks!");
3553 if (options->TestingTorNetwork) {
3554 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
3555 "almost unusable in the public Tor network, and is "
3556 "therefore only advised if you are building a "
3557 "testing Tor network!");
3560 if (options->AccelName && !options->HardwareAccel)
3561 options->HardwareAccel = 1;
3562 if (options->AccelDir && !options->AccelName)
3563 REJECT("Can't use hardware crypto accelerator dir without engine name.");
3565 if (options->PublishServerDescriptor)
3566 SMARTLIST_FOREACH(options->PublishServerDescriptor, const char *, pubdes, {
3567 if (!strcmp(pubdes, "1") || !strcmp(pubdes, "0"))
3568 if (smartlist_len(options->PublishServerDescriptor) > 1) {
3569 COMPLAIN("You have passed a list of multiple arguments to the "
3570 "PublishServerDescriptor option that includes 0 or 1. "
3571 "0 or 1 should only be used as the sole argument. "
3572 "This configuration will be rejected in a future release.");
3573 break;
3577 if (options->BridgeRelay == 1 && ! options->ORPort_set)
3578 REJECT("BridgeRelay is 1, ORPort is not set. This is an invalid "
3579 "combination.");
3581 return 0;
3582 #undef REJECT
3583 #undef COMPLAIN
3586 /* Given the value that the user has set for MaxMemInQueues, compute the
3587 * actual maximum value. We clip this value if it's too low, and autodetect
3588 * it if it's set to 0. */
3589 static uint64_t
3590 compute_real_max_mem_in_queues(const uint64_t val, int log_guess)
3592 uint64_t result;
3594 if (val == 0) {
3595 #define ONE_GIGABYTE (U64_LITERAL(1) << 30)
3596 #define ONE_MEGABYTE (U64_LITERAL(1) << 20)
3597 #if SIZEOF_VOID_P >= 8
3598 #define MAX_DEFAULT_MAXMEM (8*ONE_GIGABYTE)
3599 #else
3600 #define MAX_DEFAULT_MAXMEM (2*ONE_GIGABYTE)
3601 #endif
3602 /* The user didn't pick a memory limit. Choose a very large one
3603 * that is still smaller than the system memory */
3604 static int notice_sent = 0;
3605 size_t ram = 0;
3606 if (get_total_system_memory(&ram) < 0) {
3607 /* We couldn't determine our total system memory! */
3608 #if SIZEOF_VOID_P >= 8
3609 /* 64-bit system. Let's hope for 8 GB. */
3610 result = 8 * ONE_GIGABYTE;
3611 #else
3612 /* (presumably) 32-bit system. Let's hope for 1 GB. */
3613 result = ONE_GIGABYTE;
3614 #endif
3615 } else {
3616 /* We detected it, so let's pick 3/4 of the total RAM as our limit. */
3617 const uint64_t avail = (ram / 4) * 3;
3619 /* Make sure it's in range from 0.25 GB to 8 GB. */
3620 if (avail > MAX_DEFAULT_MAXMEM) {
3621 /* If you want to use more than this much RAM, you need to configure
3622 it yourself */
3623 result = MAX_DEFAULT_MAXMEM;
3624 } else if (avail < ONE_GIGABYTE / 4) {
3625 result = ONE_GIGABYTE / 4;
3626 } else {
3627 result = avail;
3630 if (log_guess && ! notice_sent) {
3631 log_notice(LD_CONFIG, "%sMaxMemInQueues is set to "U64_FORMAT" MB. "
3632 "You can override this by setting MaxMemInQueues by hand.",
3633 ram ? "Based on detected system memory, " : "",
3634 U64_PRINTF_ARG(result / ONE_MEGABYTE));
3635 notice_sent = 1;
3637 return result;
3638 } else if (val < ONE_GIGABYTE / 4) {
3639 log_warn(LD_CONFIG, "MaxMemInQueues must be at least 256 MB for now. "
3640 "Ideally, have it as large as you can afford.");
3641 return ONE_GIGABYTE / 4;
3642 } else {
3643 /* The value was fine all along */
3644 return val;
3648 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3649 * equal strings. */
3650 static int
3651 opt_streq(const char *s1, const char *s2)
3653 return 0 == strcmp_opt(s1, s2);
3656 /** Check if any of the previous options have changed but aren't allowed to. */
3657 static int
3658 options_transition_allowed(const or_options_t *old,
3659 const or_options_t *new_val,
3660 char **msg)
3662 if (!old)
3663 return 0;
3665 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3666 *msg = tor_strdup("PidFile is not allowed to change.");
3667 return -1;
3670 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3671 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3672 "is not allowed.");
3673 return -1;
3676 if (old->Sandbox != new_val->Sandbox) {
3677 *msg = tor_strdup("While Tor is running, changing Sandbox "
3678 "is not allowed.");
3679 return -1;
3682 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
3683 tor_asprintf(msg,
3684 "While Tor is running, changing DataDirectory "
3685 "(\"%s\"->\"%s\") is not allowed.",
3686 old->DataDirectory, new_val->DataDirectory);
3687 return -1;
3690 if (!opt_streq(old->User, new_val->User)) {
3691 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
3692 return -1;
3695 if ((old->HardwareAccel != new_val->HardwareAccel)
3696 || !opt_streq(old->AccelName, new_val->AccelName)
3697 || !opt_streq(old->AccelDir, new_val->AccelDir)) {
3698 *msg = tor_strdup("While Tor is running, changing OpenSSL hardware "
3699 "acceleration engine is not allowed.");
3700 return -1;
3703 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
3704 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
3705 "is not allowed.");
3706 return -1;
3709 if (old->DisableAllSwap != new_val->DisableAllSwap) {
3710 *msg = tor_strdup("While Tor is running, changing DisableAllSwap "
3711 "is not allowed.");
3712 return -1;
3715 if (old->TokenBucketRefillInterval != new_val->TokenBucketRefillInterval) {
3716 *msg = tor_strdup("While Tor is running, changing TokenBucketRefill"
3717 "Interval is not allowed");
3718 return -1;
3721 if (old->DisableIOCP != new_val->DisableIOCP) {
3722 *msg = tor_strdup("While Tor is running, changing DisableIOCP "
3723 "is not allowed.");
3724 return -1;
3727 if (old->DisableDebuggerAttachment &&
3728 !new_val->DisableDebuggerAttachment) {
3729 *msg = tor_strdup("While Tor is running, disabling "
3730 "DisableDebuggerAttachment is not allowed.");
3731 return -1;
3734 if (sandbox_is_active()) {
3735 #define SB_NOCHANGE_STR(opt) \
3736 do { \
3737 if (! opt_streq(old->opt, new_val->opt)) { \
3738 *msg = tor_strdup("Can't change " #opt " while Sandbox is active"); \
3739 return -1; \
3741 } while (0)
3743 SB_NOCHANGE_STR(PidFile);
3744 SB_NOCHANGE_STR(ServerDNSResolvConfFile);
3745 SB_NOCHANGE_STR(DirPortFrontPage);
3746 SB_NOCHANGE_STR(CookieAuthFile);
3747 SB_NOCHANGE_STR(ExtORPortCookieAuthFile);
3749 #undef SB_NOCHANGE_STR
3751 if (! config_lines_eq(old->Logs, new_val->Logs)) {
3752 *msg = tor_strdup("Can't change Logs while Sandbox is active");
3753 return -1;
3755 if (old->ConnLimit != new_val->ConnLimit) {
3756 *msg = tor_strdup("Can't change ConnLimit while Sandbox is active");
3757 return -1;
3759 if (server_mode(old) != server_mode(new_val)) {
3760 *msg = tor_strdup("Can't start/stop being a server while "
3761 "Sandbox is active");
3762 return -1;
3766 return 0;
3769 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3770 * will require us to rotate the CPU and DNS workers; else return 0. */
3771 static int
3772 options_transition_affects_workers(const or_options_t *old_options,
3773 const or_options_t *new_options)
3775 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3776 old_options->NumCPUs != new_options->NumCPUs ||
3777 !config_lines_eq(old_options->ORPort_lines, new_options->ORPort_lines) ||
3778 old_options->ServerDNSSearchDomains !=
3779 new_options->ServerDNSSearchDomains ||
3780 old_options->SafeLogging_ != new_options->SafeLogging_ ||
3781 old_options->ClientOnly != new_options->ClientOnly ||
3782 public_server_mode(old_options) != public_server_mode(new_options) ||
3783 !config_lines_eq(old_options->Logs, new_options->Logs) ||
3784 old_options->LogMessageDomains != new_options->LogMessageDomains)
3785 return 1;
3787 /* Check whether log options match. */
3789 /* Nothing that changed matters. */
3790 return 0;
3793 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3794 * will require us to generate a new descriptor; else return 0. */
3795 static int
3796 options_transition_affects_descriptor(const or_options_t *old_options,
3797 const or_options_t *new_options)
3799 /* XXX We can be smarter here. If your DirPort isn't being
3800 * published and you just turned it off, no need to republish. Etc. */
3801 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3802 !opt_streq(old_options->Nickname,new_options->Nickname) ||
3803 !opt_streq(old_options->Address,new_options->Address) ||
3804 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
3805 old_options->ExitPolicyRejectPrivate !=
3806 new_options->ExitPolicyRejectPrivate ||
3807 old_options->IPv6Exit != new_options->IPv6Exit ||
3808 !config_lines_eq(old_options->ORPort_lines,
3809 new_options->ORPort_lines) ||
3810 !config_lines_eq(old_options->DirPort_lines,
3811 new_options->DirPort_lines) ||
3812 old_options->ClientOnly != new_options->ClientOnly ||
3813 old_options->DisableNetwork != new_options->DisableNetwork ||
3814 old_options->PublishServerDescriptor_ !=
3815 new_options->PublishServerDescriptor_ ||
3816 get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
3817 get_effective_bwburst(old_options) !=
3818 get_effective_bwburst(new_options) ||
3819 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
3820 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
3821 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
3822 old_options->AccountingMax != new_options->AccountingMax ||
3823 public_server_mode(old_options) != public_server_mode(new_options))
3824 return 1;
3826 return 0;
3829 #ifdef _WIN32
3830 /** Return the directory on windows where we expect to find our application
3831 * data. */
3832 static char *
3833 get_windows_conf_root(void)
3835 static int is_set = 0;
3836 static char path[MAX_PATH*2+1];
3837 TCHAR tpath[MAX_PATH] = {0};
3839 LPITEMIDLIST idl;
3840 IMalloc *m;
3841 HRESULT result;
3843 if (is_set)
3844 return path;
3846 /* Find X:\documents and settings\username\application data\ .
3847 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3849 #ifdef ENABLE_LOCAL_APPDATA
3850 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
3851 #else
3852 #define APPDATA_PATH CSIDL_APPDATA
3853 #endif
3854 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
3855 getcwd(path,MAX_PATH);
3856 is_set = 1;
3857 log_warn(LD_CONFIG,
3858 "I couldn't find your application data folder: are you "
3859 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3860 path);
3861 return path;
3863 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3864 result = SHGetPathFromIDList(idl, tpath);
3865 #ifdef UNICODE
3866 wcstombs(path,tpath,sizeof(path));
3867 path[sizeof(path)-1] = '\0';
3868 #else
3869 strlcpy(path,tpath,sizeof(path));
3870 #endif
3872 /* Now we need to free the memory that the path-idl was stored in. In
3873 * typical Windows fashion, we can't just call 'free()' on it. */
3874 SHGetMalloc(&m);
3875 if (m) {
3876 m->lpVtbl->Free(m, idl);
3877 m->lpVtbl->Release(m);
3879 if (!SUCCEEDED(result)) {
3880 return NULL;
3882 strlcat(path,"\\tor",MAX_PATH);
3883 is_set = 1;
3884 return path;
3886 #endif
3888 /** Return the default location for our torrc file (if <b>defaults_file</b> is
3889 * false), or for the torrc-defaults file (if <b>defaults_file</b> is true). */
3890 static const char *
3891 get_default_conf_file(int defaults_file)
3893 #ifdef _WIN32
3894 if (defaults_file) {
3895 static char defaults_path[MAX_PATH+1];
3896 tor_snprintf(defaults_path, MAX_PATH, "%s\\torrc-defaults",
3897 get_windows_conf_root());
3898 return defaults_path;
3899 } else {
3900 static char path[MAX_PATH+1];
3901 tor_snprintf(path, MAX_PATH, "%s\\torrc",
3902 get_windows_conf_root());
3903 return path;
3905 #else
3906 return defaults_file ? CONFDIR "/torrc-defaults" : CONFDIR "/torrc";
3907 #endif
3910 /** Verify whether lst is a string containing valid-looking comma-separated
3911 * nicknames, or NULL. Will normalise <b>lst</b> to prefix '$' to any nickname
3912 * or fingerprint that needs it. Return 0 on success.
3913 * Warn and return -1 on failure.
3915 static int
3916 check_nickname_list(char **lst, const char *name, char **msg)
3918 int r = 0;
3919 smartlist_t *sl;
3920 int changes = 0;
3922 if (!*lst)
3923 return 0;
3924 sl = smartlist_new();
3926 smartlist_split_string(sl, *lst, ",",
3927 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
3929 SMARTLIST_FOREACH_BEGIN(sl, char *, s)
3931 if (!is_legal_nickname_or_hexdigest(s)) {
3932 // check if first char is dollar
3933 if (s[0] != '$') {
3934 // Try again but with a dollar symbol prepended
3935 char *prepended;
3936 tor_asprintf(&prepended, "$%s", s);
3938 if (is_legal_nickname_or_hexdigest(prepended)) {
3939 // The nickname is valid when it's prepended, swap the current
3940 // version with a prepended one
3941 tor_free(s);
3942 SMARTLIST_REPLACE_CURRENT(sl, s, prepended);
3943 changes = 1;
3944 continue;
3947 // Still not valid, free and fallback to error message
3948 tor_free(prepended);
3951 tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
3952 r = -1;
3953 break;
3956 SMARTLIST_FOREACH_END(s);
3958 // Replace the caller's nickname list with a fixed one
3959 if (changes && r == 0) {
3960 char *newNicknames = smartlist_join_strings(sl, ", ", 0, NULL);
3961 tor_free(*lst);
3962 *lst = newNicknames;
3965 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
3966 smartlist_free(sl);
3968 return r;
3971 /** Learn config file name from command line arguments, or use the default.
3973 * If <b>defaults_file</b> is true, we're looking for torrc-defaults;
3974 * otherwise, we're looking for the regular torrc_file.
3976 * Set *<b>using_default_fname</b> to true if we're using the default
3977 * configuration file name; or false if we've set it from the command line.
3979 * Set *<b>ignore_missing_torrc</b> to true if we should ignore the resulting
3980 * filename if it doesn't exist.
3982 static char *
3983 find_torrc_filename(config_line_t *cmd_arg,
3984 int defaults_file,
3985 int *using_default_fname, int *ignore_missing_torrc)
3987 char *fname=NULL;
3988 config_line_t *p_index;
3989 const char *fname_opt = defaults_file ? "--defaults-torrc" : "-f";
3990 const char *ignore_opt = defaults_file ? NULL : "--ignore-missing-torrc";
3992 if (defaults_file)
3993 *ignore_missing_torrc = 1;
3995 for (p_index = cmd_arg; p_index; p_index = p_index->next) {
3996 if (!strcmp(p_index->key, fname_opt)) {
3997 if (fname) {
3998 log_warn(LD_CONFIG, "Duplicate %s options on command line.",
3999 fname_opt);
4000 tor_free(fname);
4002 fname = expand_filename(p_index->value);
4005 char *absfname;
4006 absfname = make_path_absolute(fname);
4007 tor_free(fname);
4008 fname = absfname;
4011 *using_default_fname = 0;
4012 } else if (ignore_opt && !strcmp(p_index->key,ignore_opt)) {
4013 *ignore_missing_torrc = 1;
4017 if (*using_default_fname) {
4018 /* didn't find one, try CONFDIR */
4019 const char *dflt = get_default_conf_file(defaults_file);
4020 if (dflt && file_status(dflt) == FN_FILE) {
4021 fname = tor_strdup(dflt);
4022 } else {
4023 #ifndef _WIN32
4024 char *fn = NULL;
4025 if (!defaults_file)
4026 fn = expand_filename("~/.torrc");
4027 if (fn && file_status(fn) == FN_FILE) {
4028 fname = fn;
4029 } else {
4030 tor_free(fn);
4031 fname = tor_strdup(dflt);
4033 #else
4034 fname = tor_strdup(dflt);
4035 #endif
4038 return fname;
4041 /** Load a configuration file from disk, setting torrc_fname or
4042 * torrc_defaults_fname if successful.
4044 * If <b>defaults_file</b> is true, load torrc-defaults; otherwise load torrc.
4046 * Return the contents of the file on success, and NULL on failure.
4048 static char *
4049 load_torrc_from_disk(config_line_t *cmd_arg, int defaults_file)
4051 char *fname=NULL;
4052 char *cf = NULL;
4053 int using_default_torrc = 1;
4054 int ignore_missing_torrc = 0;
4055 char **fname_var = defaults_file ? &torrc_defaults_fname : &torrc_fname;
4057 fname = find_torrc_filename(cmd_arg, defaults_file,
4058 &using_default_torrc, &ignore_missing_torrc);
4059 tor_assert(fname);
4060 log_debug(LD_CONFIG, "Opening config file \"%s\"", fname);
4062 tor_free(*fname_var);
4063 *fname_var = fname;
4065 /* Open config file */
4066 if (file_status(fname) != FN_FILE ||
4067 !(cf = read_file_to_str(fname,0,NULL))) {
4068 if (using_default_torrc == 1 || ignore_missing_torrc) {
4069 if (!defaults_file)
4070 log_notice(LD_CONFIG, "Configuration file \"%s\" not present, "
4071 "using reasonable defaults.", fname);
4072 tor_free(fname); /* sets fname to NULL */
4073 *fname_var = NULL;
4074 cf = tor_strdup("");
4075 } else {
4076 log_warn(LD_CONFIG,
4077 "Unable to open configuration file \"%s\".", fname);
4078 goto err;
4080 } else {
4081 log_notice(LD_CONFIG, "Read configuration file \"%s\".", fname);
4084 return cf;
4085 err:
4086 tor_free(fname);
4087 *fname_var = NULL;
4088 return NULL;
4091 /** Read a configuration file into <b>options</b>, finding the configuration
4092 * file location based on the command line. After loading the file
4093 * call options_init_from_string() to load the config.
4094 * Return 0 if success, -1 if failure. */
4096 options_init_from_torrc(int argc, char **argv)
4098 char *cf=NULL, *cf_defaults=NULL;
4099 int command;
4100 int retval = -1;
4101 char *command_arg = NULL;
4102 char *errmsg=NULL;
4103 config_line_t *p_index = NULL;
4104 config_line_t *cmdline_only_options = NULL;
4106 /* Go through command-line variables */
4107 if (! have_parsed_cmdline) {
4108 /* Or we could redo the list every time we pass this place.
4109 * It does not really matter */
4110 if (config_parse_commandline(argc, argv, 0, &global_cmdline_options,
4111 &global_cmdline_only_options) < 0) {
4112 goto err;
4114 have_parsed_cmdline = 1;
4116 cmdline_only_options = global_cmdline_only_options;
4118 if (config_line_find(cmdline_only_options, "-h") ||
4119 config_line_find(cmdline_only_options, "--help")) {
4120 print_usage();
4121 exit(0);
4123 if (config_line_find(cmdline_only_options, "--list-torrc-options")) {
4124 /* For documenting validating whether we've documented everything. */
4125 list_torrc_options();
4126 exit(0);
4129 if (config_line_find(cmdline_only_options, "--version")) {
4130 printf("Tor version %s.\n",get_version());
4131 exit(0);
4134 if (config_line_find(cmdline_only_options, "--digests")) {
4135 printf("Tor version %s.\n",get_version());
4136 printf("%s", libor_get_digests());
4137 printf("%s", tor_get_digests());
4138 exit(0);
4141 if (config_line_find(cmdline_only_options, "--library-versions")) {
4142 printf("Tor version %s. \n", get_version());
4143 printf("Library versions\tCompiled\t\tRuntime\n");
4144 printf("Libevent\t\t%-15s\t\t%s\n",
4145 tor_libevent_get_header_version_str(),
4146 tor_libevent_get_version_str());
4147 printf("OpenSSL \t\t%-15s\t\t%s\n",
4148 crypto_openssl_get_header_version_str(),
4149 crypto_openssl_get_version_str());
4150 printf("Zlib \t\t%-15s\t\t%s\n",
4151 tor_zlib_get_header_version_str(),
4152 tor_zlib_get_version_str());
4153 //TODO: Hex versions?
4154 exit(0);
4157 command = CMD_RUN_TOR;
4158 for (p_index = cmdline_only_options; p_index; p_index = p_index->next) {
4159 if (!strcmp(p_index->key,"--list-fingerprint")) {
4160 command = CMD_LIST_FINGERPRINT;
4161 } else if (!strcmp(p_index->key, "--hash-password")) {
4162 command = CMD_HASH_PASSWORD;
4163 command_arg = p_index->value;
4164 } else if (!strcmp(p_index->key, "--dump-config")) {
4165 command = CMD_DUMP_CONFIG;
4166 command_arg = p_index->value;
4167 } else if (!strcmp(p_index->key, "--verify-config")) {
4168 command = CMD_VERIFY_CONFIG;
4172 if (command == CMD_HASH_PASSWORD) {
4173 cf_defaults = tor_strdup("");
4174 cf = tor_strdup("");
4175 } else {
4176 cf_defaults = load_torrc_from_disk(cmdline_only_options, 1);
4177 cf = load_torrc_from_disk(cmdline_only_options, 0);
4178 if (!cf) {
4179 if (config_line_find(cmdline_only_options, "--allow-missing-torrc")) {
4180 cf = tor_strdup("");
4181 } else {
4182 goto err;
4187 retval = options_init_from_string(cf_defaults, cf, command, command_arg,
4188 &errmsg);
4190 err:
4192 tor_free(cf);
4193 tor_free(cf_defaults);
4194 if (errmsg) {
4195 log_warn(LD_CONFIG,"%s", errmsg);
4196 tor_free(errmsg);
4198 return retval < 0 ? -1 : 0;
4201 /** Load the options from the configuration in <b>cf</b>, validate
4202 * them for consistency and take actions based on them.
4204 * Return 0 if success, negative on error:
4205 * * -1 for general errors.
4206 * * -2 for failure to parse/validate,
4207 * * -3 for transition not allowed
4208 * * -4 for error while setting the new options
4210 setopt_err_t
4211 options_init_from_string(const char *cf_defaults, const char *cf,
4212 int command, const char *command_arg,
4213 char **msg)
4215 or_options_t *oldoptions, *newoptions, *newdefaultoptions=NULL;
4216 config_line_t *cl;
4217 int retval, i;
4218 setopt_err_t err = SETOPT_ERR_MISC;
4219 tor_assert(msg);
4221 oldoptions = global_options; /* get_options unfortunately asserts if
4222 this is the first time we run*/
4224 newoptions = tor_malloc_zero(sizeof(or_options_t));
4225 newoptions->magic_ = OR_OPTIONS_MAGIC;
4226 options_init(newoptions);
4227 newoptions->command = command;
4228 newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
4230 for (i = 0; i < 2; ++i) {
4231 const char *body = i==0 ? cf_defaults : cf;
4232 if (!body)
4233 continue;
4234 /* get config lines, assign them */
4235 retval = config_get_lines(body, &cl, 1);
4236 if (retval < 0) {
4237 err = SETOPT_ERR_PARSE;
4238 goto err;
4240 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4241 config_free_lines(cl);
4242 if (retval < 0) {
4243 err = SETOPT_ERR_PARSE;
4244 goto err;
4246 if (i==0)
4247 newdefaultoptions = config_dup(&options_format, newoptions);
4250 if (newdefaultoptions == NULL) {
4251 newdefaultoptions = config_dup(&options_format, global_default_options);
4254 /* Go through command-line variables too */
4255 retval = config_assign(&options_format, newoptions,
4256 global_cmdline_options, 0, 0, msg);
4257 if (retval < 0) {
4258 err = SETOPT_ERR_PARSE;
4259 goto err;
4262 /* If this is a testing network configuration, change defaults
4263 * for a list of dependent config options, re-initialize newoptions
4264 * with the new defaults, and assign all options to it second time. */
4265 if (newoptions->TestingTorNetwork) {
4266 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4267 * this? We could, for example, make the parsing algorithm do two passes
4268 * over the configuration. If it finds any "suite" options like
4269 * TestingTorNetwork, it could change the defaults before its second pass.
4270 * Not urgent so long as this seems to work, but at any sign of trouble,
4271 * let's clean it up. -NM */
4273 /* Change defaults. */
4274 int i;
4275 for (i = 0; testing_tor_network_defaults[i].name; ++i) {
4276 const config_var_t *new_var = &testing_tor_network_defaults[i];
4277 config_var_t *old_var =
4278 config_find_option_mutable(&options_format, new_var->name);
4279 tor_assert(new_var);
4280 tor_assert(old_var);
4281 old_var->initvalue = new_var->initvalue;
4284 /* Clear newoptions and re-initialize them with new defaults. */
4285 config_free(&options_format, newoptions);
4286 config_free(&options_format, newdefaultoptions);
4287 newdefaultoptions = NULL;
4288 newoptions = tor_malloc_zero(sizeof(or_options_t));
4289 newoptions->magic_ = OR_OPTIONS_MAGIC;
4290 options_init(newoptions);
4291 newoptions->command = command;
4292 newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
4294 /* Assign all options a second time. */
4295 for (i = 0; i < 2; ++i) {
4296 const char *body = i==0 ? cf_defaults : cf;
4297 if (!body)
4298 continue;
4299 /* get config lines, assign them */
4300 retval = config_get_lines(body, &cl, 1);
4301 if (retval < 0) {
4302 err = SETOPT_ERR_PARSE;
4303 goto err;
4305 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4306 config_free_lines(cl);
4307 if (retval < 0) {
4308 err = SETOPT_ERR_PARSE;
4309 goto err;
4311 if (i==0)
4312 newdefaultoptions = config_dup(&options_format, newoptions);
4314 /* Assign command-line variables a second time too */
4315 retval = config_assign(&options_format, newoptions,
4316 global_cmdline_options, 0, 0, msg);
4317 if (retval < 0) {
4318 err = SETOPT_ERR_PARSE;
4319 goto err;
4323 /* Validate newoptions */
4324 if (options_validate(oldoptions, newoptions, newdefaultoptions,
4325 0, msg) < 0) {
4326 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
4327 goto err;
4330 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
4331 err = SETOPT_ERR_TRANSITION;
4332 goto err;
4335 if (set_options(newoptions, msg)) {
4336 err = SETOPT_ERR_SETTING;
4337 goto err; /* frees and replaces old options */
4339 config_free(&options_format, global_default_options);
4340 global_default_options = newdefaultoptions;
4342 return SETOPT_OK;
4344 err:
4345 config_free(&options_format, newoptions);
4346 config_free(&options_format, newdefaultoptions);
4347 if (*msg) {
4348 char *old_msg = *msg;
4349 tor_asprintf(msg, "Failed to parse/validate config: %s", old_msg);
4350 tor_free(old_msg);
4352 return err;
4355 /** Return the location for our configuration file.
4357 const char *
4358 get_torrc_fname(int defaults_fname)
4360 const char *fname = defaults_fname ? torrc_defaults_fname : torrc_fname;
4362 if (fname)
4363 return fname;
4364 else
4365 return get_default_conf_file(defaults_fname);
4368 /** Adjust the address map based on the MapAddress elements in the
4369 * configuration <b>options</b>
4371 void
4372 config_register_addressmaps(const or_options_t *options)
4374 smartlist_t *elts;
4375 config_line_t *opt;
4376 const char *from, *to, *msg;
4378 addressmap_clear_configured();
4379 elts = smartlist_new();
4380 for (opt = options->AddressMap; opt; opt = opt->next) {
4381 smartlist_split_string(elts, opt->value, NULL,
4382 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4383 if (smartlist_len(elts) < 2) {
4384 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
4385 opt->value);
4386 goto cleanup;
4389 from = smartlist_get(elts,0);
4390 to = smartlist_get(elts,1);
4392 if (to[0] == '.' || from[0] == '.') {
4393 log_warn(LD_CONFIG,"MapAddress '%s' is ambiguous - address starts with a"
4394 "'.'. Ignoring.",opt->value);
4395 goto cleanup;
4398 if (addressmap_register_auto(from, to, 0, ADDRMAPSRC_TORRC, &msg) < 0) {
4399 log_warn(LD_CONFIG,"MapAddress '%s' failed: %s. Ignoring.", opt->value,
4400 msg);
4401 goto cleanup;
4404 if (smartlist_len(elts) > 2)
4405 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
4407 cleanup:
4408 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4409 smartlist_clear(elts);
4411 smartlist_free(elts);
4414 /** As addressmap_register(), but detect the wildcarded status of "from" and
4415 * "to", and do not steal a reference to <b>to</b>. */
4416 /* XXXX024 move to connection_edge.c */
4418 addressmap_register_auto(const char *from, const char *to,
4419 time_t expires,
4420 addressmap_entry_source_t addrmap_source,
4421 const char **msg)
4423 int from_wildcard = 0, to_wildcard = 0;
4425 *msg = "whoops, forgot the error message";
4426 if (1) {
4427 if (!strcmp(to, "*") || !strcmp(from, "*")) {
4428 *msg = "can't remap from or to *";
4429 return -1;
4431 /* Detect asterisks in expressions of type: '*.example.com' */
4432 if (!strncmp(from,"*.",2)) {
4433 from += 2;
4434 from_wildcard = 1;
4436 if (!strncmp(to,"*.",2)) {
4437 to += 2;
4438 to_wildcard = 1;
4441 if (to_wildcard && !from_wildcard) {
4442 *msg = "can only use wildcard (i.e. '*.') if 'from' address "
4443 "uses wildcard also";
4444 return -1;
4447 if (address_is_invalid_destination(to, 1)) {
4448 *msg = "destination is invalid";
4449 return -1;
4452 addressmap_register(from, tor_strdup(to), expires, addrmap_source,
4453 from_wildcard, to_wildcard);
4455 return 0;
4459 * Initialize the logs based on the configuration file.
4461 static int
4462 options_init_logs(const or_options_t *old_options, or_options_t *options,
4463 int validate_only)
4465 config_line_t *opt;
4466 int ok;
4467 smartlist_t *elts;
4468 int daemon =
4469 #ifdef _WIN32
4471 #else
4472 options->RunAsDaemon;
4473 #endif
4475 if (options->LogTimeGranularity <= 0) {
4476 log_warn(LD_CONFIG, "Log time granularity '%d' has to be positive.",
4477 options->LogTimeGranularity);
4478 return -1;
4479 } else if (1000 % options->LogTimeGranularity != 0 &&
4480 options->LogTimeGranularity % 1000 != 0) {
4481 int granularity = options->LogTimeGranularity;
4482 if (granularity < 40) {
4483 do granularity++;
4484 while (1000 % granularity != 0);
4485 } else if (granularity < 1000) {
4486 granularity = 1000 / granularity;
4487 while (1000 % granularity != 0)
4488 granularity--;
4489 granularity = 1000 / granularity;
4490 } else {
4491 granularity = 1000 * ((granularity / 1000) + 1);
4493 log_warn(LD_CONFIG, "Log time granularity '%d' has to be either a "
4494 "divisor or a multiple of 1 second. Changing to "
4495 "'%d'.",
4496 options->LogTimeGranularity, granularity);
4497 if (!validate_only)
4498 set_log_time_granularity(granularity);
4499 } else {
4500 if (!validate_only)
4501 set_log_time_granularity(options->LogTimeGranularity);
4504 ok = 1;
4505 elts = smartlist_new();
4507 for (opt = options->Logs; opt; opt = opt->next) {
4508 log_severity_list_t *severity;
4509 const char *cfg = opt->value;
4510 severity = tor_malloc_zero(sizeof(log_severity_list_t));
4511 if (parse_log_severity_config(&cfg, severity) < 0) {
4512 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
4513 opt->value);
4514 ok = 0; goto cleanup;
4517 smartlist_split_string(elts, cfg, NULL,
4518 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4520 if (smartlist_len(elts) == 0)
4521 smartlist_add(elts, tor_strdup("stdout"));
4523 if (smartlist_len(elts) == 1 &&
4524 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
4525 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
4526 int err = smartlist_len(elts) &&
4527 !strcasecmp(smartlist_get(elts,0), "stderr");
4528 if (!validate_only) {
4529 if (daemon) {
4530 log_warn(LD_CONFIG,
4531 "Can't log to %s with RunAsDaemon set; skipping stdout",
4532 err?"stderr":"stdout");
4533 } else {
4534 add_stream_log(severity, err?"<stderr>":"<stdout>",
4535 fileno(err?stderr:stdout));
4538 goto cleanup;
4540 if (smartlist_len(elts) == 1 &&
4541 !strcasecmp(smartlist_get(elts,0), "syslog")) {
4542 #ifdef HAVE_SYSLOG_H
4543 if (!validate_only) {
4544 add_syslog_log(severity);
4546 #else
4547 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
4548 #endif
4549 goto cleanup;
4552 if (smartlist_len(elts) == 2 &&
4553 !strcasecmp(smartlist_get(elts,0), "file")) {
4554 if (!validate_only) {
4555 char *fname = expand_filename(smartlist_get(elts, 1));
4556 /* Truncate if TruncateLogFile is set and we haven't seen this option
4557 line before. */
4558 int truncate = 0;
4559 if (options->TruncateLogFile) {
4560 truncate = 1;
4561 if (old_options) {
4562 config_line_t *opt2;
4563 for (opt2 = old_options->Logs; opt2; opt2 = opt2->next)
4564 if (!strcmp(opt->value, opt2->value)) {
4565 truncate = 0;
4566 break;
4570 if (add_file_log(severity, fname, truncate) < 0) {
4571 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
4572 opt->value, strerror(errno));
4573 ok = 0;
4575 tor_free(fname);
4577 goto cleanup;
4580 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
4581 opt->value);
4582 ok = 0; goto cleanup;
4584 cleanup:
4585 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4586 smartlist_clear(elts);
4587 tor_free(severity);
4589 smartlist_free(elts);
4591 if (ok && !validate_only)
4592 logs_set_domain_logging(options->LogMessageDomains);
4594 return ok?0:-1;
4597 /** Given a smartlist of SOCKS arguments to be passed to a transport
4598 * proxy in <b>args</b>, validate them and return -1 if they are
4599 * corrupted. Return 0 if they seem OK. */
4600 static int
4601 validate_transport_socks_arguments(const smartlist_t *args)
4603 char *socks_string = NULL;
4604 size_t socks_string_len;
4606 tor_assert(args);
4607 tor_assert(smartlist_len(args) > 0);
4609 SMARTLIST_FOREACH_BEGIN(args, const char *, s) {
4610 if (!string_is_key_value(LOG_WARN, s)) { /* items should be k=v items */
4611 log_warn(LD_CONFIG, "'%s' is not a k=v item.", s);
4612 return -1;
4614 } SMARTLIST_FOREACH_END(s);
4616 socks_string = pt_stringify_socks_args(args);
4617 if (!socks_string)
4618 return -1;
4620 socks_string_len = strlen(socks_string);
4621 tor_free(socks_string);
4623 if (socks_string_len > MAX_SOCKS5_AUTH_SIZE_TOTAL) {
4624 log_warn(LD_CONFIG, "SOCKS arguments can't be more than %u bytes (%lu).",
4625 MAX_SOCKS5_AUTH_SIZE_TOTAL,
4626 (unsigned long) socks_string_len);
4627 return -1;
4630 return 0;
4633 /** Deallocate a bridge_line_t structure. */
4634 /* private */ void
4635 bridge_line_free(bridge_line_t *bridge_line)
4637 if (!bridge_line)
4638 return;
4640 if (bridge_line->socks_args) {
4641 SMARTLIST_FOREACH(bridge_line->socks_args, char*, s, tor_free(s));
4642 smartlist_free(bridge_line->socks_args);
4644 tor_free(bridge_line->transport_name);
4645 tor_free(bridge_line);
4648 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4649 * if the line is well-formed, and -1 if it isn't. If
4650 * <b>validate_only</b> is 0, and the line is well-formed, then add
4651 * the bridge described in the line to our internal bridge list.
4653 * Bridge line format:
4654 * Bridge [transport] IP:PORT [id-fingerprint] [k=v] [k=v] ...
4656 /* private */ bridge_line_t *
4657 parse_bridge_line(const char *line)
4659 smartlist_t *items = NULL;
4660 char *addrport=NULL, *fingerprint=NULL;
4661 char *field=NULL;
4662 bridge_line_t *bridge_line = tor_malloc_zero(sizeof(bridge_line_t));
4664 items = smartlist_new();
4665 smartlist_split_string(items, line, NULL,
4666 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4667 if (smartlist_len(items) < 1) {
4668 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
4669 goto err;
4672 /* first field is either a transport name or addrport */
4673 field = smartlist_get(items, 0);
4674 smartlist_del_keeporder(items, 0);
4676 if (string_is_C_identifier(field)) {
4677 /* It's a transport name. */
4678 bridge_line->transport_name = field;
4679 if (smartlist_len(items) < 1) {
4680 log_warn(LD_CONFIG, "Too few items to Bridge line.");
4681 goto err;
4683 addrport = smartlist_get(items, 0); /* Next field is addrport then. */
4684 smartlist_del_keeporder(items, 0);
4685 } else {
4686 addrport = field;
4689 if (tor_addr_port_parse(LOG_INFO, addrport,
4690 &bridge_line->addr, &bridge_line->port, 443)<0) {
4691 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
4692 goto err;
4695 /* If transports are enabled, next field could be a fingerprint or a
4696 socks argument. If transports are disabled, next field must be
4697 a fingerprint. */
4698 if (smartlist_len(items)) {
4699 if (bridge_line->transport_name) { /* transports enabled: */
4700 field = smartlist_get(items, 0);
4701 smartlist_del_keeporder(items, 0);
4703 /* If it's a key=value pair, then it's a SOCKS argument for the
4704 transport proxy... */
4705 if (string_is_key_value(LOG_DEBUG, field)) {
4706 bridge_line->socks_args = smartlist_new();
4707 smartlist_add(bridge_line->socks_args, field);
4708 } else { /* ...otherwise, it's the bridge fingerprint. */
4709 fingerprint = field;
4712 } else { /* transports disabled: */
4713 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4717 /* Handle fingerprint, if it was provided. */
4718 if (fingerprint) {
4719 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4720 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
4721 goto err;
4723 if (base16_decode(bridge_line->digest, DIGEST_LEN,
4724 fingerprint, HEX_DIGEST_LEN)<0) {
4725 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
4726 goto err;
4730 /* If we are using transports, any remaining items in the smartlist
4731 should be k=v values. */
4732 if (bridge_line->transport_name && smartlist_len(items)) {
4733 if (!bridge_line->socks_args)
4734 bridge_line->socks_args = smartlist_new();
4736 /* append remaining items of 'items' to 'socks_args' */
4737 smartlist_add_all(bridge_line->socks_args, items);
4738 smartlist_clear(items);
4740 tor_assert(smartlist_len(bridge_line->socks_args) > 0);
4743 if (bridge_line->socks_args) {
4744 if (validate_transport_socks_arguments(bridge_line->socks_args) < 0)
4745 goto err;
4748 goto done;
4750 err:
4751 bridge_line_free(bridge_line);
4752 bridge_line = NULL;
4754 done:
4755 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4756 smartlist_free(items);
4757 tor_free(addrport);
4758 tor_free(fingerprint);
4760 return bridge_line;
4763 /** Read the contents of a ClientTransportPlugin line from
4764 * <b>line</b>. Return 0 if the line is well-formed, and -1 if it
4765 * isn't.
4767 * If <b>validate_only</b> is 0, the line is well-formed, and the
4768 * transport is needed by some bridge:
4769 * - If it's an external proxy line, add the transport described in the line to
4770 * our internal transport list.
4771 * - If it's a managed proxy line, launch the managed proxy. */
4772 static int
4773 parse_client_transport_line(const or_options_t *options,
4774 const char *line, int validate_only)
4776 smartlist_t *items = NULL;
4777 int r;
4778 char *field2=NULL;
4780 const char *transports=NULL;
4781 smartlist_t *transport_list=NULL;
4782 char *addrport=NULL;
4783 tor_addr_t addr;
4784 uint16_t port = 0;
4785 int socks_ver=PROXY_NONE;
4787 /* managed proxy options */
4788 int is_managed=0;
4789 char **proxy_argv=NULL;
4790 char **tmp=NULL;
4791 int proxy_argc, i;
4792 int is_useless_proxy=1;
4794 int line_length;
4796 items = smartlist_new();
4797 smartlist_split_string(items, line, NULL,
4798 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4800 line_length = smartlist_len(items);
4801 if (line_length < 3) {
4802 log_warn(LD_CONFIG, "Too few arguments on ClientTransportPlugin line.");
4803 goto err;
4806 /* Get the first line element, split it to commas into
4807 transport_list (in case it's multiple transports) and validate
4808 the transport names. */
4809 transports = smartlist_get(items, 0);
4810 transport_list = smartlist_new();
4811 smartlist_split_string(transport_list, transports, ",",
4812 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
4813 SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
4814 /* validate transport names */
4815 if (!string_is_C_identifier(transport_name)) {
4816 log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
4817 transport_name);
4818 goto err;
4821 /* see if we actually need the transports provided by this proxy */
4822 if (!validate_only && transport_is_needed(transport_name))
4823 is_useless_proxy = 0;
4824 } SMARTLIST_FOREACH_END(transport_name);
4826 /* field2 is either a SOCKS version or "exec" */
4827 field2 = smartlist_get(items, 1);
4829 if (!strcmp(field2,"socks4")) {
4830 socks_ver = PROXY_SOCKS4;
4831 } else if (!strcmp(field2,"socks5")) {
4832 socks_ver = PROXY_SOCKS5;
4833 } else if (!strcmp(field2,"exec")) {
4834 is_managed=1;
4835 } else {
4836 log_warn(LD_CONFIG, "Strange ClientTransportPlugin field '%s'.",
4837 field2);
4838 goto err;
4841 if (is_managed && options->Sandbox) {
4842 log_warn(LD_CONFIG, "Managed proxies are not compatible with Sandbox mode."
4843 "(ClientTransportPlugin line was %s)", escaped(line));
4844 goto err;
4847 if (is_managed) { /* managed */
4848 if (!validate_only && is_useless_proxy) {
4849 log_notice(LD_GENERAL, "Pluggable transport proxy (%s) does not provide "
4850 "any needed transports and will not be launched.", line);
4853 /* If we are not just validating, use the rest of the line as the
4854 argv of the proxy to be launched. Also, make sure that we are
4855 only launching proxies that contribute useful transports. */
4856 if (!validate_only && !is_useless_proxy) {
4857 proxy_argc = line_length-2;
4858 tor_assert(proxy_argc > 0);
4859 proxy_argv = tor_calloc(sizeof(char *), (proxy_argc + 1));
4860 tmp = proxy_argv;
4861 for (i=0;i<proxy_argc;i++) { /* store arguments */
4862 *tmp++ = smartlist_get(items, 2);
4863 smartlist_del_keeporder(items, 2);
4865 *tmp = NULL; /*terminated with NULL, just like execve() likes it*/
4867 /* kickstart the thing */
4868 pt_kickstart_client_proxy(transport_list, proxy_argv);
4870 } else { /* external */
4871 if (smartlist_len(transport_list) != 1) {
4872 log_warn(LD_CONFIG, "You can't have an external proxy with "
4873 "more than one transports.");
4874 goto err;
4877 addrport = smartlist_get(items, 2);
4879 if (tor_addr_port_lookup(addrport, &addr, &port)<0) {
4880 log_warn(LD_CONFIG, "Error parsing transport "
4881 "address '%s'", addrport);
4882 goto err;
4884 if (!port) {
4885 log_warn(LD_CONFIG,
4886 "Transport address '%s' has no port.", addrport);
4887 goto err;
4890 if (!validate_only) {
4891 transport_add_from_config(&addr, port, smartlist_get(transport_list, 0),
4892 socks_ver);
4894 log_info(LD_DIR, "Transport '%s' found at %s",
4895 transports, fmt_addrport(&addr, port));
4899 r = 0;
4900 goto done;
4902 err:
4903 r = -1;
4905 done:
4906 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4907 smartlist_free(items);
4908 if (transport_list) {
4909 SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
4910 smartlist_free(transport_list);
4913 return r;
4916 /** Given a ServerTransportListenAddr <b>line</b>, return its
4917 * <address:port> string. Return NULL if the line was not
4918 * well-formed.
4920 * If <b>transport</b> is set, return NULL if the line is not
4921 * referring to <b>transport</b>.
4923 * The returned string is allocated on the heap and it's the
4924 * responsibility of the caller to free it. */
4925 static char *
4926 get_bindaddr_from_transport_listen_line(const char *line,const char *transport)
4928 smartlist_t *items = NULL;
4929 const char *parsed_transport = NULL;
4930 char *addrport = NULL;
4931 tor_addr_t addr;
4932 uint16_t port = 0;
4934 items = smartlist_new();
4935 smartlist_split_string(items, line, NULL,
4936 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4938 if (smartlist_len(items) < 2) {
4939 log_warn(LD_CONFIG,"Too few arguments on ServerTransportListenAddr line.");
4940 goto err;
4943 parsed_transport = smartlist_get(items, 0);
4944 addrport = tor_strdup(smartlist_get(items, 1));
4946 /* If 'transport' is given, check if it matches the one on the line */
4947 if (transport && strcmp(transport, parsed_transport))
4948 goto err;
4950 /* Validate addrport */
4951 if (tor_addr_port_parse(LOG_WARN, addrport, &addr, &port, -1)<0) {
4952 log_warn(LD_CONFIG, "Error parsing ServerTransportListenAddr "
4953 "address '%s'", addrport);
4954 goto err;
4957 goto done;
4959 err:
4960 tor_free(addrport);
4961 addrport = NULL;
4963 done:
4964 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4965 smartlist_free(items);
4967 return addrport;
4970 /** Given a ServerTransportOptions <b>line</b>, return a smartlist
4971 * with the options. Return NULL if the line was not well-formed.
4973 * If <b>transport</b> is set, return NULL if the line is not
4974 * referring to <b>transport</b>.
4976 * The returned smartlist and its strings are allocated on the heap
4977 * and it's the responsibility of the caller to free it. */
4978 smartlist_t *
4979 get_options_from_transport_options_line(const char *line,const char *transport)
4981 smartlist_t *items = smartlist_new();
4982 smartlist_t *options = smartlist_new();
4983 const char *parsed_transport = NULL;
4985 smartlist_split_string(items, line, NULL,
4986 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4988 if (smartlist_len(items) < 2) {
4989 log_warn(LD_CONFIG,"Too few arguments on ServerTransportOptions line.");
4990 goto err;
4993 parsed_transport = smartlist_get(items, 0);
4994 /* If 'transport' is given, check if it matches the one on the line */
4995 if (transport && strcmp(transport, parsed_transport))
4996 goto err;
4998 SMARTLIST_FOREACH_BEGIN(items, const char *, option) {
4999 if (option_sl_idx == 0) /* skip the transport field (first field)*/
5000 continue;
5002 /* validate that it's a k=v value */
5003 if (!string_is_key_value(LOG_WARN, option)) {
5004 log_warn(LD_CONFIG, "%s is not a k=v value.", escaped(option));
5005 goto err;
5008 /* add it to the options smartlist */
5009 smartlist_add(options, tor_strdup(option));
5010 log_debug(LD_CONFIG, "Added %s to the list of options", escaped(option));
5011 } SMARTLIST_FOREACH_END(option);
5013 goto done;
5015 err:
5016 SMARTLIST_FOREACH(options, char*, s, tor_free(s));
5017 smartlist_free(options);
5018 options = NULL;
5020 done:
5021 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5022 smartlist_free(items);
5024 return options;
5027 /** Given the name of a pluggable transport in <b>transport</b>, check
5028 * the configuration file to see if the user has explicitly asked for
5029 * it to listen on a specific port. Return a <address:port> string if
5030 * so, otherwise NULL. */
5031 char *
5032 get_transport_bindaddr_from_config(const char *transport)
5034 config_line_t *cl;
5035 const or_options_t *options = get_options();
5037 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
5038 char *bindaddr =
5039 get_bindaddr_from_transport_listen_line(cl->value, transport);
5040 if (bindaddr)
5041 return bindaddr;
5044 return NULL;
5047 /** Given the name of a pluggable transport in <b>transport</b>, check
5048 * the configuration file to see if the user has asked us to pass any
5049 * parameters to the pluggable transport. Return a smartlist
5050 * containing the parameters, otherwise NULL. */
5051 smartlist_t *
5052 get_options_for_server_transport(const char *transport)
5054 config_line_t *cl;
5055 const or_options_t *options = get_options();
5057 for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
5058 smartlist_t *options_sl =
5059 get_options_from_transport_options_line(cl->value, transport);
5060 if (options_sl)
5061 return options_sl;
5064 return NULL;
5067 /** Read the contents of a ServerTransportPlugin line from
5068 * <b>line</b>. Return 0 if the line is well-formed, and -1 if it
5069 * isn't.
5070 * If <b>validate_only</b> is 0, the line is well-formed, and it's a
5071 * managed proxy line, launch the managed proxy. */
5072 static int
5073 parse_server_transport_line(const or_options_t *options,
5074 const char *line, int validate_only)
5076 smartlist_t *items = NULL;
5077 int r;
5078 const char *transports=NULL;
5079 smartlist_t *transport_list=NULL;
5080 char *type=NULL;
5081 char *addrport=NULL;
5082 tor_addr_t addr;
5083 uint16_t port = 0;
5085 /* managed proxy options */
5086 int is_managed=0;
5087 char **proxy_argv=NULL;
5088 char **tmp=NULL;
5089 int proxy_argc,i;
5091 int line_length;
5093 items = smartlist_new();
5094 smartlist_split_string(items, line, NULL,
5095 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5097 line_length = smartlist_len(items);
5098 if (line_length < 3) {
5099 log_warn(LD_CONFIG, "Too few arguments on ServerTransportPlugin line.");
5100 goto err;
5103 /* Get the first line element, split it to commas into
5104 transport_list (in case it's multiple transports) and validate
5105 the transport names. */
5106 transports = smartlist_get(items, 0);
5107 transport_list = smartlist_new();
5108 smartlist_split_string(transport_list, transports, ",",
5109 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
5110 SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
5111 if (!string_is_C_identifier(transport_name)) {
5112 log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
5113 transport_name);
5114 goto err;
5116 } SMARTLIST_FOREACH_END(transport_name);
5118 type = smartlist_get(items, 1);
5120 if (!strcmp(type, "exec")) {
5121 is_managed=1;
5122 } else if (!strcmp(type, "proxy")) {
5123 is_managed=0;
5124 } else {
5125 log_warn(LD_CONFIG, "Strange ServerTransportPlugin type '%s'", type);
5126 goto err;
5129 if (is_managed && options->Sandbox) {
5130 log_warn(LD_CONFIG, "Managed proxies are not compatible with Sandbox mode."
5131 "(ServerTransportPlugin line was %s)", escaped(line));
5132 goto err;
5135 if (is_managed) { /* managed */
5136 if (!validate_only) {
5137 proxy_argc = line_length-2;
5138 tor_assert(proxy_argc > 0);
5139 proxy_argv = tor_calloc(sizeof(char *), (proxy_argc + 1));
5140 tmp = proxy_argv;
5142 for (i=0;i<proxy_argc;i++) { /* store arguments */
5143 *tmp++ = smartlist_get(items, 2);
5144 smartlist_del_keeporder(items, 2);
5146 *tmp = NULL; /*terminated with NULL, just like execve() likes it*/
5148 /* kickstart the thing */
5149 pt_kickstart_server_proxy(transport_list, proxy_argv);
5151 } else { /* external */
5152 if (smartlist_len(transport_list) != 1) {
5153 log_warn(LD_CONFIG, "You can't have an external proxy with "
5154 "more than one transports.");
5155 goto err;
5158 addrport = smartlist_get(items, 2);
5160 if (tor_addr_port_lookup(addrport, &addr, &port)<0) {
5161 log_warn(LD_CONFIG, "Error parsing transport "
5162 "address '%s'", addrport);
5163 goto err;
5165 if (!port) {
5166 log_warn(LD_CONFIG,
5167 "Transport address '%s' has no port.", addrport);
5168 goto err;
5171 if (!validate_only) {
5172 log_info(LD_DIR, "Server transport '%s' at %s.",
5173 transports, fmt_addrport(&addr, port));
5177 r = 0;
5178 goto done;
5180 err:
5181 r = -1;
5183 done:
5184 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5185 smartlist_free(items);
5186 if (transport_list) {
5187 SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
5188 smartlist_free(transport_list);
5191 return r;
5194 /** Read the contents of a DirAuthority line from <b>line</b>. If
5195 * <b>validate_only</b> is 0, and the line is well-formed, and it
5196 * shares any bits with <b>required_type</b> or <b>required_type</b>
5197 * is 0, then add the dirserver described in the line (minus whatever
5198 * bits it's missing) as a valid authority. Return 0 on success,
5199 * or -1 if the line isn't well-formed or if we can't add it. */
5200 static int
5201 parse_dir_authority_line(const char *line, dirinfo_type_t required_type,
5202 int validate_only)
5204 smartlist_t *items = NULL;
5205 int r;
5206 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
5207 uint16_t dir_port = 0, or_port = 0;
5208 char digest[DIGEST_LEN];
5209 char v3_digest[DIGEST_LEN];
5210 dirinfo_type_t type = 0;
5211 double weight = 1.0;
5213 items = smartlist_new();
5214 smartlist_split_string(items, line, NULL,
5215 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5216 if (smartlist_len(items) < 1) {
5217 log_warn(LD_CONFIG, "No arguments on DirAuthority line.");
5218 goto err;
5221 if (is_legal_nickname(smartlist_get(items, 0))) {
5222 nickname = smartlist_get(items, 0);
5223 smartlist_del_keeporder(items, 0);
5226 while (smartlist_len(items)) {
5227 char *flag = smartlist_get(items, 0);
5228 if (TOR_ISDIGIT(flag[0]))
5229 break;
5230 if (!strcasecmp(flag, "hs") ||
5231 !strcasecmp(flag, "no-hs")) {
5232 log_warn(LD_CONFIG, "The DirAuthority options 'hs' and 'no-hs' are "
5233 "obsolete; you don't need them any more.");
5234 } else if (!strcasecmp(flag, "bridge")) {
5235 type |= BRIDGE_DIRINFO;
5236 } else if (!strcasecmp(flag, "no-v2")) {
5237 /* obsolete, but may still be contained in DirAuthority lines generated
5238 by various tools */;
5239 } else if (!strcasecmpstart(flag, "orport=")) {
5240 int ok;
5241 char *portstring = flag + strlen("orport=");
5242 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
5243 if (!ok)
5244 log_warn(LD_CONFIG, "Invalid orport '%s' on DirAuthority line.",
5245 portstring);
5246 } else if (!strcmpstart(flag, "weight=")) {
5247 int ok;
5248 const char *wstring = flag + strlen("weight=");
5249 weight = tor_parse_double(wstring, 0, UINT64_MAX, &ok, NULL);
5250 if (!ok) {
5251 log_warn(LD_CONFIG, "Invalid weight '%s' on DirAuthority line.",flag);
5252 weight=1.0;
5254 } else if (!strcasecmpstart(flag, "v3ident=")) {
5255 char *idstr = flag + strlen("v3ident=");
5256 if (strlen(idstr) != HEX_DIGEST_LEN ||
5257 base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
5258 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirAuthority line",
5259 flag);
5260 } else {
5261 type |= V3_DIRINFO|EXTRAINFO_DIRINFO|MICRODESC_DIRINFO;
5263 } else {
5264 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirAuthority line",
5265 flag);
5267 tor_free(flag);
5268 smartlist_del_keeporder(items, 0);
5271 if (smartlist_len(items) < 2) {
5272 log_warn(LD_CONFIG, "Too few arguments to DirAuthority line.");
5273 goto err;
5275 addrport = smartlist_get(items, 0);
5276 smartlist_del_keeporder(items, 0);
5277 if (addr_port_lookup(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
5278 log_warn(LD_CONFIG, "Error parsing DirAuthority address '%s'", addrport);
5279 goto err;
5281 if (!dir_port) {
5282 log_warn(LD_CONFIG, "Missing port in DirAuthority address '%s'",addrport);
5283 goto err;
5286 fingerprint = smartlist_join_strings(items, "", 0, NULL);
5287 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
5288 log_warn(LD_CONFIG, "Key digest '%s' for DirAuthority is wrong length %d.",
5289 fingerprint, (int)strlen(fingerprint));
5290 goto err;
5292 if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
5293 /* a known bad fingerprint. refuse to use it. We can remove this
5294 * clause once Tor 0.1.2.17 is obsolete. */
5295 log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
5296 "torrc file (%s), or reinstall Tor and use the default torrc.",
5297 get_torrc_fname(0));
5298 goto err;
5300 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
5301 log_warn(LD_CONFIG, "Unable to decode DirAuthority key digest.");
5302 goto err;
5305 if (!validate_only && (!required_type || required_type & type)) {
5306 dir_server_t *ds;
5307 if (required_type)
5308 type &= required_type; /* pare down what we think of them as an
5309 * authority for. */
5310 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
5311 address, (int)dir_port, (char*)smartlist_get(items,0));
5312 if (!(ds = trusted_dir_server_new(nickname, address, dir_port, or_port,
5313 digest, v3_digest, type, weight)))
5314 goto err;
5315 dir_server_add(ds);
5318 r = 0;
5319 goto done;
5321 err:
5322 r = -1;
5324 done:
5325 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5326 smartlist_free(items);
5327 tor_free(addrport);
5328 tor_free(address);
5329 tor_free(nickname);
5330 tor_free(fingerprint);
5331 return r;
5334 /** Read the contents of a FallbackDir line from <b>line</b>. If
5335 * <b>validate_only</b> is 0, and the line is well-formed, then add the
5336 * dirserver described in the line as a fallback directory. Return 0 on
5337 * success, or -1 if the line isn't well-formed or if we can't add it. */
5338 static int
5339 parse_dir_fallback_line(const char *line,
5340 int validate_only)
5342 int r = -1;
5343 smartlist_t *items = smartlist_new(), *positional = smartlist_new();
5344 int orport = -1;
5345 uint16_t dirport;
5346 tor_addr_t addr;
5347 int ok;
5348 char id[DIGEST_LEN];
5349 char *address=NULL;
5350 double weight=1.0;
5352 memset(id, 0, sizeof(id));
5353 smartlist_split_string(items, line, NULL,
5354 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5355 SMARTLIST_FOREACH_BEGIN(items, const char *, cp) {
5356 const char *eq = strchr(cp, '=');
5357 ok = 1;
5358 if (! eq) {
5359 smartlist_add(positional, (char*)cp);
5360 continue;
5362 if (!strcmpstart(cp, "orport=")) {
5363 orport = (int)tor_parse_long(cp+strlen("orport="), 10,
5364 1, 65535, &ok, NULL);
5365 } else if (!strcmpstart(cp, "id=")) {
5366 ok = !base16_decode(id, DIGEST_LEN,
5367 cp+strlen("id="), strlen(cp)-strlen("id="));
5368 } else if (!strcmpstart(cp, "weight=")) {
5369 int ok;
5370 const char *wstring = cp + strlen("weight=");
5371 weight = tor_parse_double(wstring, 0, UINT64_MAX, &ok, NULL);
5372 if (!ok) {
5373 log_warn(LD_CONFIG, "Invalid weight '%s' on FallbackDir line.", cp);
5374 weight=1.0;
5378 if (!ok) {
5379 log_warn(LD_CONFIG, "Bad FallbackDir option %s", escaped(cp));
5380 goto end;
5382 } SMARTLIST_FOREACH_END(cp);
5384 if (smartlist_len(positional) != 1) {
5385 log_warn(LD_CONFIG, "Couldn't parse FallbackDir line %s", escaped(line));
5386 goto end;
5389 if (tor_digest_is_zero(id)) {
5390 log_warn(LD_CONFIG, "Missing identity on FallbackDir line");
5391 goto end;
5394 if (orport <= 0) {
5395 log_warn(LD_CONFIG, "Missing orport on FallbackDir line");
5396 goto end;
5399 if (tor_addr_port_split(LOG_INFO, smartlist_get(positional, 0),
5400 &address, &dirport) < 0 ||
5401 tor_addr_parse(&addr, address)<0) {
5402 log_warn(LD_CONFIG, "Couldn't parse address:port %s on FallbackDir line",
5403 (const char*)smartlist_get(positional, 0));
5404 goto end;
5407 if (!validate_only) {
5408 dir_server_t *ds;
5409 ds = fallback_dir_server_new(&addr, dirport, orport, id, weight);
5410 if (!ds) {
5411 log_warn(LD_CONFIG, "Couldn't create FallbackDir %s", escaped(line));
5412 goto end;
5414 dir_server_add(ds);
5417 r = 0;
5419 end:
5420 SMARTLIST_FOREACH(items, char *, cp, tor_free(cp));
5421 smartlist_free(items);
5422 smartlist_free(positional);
5423 tor_free(address);
5424 return r;
5427 /** Allocate and return a new port_cfg_t with reasonable defaults. */
5428 static port_cfg_t *
5429 port_cfg_new(void)
5431 port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t));
5432 cfg->ipv4_traffic = 1;
5433 cfg->cache_ipv4_answers = 1;
5434 cfg->prefer_ipv6_virtaddr = 1;
5435 return cfg;
5438 /** Free all storage held in <b>port</b> */
5439 static void
5440 port_cfg_free(port_cfg_t *port)
5442 tor_free(port);
5445 /** Warn for every port in <b>ports</b> of type <b>listener_type</b> that is
5446 * on a publicly routable address. */
5447 static void
5448 warn_nonlocal_client_ports(const smartlist_t *ports, const char *portname,
5449 int listener_type)
5451 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
5452 if (port->type != listener_type)
5453 continue;
5454 if (port->is_unix_addr) {
5455 /* Unix sockets aren't accessible over a network. */
5456 } else if (!tor_addr_is_internal(&port->addr, 1)) {
5457 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
5458 "Other people on the Internet might find your computer and "
5459 "use it as an open proxy. Please don't allow this unless you "
5460 "have a good reason.",
5461 fmt_addrport(&port->addr, port->port), portname);
5462 } else if (!tor_addr_is_loopback(&port->addr)) {
5463 log_notice(LD_CONFIG, "You configured a non-loopback address '%s' "
5464 "for %sPort. This allows everybody on your local network to "
5465 "use your machine as a proxy. Make sure this is what you "
5466 "wanted.",
5467 fmt_addrport(&port->addr, port->port), portname);
5469 } SMARTLIST_FOREACH_END(port);
5472 /** Warn for every Extended ORPort port in <b>ports</b> that is on a
5473 * publicly routable address. */
5474 static void
5475 warn_nonlocal_ext_orports(const smartlist_t *ports, const char *portname)
5477 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
5478 if (port->type != CONN_TYPE_EXT_OR_LISTENER)
5479 continue;
5480 if (port->is_unix_addr)
5481 continue;
5482 /* XXX maybe warn even if address is RFC1918? */
5483 if (!tor_addr_is_internal(&port->addr, 1)) {
5484 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
5485 "This is not advised; this address is supposed to only be "
5486 "exposed on localhost so that your pluggable transport "
5487 "proxies can connect to it.",
5488 fmt_addrport(&port->addr, port->port), portname);
5490 } SMARTLIST_FOREACH_END(port);
5493 /** Given a list of port_cfg_t in <b>ports</b>, warn any controller port there
5494 * is listening on any non-loopback address. If <b>forbid</b> is true,
5495 * then emit a stronger warning and remove the port from the list.
5497 static void
5498 warn_nonlocal_controller_ports(smartlist_t *ports, unsigned forbid)
5500 int warned = 0;
5501 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
5502 if (port->type != CONN_TYPE_CONTROL_LISTENER)
5503 continue;
5504 if (port->is_unix_addr)
5505 continue;
5506 if (!tor_addr_is_loopback(&port->addr)) {
5507 if (forbid) {
5508 if (!warned)
5509 log_warn(LD_CONFIG,
5510 "You have a ControlPort set to accept "
5511 "unauthenticated connections from a non-local address. "
5512 "This means that programs not running on your computer "
5513 "can reconfigure your Tor, without even having to guess a "
5514 "password. That's so bad that I'm closing your ControlPort "
5515 "for you. If you need to control your Tor remotely, try "
5516 "enabling authentication and using a tool like stunnel or "
5517 "ssh to encrypt remote access.");
5518 warned = 1;
5519 port_cfg_free(port);
5520 SMARTLIST_DEL_CURRENT(ports, port);
5521 } else {
5522 log_warn(LD_CONFIG, "You have a ControlPort set to accept "
5523 "connections from a non-local address. This means that "
5524 "programs not running on your computer can reconfigure your "
5525 "Tor. That's pretty bad, since the controller "
5526 "protocol isn't encrypted! Maybe you should just listen on "
5527 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
5528 "remote connections to your control port.");
5529 return; /* No point in checking the rest */
5532 } SMARTLIST_FOREACH_END(port);
5535 #define CL_PORT_NO_OPTIONS (1u<<0)
5536 #define CL_PORT_WARN_NONLOCAL (1u<<1)
5537 #define CL_PORT_ALLOW_EXTRA_LISTENADDR (1u<<2)
5538 #define CL_PORT_SERVER_OPTIONS (1u<<3)
5539 #define CL_PORT_FORBID_NONLOCAL (1u<<4)
5540 #define CL_PORT_TAKES_HOSTNAMES (1u<<5)
5543 * Parse port configuration for a single port type.
5545 * Read entries of the "FooPort" type from the list <b>ports</b>, and
5546 * entries of the "FooListenAddress" type from the list
5547 * <b>listenaddrs</b>. Two syntaxes are supported: a legacy syntax
5548 * where FooPort is at most a single entry containing a port number and
5549 * where FooListenAddress has any number of address:port combinations;
5550 * and a new syntax where there are no FooListenAddress entries and
5551 * where FooPort can have any number of entries of the format
5552 * "[Address:][Port] IsolationOptions".
5554 * In log messages, describe the port type as <b>portname</b>.
5556 * If no address is specified, default to <b>defaultaddr</b>. If no
5557 * FooPort is given, default to defaultport (if 0, there is no default).
5559 * If CL_PORT_NO_OPTIONS is set in <b>flags</b>, do not allow stream
5560 * isolation options in the FooPort entries.
5562 * If CL_PORT_WARN_NONLOCAL is set in <b>flags</b>, warn if any of the
5563 * ports are not on a local address. If CL_PORT_FORBID_NONLOCAL is set,
5564 * this is a contrl port with no password set: don't even allow it.
5566 * Unless CL_PORT_ALLOW_EXTRA_LISTENADDR is set in <b>flags</b>, warn
5567 * if FooListenAddress is set but FooPort is 0.
5569 * If CL_PORT_SERVER_OPTIONS is set in <b>flags</b>, do not allow stream
5570 * isolation options in the FooPort entries; instead allow the
5571 * server-port option set.
5573 * If CL_PORT_TAKES_HOSTNAMES is set in <b>flags</b>, allow the options
5574 * {No,}IPv{4,6}Traffic.
5576 * On success, if <b>out</b> is given, add a new port_cfg_t entry to
5577 * <b>out</b> for every port that the client should listen on. Return 0
5578 * on success, -1 on failure.
5580 static int
5581 parse_port_config(smartlist_t *out,
5582 const config_line_t *ports,
5583 const config_line_t *listenaddrs,
5584 const char *portname,
5585 int listener_type,
5586 const char *defaultaddr,
5587 int defaultport,
5588 unsigned flags)
5590 smartlist_t *elts;
5591 int retval = -1;
5592 const unsigned is_control = (listener_type == CONN_TYPE_CONTROL_LISTENER);
5593 const unsigned is_ext_orport = (listener_type == CONN_TYPE_EXT_OR_LISTENER);
5594 const unsigned allow_no_options = flags & CL_PORT_NO_OPTIONS;
5595 const unsigned use_server_options = flags & CL_PORT_SERVER_OPTIONS;
5596 const unsigned warn_nonlocal = flags & CL_PORT_WARN_NONLOCAL;
5597 const unsigned forbid_nonlocal = flags & CL_PORT_FORBID_NONLOCAL;
5598 const unsigned allow_spurious_listenaddr =
5599 flags & CL_PORT_ALLOW_EXTRA_LISTENADDR;
5600 const unsigned takes_hostnames = flags & CL_PORT_TAKES_HOSTNAMES;
5601 int got_zero_port=0, got_nonzero_port=0;
5603 /* FooListenAddress is deprecated; let's make it work like it used to work,
5604 * though. */
5605 if (listenaddrs) {
5606 int mainport = defaultport;
5608 if (ports && ports->next) {
5609 log_warn(LD_CONFIG, "%sListenAddress can't be used when there are "
5610 "multiple %sPort lines", portname, portname);
5611 return -1;
5612 } else if (ports) {
5613 if (!strcmp(ports->value, "auto")) {
5614 mainport = CFG_AUTO_PORT;
5615 } else {
5616 int ok;
5617 mainport = (int)tor_parse_long(ports->value, 10, 0, 65535, &ok, NULL);
5618 if (!ok) {
5619 log_warn(LD_CONFIG, "%sListenAddress can only be used with a single "
5620 "%sPort with value \"auto\" or 1-65535 and no options set.",
5621 portname, portname);
5622 return -1;
5627 if (mainport == 0) {
5628 if (allow_spurious_listenaddr)
5629 return 1; /*DOCDOC*/
5630 log_warn(LD_CONFIG, "%sPort must be defined if %sListenAddress is used",
5631 portname, portname);
5632 return -1;
5635 if (use_server_options && out) {
5636 /* Add a no_listen port. */
5637 port_cfg_t *cfg = port_cfg_new();
5638 cfg->type = listener_type;
5639 cfg->port = mainport;
5640 tor_addr_make_unspec(&cfg->addr); /* Server ports default to 0.0.0.0 */
5641 cfg->no_listen = 1;
5642 cfg->bind_ipv4_only = 1;
5643 cfg->ipv4_traffic = 1;
5644 cfg->prefer_ipv6_virtaddr = 1;
5645 smartlist_add(out, cfg);
5648 for (; listenaddrs; listenaddrs = listenaddrs->next) {
5649 tor_addr_t addr;
5650 uint16_t port = 0;
5651 if (tor_addr_port_lookup(listenaddrs->value, &addr, &port) < 0) {
5652 log_warn(LD_CONFIG, "Unable to parse %sListenAddress '%s'",
5653 portname, listenaddrs->value);
5654 return -1;
5656 if (out) {
5657 port_cfg_t *cfg = port_cfg_new();
5658 cfg->type = listener_type;
5659 cfg->port = port ? port : mainport;
5660 tor_addr_copy(&cfg->addr, &addr);
5661 cfg->session_group = SESSION_GROUP_UNSET;
5662 cfg->isolation_flags = ISO_DEFAULT;
5663 cfg->no_advertise = 1;
5664 smartlist_add(out, cfg);
5668 if (warn_nonlocal && out) {
5669 if (is_control)
5670 warn_nonlocal_controller_ports(out, forbid_nonlocal);
5671 else if (is_ext_orport)
5672 warn_nonlocal_ext_orports(out, portname);
5673 else
5674 warn_nonlocal_client_ports(out, portname, listener_type);
5676 return 0;
5677 } /* end if (listenaddrs) */
5679 /* No ListenAddress lines. If there's no FooPort, then maybe make a default
5680 * one. */
5681 if (! ports) {
5682 if (defaultport && out) {
5683 port_cfg_t *cfg = port_cfg_new();
5684 cfg->type = listener_type;
5685 cfg->port = defaultport;
5686 tor_addr_parse(&cfg->addr, defaultaddr);
5687 cfg->session_group = SESSION_GROUP_UNSET;
5688 cfg->isolation_flags = ISO_DEFAULT;
5689 smartlist_add(out, cfg);
5691 return 0;
5694 /* At last we can actually parse the FooPort lines. The syntax is:
5695 * [Addr:](Port|auto) [Options].*/
5696 elts = smartlist_new();
5698 for (; ports; ports = ports->next) {
5699 tor_addr_t addr;
5700 int port;
5701 int sessiongroup = SESSION_GROUP_UNSET;
5702 unsigned isolation = ISO_DEFAULT;
5703 int prefer_no_auth = 0;
5705 char *addrport;
5706 uint16_t ptmp=0;
5707 int ok;
5708 int no_listen = 0, no_advertise = 0, all_addrs = 0,
5709 bind_ipv4_only = 0, bind_ipv6_only = 0,
5710 ipv4_traffic = 1, ipv6_traffic = 0, prefer_ipv6 = 0,
5711 cache_ipv4 = 1, use_cached_ipv4 = 0,
5712 cache_ipv6 = 0, use_cached_ipv6 = 0,
5713 prefer_ipv6_automap = 1;
5715 smartlist_split_string(elts, ports->value, NULL,
5716 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
5717 if (smartlist_len(elts) == 0) {
5718 log_warn(LD_CONFIG, "Invalid %sPort line with no value", portname);
5719 goto err;
5722 if (allow_no_options && smartlist_len(elts) > 1) {
5723 log_warn(LD_CONFIG, "Too many options on %sPort line", portname);
5724 goto err;
5727 /* Now parse the addr/port value */
5728 addrport = smartlist_get(elts, 0);
5729 if (!strcmp(addrport, "auto")) {
5730 port = CFG_AUTO_PORT;
5731 tor_addr_parse(&addr, defaultaddr);
5732 } else if (!strcasecmpend(addrport, ":auto")) {
5733 char *addrtmp = tor_strndup(addrport, strlen(addrport)-5);
5734 port = CFG_AUTO_PORT;
5735 if (tor_addr_port_lookup(addrtmp, &addr, &ptmp)<0 || ptmp) {
5736 log_warn(LD_CONFIG, "Invalid address '%s' for %sPort",
5737 escaped(addrport), portname);
5738 tor_free(addrtmp);
5739 goto err;
5741 } else {
5742 /* Try parsing integer port before address, because, who knows?
5743 "9050" might be a valid address. */
5744 port = (int) tor_parse_long(addrport, 10, 0, 65535, &ok, NULL);
5745 if (ok) {
5746 tor_addr_parse(&addr, defaultaddr);
5747 } else if (tor_addr_port_lookup(addrport, &addr, &ptmp) == 0) {
5748 if (ptmp == 0) {
5749 log_warn(LD_CONFIG, "%sPort line has address but no port", portname);
5750 goto err;
5752 port = ptmp;
5753 } else {
5754 log_warn(LD_CONFIG, "Couldn't parse address '%s' for %sPort",
5755 escaped(addrport), portname);
5756 goto err;
5760 /* Now parse the rest of the options, if any. */
5761 if (use_server_options) {
5762 /* This is a server port; parse advertising options */
5763 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
5764 if (elt_sl_idx == 0)
5765 continue; /* Skip addr:port */
5767 if (!strcasecmp(elt, "NoAdvertise")) {
5768 no_advertise = 1;
5769 } else if (!strcasecmp(elt, "NoListen")) {
5770 no_listen = 1;
5771 #if 0
5772 /* not implemented yet. */
5773 } else if (!strcasecmp(elt, "AllAddrs")) {
5775 all_addrs = 1;
5776 #endif
5777 } else if (!strcasecmp(elt, "IPv4Only")) {
5778 bind_ipv4_only = 1;
5779 } else if (!strcasecmp(elt, "IPv6Only")) {
5780 bind_ipv6_only = 1;
5781 } else {
5782 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
5783 portname, escaped(elt));
5785 } SMARTLIST_FOREACH_END(elt);
5787 if (no_advertise && no_listen) {
5788 log_warn(LD_CONFIG, "Tried to set both NoListen and NoAdvertise "
5789 "on %sPort line '%s'",
5790 portname, escaped(ports->value));
5791 goto err;
5793 if (bind_ipv4_only && bind_ipv6_only) {
5794 log_warn(LD_CONFIG, "Tried to set both IPv4Only and IPv6Only "
5795 "on %sPort line '%s'",
5796 portname, escaped(ports->value));
5797 goto err;
5799 if (bind_ipv4_only && tor_addr_family(&addr) == AF_INET6) {
5800 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv6",
5801 portname);
5802 goto err;
5804 if (bind_ipv6_only && tor_addr_family(&addr) == AF_INET) {
5805 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv4",
5806 portname);
5807 goto err;
5809 } else {
5810 /* This is a client port; parse isolation options */
5811 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
5812 int no = 0, isoflag = 0;
5813 const char *elt_orig = elt;
5814 if (elt_sl_idx == 0)
5815 continue; /* Skip addr:port */
5816 if (!strcasecmpstart(elt, "SessionGroup=")) {
5817 int group = (int)tor_parse_long(elt+strlen("SessionGroup="),
5818 10, 0, INT_MAX, &ok, NULL);
5819 if (!ok) {
5820 log_warn(LD_CONFIG, "Invalid %sPort option '%s'",
5821 portname, escaped(elt));
5822 goto err;
5824 if (sessiongroup >= 0) {
5825 log_warn(LD_CONFIG, "Multiple SessionGroup options on %sPort",
5826 portname);
5827 goto err;
5829 sessiongroup = group;
5830 continue;
5833 if (!strcasecmpstart(elt, "No")) {
5834 no = 1;
5835 elt += 2;
5838 if (takes_hostnames) {
5839 if (!strcasecmp(elt, "IPv4Traffic")) {
5840 ipv4_traffic = ! no;
5841 continue;
5842 } else if (!strcasecmp(elt, "IPv6Traffic")) {
5843 ipv6_traffic = ! no;
5844 continue;
5845 } else if (!strcasecmp(elt, "PreferIPv6")) {
5846 prefer_ipv6 = ! no;
5847 continue;
5850 if (!strcasecmp(elt, "CacheIPv4DNS")) {
5851 cache_ipv4 = ! no;
5852 continue;
5853 } else if (!strcasecmp(elt, "CacheIPv6DNS")) {
5854 cache_ipv6 = ! no;
5855 continue;
5856 } else if (!strcasecmp(elt, "CacheDNS")) {
5857 cache_ipv4 = cache_ipv6 = ! no;
5858 continue;
5859 } else if (!strcasecmp(elt, "UseIPv4Cache")) {
5860 use_cached_ipv4 = ! no;
5861 continue;
5862 } else if (!strcasecmp(elt, "UseIPv6Cache")) {
5863 use_cached_ipv6 = ! no;
5864 continue;
5865 } else if (!strcasecmp(elt, "UseDNSCache")) {
5866 use_cached_ipv4 = use_cached_ipv6 = ! no;
5867 continue;
5868 } else if (!strcasecmp(elt, "PreferIPv6Automap")) {
5869 prefer_ipv6_automap = ! no;
5870 continue;
5871 } else if (!strcasecmp(elt, "PreferSOCKSNoAuth")) {
5872 prefer_no_auth = ! no;
5873 continue;
5876 if (!strcasecmpend(elt, "s"))
5877 elt[strlen(elt)-1] = '\0'; /* kill plurals. */
5879 if (!strcasecmp(elt, "IsolateDestPort")) {
5880 isoflag = ISO_DESTPORT;
5881 } else if (!strcasecmp(elt, "IsolateDestAddr")) {
5882 isoflag = ISO_DESTADDR;
5883 } else if (!strcasecmp(elt, "IsolateSOCKSAuth")) {
5884 isoflag = ISO_SOCKSAUTH;
5885 } else if (!strcasecmp(elt, "IsolateClientProtocol")) {
5886 isoflag = ISO_CLIENTPROTO;
5887 } else if (!strcasecmp(elt, "IsolateClientAddr")) {
5888 isoflag = ISO_CLIENTADDR;
5889 } else {
5890 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
5891 portname, escaped(elt_orig));
5894 if (no) {
5895 isolation &= ~isoflag;
5896 } else {
5897 isolation |= isoflag;
5899 } SMARTLIST_FOREACH_END(elt);
5902 if (port)
5903 got_nonzero_port = 1;
5904 else
5905 got_zero_port = 1;
5907 if (ipv4_traffic == 0 && ipv6_traffic == 0) {
5908 log_warn(LD_CONFIG, "You have a %sPort entry with both IPv4 and "
5909 "IPv6 disabled; that won't work.", portname);
5910 goto err;
5913 if (out && port) {
5914 port_cfg_t *cfg = port_cfg_new();
5915 tor_addr_copy(&cfg->addr, &addr);
5916 cfg->port = port;
5917 cfg->type = listener_type;
5918 cfg->isolation_flags = isolation;
5919 cfg->session_group = sessiongroup;
5920 cfg->no_advertise = no_advertise;
5921 cfg->no_listen = no_listen;
5922 cfg->all_addrs = all_addrs;
5923 cfg->bind_ipv4_only = bind_ipv4_only;
5924 cfg->bind_ipv6_only = bind_ipv6_only;
5925 cfg->ipv4_traffic = ipv4_traffic;
5926 cfg->ipv6_traffic = ipv6_traffic;
5927 cfg->prefer_ipv6 = prefer_ipv6;
5928 cfg->cache_ipv4_answers = cache_ipv4;
5929 cfg->cache_ipv6_answers = cache_ipv6;
5930 cfg->use_cached_ipv4_answers = use_cached_ipv4;
5931 cfg->use_cached_ipv6_answers = use_cached_ipv6;
5932 cfg->prefer_ipv6_virtaddr = prefer_ipv6_automap;
5933 cfg->socks_prefer_no_auth = prefer_no_auth;
5934 if (! (isolation & ISO_SOCKSAUTH))
5935 cfg->socks_prefer_no_auth = 1;
5937 smartlist_add(out, cfg);
5939 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
5940 smartlist_clear(elts);
5943 if (warn_nonlocal && out) {
5944 if (is_control)
5945 warn_nonlocal_controller_ports(out, forbid_nonlocal);
5946 else if (is_ext_orport)
5947 warn_nonlocal_ext_orports(out, portname);
5948 else
5949 warn_nonlocal_client_ports(out, portname, listener_type);
5952 if (got_zero_port && got_nonzero_port) {
5953 log_warn(LD_CONFIG, "You specified a nonzero %sPort along with '%sPort 0' "
5954 "in the same configuration. Did you mean to disable %sPort or "
5955 "not?", portname, portname, portname);
5956 goto err;
5959 retval = 0;
5960 err:
5961 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
5962 smartlist_free(elts);
5963 return retval;
5966 /** Parse a list of config_line_t for an AF_UNIX unix socket listener option
5967 * from <b>cfg</b> and add them to <b>out</b>. No fancy options are
5968 * supported: the line contains nothing but the path to the AF_UNIX socket. */
5969 static int
5970 parse_unix_socket_config(smartlist_t *out, const config_line_t *cfg,
5971 int listener_type)
5974 if (!out)
5975 return 0;
5977 for ( ; cfg; cfg = cfg->next) {
5978 size_t len = strlen(cfg->value);
5979 port_cfg_t *port = tor_malloc_zero(sizeof(port_cfg_t) + len + 1);
5980 port->is_unix_addr = 1;
5981 memcpy(port->unix_addr, cfg->value, len+1);
5982 port->type = listener_type;
5983 smartlist_add(out, port);
5986 return 0;
5989 /** Return the number of ports which are actually going to listen with type
5990 * <b>listenertype</b>. Do not count no_listen ports. Do not count unix
5991 * sockets. */
5992 static int
5993 count_real_listeners(const smartlist_t *ports, int listenertype)
5995 int n = 0;
5996 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
5997 if (port->no_listen || port->is_unix_addr)
5998 continue;
5999 if (port->type != listenertype)
6000 continue;
6001 ++n;
6002 } SMARTLIST_FOREACH_END(port);
6003 return n;
6006 /** Parse all client port types (Socks, DNS, Trans, NATD) from
6007 * <b>options</b>. On success, set *<b>n_ports_out</b> to the number
6008 * of ports that are listed, update the *Port_set values in
6009 * <b>options</b>, and return 0. On failure, set *<b>msg</b> to a
6010 * description of the problem and return -1.
6012 * If <b>validate_only</b> is false, set configured_client_ports to the
6013 * new list of ports parsed from <b>options</b>.
6015 static int
6016 parse_ports(or_options_t *options, int validate_only,
6017 char **msg, int *n_ports_out)
6019 smartlist_t *ports;
6020 int retval = -1;
6022 ports = smartlist_new();
6024 *n_ports_out = 0;
6026 if (parse_port_config(ports,
6027 options->SocksPort_lines, options->SocksListenAddress,
6028 "Socks", CONN_TYPE_AP_LISTENER,
6029 "127.0.0.1", 9050,
6030 CL_PORT_WARN_NONLOCAL|CL_PORT_ALLOW_EXTRA_LISTENADDR|
6031 CL_PORT_TAKES_HOSTNAMES) < 0) {
6032 *msg = tor_strdup("Invalid SocksPort/SocksListenAddress configuration");
6033 goto err;
6035 if (parse_port_config(ports,
6036 options->DNSPort_lines, options->DNSListenAddress,
6037 "DNS", CONN_TYPE_AP_DNS_LISTENER,
6038 "127.0.0.1", 0,
6039 CL_PORT_WARN_NONLOCAL|CL_PORT_TAKES_HOSTNAMES) < 0) {
6040 *msg = tor_strdup("Invalid DNSPort/DNSListenAddress configuration");
6041 goto err;
6043 if (parse_port_config(ports,
6044 options->TransPort_lines, options->TransListenAddress,
6045 "Trans", CONN_TYPE_AP_TRANS_LISTENER,
6046 "127.0.0.1", 0,
6047 CL_PORT_WARN_NONLOCAL) < 0) {
6048 *msg = tor_strdup("Invalid TransPort/TransListenAddress configuration");
6049 goto err;
6051 if (parse_port_config(ports,
6052 options->NATDPort_lines, options->NATDListenAddress,
6053 "NATD", CONN_TYPE_AP_NATD_LISTENER,
6054 "127.0.0.1", 0,
6055 CL_PORT_WARN_NONLOCAL) < 0) {
6056 *msg = tor_strdup("Invalid NatdPort/NatdListenAddress configuration");
6057 goto err;
6060 unsigned control_port_flags = CL_PORT_NO_OPTIONS | CL_PORT_WARN_NONLOCAL;
6061 const int any_passwords = (options->HashedControlPassword ||
6062 options->HashedControlSessionPassword ||
6063 options->CookieAuthentication);
6064 if (! any_passwords)
6065 control_port_flags |= CL_PORT_FORBID_NONLOCAL;
6067 if (parse_port_config(ports,
6068 options->ControlPort_lines,
6069 options->ControlListenAddress,
6070 "Control", CONN_TYPE_CONTROL_LISTENER,
6071 "127.0.0.1", 0,
6072 control_port_flags) < 0) {
6073 *msg = tor_strdup("Invalid ControlPort/ControlListenAddress "
6074 "configuration");
6075 goto err;
6077 if (parse_unix_socket_config(ports,
6078 options->ControlSocket,
6079 CONN_TYPE_CONTROL_LISTENER) < 0) {
6080 *msg = tor_strdup("Invalid ControlSocket configuration");
6081 goto err;
6084 if (! options->ClientOnly) {
6085 if (parse_port_config(ports,
6086 options->ORPort_lines, options->ORListenAddress,
6087 "OR", CONN_TYPE_OR_LISTENER,
6088 "0.0.0.0", 0,
6089 CL_PORT_SERVER_OPTIONS) < 0) {
6090 *msg = tor_strdup("Invalid ORPort/ORListenAddress configuration");
6091 goto err;
6093 if (parse_port_config(ports,
6094 options->ExtORPort_lines, NULL,
6095 "ExtOR", CONN_TYPE_EXT_OR_LISTENER,
6096 "127.0.0.1", 0,
6097 CL_PORT_SERVER_OPTIONS|CL_PORT_WARN_NONLOCAL) < 0) {
6098 *msg = tor_strdup("Invalid ExtORPort configuration");
6099 goto err;
6101 if (parse_port_config(ports,
6102 options->DirPort_lines, options->DirListenAddress,
6103 "Dir", CONN_TYPE_DIR_LISTENER,
6104 "0.0.0.0", 0,
6105 CL_PORT_SERVER_OPTIONS) < 0) {
6106 *msg = tor_strdup("Invalid DirPort/DirListenAddress configuration");
6107 goto err;
6111 if (check_server_ports(ports, options) < 0) {
6112 *msg = tor_strdup("Misconfigured server ports");
6113 goto err;
6116 *n_ports_out = smartlist_len(ports);
6118 retval = 0;
6120 /* Update the *Port_set options. The !! here is to force a boolean out of
6121 an integer. */
6122 options->ORPort_set =
6123 !! count_real_listeners(ports, CONN_TYPE_OR_LISTENER);
6124 options->SocksPort_set =
6125 !! count_real_listeners(ports, CONN_TYPE_AP_LISTENER);
6126 options->TransPort_set =
6127 !! count_real_listeners(ports, CONN_TYPE_AP_TRANS_LISTENER);
6128 options->NATDPort_set =
6129 !! count_real_listeners(ports, CONN_TYPE_AP_NATD_LISTENER);
6130 options->ControlPort_set =
6131 !! count_real_listeners(ports, CONN_TYPE_CONTROL_LISTENER);
6132 options->DirPort_set =
6133 !! count_real_listeners(ports, CONN_TYPE_DIR_LISTENER);
6134 options->DNSPort_set =
6135 !! count_real_listeners(ports, CONN_TYPE_AP_DNS_LISTENER);
6136 options->ExtORPort_set =
6137 !! count_real_listeners(ports, CONN_TYPE_EXT_OR_LISTENER);
6139 if (!validate_only) {
6140 if (configured_ports) {
6141 SMARTLIST_FOREACH(configured_ports,
6142 port_cfg_t *, p, port_cfg_free(p));
6143 smartlist_free(configured_ports);
6145 configured_ports = ports;
6146 ports = NULL; /* prevent free below. */
6149 err:
6150 if (ports) {
6151 SMARTLIST_FOREACH(ports, port_cfg_t *, p, port_cfg_free(p));
6152 smartlist_free(ports);
6154 return retval;
6157 /** Given a list of <b>port_cfg_t</b> in <b>ports</b>, check them for internal
6158 * consistency and warn as appropriate. */
6159 static int
6160 check_server_ports(const smartlist_t *ports,
6161 const or_options_t *options)
6163 int n_orport_advertised = 0;
6164 int n_orport_advertised_ipv4 = 0;
6165 int n_orport_listeners = 0;
6166 int n_dirport_advertised = 0;
6167 int n_dirport_listeners = 0;
6168 int n_low_port = 0;
6169 int r = 0;
6171 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
6172 if (port->type == CONN_TYPE_DIR_LISTENER) {
6173 if (! port->no_advertise)
6174 ++n_dirport_advertised;
6175 if (! port->no_listen)
6176 ++n_dirport_listeners;
6177 } else if (port->type == CONN_TYPE_OR_LISTENER) {
6178 if (! port->no_advertise) {
6179 ++n_orport_advertised;
6180 if (tor_addr_family(&port->addr) == AF_INET ||
6181 (tor_addr_family(&port->addr) == AF_UNSPEC &&
6182 !port->bind_ipv6_only))
6183 ++n_orport_advertised_ipv4;
6185 if (! port->no_listen)
6186 ++n_orport_listeners;
6187 } else {
6188 continue;
6190 #ifndef _WIN32
6191 if (!port->no_listen && port->port < 1024)
6192 ++n_low_port;
6193 #endif
6194 } SMARTLIST_FOREACH_END(port);
6196 if (n_orport_advertised && !n_orport_listeners) {
6197 log_warn(LD_CONFIG, "We are advertising an ORPort, but not actually "
6198 "listening on one.");
6199 r = -1;
6201 if (n_orport_listeners && !n_orport_advertised) {
6202 log_warn(LD_CONFIG, "We are listening on an ORPort, but not advertising "
6203 "any ORPorts. This will keep us from building a %s "
6204 "descriptor, and make us impossible to use.",
6205 options->BridgeRelay ? "bridge" : "router");
6206 r = -1;
6208 if (n_dirport_advertised && !n_dirport_listeners) {
6209 log_warn(LD_CONFIG, "We are advertising a DirPort, but not actually "
6210 "listening on one.");
6211 r = -1;
6213 if (n_dirport_advertised > 1) {
6214 log_warn(LD_CONFIG, "Can't advertise more than one DirPort.");
6215 r = -1;
6217 if (n_orport_advertised && !n_orport_advertised_ipv4 &&
6218 !options->BridgeRelay) {
6219 log_warn(LD_CONFIG, "Configured non-bridge only to listen on an IPv6 "
6220 "address.");
6221 r = -1;
6224 if (n_low_port && options->AccountingMax) {
6225 log_warn(LD_CONFIG,
6226 "You have set AccountingMax to use hibernation. You have also "
6227 "chosen a low DirPort or OrPort. This combination can make Tor stop "
6228 "working when it tries to re-attach the port after a period of "
6229 "hibernation. Please choose a different port or turn off "
6230 "hibernation unless you know this combination will work on your "
6231 "platform.");
6234 return r;
6237 /** Return a list of port_cfg_t for client ports parsed from the
6238 * options. */
6239 const smartlist_t *
6240 get_configured_ports(void)
6242 if (!configured_ports)
6243 configured_ports = smartlist_new();
6244 return configured_ports;
6247 /** Return an address:port string representation of the address
6248 * where the first <b>listener_type</b> listener waits for
6249 * connections. Return NULL if we couldn't find a listener. The
6250 * string is allocated on the heap and it's the responsibility of the
6251 * caller to free it after use.
6253 * This function is meant to be used by the pluggable transport proxy
6254 * spawning code, please make sure that it fits your purposes before
6255 * using it. */
6256 char *
6257 get_first_listener_addrport_string(int listener_type)
6259 static const char *ipv4_localhost = "127.0.0.1";
6260 static const char *ipv6_localhost = "[::1]";
6261 const char *address;
6262 uint16_t port;
6263 char *string = NULL;
6265 if (!configured_ports)
6266 return NULL;
6268 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
6269 if (cfg->no_listen)
6270 continue;
6272 if (cfg->type == listener_type &&
6273 tor_addr_family(&cfg->addr) != AF_UNSPEC) {
6275 /* We found the first listener of the type we are interested in! */
6277 /* If a listener is listening on INADDR_ANY, assume that it's
6278 also listening on 127.0.0.1, and point the transport proxy
6279 there: */
6280 if (tor_addr_is_null(&cfg->addr))
6281 address = tor_addr_is_v4(&cfg->addr) ? ipv4_localhost : ipv6_localhost;
6282 else
6283 address = fmt_and_decorate_addr(&cfg->addr);
6285 /* If a listener is configured with port 'auto', we are forced
6286 to iterate all listener connections and find out in which
6287 port it ended up listening: */
6288 if (cfg->port == CFG_AUTO_PORT) {
6289 port = router_get_active_listener_port_by_type_af(listener_type,
6290 tor_addr_family(&cfg->addr));
6291 if (!port)
6292 return NULL;
6293 } else {
6294 port = cfg->port;
6297 tor_asprintf(&string, "%s:%u", address, port);
6299 return string;
6302 } SMARTLIST_FOREACH_END(cfg);
6304 return NULL;
6307 /** Return the first advertised port of type <b>listener_type</b> in
6308 <b>address_family</b>. */
6310 get_first_advertised_port_by_type_af(int listener_type, int address_family)
6312 if (!configured_ports)
6313 return 0;
6314 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
6315 if (cfg->type == listener_type &&
6316 !cfg->no_advertise &&
6317 (tor_addr_family(&cfg->addr) == address_family ||
6318 tor_addr_family(&cfg->addr) == AF_UNSPEC)) {
6319 if (tor_addr_family(&cfg->addr) != AF_UNSPEC ||
6320 (address_family == AF_INET && !cfg->bind_ipv6_only) ||
6321 (address_family == AF_INET6 && !cfg->bind_ipv4_only)) {
6322 return cfg->port;
6325 } SMARTLIST_FOREACH_END(cfg);
6326 return 0;
6329 /** Adjust the value of options->DataDirectory, or fill it in if it's
6330 * absent. Return 0 on success, -1 on failure. */
6331 static int
6332 normalize_data_directory(or_options_t *options)
6334 #ifdef _WIN32
6335 char *p;
6336 if (options->DataDirectory)
6337 return 0; /* all set */
6338 p = tor_malloc(MAX_PATH);
6339 strlcpy(p,get_windows_conf_root(),MAX_PATH);
6340 options->DataDirectory = p;
6341 return 0;
6342 #else
6343 const char *d = options->DataDirectory;
6344 if (!d)
6345 d = "~/.tor";
6347 if (strncmp(d,"~/",2) == 0) {
6348 char *fn = expand_filename(d);
6349 if (!fn) {
6350 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
6351 return -1;
6353 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
6354 /* If our homedir is /, we probably don't want to use it. */
6355 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
6356 * want. */
6357 log_warn(LD_CONFIG,
6358 "Default DataDirectory is \"~/.tor\". This expands to "
6359 "\"%s\", which is probably not what you want. Using "
6360 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
6361 tor_free(fn);
6362 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
6364 tor_free(options->DataDirectory);
6365 options->DataDirectory = fn;
6367 return 0;
6368 #endif
6371 /** Check and normalize the value of options->DataDirectory; return 0 if it
6372 * is sane, -1 otherwise. */
6373 static int
6374 validate_data_directory(or_options_t *options)
6376 if (normalize_data_directory(options) < 0)
6377 return -1;
6378 tor_assert(options->DataDirectory);
6379 if (strlen(options->DataDirectory) > (512-128)) {
6380 log_warn(LD_CONFIG, "DataDirectory is too long.");
6381 return -1;
6383 return 0;
6386 /** This string must remain the same forevermore. It is how we
6387 * recognize that the torrc file doesn't need to be backed up. */
6388 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
6389 "if you edit it, comments will not be preserved"
6390 /** This string can change; it tries to give the reader an idea
6391 * that editing this file by hand is not a good plan. */
6392 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
6393 "to torrc.orig.1 or similar, and Tor will ignore it"
6395 /** Save a configuration file for the configuration in <b>options</b>
6396 * into the file <b>fname</b>. If the file already exists, and
6397 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
6398 * replace it. Return 0 on success, -1 on failure. */
6399 static int
6400 write_configuration_file(const char *fname, const or_options_t *options)
6402 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
6403 int rename_old = 0, r;
6405 tor_assert(fname);
6407 switch (file_status(fname)) {
6408 case FN_FILE:
6409 old_val = read_file_to_str(fname, 0, NULL);
6410 if (!old_val || strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
6411 rename_old = 1;
6413 tor_free(old_val);
6414 break;
6415 case FN_NOENT:
6416 break;
6417 case FN_ERROR:
6418 case FN_DIR:
6419 default:
6420 log_warn(LD_CONFIG,
6421 "Config file \"%s\" is not a file? Failing.", fname);
6422 return -1;
6425 if (!(new_conf = options_dump(options, OPTIONS_DUMP_MINIMAL))) {
6426 log_warn(LD_BUG, "Couldn't get configuration string");
6427 goto err;
6430 tor_asprintf(&new_val, "%s\n%s\n\n%s",
6431 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
6433 if (rename_old) {
6434 int i = 1;
6435 char *fn_tmp = NULL;
6436 while (1) {
6437 tor_asprintf(&fn_tmp, "%s.orig.%d", fname, i);
6438 if (file_status(fn_tmp) == FN_NOENT)
6439 break;
6440 tor_free(fn_tmp);
6441 ++i;
6443 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
6444 if (tor_rename(fname, fn_tmp) < 0) {//XXXX sandbox doesn't allow
6445 log_warn(LD_FS,
6446 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
6447 fname, fn_tmp, strerror(errno));
6448 tor_free(fn_tmp);
6449 goto err;
6451 tor_free(fn_tmp);
6454 if (write_str_to_file(fname, new_val, 0) < 0)
6455 goto err;
6457 r = 0;
6458 goto done;
6459 err:
6460 r = -1;
6461 done:
6462 tor_free(new_val);
6463 tor_free(new_conf);
6464 return r;
6468 * Save the current configuration file value to disk. Return 0 on
6469 * success, -1 on failure.
6472 options_save_current(void)
6474 /* This fails if we can't write to our configuration file.
6476 * If we try falling back to datadirectory or something, we have a better
6477 * chance of saving the configuration, but a better chance of doing
6478 * something the user never expected. */
6479 return write_configuration_file(get_torrc_fname(0), get_options());
6482 /** Return the number of cpus configured in <b>options</b>. If we are
6483 * told to auto-detect the number of cpus, return the auto-detected number. */
6485 get_num_cpus(const or_options_t *options)
6487 if (options->NumCPUs == 0) {
6488 int n = compute_num_cpus();
6489 return (n >= 1) ? n : 1;
6490 } else {
6491 return options->NumCPUs;
6496 * Initialize the libevent library.
6498 static void
6499 init_libevent(const or_options_t *options)
6501 const char *badness=NULL;
6502 tor_libevent_cfg cfg;
6504 tor_assert(options);
6506 configure_libevent_logging();
6507 /* If the kernel complains that some method (say, epoll) doesn't
6508 * exist, we don't care about it, since libevent will cope.
6510 suppress_libevent_log_msg("Function not implemented");
6512 tor_check_libevent_header_compatibility();
6514 memset(&cfg, 0, sizeof(cfg));
6515 cfg.disable_iocp = options->DisableIOCP;
6516 cfg.num_cpus = get_num_cpus(options);
6517 cfg.msec_per_tick = options->TokenBucketRefillInterval;
6519 tor_libevent_initialize(&cfg);
6521 suppress_libevent_log_msg(NULL);
6523 tor_check_libevent_version(tor_libevent_get_method(),
6524 server_mode(get_options()),
6525 &badness);
6526 if (badness) {
6527 const char *v = tor_libevent_get_version_str();
6528 const char *m = tor_libevent_get_method();
6529 control_event_general_status(LOG_WARN,
6530 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
6531 v, m, badness);
6535 /** Return a newly allocated string holding a filename relative to the data
6536 * directory. If <b>sub1</b> is present, it is the first path component after
6537 * the data directory. If <b>sub2</b> is also present, it is the second path
6538 * component after the data directory. If <b>suffix</b> is present, it
6539 * is appended to the filename.
6541 * Examples:
6542 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
6543 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
6544 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
6545 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
6547 * Note: Consider using the get_datadir_fname* macros in or.h.
6549 char *
6550 options_get_datadir_fname2_suffix(const or_options_t *options,
6551 const char *sub1, const char *sub2,
6552 const char *suffix)
6554 char *fname = NULL;
6555 size_t len;
6556 tor_assert(options);
6557 tor_assert(options->DataDirectory);
6558 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
6559 len = strlen(options->DataDirectory);
6560 if (sub1) {
6561 len += strlen(sub1)+1;
6562 if (sub2)
6563 len += strlen(sub2)+1;
6565 if (suffix)
6566 len += strlen(suffix);
6567 len++;
6568 fname = tor_malloc(len);
6569 if (sub1) {
6570 if (sub2) {
6571 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
6572 options->DataDirectory, sub1, sub2);
6573 } else {
6574 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
6575 options->DataDirectory, sub1);
6577 } else {
6578 strlcpy(fname, options->DataDirectory, len);
6580 if (suffix)
6581 strlcat(fname, suffix, len);
6582 return fname;
6585 /** Check wether the data directory has a private subdirectory
6586 * <b>subdir</b>. If not, try to create it. Return 0 on success,
6587 * -1 otherwise. */
6589 check_or_create_data_subdir(const char *subdir)
6591 char *statsdir = get_datadir_fname(subdir);
6592 int return_val = 0;
6594 if (check_private_dir(statsdir, CPD_CREATE, get_options()->User) < 0) {
6595 log_warn(LD_HIST, "Unable to create %s/ directory!", subdir);
6596 return_val = -1;
6598 tor_free(statsdir);
6599 return return_val;
6602 /** Create a file named <b>fname</b> with contents <b>str</b> in the
6603 * subdirectory <b>subdir</b> of the data directory. <b>descr</b>
6604 * should be a short description of the file's content and will be
6605 * used for the warning message, if it's present and the write process
6606 * fails. Return 0 on success, -1 otherwise.*/
6608 write_to_data_subdir(const char* subdir, const char* fname,
6609 const char* str, const char* descr)
6611 char *filename = get_datadir_fname2(subdir, fname);
6612 int return_val = 0;
6614 if (write_str_to_file(filename, str, 0) < 0) {
6615 log_warn(LD_HIST, "Unable to write %s to disk!", descr ? descr : fname);
6616 return_val = -1;
6618 tor_free(filename);
6619 return return_val;
6622 /** Given a file name check to see whether the file exists but has not been
6623 * modified for a very long time. If so, remove it. */
6624 void
6625 remove_file_if_very_old(const char *fname, time_t now)
6627 #define VERY_OLD_FILE_AGE (28*24*60*60)
6628 struct stat st;
6630 log_debug(LD_FS, "stat()ing %s", fname);
6631 if (stat(sandbox_intern_string(fname), &st)==0 &&
6632 st.st_mtime < now-VERY_OLD_FILE_AGE) {
6633 char buf[ISO_TIME_LEN+1];
6634 format_local_iso_time(buf, st.st_mtime);
6635 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
6636 "Removing it.", fname, buf);
6637 if (unlink(fname) != 0) {
6638 log_warn(LD_FS, "Failed to unlink %s: %s",
6639 fname, strerror(errno));
6644 /** Return a smartlist of ports that must be forwarded by
6645 * tor-fw-helper. The smartlist contains the ports in a string format
6646 * that is understandable by tor-fw-helper. */
6647 smartlist_t *
6648 get_list_of_ports_to_forward(void)
6650 smartlist_t *ports_to_forward = smartlist_new();
6651 int port = 0;
6653 /** XXX TODO tor-fw-helper does not support forwarding ports to
6654 other hosts than the local one. If the user is binding to a
6655 different IP address, tor-fw-helper won't work. */
6656 port = router_get_advertised_or_port(get_options()); /* Get ORPort */
6657 if (port)
6658 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
6660 port = router_get_advertised_dir_port(get_options(), 0); /* Get DirPort */
6661 if (port)
6662 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
6664 /* Get ports of transport proxies */
6666 smartlist_t *transport_ports = get_transport_proxy_ports();
6667 if (transport_ports) {
6668 smartlist_add_all(ports_to_forward, transport_ports);
6669 smartlist_free(transport_ports);
6673 if (!smartlist_len(ports_to_forward)) {
6674 smartlist_free(ports_to_forward);
6675 ports_to_forward = NULL;
6678 return ports_to_forward;
6681 /** Helper to implement GETINFO functions about configuration variables (not
6682 * their values). Given a "config/names" question, set *<b>answer</b> to a
6683 * new string describing the supported configuration variables and their
6684 * types. */
6686 getinfo_helper_config(control_connection_t *conn,
6687 const char *question, char **answer,
6688 const char **errmsg)
6690 (void) conn;
6691 (void) errmsg;
6692 if (!strcmp(question, "config/names")) {
6693 smartlist_t *sl = smartlist_new();
6694 int i;
6695 for (i = 0; option_vars_[i].name; ++i) {
6696 const config_var_t *var = &option_vars_[i];
6697 const char *type;
6698 /* don't tell controller about triple-underscore options */
6699 if (!strncmp(option_vars_[i].name, "___", 3))
6700 continue;
6701 switch (var->type) {
6702 case CONFIG_TYPE_STRING: type = "String"; break;
6703 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
6704 case CONFIG_TYPE_UINT: type = "Integer"; break;
6705 case CONFIG_TYPE_INT: type = "SignedInteger"; break;
6706 case CONFIG_TYPE_PORT: type = "Port"; break;
6707 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
6708 case CONFIG_TYPE_MSEC_INTERVAL: type = "TimeMsecInterval"; break;
6709 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
6710 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
6711 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
6712 case CONFIG_TYPE_AUTOBOOL: type = "Boolean+Auto"; break;
6713 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
6714 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
6715 case CONFIG_TYPE_CSV: type = "CommaList"; break;
6716 case CONFIG_TYPE_CSV_INTERVAL: type = "TimeIntervalCommaList"; break;
6717 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
6718 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
6719 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
6720 default:
6721 case CONFIG_TYPE_OBSOLETE:
6722 type = NULL; break;
6724 if (!type)
6725 continue;
6726 smartlist_add_asprintf(sl, "%s %s\n",var->name,type);
6728 *answer = smartlist_join_strings(sl, "", 0, NULL);
6729 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
6730 smartlist_free(sl);
6731 } else if (!strcmp(question, "config/defaults")) {
6732 smartlist_t *sl = smartlist_new();
6733 int i;
6734 for (i = 0; option_vars_[i].name; ++i) {
6735 const config_var_t *var = &option_vars_[i];
6736 if (var->initvalue != NULL) {
6737 char *val = esc_for_log(var->initvalue);
6738 smartlist_add_asprintf(sl, "%s %s\n",var->name,val);
6739 tor_free(val);
6742 *answer = smartlist_join_strings(sl, "", 0, NULL);
6743 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
6744 smartlist_free(sl);
6746 return 0;
6749 /** Parse outbound bind address option lines. If <b>validate_only</b>
6750 * is not 0 update OutboundBindAddressIPv4_ and
6751 * OutboundBindAddressIPv6_ in <b>options</b>. On failure, set
6752 * <b>msg</b> (if provided) to a newly allocated string containing a
6753 * description of the problem and return -1. */
6754 static int
6755 parse_outbound_addresses(or_options_t *options, int validate_only, char **msg)
6757 const config_line_t *lines = options->OutboundBindAddress;
6758 int found_v4 = 0, found_v6 = 0;
6760 if (!validate_only) {
6761 memset(&options->OutboundBindAddressIPv4_, 0,
6762 sizeof(options->OutboundBindAddressIPv4_));
6763 memset(&options->OutboundBindAddressIPv6_, 0,
6764 sizeof(options->OutboundBindAddressIPv6_));
6766 while (lines) {
6767 tor_addr_t addr, *dst_addr = NULL;
6768 int af = tor_addr_parse(&addr, lines->value);
6769 switch (af) {
6770 case AF_INET:
6771 if (found_v4) {
6772 if (msg)
6773 tor_asprintf(msg, "Multiple IPv4 outbound bind addresses "
6774 "configured: %s", lines->value);
6775 return -1;
6777 found_v4 = 1;
6778 dst_addr = &options->OutboundBindAddressIPv4_;
6779 break;
6780 case AF_INET6:
6781 if (found_v6) {
6782 if (msg)
6783 tor_asprintf(msg, "Multiple IPv6 outbound bind addresses "
6784 "configured: %s", lines->value);
6785 return -1;
6787 found_v6 = 1;
6788 dst_addr = &options->OutboundBindAddressIPv6_;
6789 break;
6790 default:
6791 if (msg)
6792 tor_asprintf(msg, "Outbound bind address '%s' didn't parse.",
6793 lines->value);
6794 return -1;
6796 if (!validate_only)
6797 tor_addr_copy(dst_addr, &addr);
6798 lines = lines->next;
6800 return 0;
6803 /** Load one of the geoip files, <a>family</a> determining which
6804 * one. <a>default_fname</a> is used if on Windows and
6805 * <a>fname</a> equals "<default>". */
6806 static void
6807 config_load_geoip_file_(sa_family_t family,
6808 const char *fname,
6809 const char *default_fname)
6811 #ifdef _WIN32
6812 char *free_fname = NULL; /* Used to hold any temporary-allocated value */
6813 /* XXXX Don't use this "<default>" junk; make our filename options
6814 * understand prefixes somehow. -NM */
6815 if (!strcmp(fname, "<default>")) {
6816 const char *conf_root = get_windows_conf_root();
6817 tor_asprintf(&free_fname, "%s\\%s", conf_root, default_fname);
6818 fname = free_fname;
6820 geoip_load_file(family, fname);
6821 tor_free(free_fname);
6822 #else
6823 (void)default_fname;
6824 geoip_load_file(family, fname);
6825 #endif
6828 /** Load geoip files for IPv4 and IPv6 if <a>options</a> and
6829 * <a>old_options</a> indicate we should. */
6830 static void
6831 config_maybe_load_geoip_files_(const or_options_t *options,
6832 const or_options_t *old_options)
6834 /* XXXX024 Reload GeoIPFile on SIGHUP. -NM */
6836 if (options->GeoIPFile &&
6837 ((!old_options || !opt_streq(old_options->GeoIPFile,
6838 options->GeoIPFile))
6839 || !geoip_is_loaded(AF_INET)))
6840 config_load_geoip_file_(AF_INET, options->GeoIPFile, "geoip");
6841 if (options->GeoIPv6File &&
6842 ((!old_options || !opt_streq(old_options->GeoIPv6File,
6843 options->GeoIPv6File))
6844 || !geoip_is_loaded(AF_INET6)))
6845 config_load_geoip_file_(AF_INET6, options->GeoIPv6File, "geoip6");
6848 /** Initialize cookie authentication (used so far by the ControlPort
6849 * and Extended ORPort).
6851 * Allocate memory and create a cookie (of length <b>cookie_len</b>)
6852 * in <b>cookie_out</b>.
6853 * Then write it down to <b>fname</b> and prepend it with <b>header</b>.
6855 * If <b>group_readable</b> is set, set <b>fname</b> to be readable
6856 * by the default GID.
6858 * If the whole procedure was successful, set
6859 * <b>cookie_is_set_out</b> to True. */
6861 init_cookie_authentication(const char *fname, const char *header,
6862 int cookie_len, int group_readable,
6863 uint8_t **cookie_out, int *cookie_is_set_out)
6865 char cookie_file_str_len = strlen(header) + cookie_len;
6866 char *cookie_file_str = tor_malloc(cookie_file_str_len);
6867 int retval = -1;
6869 /* We don't want to generate a new cookie every time we call
6870 * options_act(). One should be enough. */
6871 if (*cookie_is_set_out) {
6872 retval = 0; /* we are all set */
6873 goto done;
6876 /* If we've already set the cookie, free it before re-setting
6877 it. This can happen if we previously generated a cookie, but
6878 couldn't write it to a disk. */
6879 if (*cookie_out)
6880 tor_free(*cookie_out);
6882 /* Generate the cookie */
6883 *cookie_out = tor_malloc(cookie_len);
6884 if (crypto_rand((char *)*cookie_out, cookie_len) < 0)
6885 goto done;
6887 /* Create the string that should be written on the file. */
6888 memcpy(cookie_file_str, header, strlen(header));
6889 memcpy(cookie_file_str+strlen(header), *cookie_out, cookie_len);
6890 if (write_bytes_to_file(fname, cookie_file_str, cookie_file_str_len, 1)) {
6891 log_warn(LD_FS,"Error writing auth cookie to %s.", escaped(fname));
6892 goto done;
6895 #ifndef _WIN32
6896 if (group_readable) {
6897 if (chmod(fname, 0640)) {
6898 log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
6901 #else
6902 (void) group_readable;
6903 #endif
6905 /* Success! */
6906 log_info(LD_GENERAL, "Generated auth cookie file in '%s'.", escaped(fname));
6907 *cookie_is_set_out = 1;
6908 retval = 0;
6910 done:
6911 memwipe(cookie_file_str, 0, cookie_file_str_len);
6912 tor_free(cookie_file_str);
6913 return retval;