sandbox: tolerate reloading with DirPortFrontPage set
[tor.git] / src / or / config.c
blobb346f6648e3b045c40164c6005e9c4615717b1be
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 V(AuthDirBadDir, LINELIST, NULL),
144 V(AuthDirBadDirCCs, CSV, ""),
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, "250 KB"),
151 V(AuthDirReject, LINELIST, NULL),
152 V(AuthDirRejectCCs, CSV, ""),
153 V(AuthDirRejectUnlisted, BOOL, "0"),
154 V(AuthDirListBadDirs, BOOL, "0"),
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(ExtraInfoStatistics, BOOL, "1"),
242 V(FallbackDir, LINELIST, NULL),
244 OBSOLETE("FallbackNetworkstatusFile"),
245 V(FascistFirewall, BOOL, "0"),
246 V(FirewallPorts, CSV, ""),
247 V(FastFirstHopPK, AUTOBOOL, "auto"),
248 V(FetchDirInfoEarly, BOOL, "0"),
249 V(FetchDirInfoExtraEarly, BOOL, "0"),
250 V(FetchServerDescriptors, BOOL, "1"),
251 V(FetchHidServDescriptors, BOOL, "1"),
252 V(FetchUselessDescriptors, BOOL, "0"),
253 OBSOLETE("FetchV2Networkstatus"),
254 V(GeoIPExcludeUnknown, AUTOBOOL, "auto"),
255 #ifdef _WIN32
256 V(GeoIPFile, FILENAME, "<default>"),
257 V(GeoIPv6File, FILENAME, "<default>"),
258 #else
259 V(GeoIPFile, FILENAME,
260 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
261 V(GeoIPv6File, FILENAME,
262 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip6"),
263 #endif
264 OBSOLETE("GiveGuardFlagTo_CVE_2011_2768_VulnerableRelays"),
265 OBSOLETE("Group"),
266 V(GuardLifetime, INTERVAL, "0 minutes"),
267 V(HardwareAccel, BOOL, "0"),
268 V(HeartbeatPeriod, INTERVAL, "6 hours"),
269 V(AccelName, STRING, NULL),
270 V(AccelDir, FILENAME, NULL),
271 V(HashedControlPassword, LINELIST, NULL),
272 V(HidServDirectoryV2, BOOL, "1"),
273 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
274 OBSOLETE("HiddenServiceExcludeNodes"),
275 OBSOLETE("HiddenServiceNodes"),
276 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
277 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
278 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
279 VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
280 V(HidServAuth, LINELIST, NULL),
281 OBSOLETE("HSAuthoritativeDir"),
282 OBSOLETE("HSAuthorityRecordStats"),
283 V(CloseHSClientCircuitsImmediatelyOnTimeout, BOOL, "0"),
284 V(CloseHSServiceRendCircuitsImmediatelyOnTimeout, BOOL, "0"),
285 V(HTTPProxy, STRING, NULL),
286 V(HTTPProxyAuthenticator, STRING, NULL),
287 V(HTTPSProxy, STRING, NULL),
288 V(HTTPSProxyAuthenticator, STRING, NULL),
289 V(IPv6Exit, BOOL, "0"),
290 VAR("ServerTransportPlugin", LINELIST, ServerTransportPlugin, NULL),
291 V(ServerTransportListenAddr, LINELIST, NULL),
292 V(ServerTransportOptions, LINELIST, NULL),
293 V(Socks4Proxy, STRING, NULL),
294 V(Socks5Proxy, STRING, NULL),
295 V(Socks5ProxyUsername, STRING, NULL),
296 V(Socks5ProxyPassword, STRING, NULL),
297 OBSOLETE("IgnoreVersion"),
298 V(KeepalivePeriod, INTERVAL, "5 minutes"),
299 VAR("Log", LINELIST, Logs, NULL),
300 V(LogMessageDomains, BOOL, "0"),
301 OBSOLETE("LinkPadding"),
302 OBSOLETE("LogLevel"),
303 OBSOLETE("LogFile"),
304 V(LogTimeGranularity, MSEC_INTERVAL, "1 second"),
305 V(LongLivedPorts, CSV,
306 "21,22,706,1863,5050,5190,5222,5223,6523,6667,6697,8300"),
307 VAR("MapAddress", LINELIST, AddressMap, NULL),
308 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
309 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
310 V(MaxClientCircuitsPending, UINT, "32"),
311 VAR("MaxMemInQueues", MEMUNIT, MaxMemInQueues_raw, "0"),
312 OBSOLETE("MaxOnionsPending"),
313 V(MaxOnionQueueDelay, MSEC_INTERVAL, "1750 msec"),
314 V(MinMeasuredBWsForAuthToIgnoreAdvertised, INT, "500"),
315 OBSOLETE("MonthlyAccountingStart"),
316 V(MyFamily, STRING, NULL),
317 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
318 VAR("NamingAuthoritativeDirectory",BOOL, NamingAuthoritativeDir, "0"),
319 V(NATDListenAddress, LINELIST, NULL),
320 VPORT(NATDPort, LINELIST, NULL),
321 V(Nickname, STRING, NULL),
322 V(PredictedPortsRelevanceTime, INTERVAL, "1 hour"),
323 V(WarnUnsafeSocks, BOOL, "1"),
324 OBSOLETE("NoPublish"),
325 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
326 V(NumCPUs, UINT, "0"),
327 V(NumDirectoryGuards, UINT, "0"),
328 V(NumEntryGuards, UINT, "3"),
329 V(ORListenAddress, LINELIST, NULL),
330 VPORT(ORPort, LINELIST, NULL),
331 V(OutboundBindAddress, LINELIST, NULL),
333 OBSOLETE("PathBiasDisableRate"),
334 V(PathBiasCircThreshold, INT, "-1"),
335 V(PathBiasNoticeRate, DOUBLE, "-1"),
336 V(PathBiasWarnRate, DOUBLE, "-1"),
337 V(PathBiasExtremeRate, DOUBLE, "-1"),
338 V(PathBiasScaleThreshold, INT, "-1"),
339 OBSOLETE("PathBiasScaleFactor"),
340 OBSOLETE("PathBiasMultFactor"),
341 V(PathBiasDropGuards, AUTOBOOL, "0"),
342 OBSOLETE("PathBiasUseCloseCounts"),
344 V(PathBiasUseThreshold, INT, "-1"),
345 V(PathBiasNoticeUseRate, DOUBLE, "-1"),
346 V(PathBiasExtremeUseRate, DOUBLE, "-1"),
347 V(PathBiasScaleUseThreshold, INT, "-1"),
349 V(PathsNeededToBuildCircuits, DOUBLE, "-1"),
350 OBSOLETE("PathlenCoinWeight"),
351 V(PerConnBWBurst, MEMUNIT, "0"),
352 V(PerConnBWRate, MEMUNIT, "0"),
353 V(PidFile, STRING, NULL),
354 V(TestingTorNetwork, BOOL, "0"),
355 V(TestingMinExitFlagThreshold, MEMUNIT, "0"),
356 V(TestingMinFastFlagThreshold, MEMUNIT, "0"),
357 V(OptimisticData, AUTOBOOL, "auto"),
358 V(PortForwarding, BOOL, "0"),
359 V(PortForwardingHelper, FILENAME, "tor-fw-helper"),
360 OBSOLETE("PreferTunneledDirConns"),
361 V(ProtocolWarnings, BOOL, "0"),
362 V(PublishServerDescriptor, CSV, "1"),
363 V(PublishHidServDescriptors, BOOL, "1"),
364 V(ReachableAddresses, LINELIST, NULL),
365 V(ReachableDirAddresses, LINELIST, NULL),
366 V(ReachableORAddresses, LINELIST, NULL),
367 V(RecommendedVersions, LINELIST, NULL),
368 V(RecommendedClientVersions, LINELIST, NULL),
369 V(RecommendedServerVersions, LINELIST, NULL),
370 OBSOLETE("RedirectExit"),
371 V(RefuseUnknownExits, AUTOBOOL, "auto"),
372 V(RejectPlaintextPorts, CSV, ""),
373 V(RelayBandwidthBurst, MEMUNIT, "0"),
374 V(RelayBandwidthRate, MEMUNIT, "0"),
375 OBSOLETE("RendExcludeNodes"),
376 OBSOLETE("RendNodes"),
377 V(RendPostPeriod, INTERVAL, "1 hour"),
378 V(RephistTrackTime, INTERVAL, "24 hours"),
379 OBSOLETE("RouterFile"),
380 V(RunAsDaemon, BOOL, "0"),
381 // V(RunTesting, BOOL, "0"),
382 OBSOLETE("RunTesting"), // currently unused
383 V(Sandbox, BOOL, "0"),
384 V(SafeLogging, STRING, "1"),
385 V(SafeSocks, BOOL, "0"),
386 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
387 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
388 V(ServerDNSDetectHijacking, BOOL, "1"),
389 V(ServerDNSRandomizeCase, BOOL, "1"),
390 V(ServerDNSResolvConfFile, STRING, NULL),
391 V(ServerDNSSearchDomains, BOOL, "0"),
392 V(ServerDNSTestAddresses, CSV,
393 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
394 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
395 V(SocksListenAddress, LINELIST, NULL),
396 V(SocksPolicy, LINELIST, NULL),
397 VPORT(SocksPort, LINELIST, NULL),
398 V(SocksTimeout, INTERVAL, "2 minutes"),
399 V(SSLKeyLifetime, INTERVAL, "0"),
400 OBSOLETE("StatusFetchPeriod"),
401 V(StrictNodes, BOOL, "0"),
402 V(Support022HiddenServices, AUTOBOOL, "auto"),
403 OBSOLETE("SysLog"),
404 V(TestSocks, BOOL, "0"),
405 OBSOLETE("TestVia"),
406 V(TokenBucketRefillInterval, MSEC_INTERVAL, "100 msec"),
407 V(Tor2webMode, BOOL, "0"),
408 V(TLSECGroup, STRING, NULL),
409 V(TrackHostExits, CSV, NULL),
410 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
411 OBSOLETE("TrafficShaping"),
412 V(TransListenAddress, LINELIST, NULL),
413 VPORT(TransPort, LINELIST, NULL),
414 V(TransProxyType, STRING, "default"),
415 OBSOLETE("TunnelDirConns"),
416 V(UpdateBridgesFromAuthority, BOOL, "0"),
417 V(UseBridges, BOOL, "0"),
418 V(UseEntryGuards, BOOL, "1"),
419 V(UseEntryGuardsAsDirGuards, BOOL, "1"),
420 V(UseMicrodescriptors, AUTOBOOL, "auto"),
421 V(UseNTorHandshake, AUTOBOOL, "1"),
422 V(User, STRING, NULL),
423 V(UserspaceIOCPBuffers, BOOL, "0"),
424 OBSOLETE("V1AuthoritativeDirectory"),
425 OBSOLETE("V2AuthoritativeDirectory"),
426 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
427 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
428 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
429 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
430 V(TestingV3AuthVotingStartOffset, INTERVAL, "0"),
431 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
432 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
433 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
434 V(V3AuthNIntervalsValid, UINT, "3"),
435 V(V3AuthUseLegacyKey, BOOL, "0"),
436 V(V3BandwidthsFile, FILENAME, NULL),
437 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
438 V(VirtualAddrNetworkIPv4, STRING, "127.192.0.0/10"),
439 V(VirtualAddrNetworkIPv6, STRING, "[FE80::]/10"),
440 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
441 V(UseFilteringSSLBufferevents, BOOL, "0"),
442 VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
443 VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
444 VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
445 VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
446 VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
447 NULL),
448 VAR("__OwningControllerProcess",STRING,OwningControllerProcess, NULL),
449 V(MinUptimeHidServDirectoryV2, INTERVAL, "25 hours"),
450 V(VoteOnHidServDirectoriesV2, BOOL, "1"),
451 V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 60, 60, 120, "
452 "300, 900, 2147483647"),
453 V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 60, 300, 600, "
454 "2147483647"),
455 V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
456 "300, 600, 1800, 1800, 1800, 1800, "
457 "1800, 3600, 7200"),
458 V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
459 "300, 600, 1800, 3600, 3600, 3600, "
460 "10800, 21600, 43200"),
461 V(TestingBridgeDownloadSchedule, CSV_INTERVAL, "3600, 900, 900, 3600"),
462 V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "10 minutes"),
463 V(TestingDirConnectionMaxStall, INTERVAL, "5 minutes"),
464 V(TestingConsensusMaxDownloadTries, UINT, "8"),
465 V(TestingDescriptorMaxDownloadTries, UINT, "8"),
466 V(TestingMicrodescMaxDownloadTries, UINT, "8"),
467 V(TestingCertMaxDownloadTries, UINT, "8"),
468 V(TestingDirAuthVoteGuard, ROUTERSET, NULL),
469 VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "0"),
471 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
474 /** Override default values with these if the user sets the TestingTorNetwork
475 * option. */
476 static const config_var_t testing_tor_network_defaults[] = {
477 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
478 V(DirAllowPrivateAddresses, BOOL, "1"),
479 V(EnforceDistinctSubnets, BOOL, "0"),
480 V(AssumeReachable, BOOL, "1"),
481 V(AuthDirMaxServersPerAddr, UINT, "0"),
482 V(AuthDirMaxServersPerAuthAddr,UINT, "0"),
483 V(ClientDNSRejectInternalAddresses, BOOL,"0"),
484 V(ClientRejectInternalAddresses, BOOL, "0"),
485 V(CountPrivateBandwidth, BOOL, "1"),
486 V(ExitPolicyRejectPrivate, BOOL, "0"),
487 V(ExtendAllowPrivateAddresses, BOOL, "1"),
488 V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
489 V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
490 V(V3AuthDistDelay, INTERVAL, "20 seconds"),
491 V(TestingV3AuthInitialVotingInterval, INTERVAL, "5 minutes"),
492 V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
493 V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
494 V(TestingV3AuthVotingStartOffset, INTERVAL, "0"),
495 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
496 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
497 V(MinUptimeHidServDirectoryV2, INTERVAL, "0 minutes"),
498 V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 5, 10, 15, "
499 "20, 30, 60"),
500 V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, 15, 20, "
501 "30, 60"),
502 V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
503 "15, 20, 30, 60"),
504 V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
505 "15, 20, 30, 60"),
506 V(TestingBridgeDownloadSchedule, CSV_INTERVAL, "60, 30, 30, 60"),
507 V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "5 seconds"),
508 V(TestingDirConnectionMaxStall, INTERVAL, "30 seconds"),
509 V(TestingConsensusMaxDownloadTries, UINT, "80"),
510 V(TestingDescriptorMaxDownloadTries, UINT, "80"),
511 V(TestingMicrodescMaxDownloadTries, UINT, "80"),
512 V(TestingCertMaxDownloadTries, UINT, "80"),
513 V(TestingEnableConnBwEvent, BOOL, "1"),
514 V(TestingEnableCellStatsEvent, BOOL, "1"),
515 V(TestingEnableTbEmptyEvent, BOOL, "1"),
516 VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "1"),
518 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
521 #undef VAR
522 #undef V
523 #undef OBSOLETE
525 #ifdef _WIN32
526 static char *get_windows_conf_root(void);
527 #endif
528 static int options_act_reversible(const or_options_t *old_options, char **msg);
529 static int options_act(const or_options_t *old_options);
530 static int options_transition_allowed(const or_options_t *old,
531 const or_options_t *new,
532 char **msg);
533 static int options_transition_affects_workers(
534 const or_options_t *old_options, const or_options_t *new_options);
535 static int options_transition_affects_descriptor(
536 const or_options_t *old_options, const or_options_t *new_options);
537 static int check_nickname_list(char **lst, const char *name, char **msg);
539 static int parse_client_transport_line(const or_options_t *options,
540 const char *line, int validate_only);
542 static int parse_server_transport_line(const or_options_t *options,
543 const char *line, int validate_only);
544 static char *get_bindaddr_from_transport_listen_line(const char *line,
545 const char *transport);
546 static int parse_dir_authority_line(const char *line,
547 dirinfo_type_t required_type,
548 int validate_only);
549 static int parse_dir_fallback_line(const char *line,
550 int validate_only);
551 static void port_cfg_free(port_cfg_t *port);
552 static int parse_ports(or_options_t *options, int validate_only,
553 char **msg_out, int *n_ports_out);
554 static int check_server_ports(const smartlist_t *ports,
555 const or_options_t *options);
557 static int validate_data_directory(or_options_t *options);
558 static int write_configuration_file(const char *fname,
559 const or_options_t *options);
560 static int options_init_logs(or_options_t *options, int validate_only);
562 static void init_libevent(const or_options_t *options);
563 static int opt_streq(const char *s1, const char *s2);
564 static int parse_outbound_addresses(or_options_t *options, int validate_only,
565 char **msg);
566 static void config_maybe_load_geoip_files_(const or_options_t *options,
567 const or_options_t *old_options);
568 static int options_validate_cb(void *old_options, void *options,
569 void *default_options,
570 int from_setconf, char **msg);
571 static uint64_t compute_real_max_mem_in_queues(const uint64_t val,
572 int log_guess);
574 /** Magic value for or_options_t. */
575 #define OR_OPTIONS_MAGIC 9090909
577 /** Configuration format for or_options_t. */
578 STATIC config_format_t options_format = {
579 sizeof(or_options_t),
580 OR_OPTIONS_MAGIC,
581 STRUCT_OFFSET(or_options_t, magic_),
582 option_abbrevs_,
583 option_vars_,
584 options_validate_cb,
585 NULL
589 * Functions to read and write the global options pointer.
592 /** Command-line and config-file options. */
593 static or_options_t *global_options = NULL;
594 /** The fallback options_t object; this is where we look for options not
595 * in torrc before we fall back to Tor's defaults. */
596 static or_options_t *global_default_options = NULL;
597 /** Name of most recently read torrc file. */
598 static char *torrc_fname = NULL;
599 /** Name of the most recently read torrc-defaults file.*/
600 static char *torrc_defaults_fname;
601 /** Configuration options set by command line. */
602 static config_line_t *global_cmdline_options = NULL;
603 /** Non-configuration options set by the command line */
604 static config_line_t *global_cmdline_only_options = NULL;
605 /** Boolean: Have we parsed the command line? */
606 static int have_parsed_cmdline = 0;
607 /** Contents of most recently read DirPortFrontPage file. */
608 static char *global_dirfrontpagecontents = NULL;
609 /** List of port_cfg_t for all configured ports. */
610 static smartlist_t *configured_ports = NULL;
612 /** Return the contents of our frontpage string, or NULL if not configured. */
613 const char *
614 get_dirportfrontpage(void)
616 return global_dirfrontpagecontents;
619 /** Return the currently configured options. */
620 or_options_t *
621 get_options_mutable(void)
623 tor_assert(global_options);
624 return global_options;
627 /** Returns the currently configured options */
628 MOCK_IMPL(const or_options_t *,
629 get_options,(void))
631 return get_options_mutable();
634 /** Change the current global options to contain <b>new_val</b> instead of
635 * their current value; take action based on the new value; free the old value
636 * as necessary. Returns 0 on success, -1 on failure.
639 set_options(or_options_t *new_val, char **msg)
641 int i;
642 smartlist_t *elements;
643 config_line_t *line;
644 or_options_t *old_options = global_options;
645 global_options = new_val;
646 /* Note that we pass the *old* options below, for comparison. It
647 * pulls the new options directly out of global_options. */
648 if (options_act_reversible(old_options, msg)<0) {
649 tor_assert(*msg);
650 global_options = old_options;
651 return -1;
653 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
654 log_err(LD_BUG,
655 "Acting on config options left us in a broken state. Dying.");
656 exit(1);
658 /* Issues a CONF_CHANGED event to notify controller of the change. If Tor is
659 * just starting up then the old_options will be undefined. */
660 if (old_options && old_options != global_options) {
661 elements = smartlist_new();
662 for (i=0; options_format.vars[i].name; ++i) {
663 const config_var_t *var = &options_format.vars[i];
664 const char *var_name = var->name;
665 if (var->type == CONFIG_TYPE_LINELIST_S ||
666 var->type == CONFIG_TYPE_OBSOLETE) {
667 continue;
669 if (!config_is_same(&options_format, new_val, old_options, var_name)) {
670 line = config_get_assigned_option(&options_format, new_val,
671 var_name, 1);
673 if (line) {
674 config_line_t *next;
675 for (; line; line = next) {
676 next = line->next;
677 smartlist_add(elements, line->key);
678 smartlist_add(elements, line->value);
679 tor_free(line);
681 } else {
682 smartlist_add(elements, tor_strdup(options_format.vars[i].name));
683 smartlist_add(elements, NULL);
687 control_event_conf_changed(elements);
688 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
689 smartlist_free(elements);
692 if (old_options != global_options)
693 config_free(&options_format, old_options);
695 return 0;
698 extern const char tor_git_revision[]; /* from tor_main.c */
700 /** The version of this Tor process, as parsed. */
701 static char *the_tor_version = NULL;
702 /** A shorter version of this Tor process's version, for export in our router
703 * descriptor. (Does not include the git version, if any.) */
704 static char *the_short_tor_version = NULL;
706 /** Return the current Tor version. */
707 const char *
708 get_version(void)
710 if (the_tor_version == NULL) {
711 if (strlen(tor_git_revision)) {
712 tor_asprintf(&the_tor_version, "%s (git-%s)", get_short_version(),
713 tor_git_revision);
714 } else {
715 the_tor_version = tor_strdup(get_short_version());
718 return the_tor_version;
721 /** Return the current Tor version, without any git tag. */
722 const char *
723 get_short_version(void)
726 if (the_short_tor_version == NULL) {
727 #ifdef TOR_BUILD_TAG
728 tor_asprintf(&the_short_tor_version, "%s (%s)", VERSION, TOR_BUILD_TAG);
729 #else
730 the_short_tor_version = tor_strdup(VERSION);
731 #endif
733 return the_short_tor_version;
736 /** Release additional memory allocated in options
738 STATIC void
739 or_options_free(or_options_t *options)
741 if (!options)
742 return;
744 routerset_free(options->ExcludeExitNodesUnion_);
745 if (options->NodeFamilySets) {
746 SMARTLIST_FOREACH(options->NodeFamilySets, routerset_t *,
747 rs, routerset_free(rs));
748 smartlist_free(options->NodeFamilySets);
750 tor_free(options->BridgePassword_AuthDigest_);
751 tor_free(options->command_arg);
752 config_free(&options_format, options);
755 /** Release all memory and resources held by global configuration structures.
757 void
758 config_free_all(void)
760 or_options_free(global_options);
761 global_options = NULL;
762 or_options_free(global_default_options);
763 global_default_options = NULL;
765 config_free_lines(global_cmdline_options);
766 global_cmdline_options = NULL;
768 config_free_lines(global_cmdline_only_options);
769 global_cmdline_only_options = NULL;
771 if (configured_ports) {
772 SMARTLIST_FOREACH(configured_ports,
773 port_cfg_t *, p, port_cfg_free(p));
774 smartlist_free(configured_ports);
775 configured_ports = NULL;
778 tor_free(torrc_fname);
779 tor_free(torrc_defaults_fname);
780 tor_free(the_tor_version);
781 tor_free(global_dirfrontpagecontents);
783 tor_free(the_short_tor_version);
784 tor_free(the_tor_version);
787 /** Make <b>address</b> -- a piece of information related to our operation as
788 * a client -- safe to log according to the settings in options->SafeLogging,
789 * and return it.
791 * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
793 const char *
794 safe_str_client(const char *address)
796 tor_assert(address);
797 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
798 return "[scrubbed]";
799 else
800 return address;
803 /** Make <b>address</b> -- a piece of information of unspecified sensitivity
804 * -- safe to log according to the settings in options->SafeLogging, and
805 * return it.
807 * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
808 * otherwise.)
810 const char *
811 safe_str(const char *address)
813 tor_assert(address);
814 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
815 return "[scrubbed]";
816 else
817 return address;
820 /** Equivalent to escaped(safe_str_client(address)). See reentrancy note on
821 * escaped(): don't use this outside the main thread, or twice in the same
822 * log statement. */
823 const char *
824 escaped_safe_str_client(const char *address)
826 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
827 return "[scrubbed]";
828 else
829 return escaped(address);
832 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
833 * escaped(): don't use this outside the main thread, or twice in the same
834 * log statement. */
835 const char *
836 escaped_safe_str(const char *address)
838 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
839 return "[scrubbed]";
840 else
841 return escaped(address);
844 /** Add the default directory authorities directly into the trusted dir list,
845 * but only add them insofar as they share bits with <b>type</b>. */
846 static void
847 add_default_trusted_dir_authorities(dirinfo_type_t type)
849 int i;
850 const char *authorities[] = {
851 "moria1 orport=9101 "
852 "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
853 "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
854 "tor26 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
855 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
856 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
857 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
858 "Tonga orport=443 bridge 82.94.251.203:80 "
859 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
860 "turtles orport=9090 "
861 "v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
862 "76.73.17.194:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
863 "gabelmoo orport=443 "
864 "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
865 "212.112.245.170:80 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
866 "dannenberg orport=443 "
867 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
868 "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
869 "urras orport=80 v3ident=80550987E1D626E3EBA5E5E75A458DE0626D088C "
870 "208.83.223.34:443 0AD3 FA88 4D18 F89E EA2D 89C0 1937 9E0E 7FD9 4417",
871 "maatuska orport=80 "
872 "v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
873 "171.25.193.9:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
874 "Faravahar orport=443 "
875 "v3ident=EFCBE720AB3A82B99F9E953CD5BF50F7EEFC7B97 "
876 "154.35.32.5:80 CF6D 0AAF B385 BE71 B8E1 11FC 5CFF 4B47 9237 33BC",
877 NULL
879 for (i=0; authorities[i]; i++) {
880 if (parse_dir_authority_line(authorities[i], type, 0)<0) {
881 log_err(LD_BUG, "Couldn't parse internal DirAuthority line %s",
882 authorities[i]);
887 /** Add the default fallback directory servers into the fallback directory
888 * server list. */
889 static void
890 add_default_fallback_dir_servers(void)
892 int i;
893 const char *fallback[] = {
894 NULL
896 for (i=0; fallback[i]; i++) {
897 if (parse_dir_fallback_line(fallback[i], 0)<0) {
898 log_err(LD_BUG, "Couldn't parse internal FallbackDir line %s",
899 fallback[i]);
904 /** Look at all the config options for using alternate directory
905 * authorities, and make sure none of them are broken. Also, warn the
906 * user if we changed any dangerous ones.
908 static int
909 validate_dir_servers(or_options_t *options, or_options_t *old_options)
911 config_line_t *cl;
913 if (options->DirAuthorities &&
914 (options->AlternateDirAuthority || options->AlternateBridgeAuthority)) {
915 log_warn(LD_CONFIG,
916 "You cannot set both DirAuthority and Alternate*Authority.");
917 return -1;
920 /* do we want to complain to the user about being partitionable? */
921 if ((options->DirAuthorities &&
922 (!old_options ||
923 !config_lines_eq(options->DirAuthorities,
924 old_options->DirAuthorities))) ||
925 (options->AlternateDirAuthority &&
926 (!old_options ||
927 !config_lines_eq(options->AlternateDirAuthority,
928 old_options->AlternateDirAuthority)))) {
929 log_warn(LD_CONFIG,
930 "You have used DirAuthority or AlternateDirAuthority to "
931 "specify alternate directory authorities in "
932 "your configuration. This is potentially dangerous: it can "
933 "make you look different from all other Tor users, and hurt "
934 "your anonymity. Even if you've specified the same "
935 "authorities as Tor uses by default, the defaults could "
936 "change in the future. Be sure you know what you're doing.");
939 /* Now go through the four ways you can configure an alternate
940 * set of directory authorities, and make sure none are broken. */
941 for (cl = options->DirAuthorities; cl; cl = cl->next)
942 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
943 return -1;
944 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
945 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
946 return -1;
947 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
948 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
949 return -1;
950 for (cl = options->FallbackDir; cl; cl = cl->next)
951 if (parse_dir_fallback_line(cl->value, 1)<0)
952 return -1;
953 return 0;
956 /** Look at all the config options and assign new dir authorities
957 * as appropriate.
959 static int
960 consider_adding_dir_servers(const or_options_t *options,
961 const or_options_t *old_options)
963 config_line_t *cl;
964 int need_to_update =
965 !smartlist_len(router_get_trusted_dir_servers()) ||
966 !smartlist_len(router_get_fallback_dir_servers()) || !old_options ||
967 !config_lines_eq(options->DirAuthorities, old_options->DirAuthorities) ||
968 !config_lines_eq(options->FallbackDir, old_options->FallbackDir) ||
969 !config_lines_eq(options->AlternateBridgeAuthority,
970 old_options->AlternateBridgeAuthority) ||
971 !config_lines_eq(options->AlternateDirAuthority,
972 old_options->AlternateDirAuthority);
974 if (!need_to_update)
975 return 0; /* all done */
977 /* Start from a clean slate. */
978 clear_dir_servers();
980 if (!options->DirAuthorities) {
981 /* then we may want some of the defaults */
982 dirinfo_type_t type = NO_DIRINFO;
983 if (!options->AlternateBridgeAuthority)
984 type |= BRIDGE_DIRINFO;
985 if (!options->AlternateDirAuthority)
986 type |= V3_DIRINFO | EXTRAINFO_DIRINFO | MICRODESC_DIRINFO;
987 add_default_trusted_dir_authorities(type);
989 if (!options->FallbackDir)
990 add_default_fallback_dir_servers();
992 for (cl = options->DirAuthorities; cl; cl = cl->next)
993 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
994 return -1;
995 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
996 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
997 return -1;
998 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
999 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1000 return -1;
1001 for (cl = options->FallbackDir; cl; cl = cl->next)
1002 if (parse_dir_fallback_line(cl->value, 0)<0)
1003 return -1;
1004 return 0;
1007 /** Fetch the active option list, and take actions based on it. All of the
1008 * things we do should survive being done repeatedly. If present,
1009 * <b>old_options</b> contains the previous value of the options.
1011 * Return 0 if all goes well, return -1 if things went badly.
1013 static int
1014 options_act_reversible(const or_options_t *old_options, char **msg)
1016 smartlist_t *new_listeners = smartlist_new();
1017 smartlist_t *replaced_listeners = smartlist_new();
1018 static int libevent_initialized = 0;
1019 or_options_t *options = get_options_mutable();
1020 int running_tor = options->command == CMD_RUN_TOR;
1021 int set_conn_limit = 0;
1022 int r = -1;
1023 int logs_marked = 0;
1024 int old_min_log_level = get_min_log_level();
1026 /* Daemonize _first_, since we only want to open most of this stuff in
1027 * the subprocess. Libevent bases can't be reliably inherited across
1028 * processes. */
1029 if (running_tor && options->RunAsDaemon) {
1030 /* No need to roll back, since you can't change the value. */
1031 start_daemon();
1034 #ifndef HAVE_SYS_UN_H
1035 if (options->ControlSocket || options->ControlSocketsGroupWritable) {
1036 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported "
1037 "on this OS/with this build.");
1038 goto rollback;
1040 #else
1041 if (options->ControlSocketsGroupWritable && !options->ControlSocket) {
1042 *msg = tor_strdup("Setting ControlSocketGroupWritable without setting"
1043 "a ControlSocket makes no sense.");
1044 goto rollback;
1046 #endif
1048 if (running_tor) {
1049 int n_ports=0;
1050 /* We need to set the connection limit before we can open the listeners. */
1051 if (! sandbox_is_active()) {
1052 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1053 &options->ConnLimit_) < 0) {
1054 *msg = tor_strdup("Problem with ConnLimit value. "
1055 "See logs for details.");
1056 goto rollback;
1058 set_conn_limit = 1;
1059 } else {
1060 tor_assert(old_options);
1061 options->ConnLimit_ = old_options->ConnLimit_;
1064 /* Set up libevent. (We need to do this before we can register the
1065 * listeners as listeners.) */
1066 if (running_tor && !libevent_initialized) {
1067 init_libevent(options);
1068 libevent_initialized = 1;
1071 /* Adjust the port configuration so we can launch listeners. */
1072 if (parse_ports(options, 0, msg, &n_ports)) {
1073 if (!*msg)
1074 *msg = tor_strdup("Unexpected problem parsing port config");
1075 goto rollback;
1078 /* Set the hibernation state appropriately.*/
1079 consider_hibernation(time(NULL));
1081 /* Launch the listeners. (We do this before we setuid, so we can bind to
1082 * ports under 1024.) We don't want to rebind if we're hibernating. If
1083 * networking is disabled, this will close all but the control listeners,
1084 * but disable those. */
1085 if (!we_are_hibernating()) {
1086 if (retry_all_listeners(replaced_listeners, new_listeners,
1087 options->DisableNetwork) < 0) {
1088 *msg = tor_strdup("Failed to bind one of the listener ports.");
1089 goto rollback;
1092 if (options->DisableNetwork) {
1093 /* Aggressively close non-controller stuff, NOW */
1094 log_notice(LD_NET, "DisableNetwork is set. Tor will not make or accept "
1095 "non-control network connections. Shutting down all existing "
1096 "connections.");
1097 connection_mark_all_noncontrol_connections();
1101 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1102 /* Open /dev/pf before dropping privileges. */
1103 if (options->TransPort_set &&
1104 options->TransProxyType_parsed == TPT_DEFAULT) {
1105 if (get_pf_socket() < 0) {
1106 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1107 goto rollback;
1110 #endif
1112 /* Attempt to lock all current and future memory with mlockall() only once */
1113 if (options->DisableAllSwap) {
1114 if (tor_mlockall() == -1) {
1115 *msg = tor_strdup("DisableAllSwap failure. Do you have proper "
1116 "permissions?");
1117 goto done;
1121 /* Setuid/setgid as appropriate */
1122 if (options->User) {
1123 if (switch_id(options->User) != 0) {
1124 /* No need to roll back, since you can't change the value. */
1125 *msg = tor_strdup("Problem with User value. See logs for details.");
1126 goto done;
1130 /* Ensure data directory is private; create if possible. */
1131 if (check_private_dir(options->DataDirectory,
1132 running_tor ? CPD_CREATE : CPD_CHECK,
1133 options->User)<0) {
1134 tor_asprintf(msg,
1135 "Couldn't access/create private data directory \"%s\"",
1136 options->DataDirectory);
1137 goto done;
1138 /* No need to roll back, since you can't change the value. */
1141 /* Bail out at this point if we're not going to be a client or server:
1142 * we don't run Tor itself. */
1143 if (!running_tor)
1144 goto commit;
1146 if (!sandbox_is_active()) {
1147 mark_logs_temp(); /* Close current logs once new logs are open. */
1148 logs_marked = 1;
1149 if (options_init_logs(options, 0)<0) { /* Configure the tor_log(s) */
1150 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1151 goto rollback;
1155 commit:
1156 r = 0;
1157 if (logs_marked) {
1158 log_severity_list_t *severity =
1159 tor_malloc_zero(sizeof(log_severity_list_t));
1160 close_temp_logs();
1161 add_callback_log(severity, control_event_logmsg);
1162 control_adjust_event_log_severity();
1163 tor_free(severity);
1164 tor_log_update_sigsafe_err_fds();
1168 const char *badness = NULL;
1169 int bad_safelog = 0, bad_severity = 0, new_badness = 0;
1170 if (options->SafeLogging_ != SAFELOG_SCRUB_ALL) {
1171 bad_safelog = 1;
1172 if (!old_options || old_options->SafeLogging_ != options->SafeLogging_)
1173 new_badness = 1;
1175 if (get_min_log_level() >= LOG_INFO) {
1176 bad_severity = 1;
1177 if (get_min_log_level() != old_min_log_level)
1178 new_badness = 1;
1180 if (bad_safelog && bad_severity)
1181 badness = "you disabled SafeLogging, and "
1182 "you're logging more than \"notice\"";
1183 else if (bad_safelog)
1184 badness = "you disabled SafeLogging";
1185 else
1186 badness = "you're logging more than \"notice\"";
1187 if (new_badness)
1188 log_warn(LD_GENERAL, "Your log may contain sensitive information - %s. "
1189 "Don't log unless it serves an important reason. "
1190 "Overwrite the log afterwards.", badness);
1193 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1195 int marked = conn->marked_for_close;
1196 log_notice(LD_NET, "Closing old %s on %s:%d",
1197 conn_type_to_string(conn->type), conn->address, conn->port);
1198 connection_close_immediate(conn);
1199 if (!marked) {
1200 connection_mark_for_close(conn);
1203 goto done;
1205 rollback:
1206 r = -1;
1207 tor_assert(*msg);
1209 if (logs_marked) {
1210 rollback_log_changes();
1211 control_adjust_event_log_severity();
1214 if (set_conn_limit && old_options)
1215 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1216 &options->ConnLimit_);
1218 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1220 log_notice(LD_NET, "Closing partially-constructed %s on %s:%d",
1221 conn_type_to_string(conn->type), conn->address, conn->port);
1222 connection_close_immediate(conn);
1223 connection_mark_for_close(conn);
1226 done:
1227 smartlist_free(new_listeners);
1228 smartlist_free(replaced_listeners);
1229 return r;
1232 /** If we need to have a GEOIP ip-to-country map to run with our configured
1233 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1235 options_need_geoip_info(const or_options_t *options, const char **reason_out)
1237 int bridge_usage =
1238 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1239 int routerset_usage =
1240 routerset_needs_geoip(options->EntryNodes) ||
1241 routerset_needs_geoip(options->ExitNodes) ||
1242 routerset_needs_geoip(options->ExcludeExitNodes) ||
1243 routerset_needs_geoip(options->ExcludeNodes);
1245 if (routerset_usage && reason_out) {
1246 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1247 "countries, and we need GEOIP information to figure out which ones they "
1248 "are.";
1249 } else if (bridge_usage && reason_out) {
1250 *reason_out = "We've been configured to see which countries can access "
1251 "us as a bridge, and we need GEOIP information to tell which countries "
1252 "clients are in.";
1254 return bridge_usage || routerset_usage;
1257 /** Return the bandwidthrate that we are going to report to the authorities
1258 * based on the config options. */
1259 uint32_t
1260 get_effective_bwrate(const or_options_t *options)
1262 uint64_t bw = options->BandwidthRate;
1263 if (bw > options->MaxAdvertisedBandwidth)
1264 bw = options->MaxAdvertisedBandwidth;
1265 if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1266 bw = options->RelayBandwidthRate;
1267 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1268 return (uint32_t)bw;
1271 /** Return the bandwidthburst that we are going to report to the authorities
1272 * based on the config options. */
1273 uint32_t
1274 get_effective_bwburst(const or_options_t *options)
1276 uint64_t bw = options->BandwidthBurst;
1277 if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1278 bw = options->RelayBandwidthBurst;
1279 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1280 return (uint32_t)bw;
1283 /** Return True if any changes from <b>old_options</b> to
1284 * <b>new_options</b> needs us to refresh our TLS context. */
1285 static int
1286 options_transition_requires_fresh_tls_context(const or_options_t *old_options,
1287 const or_options_t *new_options)
1289 tor_assert(new_options);
1291 if (!old_options)
1292 return 0;
1294 if ((old_options->DynamicDHGroups != new_options->DynamicDHGroups)) {
1295 return 1;
1298 if (!opt_streq(old_options->TLSECGroup, new_options->TLSECGroup))
1299 return 1;
1301 return 0;
1304 /** Fetch the active option list, and take actions based on it. All of the
1305 * things we do should survive being done repeatedly. If present,
1306 * <b>old_options</b> contains the previous value of the options.
1308 * Return 0 if all goes well, return -1 if it's time to die.
1310 * Note: We haven't moved all the "act on new configuration" logic
1311 * here yet. Some is still in do_hup() and other places.
1313 static int
1314 options_act(const or_options_t *old_options)
1316 config_line_t *cl;
1317 or_options_t *options = get_options_mutable();
1318 int running_tor = options->command == CMD_RUN_TOR;
1319 char *msg=NULL;
1320 const int transition_affects_workers =
1321 old_options && options_transition_affects_workers(old_options, options);
1322 int old_ewma_enabled;
1324 /* disable ptrace and later, other basic debugging techniques */
1326 /* Remember if we already disabled debugger attachment */
1327 static int disabled_debugger_attach = 0;
1328 /* Remember if we already warned about being configured not to disable
1329 * debugger attachment */
1330 static int warned_debugger_attach = 0;
1331 /* Don't disable debugger attachment when we're running the unit tests. */
1332 if (options->DisableDebuggerAttachment && !disabled_debugger_attach &&
1333 running_tor) {
1334 int ok = tor_disable_debugger_attach();
1335 if (warned_debugger_attach && ok == 1) {
1336 log_notice(LD_CONFIG, "Disabled attaching debuggers for unprivileged "
1337 "users.");
1339 disabled_debugger_attach = (ok == 1);
1340 } else if (!options->DisableDebuggerAttachment &&
1341 !warned_debugger_attach) {
1342 log_notice(LD_CONFIG, "Not disabling debugger attaching for "
1343 "unprivileged users.");
1344 warned_debugger_attach = 1;
1348 /* Write control ports to disk as appropriate */
1349 control_ports_write_to_file();
1351 if (running_tor && !have_lockfile()) {
1352 if (try_locking(options, 1) < 0)
1353 return -1;
1356 if (consider_adding_dir_servers(options, old_options) < 0)
1357 return -1;
1359 #ifdef NON_ANONYMOUS_MODE_ENABLED
1360 log_warn(LD_GENERAL, "This copy of Tor was compiled to run in a "
1361 "non-anonymous mode. It will provide NO ANONYMITY.");
1362 #endif
1364 #ifdef ENABLE_TOR2WEB_MODE
1365 if (!options->Tor2webMode) {
1366 log_err(LD_CONFIG, "This copy of Tor was compiled to run in "
1367 "'tor2web mode'. It can only be run with the Tor2webMode torrc "
1368 "option enabled.");
1369 return -1;
1371 #else
1372 if (options->Tor2webMode) {
1373 log_err(LD_CONFIG, "This copy of Tor was not compiled to run in "
1374 "'tor2web mode'. It cannot be run with the Tor2webMode torrc "
1375 "option enabled. To enable Tor2webMode recompile with the "
1376 "--enable-tor2webmode option.");
1377 return -1;
1379 #endif
1381 /* If we are a bridge with a pluggable transport proxy but no
1382 Extended ORPort, inform the user that she is missing out. */
1383 if (server_mode(options) && options->ServerTransportPlugin &&
1384 !options->ExtORPort_lines) {
1385 log_notice(LD_CONFIG, "We use pluggable transports but the Extended "
1386 "ORPort is disabled. Tor and your pluggable transports proxy "
1387 "communicate with each other via the Extended ORPort so it "
1388 "is suggested you enable it: it will also allow your Bridge "
1389 "to collect statistics about its clients that use pluggable "
1390 "transports. Please enable it using the ExtORPort torrc option "
1391 "(e.g. set 'ExtORPort auto').");
1394 if (options->Bridges) {
1395 mark_bridge_list();
1396 for (cl = options->Bridges; cl; cl = cl->next) {
1397 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
1398 if (!bridge_line) {
1399 log_warn(LD_BUG,
1400 "Previously validated Bridge line could not be added!");
1401 return -1;
1403 bridge_add_from_config(bridge_line);
1405 sweep_bridge_list();
1408 if (running_tor && rend_config_services(options, 0)<0) {
1409 log_warn(LD_BUG,
1410 "Previously validated hidden services line could not be added!");
1411 return -1;
1414 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1415 log_warn(LD_BUG, "Previously validated client authorization for "
1416 "hidden services could not be added!");
1417 return -1;
1420 /* Load state */
1421 if (! or_state_loaded() && running_tor) {
1422 if (or_state_load())
1423 return -1;
1424 rep_hist_load_mtbf_data(time(NULL));
1427 mark_transport_list();
1428 pt_prepare_proxy_list_for_config_read();
1429 if (options->ClientTransportPlugin) {
1430 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
1431 if (parse_client_transport_line(options, cl->value, 0)<0) {
1432 log_warn(LD_BUG,
1433 "Previously validated ClientTransportPlugin line "
1434 "could not be added!");
1435 return -1;
1440 if (options->ServerTransportPlugin && server_mode(options)) {
1441 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
1442 if (parse_server_transport_line(options, cl->value, 0)<0) {
1443 log_warn(LD_BUG,
1444 "Previously validated ServerTransportPlugin line "
1445 "could not be added!");
1446 return -1;
1450 sweep_transport_list();
1451 sweep_proxy_list();
1453 /* Start the PT proxy configuration. By doing this configuration
1454 here, we also figure out which proxies need to be restarted and
1455 which not. */
1456 if (pt_proxies_configuration_pending() && !net_is_disabled())
1457 pt_configure_remaining_proxies();
1459 /* Bail out at this point if we're not going to be a client or server:
1460 * we want to not fork, and to log stuff to stderr. */
1461 if (!running_tor)
1462 return 0;
1464 /* Finish backgrounding the process */
1465 if (options->RunAsDaemon) {
1466 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1467 finish_daemon(options->DataDirectory);
1470 /* If needed, generate a new TLS DH prime according to the current torrc. */
1471 if (server_mode(options) && options->DynamicDHGroups) {
1472 char *keydir = get_datadir_fname("keys");
1473 if (check_private_dir(keydir, CPD_CREATE, options->User)) {
1474 tor_free(keydir);
1475 return -1;
1477 tor_free(keydir);
1479 if (!old_options || !old_options->DynamicDHGroups) {
1480 char *fname = get_datadir_fname2("keys", "dynamic_dh_params");
1481 crypto_set_tls_dh_prime(fname);
1482 tor_free(fname);
1484 } else { /* clients don't need a dynamic DH prime. */
1485 crypto_set_tls_dh_prime(NULL);
1488 /* We want to reinit keys as needed before we do much of anything else:
1489 keys are important, and other things can depend on them. */
1490 if (transition_affects_workers ||
1491 (options->V3AuthoritativeDir && (!old_options ||
1492 !old_options->V3AuthoritativeDir))) {
1493 if (init_keys() < 0) {
1494 log_warn(LD_BUG,"Error initializing keys; exiting");
1495 return -1;
1497 } else if (old_options &&
1498 options_transition_requires_fresh_tls_context(old_options,
1499 options)) {
1500 if (router_initialize_tls_context() < 0) {
1501 log_warn(LD_BUG,"Error initializing TLS context.");
1502 return -1;
1506 /* Write our PID to the PID file. If we do not have write permissions we
1507 * will log a warning */
1508 if (options->PidFile && !sandbox_is_active()) {
1509 write_pidfile(options->PidFile);
1512 /* Register addressmap directives */
1513 config_register_addressmaps(options);
1514 parse_virtual_addr_network(options->VirtualAddrNetworkIPv4, AF_INET,0,NULL);
1515 parse_virtual_addr_network(options->VirtualAddrNetworkIPv6, AF_INET6,0,NULL);
1517 /* Update address policies. */
1518 if (policies_parse_from_options(options) < 0) {
1519 /* This should be impossible, but let's be sure. */
1520 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1521 return -1;
1524 if (init_control_cookie_authentication(options->CookieAuthentication) < 0) {
1525 log_warn(LD_CONFIG,"Error creating control cookie authentication file.");
1526 return -1;
1529 /* If we have an ExtORPort, initialize its auth cookie. */
1530 if (init_ext_or_cookie_authentication(!!options->ExtORPort_lines) < 0) {
1531 log_warn(LD_CONFIG,"Error creating Extended ORPort cookie file.");
1532 return -1;
1535 monitor_owning_controller_process(options->OwningControllerProcess);
1537 /* reload keys as needed for rendezvous services. */
1538 if (rend_service_load_all_keys()<0) {
1539 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1540 return -1;
1543 /* Set up accounting */
1544 if (accounting_parse_options(options, 0)<0) {
1545 log_warn(LD_CONFIG,"Error in accounting options");
1546 return -1;
1548 if (accounting_is_enabled(options))
1549 configure_accounting(time(NULL));
1551 #ifdef USE_BUFFEREVENTS
1552 /* If we're using the bufferevents implementation and our rate limits
1553 * changed, we need to tell the rate-limiting system about it. */
1554 if (!old_options ||
1555 old_options->BandwidthRate != options->BandwidthRate ||
1556 old_options->BandwidthBurst != options->BandwidthBurst ||
1557 old_options->RelayBandwidthRate != options->RelayBandwidthRate ||
1558 old_options->RelayBandwidthBurst != options->RelayBandwidthBurst)
1559 connection_bucket_init();
1560 #endif
1562 old_ewma_enabled = cell_ewma_enabled();
1563 /* Change the cell EWMA settings */
1564 cell_ewma_set_scale_factor(options, networkstatus_get_latest_consensus());
1565 /* If we just enabled ewma, set the cmux policy on all active channels */
1566 if (cell_ewma_enabled() && !old_ewma_enabled) {
1567 channel_set_cmux_policy_everywhere(&ewma_policy);
1568 } else if (!cell_ewma_enabled() && old_ewma_enabled) {
1569 /* Turn it off everywhere */
1570 channel_set_cmux_policy_everywhere(NULL);
1573 /* Update the BridgePassword's hashed version as needed. We store this as a
1574 * digest so that we can do side-channel-proof comparisons on it.
1576 if (options->BridgePassword) {
1577 char *http_authenticator;
1578 http_authenticator = alloc_http_authenticator(options->BridgePassword);
1579 if (!http_authenticator) {
1580 log_warn(LD_BUG, "Unable to allocate HTTP authenticator. Not setting "
1581 "BridgePassword.");
1582 return -1;
1584 options->BridgePassword_AuthDigest_ = tor_malloc(DIGEST256_LEN);
1585 crypto_digest256(options->BridgePassword_AuthDigest_,
1586 http_authenticator, strlen(http_authenticator),
1587 DIGEST_SHA256);
1588 tor_free(http_authenticator);
1591 if (parse_outbound_addresses(options, 0, &msg) < 0) {
1592 log_warn(LD_BUG, "Failed parsing oubound bind addresses: %s", msg);
1593 tor_free(msg);
1594 return -1;
1597 /* Check for transitions that need action. */
1598 if (old_options) {
1599 int revise_trackexithosts = 0;
1600 int revise_automap_entries = 0;
1601 if ((options->UseEntryGuards && !old_options->UseEntryGuards) ||
1602 options->UseBridges != old_options->UseBridges ||
1603 (options->UseBridges &&
1604 !config_lines_eq(options->Bridges, old_options->Bridges)) ||
1605 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes) ||
1606 !routerset_equal(old_options->ExcludeExitNodes,
1607 options->ExcludeExitNodes) ||
1608 !routerset_equal(old_options->EntryNodes, options->EntryNodes) ||
1609 !routerset_equal(old_options->ExitNodes, options->ExitNodes) ||
1610 options->StrictNodes != old_options->StrictNodes) {
1611 log_info(LD_CIRC,
1612 "Changed to using entry guards or bridges, or changed "
1613 "preferred or excluded node lists. "
1614 "Abandoning previous circuits.");
1615 circuit_mark_all_unused_circs();
1616 circuit_mark_all_dirty_circs_as_unusable();
1617 revise_trackexithosts = 1;
1620 if (!smartlist_strings_eq(old_options->TrackHostExits,
1621 options->TrackHostExits))
1622 revise_trackexithosts = 1;
1624 if (revise_trackexithosts)
1625 addressmap_clear_excluded_trackexithosts(options);
1627 if (!options->AutomapHostsOnResolve) {
1628 if (old_options->AutomapHostsOnResolve)
1629 revise_automap_entries = 1;
1630 } else {
1631 if (!smartlist_strings_eq(old_options->AutomapHostsSuffixes,
1632 options->AutomapHostsSuffixes))
1633 revise_automap_entries = 1;
1634 else if (!opt_streq(old_options->VirtualAddrNetworkIPv4,
1635 options->VirtualAddrNetworkIPv4) ||
1636 !opt_streq(old_options->VirtualAddrNetworkIPv6,
1637 options->VirtualAddrNetworkIPv6))
1638 revise_automap_entries = 1;
1641 if (revise_automap_entries)
1642 addressmap_clear_invalid_automaps(options);
1644 /* How long should we delay counting bridge stats after becoming a bridge?
1645 * We use this so we don't count people who used our bridge thinking it is
1646 * a relay. If you change this, don't forget to change the log message
1647 * below. It's 4 hours (the time it takes to stop being used by clients)
1648 * plus some extra time for clock skew. */
1649 #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
1651 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
1652 int was_relay = 0;
1653 if (options->BridgeRelay) {
1654 time_t int_start = time(NULL);
1655 if (config_lines_eq(old_options->ORPort_lines,options->ORPort_lines)) {
1656 int_start += RELAY_BRIDGE_STATS_DELAY;
1657 was_relay = 1;
1659 geoip_bridge_stats_init(int_start);
1660 log_info(LD_CONFIG, "We are acting as a bridge now. Starting new "
1661 "GeoIP stats interval%s.", was_relay ? " in 6 "
1662 "hours from now" : "");
1663 } else {
1664 geoip_bridge_stats_term();
1665 log_info(LD_GENERAL, "We are no longer acting as a bridge. "
1666 "Forgetting GeoIP stats.");
1670 if (transition_affects_workers) {
1671 log_info(LD_GENERAL,
1672 "Worker-related options changed. Rotating workers.");
1674 if (server_mode(options) && !server_mode(old_options)) {
1675 ip_address_changed(0);
1676 if (can_complete_circuit || !any_predicted_circuits(time(NULL)))
1677 inform_testing_reachability();
1679 cpuworkers_rotate();
1680 if (dns_reset())
1681 return -1;
1682 } else {
1683 if (dns_reset())
1684 return -1;
1687 if (options->PerConnBWRate != old_options->PerConnBWRate ||
1688 options->PerConnBWBurst != old_options->PerConnBWBurst)
1689 connection_or_update_token_buckets(get_connection_array(), options);
1692 config_maybe_load_geoip_files_(options, old_options);
1694 if (geoip_is_loaded(AF_INET) && options->GeoIPExcludeUnknown) {
1695 /* ExcludeUnknown is true or "auto" */
1696 const int is_auto = options->GeoIPExcludeUnknown == -1;
1697 int changed;
1699 changed = routerset_add_unknown_ccs(&options->ExcludeNodes, is_auto);
1700 changed += routerset_add_unknown_ccs(&options->ExcludeExitNodes, is_auto);
1702 if (changed)
1703 routerset_add_unknown_ccs(&options->ExcludeExitNodesUnion_, is_auto);
1706 if (options->CellStatistics || options->DirReqStatistics ||
1707 options->EntryStatistics || options->ExitPortStatistics ||
1708 options->ConnDirectionStatistics ||
1709 options->BridgeAuthoritativeDir) {
1710 time_t now = time(NULL);
1711 int print_notice = 0;
1713 /* Only collect directory-request statistics on relays and bridges. */
1714 if (!server_mode(options)) {
1715 options->DirReqStatistics = 0;
1718 /* Only collect other relay-only statistics on relays. */
1719 if (!public_server_mode(options)) {
1720 options->CellStatistics = 0;
1721 options->EntryStatistics = 0;
1722 options->ExitPortStatistics = 0;
1725 if ((!old_options || !old_options->CellStatistics) &&
1726 options->CellStatistics) {
1727 rep_hist_buffer_stats_init(now);
1728 print_notice = 1;
1730 if ((!old_options || !old_options->DirReqStatistics) &&
1731 options->DirReqStatistics) {
1732 if (geoip_is_loaded(AF_INET)) {
1733 geoip_dirreq_stats_init(now);
1734 print_notice = 1;
1735 } else {
1736 options->DirReqStatistics = 0;
1737 /* Don't warn Tor clients, they don't use statistics */
1738 if (options->ORPort_set)
1739 log_notice(LD_CONFIG, "Configured to measure directory request "
1740 "statistics, but no GeoIP database found. "
1741 "Please specify a GeoIP database using the "
1742 "GeoIPFile option.");
1745 if ((!old_options || !old_options->EntryStatistics) &&
1746 options->EntryStatistics && !should_record_bridge_info(options)) {
1747 if (geoip_is_loaded(AF_INET) || geoip_is_loaded(AF_INET6)) {
1748 geoip_entry_stats_init(now);
1749 print_notice = 1;
1750 } else {
1751 options->EntryStatistics = 0;
1752 log_notice(LD_CONFIG, "Configured to measure entry node "
1753 "statistics, but no GeoIP database found. "
1754 "Please specify a GeoIP database using the "
1755 "GeoIPFile option.");
1758 if ((!old_options || !old_options->ExitPortStatistics) &&
1759 options->ExitPortStatistics) {
1760 rep_hist_exit_stats_init(now);
1761 print_notice = 1;
1763 if ((!old_options || !old_options->ConnDirectionStatistics) &&
1764 options->ConnDirectionStatistics) {
1765 rep_hist_conn_stats_init(now);
1767 if ((!old_options || !old_options->BridgeAuthoritativeDir) &&
1768 options->BridgeAuthoritativeDir) {
1769 rep_hist_desc_stats_init(now);
1770 print_notice = 1;
1772 if (print_notice)
1773 log_notice(LD_CONFIG, "Configured to measure statistics. Look for "
1774 "the *-stats files that will first be written to the "
1775 "data directory in 24 hours from now.");
1778 if (old_options && old_options->CellStatistics &&
1779 !options->CellStatistics)
1780 rep_hist_buffer_stats_term();
1781 if (old_options && old_options->DirReqStatistics &&
1782 !options->DirReqStatistics)
1783 geoip_dirreq_stats_term();
1784 if (old_options && old_options->EntryStatistics &&
1785 !options->EntryStatistics)
1786 geoip_entry_stats_term();
1787 if (old_options && old_options->ExitPortStatistics &&
1788 !options->ExitPortStatistics)
1789 rep_hist_exit_stats_term();
1790 if (old_options && old_options->ConnDirectionStatistics &&
1791 !options->ConnDirectionStatistics)
1792 rep_hist_conn_stats_term();
1793 if (old_options && old_options->BridgeAuthoritativeDir &&
1794 !options->BridgeAuthoritativeDir)
1795 rep_hist_desc_stats_term();
1797 /* Check if we need to parse and add the EntryNodes config option. */
1798 if (options->EntryNodes &&
1799 (!old_options ||
1800 !routerset_equal(old_options->EntryNodes,options->EntryNodes) ||
1801 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes)))
1802 entry_nodes_should_be_added();
1804 /* Since our options changed, we might need to regenerate and upload our
1805 * server descriptor.
1807 if (!old_options ||
1808 options_transition_affects_descriptor(old_options, options))
1809 mark_my_descriptor_dirty("config change");
1811 /* We may need to reschedule some directory stuff if our status changed. */
1812 if (old_options) {
1813 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1814 dirvote_recalculate_timing(options, time(NULL));
1815 if (!bool_eq(directory_fetches_dir_info_early(options),
1816 directory_fetches_dir_info_early(old_options)) ||
1817 !bool_eq(directory_fetches_dir_info_later(options),
1818 directory_fetches_dir_info_later(old_options))) {
1819 /* Make sure update_router_have_min_dir_info gets called. */
1820 router_dir_info_changed();
1821 /* We might need to download a new consensus status later or sooner than
1822 * we had expected. */
1823 update_consensus_networkstatus_fetch_time(time(NULL));
1827 /* Load the webpage we're going to serve every time someone asks for '/' on
1828 our DirPort. */
1829 tor_free(global_dirfrontpagecontents);
1830 if (options->DirPortFrontPage) {
1831 global_dirfrontpagecontents =
1832 read_file_to_str(options->DirPortFrontPage, 0, NULL);
1833 if (!global_dirfrontpagecontents) {
1834 log_warn(LD_CONFIG,
1835 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1836 options->DirPortFrontPage);
1840 return 0;
1843 static const struct {
1844 const char *name;
1845 int takes_argument;
1846 } CMDLINE_ONLY_OPTIONS[] = {
1847 { "-f", 1 },
1848 { "--allow-missing-torrc", 0 },
1849 { "--defaults-torrc", 1 },
1850 { "--hash-password", 1 },
1851 { "--dump-config", 1 },
1852 { "--list-fingerprint", 0 },
1853 { "--verify-config", 0 },
1854 { "--ignore-missing-torrc", 0 },
1855 { "--quiet", 0 },
1856 { "--hush", 0 },
1857 { "--version", 0 },
1858 { "--library-versions", 0 },
1859 { "-h", 0 },
1860 { "--help", 0 },
1861 { "--list-torrc-options", 0 },
1862 { "--digests", 0 },
1863 { "--nt-service", 0 },
1864 { "-nt-service", 0 },
1865 { NULL, 0 },
1868 /** Helper: Read a list of configuration options from the command line. If
1869 * successful, or if ignore_errors is set, put them in *<b>result</b>, put the
1870 * commandline-only options in *<b>cmdline_result</b>, and return 0;
1871 * otherwise, return -1 and leave *<b>result</b> and <b>cmdline_result</b>
1872 * alone. */
1874 config_parse_commandline(int argc, char **argv, int ignore_errors,
1875 config_line_t **result,
1876 config_line_t **cmdline_result)
1878 config_line_t *param = NULL;
1880 config_line_t *front = NULL;
1881 config_line_t **new = &front;
1883 config_line_t *front_cmdline = NULL;
1884 config_line_t **new_cmdline = &front_cmdline;
1886 char *s, *arg;
1887 int i = 1;
1889 while (i < argc) {
1890 unsigned command = CONFIG_LINE_NORMAL;
1891 int want_arg = 1;
1892 int is_cmdline = 0;
1893 int j;
1895 for (j = 0; CMDLINE_ONLY_OPTIONS[j].name != NULL; ++j) {
1896 if (!strcmp(argv[i], CMDLINE_ONLY_OPTIONS[j].name)) {
1897 is_cmdline = 1;
1898 want_arg = CMDLINE_ONLY_OPTIONS[j].takes_argument;
1899 break;
1903 s = argv[i];
1905 /* Each keyword may be prefixed with one or two dashes. */
1906 if (*s == '-')
1907 s++;
1908 if (*s == '-')
1909 s++;
1910 /* Figure out the command, if any. */
1911 if (*s == '+') {
1912 s++;
1913 command = CONFIG_LINE_APPEND;
1914 } else if (*s == '/') {
1915 s++;
1916 command = CONFIG_LINE_CLEAR;
1917 /* A 'clear' command has no argument. */
1918 want_arg = 0;
1921 if (want_arg && i == argc-1) {
1922 if (ignore_errors) {
1923 arg = strdup("");
1924 } else {
1925 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1926 argv[i]);
1927 config_free_lines(front);
1928 config_free_lines(front_cmdline);
1929 return -1;
1931 } else {
1932 arg = want_arg ? tor_strdup(argv[i+1]) : strdup("");
1935 param = tor_malloc_zero(sizeof(config_line_t));
1936 param->key = is_cmdline ? tor_strdup(argv[i]) : tor_strdup(s);
1937 param->value = arg;
1938 param->command = command;
1939 param->next = NULL;
1940 log_debug(LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
1941 param->key, param->value);
1943 if (is_cmdline) {
1944 *new_cmdline = param;
1945 new_cmdline = &((*new_cmdline)->next);
1946 } else {
1947 *new = param;
1948 new = &((*new)->next);
1951 i += want_arg ? 2 : 1;
1953 *cmdline_result = front_cmdline;
1954 *result = front;
1955 return 0;
1958 /** Return true iff key is a valid configuration option. */
1960 option_is_recognized(const char *key)
1962 const config_var_t *var = config_find_option(&options_format, key);
1963 return (var != NULL);
1966 /** Return the canonical name of a configuration option, or NULL
1967 * if no such option exists. */
1968 const char *
1969 option_get_canonical_name(const char *key)
1971 const config_var_t *var = config_find_option(&options_format, key);
1972 return var ? var->name : NULL;
1975 /** Return a canonical list of the options assigned for key.
1977 config_line_t *
1978 option_get_assignment(const or_options_t *options, const char *key)
1980 return config_get_assigned_option(&options_format, options, key, 1);
1983 /** Try assigning <b>list</b> to the global options. You do this by duping
1984 * options, assigning list to the new one, then validating it. If it's
1985 * ok, then throw out the old one and stick with the new one. Else,
1986 * revert to old and return failure. Return SETOPT_OK on success, or
1987 * a setopt_err_t on failure.
1989 * If not success, point *<b>msg</b> to a newly allocated string describing
1990 * what went wrong.
1992 setopt_err_t
1993 options_trial_assign(config_line_t *list, int use_defaults,
1994 int clear_first, char **msg)
1996 int r;
1997 or_options_t *trial_options = config_dup(&options_format, get_options());
1999 if ((r=config_assign(&options_format, trial_options,
2000 list, use_defaults, clear_first, msg)) < 0) {
2001 config_free(&options_format, trial_options);
2002 return r;
2005 if (options_validate(get_options_mutable(), trial_options,
2006 global_default_options, 1, msg) < 0) {
2007 config_free(&options_format, trial_options);
2008 return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2011 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2012 config_free(&options_format, trial_options);
2013 return SETOPT_ERR_TRANSITION;
2016 if (set_options(trial_options, msg)<0) {
2017 config_free(&options_format, trial_options);
2018 return SETOPT_ERR_SETTING;
2021 /* we liked it. put it in place. */
2022 return SETOPT_OK;
2025 /** Print a usage message for tor. */
2026 static void
2027 print_usage(void)
2029 printf(
2030 "Copyright (c) 2001-2004, Roger Dingledine\n"
2031 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2032 "Copyright (c) 2007-2013, The Tor Project, Inc.\n\n"
2033 "tor -f <torrc> [args]\n"
2034 "See man page for options, or https://www.torproject.org/ for "
2035 "documentation.\n");
2038 /** Print all non-obsolete torrc options. */
2039 static void
2040 list_torrc_options(void)
2042 int i;
2043 smartlist_t *lines = smartlist_new();
2044 for (i = 0; option_vars_[i].name; ++i) {
2045 const config_var_t *var = &option_vars_[i];
2046 if (var->type == CONFIG_TYPE_OBSOLETE ||
2047 var->type == CONFIG_TYPE_LINELIST_V)
2048 continue;
2049 printf("%s\n", var->name);
2051 smartlist_free(lines);
2054 /** Last value actually set by resolve_my_address. */
2055 static uint32_t last_resolved_addr = 0;
2057 /** Accessor for last_resolved_addr from outside this file. */
2058 uint32_t
2059 get_last_resolved_addr(void)
2061 return last_resolved_addr;
2065 * Use <b>options-\>Address</b> to guess our public IP address.
2067 * Return 0 if all is well, or -1 if we can't find a suitable
2068 * public IP address.
2070 * If we are returning 0:
2071 * - Put our public IP address (in host order) into *<b>addr_out</b>.
2072 * - If <b>method_out</b> is non-NULL, set *<b>method_out</b> to a static
2073 * string describing how we arrived at our answer.
2074 * - If <b>hostname_out</b> is non-NULL, and we resolved a hostname to
2075 * get our address, set *<b>hostname_out</b> to a newly allocated string
2076 * holding that hostname. (If we didn't get our address by resolving a
2077 * hostname, set *<b>hostname_out</b> to NULL.)
2079 * XXXX ipv6
2082 resolve_my_address(int warn_severity, const or_options_t *options,
2083 uint32_t *addr_out,
2084 const char **method_out, char **hostname_out)
2086 struct in_addr in;
2087 uint32_t addr; /* host order */
2088 char hostname[256];
2089 const char *method_used;
2090 const char *hostname_used;
2091 int explicit_ip=1;
2092 int explicit_hostname=1;
2093 int from_interface=0;
2094 char *addr_string = NULL;
2095 const char *address = options->Address;
2096 int notice_severity = warn_severity <= LOG_NOTICE ?
2097 LOG_NOTICE : warn_severity;
2099 tor_addr_t myaddr;
2100 tor_assert(addr_out);
2103 * Step one: Fill in 'hostname' to be our best guess.
2106 if (address && *address) {
2107 strlcpy(hostname, address, sizeof(hostname));
2108 } else { /* then we need to guess our address */
2109 explicit_ip = 0; /* it's implicit */
2110 explicit_hostname = 0; /* it's implicit */
2112 if (gethostname(hostname, sizeof(hostname)) < 0) {
2113 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2114 return -1;
2116 log_debug(LD_CONFIG, "Guessed local host name as '%s'", hostname);
2120 * Step two: Now that we know 'hostname', parse it or resolve it. If
2121 * it doesn't parse or resolve, look at the interface address. Set 'addr'
2122 * to be our (host-order) 32-bit answer.
2125 if (tor_inet_aton(hostname, &in) == 0) {
2126 /* then we have to resolve it */
2127 explicit_ip = 0;
2128 if (tor_lookup_hostname(hostname, &addr)) { /* failed to resolve */
2129 uint32_t interface_ip; /* host order */
2131 if (explicit_hostname) {
2132 log_fn(warn_severity, LD_CONFIG,
2133 "Could not resolve local Address '%s'. Failing.", hostname);
2134 return -1;
2136 log_fn(notice_severity, LD_CONFIG,
2137 "Could not resolve guessed local hostname '%s'. "
2138 "Trying something else.", hostname);
2139 if (get_interface_address(warn_severity, &interface_ip)) {
2140 log_fn(warn_severity, LD_CONFIG,
2141 "Could not get local interface IP address. Failing.");
2142 return -1;
2144 from_interface = 1;
2145 addr = interface_ip;
2146 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2147 "local interface. Using that.", fmt_addr32(addr));
2148 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2149 } else { /* resolved hostname into addr */
2150 tor_addr_from_ipv4h(&myaddr, addr);
2152 if (!explicit_hostname &&
2153 tor_addr_is_internal(&myaddr, 0)) {
2154 tor_addr_t interface_ip;
2156 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2157 "resolves to a private IP address (%s). Trying something "
2158 "else.", hostname, fmt_addr32(addr));
2160 if (get_interface_address6(warn_severity, AF_INET, &interface_ip)<0) {
2161 log_fn(warn_severity, LD_CONFIG,
2162 "Could not get local interface IP address. Too bad.");
2163 } else if (tor_addr_is_internal(&interface_ip, 0)) {
2164 log_fn(notice_severity, LD_CONFIG,
2165 "Interface IP address '%s' is a private address too. "
2166 "Ignoring.", fmt_addr(&interface_ip));
2167 } else {
2168 from_interface = 1;
2169 addr = tor_addr_to_ipv4h(&interface_ip);
2170 log_fn(notice_severity, LD_CONFIG,
2171 "Learned IP address '%s' for local interface."
2172 " Using that.", fmt_addr32(addr));
2173 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2177 } else {
2178 addr = ntohl(in.s_addr); /* set addr so that addr_string is not
2179 * illformed */
2183 * Step three: Check whether 'addr' is an internal IP address, and error
2184 * out if it is and we don't want that.
2187 tor_addr_from_ipv4h(&myaddr,addr);
2189 addr_string = tor_dup_ip(addr);
2190 if (tor_addr_is_internal(&myaddr, 0)) {
2191 /* make sure we're ok with publishing an internal IP */
2192 if (!options->DirAuthorities && !options->AlternateDirAuthority) {
2193 /* if they are using the default authorities, disallow internal IPs
2194 * always. */
2195 log_fn(warn_severity, LD_CONFIG,
2196 "Address '%s' resolves to private IP address '%s'. "
2197 "Tor servers that use the default DirAuthorities must have "
2198 "public IP addresses.", hostname, addr_string);
2199 tor_free(addr_string);
2200 return -1;
2202 if (!explicit_ip) {
2203 /* even if they've set their own authorities, require an explicit IP if
2204 * they're using an internal address. */
2205 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2206 "IP address '%s'. Please set the Address config option to be "
2207 "the IP address you want to use.", hostname, addr_string);
2208 tor_free(addr_string);
2209 return -1;
2214 * Step four: We have a winner! 'addr' is our answer for sure, and
2215 * 'addr_string' is its string form. Fill out the various fields to
2216 * say how we decided it.
2219 log_debug(LD_CONFIG, "Resolved Address to '%s'.", addr_string);
2221 if (explicit_ip) {
2222 method_used = "CONFIGURED";
2223 hostname_used = NULL;
2224 } else if (explicit_hostname) {
2225 method_used = "RESOLVED";
2226 hostname_used = hostname;
2227 } else if (from_interface) {
2228 method_used = "INTERFACE";
2229 hostname_used = NULL;
2230 } else {
2231 method_used = "GETHOSTNAME";
2232 hostname_used = hostname;
2235 *addr_out = addr;
2236 if (method_out)
2237 *method_out = method_used;
2238 if (hostname_out)
2239 *hostname_out = hostname_used ? tor_strdup(hostname_used) : NULL;
2242 * Step five: Check if the answer has changed since last time (or if
2243 * there was no last time), and if so call various functions to keep
2244 * us up-to-date.
2247 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2248 /* Leave this as a notice, regardless of the requested severity,
2249 * at least until dynamic IP address support becomes bulletproof. */
2250 log_notice(LD_NET,
2251 "Your IP address seems to have changed to %s "
2252 "(METHOD=%s%s%s). Updating.",
2253 addr_string, method_used,
2254 hostname_used ? " HOSTNAME=" : "",
2255 hostname_used ? hostname_used : "");
2256 ip_address_changed(0);
2259 if (last_resolved_addr != *addr_out) {
2260 control_event_server_status(LOG_NOTICE,
2261 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s%s%s",
2262 addr_string, method_used,
2263 hostname_used ? " HOSTNAME=" : "",
2264 hostname_used ? hostname_used : "");
2266 last_resolved_addr = *addr_out;
2269 * And finally, clean up and return success.
2272 tor_free(addr_string);
2273 return 0;
2276 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2277 * on a private network.
2280 is_local_addr(const tor_addr_t *addr)
2282 if (tor_addr_is_internal(addr, 0))
2283 return 1;
2284 /* Check whether ip is on the same /24 as we are. */
2285 if (get_options()->EnforceDistinctSubnets == 0)
2286 return 0;
2287 if (tor_addr_family(addr) == AF_INET) {
2288 /*XXXX023 IP6 what corresponds to an /24? */
2289 uint32_t ip = tor_addr_to_ipv4h(addr);
2291 /* It's possible that this next check will hit before the first time
2292 * resolve_my_address actually succeeds. (For clients, it is likely that
2293 * resolve_my_address will never be called at all). In those cases,
2294 * last_resolved_addr will be 0, and so checking to see whether ip is on
2295 * the same /24 as last_resolved_addr will be the same as checking whether
2296 * it was on net 0, which is already done by tor_addr_is_internal.
2298 if ((last_resolved_addr & (uint32_t)0xffffff00ul)
2299 == (ip & (uint32_t)0xffffff00ul))
2300 return 1;
2302 return 0;
2305 /** Return a new empty or_options_t. Used for testing. */
2306 or_options_t *
2307 options_new(void)
2309 return config_new(&options_format);
2312 /** Set <b>options</b> to hold reasonable defaults for most options.
2313 * Each option defaults to zero. */
2314 void
2315 options_init(or_options_t *options)
2317 config_init(&options_format, options);
2320 /** Return a string containing a possible configuration file that would give
2321 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2322 * include options that are the same as Tor's defaults.
2324 char *
2325 options_dump(const or_options_t *options, int how_to_dump)
2327 const or_options_t *use_defaults;
2328 int minimal;
2329 switch (how_to_dump) {
2330 case OPTIONS_DUMP_MINIMAL:
2331 use_defaults = global_default_options;
2332 minimal = 1;
2333 break;
2334 case OPTIONS_DUMP_DEFAULTS:
2335 use_defaults = NULL;
2336 minimal = 1;
2337 break;
2338 case OPTIONS_DUMP_ALL:
2339 use_defaults = NULL;
2340 minimal = 0;
2341 break;
2342 default:
2343 log_warn(LD_BUG, "Bogus value for how_to_dump==%d", how_to_dump);
2344 return NULL;
2347 return config_dump(&options_format, use_defaults, options, minimal, 0);
2350 /** Return 0 if every element of sl is a string holding a decimal
2351 * representation of a port number, or if sl is NULL.
2352 * Otherwise set *msg and return -1. */
2353 static int
2354 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2356 int i;
2357 tor_assert(name);
2359 if (!sl)
2360 return 0;
2362 SMARTLIST_FOREACH(sl, const char *, cp,
2364 i = atoi(cp);
2365 if (i < 1 || i > 65535) {
2366 tor_asprintf(msg, "Port '%s' out of range in %s", cp, name);
2367 return -1;
2370 return 0;
2373 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2374 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2375 * Else return 0.
2377 static int
2378 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2380 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2381 /* This handles an understandable special case where somebody says "2gb"
2382 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2383 --*value;
2385 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2386 tor_asprintf(msg, "%s ("U64_FORMAT") must be at most %d",
2387 desc, U64_PRINTF_ARG(*value),
2388 ROUTER_MAX_DECLARED_BANDWIDTH);
2389 return -1;
2391 return 0;
2394 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2395 * and write it to <b>options</b>-\>PublishServerDescriptor_. Treat "1"
2396 * as "v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2397 * Treat "0" as "".
2398 * Return 0 on success or -1 if not a recognized authority type (in which
2399 * case the value of PublishServerDescriptor_ is undefined). */
2400 static int
2401 compute_publishserverdescriptor(or_options_t *options)
2403 smartlist_t *list = options->PublishServerDescriptor;
2404 dirinfo_type_t *auth = &options->PublishServerDescriptor_;
2405 *auth = NO_DIRINFO;
2406 if (!list) /* empty list, answer is none */
2407 return 0;
2408 SMARTLIST_FOREACH_BEGIN(list, const char *, string) {
2409 if (!strcasecmp(string, "v1"))
2410 log_warn(LD_CONFIG, "PublishServerDescriptor v1 has no effect, because "
2411 "there are no v1 directory authorities anymore.");
2412 else if (!strcmp(string, "1"))
2413 if (options->BridgeRelay)
2414 *auth |= BRIDGE_DIRINFO;
2415 else
2416 *auth |= V3_DIRINFO;
2417 else if (!strcasecmp(string, "v2"))
2418 log_warn(LD_CONFIG, "PublishServerDescriptor v2 has no effect, because "
2419 "there are no v2 directory authorities anymore.");
2420 else if (!strcasecmp(string, "v3"))
2421 *auth |= V3_DIRINFO;
2422 else if (!strcasecmp(string, "bridge"))
2423 *auth |= BRIDGE_DIRINFO;
2424 else if (!strcasecmp(string, "hidserv"))
2425 log_warn(LD_CONFIG,
2426 "PublishServerDescriptor hidserv is invalid. See "
2427 "PublishHidServDescriptors.");
2428 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2429 /* no authority */;
2430 else
2431 return -1;
2432 } SMARTLIST_FOREACH_END(string);
2433 return 0;
2436 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2437 * services can overload the directory system. */
2438 #define MIN_REND_POST_PERIOD (10*60)
2440 /** Higest allowable value for PredictedPortsRelevanceTime; if this is
2441 * too high, our selection of exits will decrease for an extended
2442 * period of time to an uncomfortable level .*/
2443 #define MAX_PREDICTED_CIRCS_RELEVANCE (60*60)
2445 /** Highest allowable value for RendPostPeriod. */
2446 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2448 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2449 * will generate too many circuits and potentially overload the network. */
2450 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2452 /** Highest allowable value for MaxCircuitDirtiness: prevents time_t
2453 * overflows. */
2454 #define MAX_MAX_CIRCUIT_DIRTINESS (30*24*60*60)
2456 /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
2457 * will generate too many circuits and potentially overload the network. */
2458 #define MIN_CIRCUIT_STREAM_TIMEOUT 10
2460 /** Lowest allowable value for HeartbeatPeriod; if this is too low, we might
2461 * expose more information than we're comfortable with. */
2462 #define MIN_HEARTBEAT_PERIOD (30*60)
2464 /** Lowest recommended value for CircuitBuildTimeout; if it is set too low
2465 * and LearnCircuitBuildTimeout is off, the failure rate for circuit
2466 * construction may be very high. In that case, if it is set below this
2467 * threshold emit a warning.
2468 * */
2469 #define RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT (10)
2471 static int
2472 options_validate_cb(void *old_options, void *options, void *default_options,
2473 int from_setconf, char **msg)
2475 return options_validate(old_options, options, default_options,
2476 from_setconf, msg);
2479 /** Return 0 if every setting in <b>options</b> is reasonable, is a
2480 * permissible transition from <b>old_options</b>, and none of the
2481 * testing-only settings differ from <b>default_options</b> unless in
2482 * testing mode. Else return -1. Should have no side effects, except for
2483 * normalizing the contents of <b>options</b>.
2485 * On error, tor_strdup an error explanation into *<b>msg</b>.
2487 * XXX
2488 * If <b>from_setconf</b>, we were called by the controller, and our
2489 * Log line should stay empty. If it's 0, then give us a default log
2490 * if there are no logs defined.
2492 STATIC int
2493 options_validate(or_options_t *old_options, or_options_t *options,
2494 or_options_t *default_options, int from_setconf, char **msg)
2496 int i;
2497 config_line_t *cl;
2498 const char *uname = get_uname();
2499 int n_ports=0;
2500 #define REJECT(arg) \
2501 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2502 #define COMPLAIN(arg) STMT_BEGIN log_warn(LD_CONFIG, arg); STMT_END
2504 tor_assert(msg);
2505 *msg = NULL;
2507 if (server_mode(options) &&
2508 (!strcmpstart(uname, "Windows 95") ||
2509 !strcmpstart(uname, "Windows 98") ||
2510 !strcmpstart(uname, "Windows Me"))) {
2511 log_warn(LD_CONFIG, "Tor is running as a server, but you are "
2512 "running %s; this probably won't work. See "
2513 "https://www.torproject.org/docs/faq.html#BestOSForRelay "
2514 "for details.", uname);
2517 if (parse_ports(options, 1, msg, &n_ports) < 0)
2518 return -1;
2520 if (parse_outbound_addresses(options, 1, msg) < 0)
2521 return -1;
2523 if (validate_data_directory(options)<0)
2524 REJECT("Invalid DataDirectory");
2526 if (options->Nickname == NULL) {
2527 if (server_mode(options)) {
2528 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
2530 } else {
2531 if (!is_legal_nickname(options->Nickname)) {
2532 tor_asprintf(msg,
2533 "Nickname '%s' is wrong length or contains illegal characters.",
2534 options->Nickname);
2535 return -1;
2539 if (server_mode(options) && !options->ContactInfo)
2540 log_notice(LD_CONFIG, "Your ContactInfo config option is not set. "
2541 "Please consider setting it, so we can contact you if your server is "
2542 "misconfigured or something else goes wrong.");
2544 /* Special case on first boot if no Log options are given. */
2545 if (!options->Logs && !options->RunAsDaemon && !from_setconf) {
2546 if (quiet_level == 0)
2547 config_line_append(&options->Logs, "Log", "notice stdout");
2548 else if (quiet_level == 1)
2549 config_line_append(&options->Logs, "Log", "warn stdout");
2552 if (options_init_logs(options, 1)<0) /* Validate the tor_log(s) */
2553 REJECT("Failed to validate Log options. See logs for details.");
2555 if (authdir_mode(options)) {
2556 /* confirm that our address isn't broken, so we can complain now */
2557 uint32_t tmp;
2558 if (resolve_my_address(LOG_WARN, options, &tmp, NULL, NULL) < 0)
2559 REJECT("Failed to resolve/guess local address. See logs for details.");
2562 #ifndef _WIN32
2563 if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
2564 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
2565 #endif
2567 /* XXXX require that the only port not be DirPort? */
2568 /* XXXX require that at least one port be listened-upon. */
2569 if (n_ports == 0 && !options->RendConfigLines)
2570 log_warn(LD_CONFIG,
2571 "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
2572 "undefined, and there aren't any hidden services configured. "
2573 "Tor will still run, but probably won't do anything.");
2575 options->TransProxyType_parsed = TPT_DEFAULT;
2576 #ifdef USE_TRANSPARENT
2577 if (options->TransProxyType) {
2578 if (!strcasecmp(options->TransProxyType, "default")) {
2579 options->TransProxyType_parsed = TPT_DEFAULT;
2580 } else if (!strcasecmp(options->TransProxyType, "pf-divert")) {
2581 #ifndef __OpenBSD__
2582 REJECT("pf-divert is a OpenBSD-specific feature.");
2583 #else
2584 options->TransProxyType_parsed = TPT_PF_DIVERT;
2585 #endif
2586 } else if (!strcasecmp(options->TransProxyType, "tproxy")) {
2587 #ifndef __linux__
2588 REJECT("TPROXY is a Linux-specific feature.");
2589 #else
2590 options->TransProxyType_parsed = TPT_TPROXY;
2591 #endif
2592 } else if (!strcasecmp(options->TransProxyType, "ipfw")) {
2593 #ifndef __FreeBSD__
2594 REJECT("ipfw is a FreeBSD-specific feature.");
2595 #else
2596 options->TransProxyType_parsed = TPT_IPFW;
2597 #endif
2598 } else {
2599 REJECT("Unrecognized value for TransProxyType");
2602 if (strcasecmp(options->TransProxyType, "default") &&
2603 !options->TransPort_set) {
2604 REJECT("Cannot use TransProxyType without any valid TransPort or "
2605 "TransListenAddress.");
2608 #else
2609 if (options->TransPort_set)
2610 REJECT("TransPort and TransListenAddress are disabled "
2611 "in this build.");
2612 #endif
2614 if (options->TokenBucketRefillInterval <= 0
2615 || options->TokenBucketRefillInterval > 1000) {
2616 REJECT("TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
2619 if (options->ExcludeExitNodes || options->ExcludeNodes) {
2620 options->ExcludeExitNodesUnion_ = routerset_new();
2621 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeExitNodes);
2622 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeNodes);
2625 if (options->NodeFamilies) {
2626 options->NodeFamilySets = smartlist_new();
2627 for (cl = options->NodeFamilies; cl; cl = cl->next) {
2628 routerset_t *rs = routerset_new();
2629 if (routerset_parse(rs, cl->value, cl->key) == 0) {
2630 smartlist_add(options->NodeFamilySets, rs);
2631 } else {
2632 routerset_free(rs);
2637 if (options->TLSECGroup && (strcasecmp(options->TLSECGroup, "P256") &&
2638 strcasecmp(options->TLSECGroup, "P224"))) {
2639 COMPLAIN("Unrecognized TLSECGroup: Falling back to the default.");
2640 tor_free(options->TLSECGroup);
2643 if (options->ExcludeNodes && options->StrictNodes) {
2644 COMPLAIN("You have asked to exclude certain relays from all positions "
2645 "in your circuits. Expect hidden services and other Tor "
2646 "features to be broken in unpredictable ways.");
2649 if (options->AuthoritativeDir) {
2650 if (!options->ContactInfo && !options->TestingTorNetwork)
2651 REJECT("Authoritative directory servers must set ContactInfo");
2652 if (!options->RecommendedClientVersions)
2653 options->RecommendedClientVersions =
2654 config_lines_dup(options->RecommendedVersions);
2655 if (!options->RecommendedServerVersions)
2656 options->RecommendedServerVersions =
2657 config_lines_dup(options->RecommendedVersions);
2658 if (options->VersioningAuthoritativeDir &&
2659 (!options->RecommendedClientVersions ||
2660 !options->RecommendedServerVersions))
2661 REJECT("Versioning authoritative dir servers must set "
2662 "Recommended*Versions.");
2663 if (options->UseEntryGuards) {
2664 log_info(LD_CONFIG, "Authoritative directory servers can't set "
2665 "UseEntryGuards. Disabling.");
2666 options->UseEntryGuards = 0;
2668 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
2669 log_info(LD_CONFIG, "Authoritative directories always try to download "
2670 "extra-info documents. Setting DownloadExtraInfo.");
2671 options->DownloadExtraInfo = 1;
2673 if (!(options->BridgeAuthoritativeDir ||
2674 options->V3AuthoritativeDir))
2675 REJECT("AuthoritativeDir is set, but none of "
2676 "(Bridge/V3)AuthoritativeDir is set.");
2677 /* If we have a v3bandwidthsfile and it's broken, complain on startup */
2678 if (options->V3BandwidthsFile && !old_options) {
2679 dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
2683 if (options->AuthoritativeDir && !options->DirPort_set)
2684 REJECT("Running as authoritative directory, but no DirPort set.");
2686 if (options->AuthoritativeDir && !options->ORPort_set)
2687 REJECT("Running as authoritative directory, but no ORPort set.");
2689 if (options->AuthoritativeDir && options->ClientOnly)
2690 REJECT("Running as authoritative directory, but ClientOnly also set.");
2692 if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
2693 REJECT("FetchDirInfoExtraEarly requires that you also set "
2694 "FetchDirInfoEarly");
2696 if (options->ConnLimit <= 0) {
2697 tor_asprintf(msg,
2698 "ConnLimit must be greater than 0, but was set to %d",
2699 options->ConnLimit);
2700 return -1;
2703 if (options->PathsNeededToBuildCircuits >= 0.0) {
2704 if (options->PathsNeededToBuildCircuits < 0.25) {
2705 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too low. Increasing "
2706 "to 0.25");
2707 options->PathsNeededToBuildCircuits = 0.25;
2708 } else if (options->PathsNeededToBuildCircuits > 0.95) {
2709 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too high. Decreasing "
2710 "to 0.95");
2711 options->PathsNeededToBuildCircuits = 0.95;
2715 if (options->MaxClientCircuitsPending <= 0 ||
2716 options->MaxClientCircuitsPending > MAX_MAX_CLIENT_CIRCUITS_PENDING) {
2717 tor_asprintf(msg,
2718 "MaxClientCircuitsPending must be between 1 and %d, but "
2719 "was set to %d", MAX_MAX_CLIENT_CIRCUITS_PENDING,
2720 options->MaxClientCircuitsPending);
2721 return -1;
2724 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
2725 return -1;
2727 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
2728 return -1;
2730 if (validate_ports_csv(options->RejectPlaintextPorts,
2731 "RejectPlaintextPorts", msg) < 0)
2732 return -1;
2734 if (validate_ports_csv(options->WarnPlaintextPorts,
2735 "WarnPlaintextPorts", msg) < 0)
2736 return -1;
2738 if (options->FascistFirewall && !options->ReachableAddresses) {
2739 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
2740 /* We already have firewall ports set, so migrate them to
2741 * ReachableAddresses, which will set ReachableORAddresses and
2742 * ReachableDirAddresses if they aren't set explicitly. */
2743 smartlist_t *instead = smartlist_new();
2744 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
2745 new_line->key = tor_strdup("ReachableAddresses");
2746 /* If we're configured with the old format, we need to prepend some
2747 * open ports. */
2748 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
2750 int p = atoi(portno);
2751 if (p<0) continue;
2752 smartlist_add_asprintf(instead, "*:%d", p);
2754 new_line->value = smartlist_join_strings(instead,",",0,NULL);
2755 /* These have been deprecated since 0.1.1.5-alpha-cvs */
2756 log_notice(LD_CONFIG,
2757 "Converting FascistFirewall and FirewallPorts "
2758 "config options to new format: \"ReachableAddresses %s\"",
2759 new_line->value);
2760 options->ReachableAddresses = new_line;
2761 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
2762 smartlist_free(instead);
2763 } else {
2764 /* We do not have FirewallPorts set, so add 80 to
2765 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
2766 if (!options->ReachableDirAddresses) {
2767 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
2768 new_line->key = tor_strdup("ReachableDirAddresses");
2769 new_line->value = tor_strdup("*:80");
2770 options->ReachableDirAddresses = new_line;
2771 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
2772 "to new format: \"ReachableDirAddresses *:80\"");
2774 if (!options->ReachableORAddresses) {
2775 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
2776 new_line->key = tor_strdup("ReachableORAddresses");
2777 new_line->value = tor_strdup("*:443");
2778 options->ReachableORAddresses = new_line;
2779 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
2780 "to new format: \"ReachableORAddresses *:443\"");
2785 for (i=0; i<3; i++) {
2786 config_line_t **linep =
2787 (i==0) ? &options->ReachableAddresses :
2788 (i==1) ? &options->ReachableORAddresses :
2789 &options->ReachableDirAddresses;
2790 if (!*linep)
2791 continue;
2792 /* We need to end with a reject *:*, not an implicit accept *:* */
2793 for (;;) {
2794 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
2795 break;
2796 linep = &((*linep)->next);
2797 if (!*linep) {
2798 *linep = tor_malloc_zero(sizeof(config_line_t));
2799 (*linep)->key = tor_strdup(
2800 (i==0) ? "ReachableAddresses" :
2801 (i==1) ? "ReachableORAddresses" :
2802 "ReachableDirAddresses");
2803 (*linep)->value = tor_strdup("reject *:*");
2804 break;
2809 if ((options->ReachableAddresses ||
2810 options->ReachableORAddresses ||
2811 options->ReachableDirAddresses) &&
2812 server_mode(options))
2813 REJECT("Servers must be able to freely connect to the rest "
2814 "of the Internet, so they must not set Reachable*Addresses "
2815 "or FascistFirewall.");
2817 if (options->UseBridges &&
2818 server_mode(options))
2819 REJECT("Servers must be able to freely connect to the rest "
2820 "of the Internet, so they must not set UseBridges.");
2822 /* If both of these are set, we'll end up with funny behavior where we
2823 * demand enough entrynodes be up and running else we won't build
2824 * circuits, yet we never actually use them. */
2825 if (options->UseBridges && options->EntryNodes)
2826 REJECT("You cannot set both UseBridges and EntryNodes.");
2828 if (options->EntryNodes && !options->UseEntryGuards) {
2829 REJECT("If EntryNodes is set, UseEntryGuards must be enabled.");
2832 options->MaxMemInQueues =
2833 compute_real_max_mem_in_queues(options->MaxMemInQueues_raw,
2834 server_mode(options));
2836 options->AllowInvalid_ = 0;
2838 if (options->AllowInvalidNodes) {
2839 SMARTLIST_FOREACH_BEGIN(options->AllowInvalidNodes, const char *, cp) {
2840 if (!strcasecmp(cp, "entry"))
2841 options->AllowInvalid_ |= ALLOW_INVALID_ENTRY;
2842 else if (!strcasecmp(cp, "exit"))
2843 options->AllowInvalid_ |= ALLOW_INVALID_EXIT;
2844 else if (!strcasecmp(cp, "middle"))
2845 options->AllowInvalid_ |= ALLOW_INVALID_MIDDLE;
2846 else if (!strcasecmp(cp, "introduction"))
2847 options->AllowInvalid_ |= ALLOW_INVALID_INTRODUCTION;
2848 else if (!strcasecmp(cp, "rendezvous"))
2849 options->AllowInvalid_ |= ALLOW_INVALID_RENDEZVOUS;
2850 else {
2851 tor_asprintf(msg,
2852 "Unrecognized value '%s' in AllowInvalidNodes", cp);
2853 return -1;
2855 } SMARTLIST_FOREACH_END(cp);
2858 if (!options->SafeLogging ||
2859 !strcasecmp(options->SafeLogging, "0")) {
2860 options->SafeLogging_ = SAFELOG_SCRUB_NONE;
2861 } else if (!strcasecmp(options->SafeLogging, "relay")) {
2862 options->SafeLogging_ = SAFELOG_SCRUB_RELAY;
2863 } else if (!strcasecmp(options->SafeLogging, "1")) {
2864 options->SafeLogging_ = SAFELOG_SCRUB_ALL;
2865 } else {
2866 tor_asprintf(msg,
2867 "Unrecognized value '%s' in SafeLogging",
2868 escaped(options->SafeLogging));
2869 return -1;
2872 if (compute_publishserverdescriptor(options) < 0) {
2873 tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
2874 return -1;
2877 if ((options->BridgeRelay
2878 || options->PublishServerDescriptor_ & BRIDGE_DIRINFO)
2879 && (options->PublishServerDescriptor_ & V3_DIRINFO)) {
2880 REJECT("Bridges are not supposed to publish router descriptors to the "
2881 "directory authorities. Please correct your "
2882 "PublishServerDescriptor line.");
2885 if (options->BridgeRelay && options->DirPort_set) {
2886 log_warn(LD_CONFIG, "Can't set a DirPort on a bridge relay; disabling "
2887 "DirPort");
2888 config_free_lines(options->DirPort_lines);
2889 options->DirPort_lines = NULL;
2890 options->DirPort_set = 0;
2893 if (options->MinUptimeHidServDirectoryV2 < 0) {
2894 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
2895 "least 0 seconds. Changing to 0.");
2896 options->MinUptimeHidServDirectoryV2 = 0;
2899 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
2900 log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
2901 "raising to %d seconds.", MIN_REND_POST_PERIOD);
2902 options->RendPostPeriod = MIN_REND_POST_PERIOD;
2905 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
2906 log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
2907 MAX_DIR_PERIOD);
2908 options->RendPostPeriod = MAX_DIR_PERIOD;
2911 if (options->PredictedPortsRelevanceTime >
2912 MAX_PREDICTED_CIRCS_RELEVANCE) {
2913 log_warn(LD_CONFIG, "PredictedPortsRelevanceTime is too large; "
2914 "clipping to %ds.", MAX_PREDICTED_CIRCS_RELEVANCE);
2915 options->PredictedPortsRelevanceTime = MAX_PREDICTED_CIRCS_RELEVANCE;
2918 if (options->Tor2webMode && options->LearnCircuitBuildTimeout) {
2919 /* LearnCircuitBuildTimeout and Tor2webMode are incompatible in
2920 * two ways:
2922 * - LearnCircuitBuildTimeout results in a low CBT, which
2923 * Tor2webMode's use of one-hop rendezvous circuits lowers
2924 * much further, producing *far* too many timeouts.
2926 * - The adaptive CBT code does not update its timeout estimate
2927 * using build times for single-hop circuits.
2929 * If we fix both of these issues someday, we should test
2930 * Tor2webMode with LearnCircuitBuildTimeout on again. */
2931 log_notice(LD_CONFIG,"Tor2webMode is enabled; turning "
2932 "LearnCircuitBuildTimeout off.");
2933 options->LearnCircuitBuildTimeout = 0;
2936 if (options->Tor2webMode && options->UseEntryGuards) {
2937 /* tor2web mode clients do not (and should not) use entry guards
2938 * in any meaningful way. Further, tor2web mode causes the hidden
2939 * service client code to do things which break the path bias
2940 * detector, and it's far easier to turn off entry guards (and
2941 * thus the path bias detector with it) than to figure out how to
2942 * make a piece of code which cannot possibly help tor2web mode
2943 * users compatible with tor2web mode.
2945 log_notice(LD_CONFIG,
2946 "Tor2WebMode is enabled; disabling UseEntryGuards.");
2947 options->UseEntryGuards = 0;
2950 if (!(options->UseEntryGuards) &&
2951 (options->RendConfigLines != NULL)) {
2952 log_warn(LD_CONFIG,
2953 "UseEntryGuards is disabled, but you have configured one or more "
2954 "hidden services on this Tor instance. Your hidden services "
2955 "will be very easy to locate using a well-known attack -- see "
2956 "http://freehaven.net/anonbib/#hs-attack06 for details.");
2959 if (!options->LearnCircuitBuildTimeout && options->CircuitBuildTimeout &&
2960 options->CircuitBuildTimeout < RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT) {
2961 log_warn(LD_CONFIG,
2962 "CircuitBuildTimeout is shorter (%d seconds) than the recommended "
2963 "minimum (%d seconds), and LearnCircuitBuildTimeout is disabled. "
2964 "If tor isn't working, raise this value or enable "
2965 "LearnCircuitBuildTimeout.",
2966 options->CircuitBuildTimeout,
2967 RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT );
2968 } else if (!options->LearnCircuitBuildTimeout &&
2969 !options->CircuitBuildTimeout) {
2970 log_notice(LD_CONFIG, "You disabled LearnCircuitBuildTimeout, but didn't "
2971 "a CircuitBuildTimeout. I'll pick a plausible default.");
2974 if (options->PathBiasNoticeRate > 1.0) {
2975 tor_asprintf(msg,
2976 "PathBiasNoticeRate is too high. "
2977 "It must be between 0 and 1.0");
2978 return -1;
2980 if (options->PathBiasWarnRate > 1.0) {
2981 tor_asprintf(msg,
2982 "PathBiasWarnRate is too high. "
2983 "It must be between 0 and 1.0");
2984 return -1;
2986 if (options->PathBiasExtremeRate > 1.0) {
2987 tor_asprintf(msg,
2988 "PathBiasExtremeRate is too high. "
2989 "It must be between 0 and 1.0");
2990 return -1;
2992 if (options->PathBiasNoticeUseRate > 1.0) {
2993 tor_asprintf(msg,
2994 "PathBiasNoticeUseRate is too high. "
2995 "It must be between 0 and 1.0");
2996 return -1;
2998 if (options->PathBiasExtremeUseRate > 1.0) {
2999 tor_asprintf(msg,
3000 "PathBiasExtremeUseRate is too high. "
3001 "It must be between 0 and 1.0");
3002 return -1;
3005 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3006 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3007 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3008 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3011 if (options->MaxCircuitDirtiness > MAX_MAX_CIRCUIT_DIRTINESS) {
3012 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too high; "
3013 "setting to %d days.", MAX_MAX_CIRCUIT_DIRTINESS/86400);
3014 options->MaxCircuitDirtiness = MAX_MAX_CIRCUIT_DIRTINESS;
3017 if (options->CircuitStreamTimeout &&
3018 options->CircuitStreamTimeout < MIN_CIRCUIT_STREAM_TIMEOUT) {
3019 log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
3020 "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
3021 options->CircuitStreamTimeout = MIN_CIRCUIT_STREAM_TIMEOUT;
3024 if (options->HeartbeatPeriod &&
3025 options->HeartbeatPeriod < MIN_HEARTBEAT_PERIOD) {
3026 log_warn(LD_CONFIG, "HeartbeatPeriod option is too short; "
3027 "raising to %d seconds.", MIN_HEARTBEAT_PERIOD);
3028 options->HeartbeatPeriod = MIN_HEARTBEAT_PERIOD;
3031 if (options->KeepalivePeriod < 1)
3032 REJECT("KeepalivePeriod option must be positive.");
3034 if (options->PortForwarding && options->Sandbox) {
3035 REJECT("PortForwarding is not compatible with Sandbox; at most one can "
3036 "be set");
3039 if (ensure_bandwidth_cap(&options->BandwidthRate,
3040 "BandwidthRate", msg) < 0)
3041 return -1;
3042 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3043 "BandwidthBurst", msg) < 0)
3044 return -1;
3045 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3046 "MaxAdvertisedBandwidth", msg) < 0)
3047 return -1;
3048 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3049 "RelayBandwidthRate", msg) < 0)
3050 return -1;
3051 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3052 "RelayBandwidthBurst", msg) < 0)
3053 return -1;
3054 if (ensure_bandwidth_cap(&options->PerConnBWRate,
3055 "PerConnBWRate", msg) < 0)
3056 return -1;
3057 if (ensure_bandwidth_cap(&options->PerConnBWBurst,
3058 "PerConnBWBurst", msg) < 0)
3059 return -1;
3060 if (ensure_bandwidth_cap(&options->AuthDirFastGuarantee,
3061 "AuthDirFastGuarantee", msg) < 0)
3062 return -1;
3063 if (ensure_bandwidth_cap(&options->AuthDirGuardBWGuarantee,
3064 "AuthDirGuardBWGuarantee", msg) < 0)
3065 return -1;
3067 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3068 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3069 if (options->RelayBandwidthBurst && !options->RelayBandwidthRate)
3070 options->RelayBandwidthRate = options->RelayBandwidthBurst;
3072 if (server_mode(options)) {
3073 if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3074 tor_asprintf(msg,
3075 "BandwidthRate is set to %d bytes/second. "
3076 "For servers, it must be at least %d.",
3077 (int)options->BandwidthRate,
3078 ROUTER_REQUIRED_MIN_BANDWIDTH);
3079 return -1;
3080 } else if (options->MaxAdvertisedBandwidth <
3081 ROUTER_REQUIRED_MIN_BANDWIDTH/2) {
3082 tor_asprintf(msg,
3083 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3084 "For servers, it must be at least %d.",
3085 (int)options->MaxAdvertisedBandwidth,
3086 ROUTER_REQUIRED_MIN_BANDWIDTH/2);
3087 return -1;
3089 if (options->RelayBandwidthRate &&
3090 options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3091 tor_asprintf(msg,
3092 "RelayBandwidthRate is set to %d bytes/second. "
3093 "For servers, it must be at least %d.",
3094 (int)options->RelayBandwidthRate,
3095 ROUTER_REQUIRED_MIN_BANDWIDTH);
3096 return -1;
3100 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3101 REJECT("RelayBandwidthBurst must be at least equal "
3102 "to RelayBandwidthRate.");
3104 if (options->BandwidthRate > options->BandwidthBurst)
3105 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3107 /* if they set relaybandwidth* really high but left bandwidth*
3108 * at the default, raise the defaults. */
3109 if (options->RelayBandwidthRate > options->BandwidthRate)
3110 options->BandwidthRate = options->RelayBandwidthRate;
3111 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3112 options->BandwidthBurst = options->RelayBandwidthBurst;
3114 if (accounting_parse_options(options, 1)<0)
3115 REJECT("Failed to parse accounting options. See logs for details.");
3117 if (options->AccountingMax) {
3118 if (options->RendConfigLines && server_mode(options)) {
3119 log_warn(LD_CONFIG, "Using accounting with a hidden service and an "
3120 "ORPort is risky: your hidden service(s) and your public "
3121 "address will all turn off at the same time, which may alert "
3122 "observers that they are being run by the same party.");
3123 } else if (config_count_key(options->RendConfigLines,
3124 "HiddenServiceDir") > 1) {
3125 log_warn(LD_CONFIG, "Using accounting with multiple hidden services is "
3126 "risky: they will all turn off at the same time, which may "
3127 "alert observers that they are being run by the same party.");
3131 if (options->HTTPProxy) { /* parse it now */
3132 if (tor_addr_port_lookup(options->HTTPProxy,
3133 &options->HTTPProxyAddr, &options->HTTPProxyPort) < 0)
3134 REJECT("HTTPProxy failed to parse or resolve. Please fix.");
3135 if (options->HTTPProxyPort == 0) { /* give it a default */
3136 options->HTTPProxyPort = 80;
3140 if (options->HTTPProxyAuthenticator) {
3141 if (strlen(options->HTTPProxyAuthenticator) >= 512)
3142 REJECT("HTTPProxyAuthenticator is too long (>= 512 chars).");
3145 if (options->HTTPSProxy) { /* parse it now */
3146 if (tor_addr_port_lookup(options->HTTPSProxy,
3147 &options->HTTPSProxyAddr, &options->HTTPSProxyPort) <0)
3148 REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
3149 if (options->HTTPSProxyPort == 0) { /* give it a default */
3150 options->HTTPSProxyPort = 443;
3154 if (options->HTTPSProxyAuthenticator) {
3155 if (strlen(options->HTTPSProxyAuthenticator) >= 512)
3156 REJECT("HTTPSProxyAuthenticator is too long (>= 512 chars).");
3159 if (options->Socks4Proxy) { /* parse it now */
3160 if (tor_addr_port_lookup(options->Socks4Proxy,
3161 &options->Socks4ProxyAddr,
3162 &options->Socks4ProxyPort) <0)
3163 REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
3164 if (options->Socks4ProxyPort == 0) { /* give it a default */
3165 options->Socks4ProxyPort = 1080;
3169 if (options->Socks5Proxy) { /* parse it now */
3170 if (tor_addr_port_lookup(options->Socks5Proxy,
3171 &options->Socks5ProxyAddr,
3172 &options->Socks5ProxyPort) <0)
3173 REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
3174 if (options->Socks5ProxyPort == 0) { /* give it a default */
3175 options->Socks5ProxyPort = 1080;
3179 /* Check if more than one proxy type has been enabled. */
3180 if (!!options->Socks4Proxy + !!options->Socks5Proxy +
3181 !!options->HTTPSProxy + !!options->ClientTransportPlugin > 1)
3182 REJECT("You have configured more than one proxy type. "
3183 "(Socks4Proxy|Socks5Proxy|HTTPSProxy|ClientTransportPlugin)");
3185 /* Check if the proxies will give surprising behavior. */
3186 if (options->HTTPProxy && !(options->Socks4Proxy ||
3187 options->Socks5Proxy ||
3188 options->HTTPSProxy)) {
3189 log_warn(LD_CONFIG, "HTTPProxy configured, but no SOCKS proxy or "
3190 "HTTPS proxy configured. Watch out: this configuration will "
3191 "proxy unencrypted directory connections only.");
3194 if (options->Socks5ProxyUsername) {
3195 size_t len;
3197 len = strlen(options->Socks5ProxyUsername);
3198 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
3199 REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
3201 if (!options->Socks5ProxyPassword)
3202 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3204 len = strlen(options->Socks5ProxyPassword);
3205 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
3206 REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
3207 } else if (options->Socks5ProxyPassword)
3208 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3210 if (options->HashedControlPassword) {
3211 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3212 if (!sl) {
3213 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3214 } else {
3215 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3216 smartlist_free(sl);
3220 if (options->HashedControlSessionPassword) {
3221 smartlist_t *sl = decode_hashed_passwords(
3222 options->HashedControlSessionPassword);
3223 if (!sl) {
3224 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3225 } else {
3226 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3227 smartlist_free(sl);
3231 if (options->OwningControllerProcess) {
3232 const char *validate_pspec_msg = NULL;
3233 if (tor_validate_process_specifier(options->OwningControllerProcess,
3234 &validate_pspec_msg)) {
3235 tor_asprintf(msg, "Bad OwningControllerProcess: %s",
3236 validate_pspec_msg);
3237 return -1;
3241 if (options->ControlPort_set && !options->HashedControlPassword &&
3242 !options->HashedControlSessionPassword &&
3243 !options->CookieAuthentication) {
3244 log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
3245 "has been configured. This means that any program on your "
3246 "computer can reconfigure your Tor. That's bad! You should "
3247 "upgrade your Tor controller as soon as possible.");
3250 if (options->CookieAuthFileGroupReadable && !options->CookieAuthFile) {
3251 log_warn(LD_CONFIG, "CookieAuthFileGroupReadable is set, but will have "
3252 "no effect: you must specify an explicit CookieAuthFile to "
3253 "have it group-readable.");
3256 if (options->UseEntryGuards && ! options->NumEntryGuards)
3257 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3259 if (options->MyFamily && options->BridgeRelay) {
3260 log_warn(LD_CONFIG, "Listing a family for a bridge relay is not "
3261 "supported: it can reveal bridge fingerprints to censors. "
3262 "You should also make sure you aren't listing this bridge's "
3263 "fingerprint in any other MyFamily.");
3265 if (check_nickname_list(&options->MyFamily, "MyFamily", msg))
3266 return -1;
3267 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3268 routerset_t *rs = routerset_new();
3269 if (routerset_parse(rs, cl->value, cl->key)) {
3270 routerset_free(rs);
3271 return -1;
3273 routerset_free(rs);
3276 if (validate_addr_policies(options, msg) < 0)
3277 return -1;
3279 if (validate_dir_servers(options, old_options) < 0)
3280 REJECT("Directory authority/fallback line did not parse. See logs "
3281 "for details.");
3283 if (options->UseBridges && !options->Bridges)
3284 REJECT("If you set UseBridges, you must specify at least one bridge.");
3286 for (cl = options->Bridges; cl; cl = cl->next) {
3287 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
3288 if (!bridge_line)
3289 REJECT("Bridge line did not parse. See logs for details.");
3290 bridge_line_free(bridge_line);
3293 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
3294 if (parse_client_transport_line(options, cl->value, 1)<0)
3295 REJECT("Invalid client transport line. See logs for details.");
3298 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
3299 if (parse_server_transport_line(options, cl->value, 1)<0)
3300 REJECT("Invalid server transport line. See logs for details.");
3303 if (options->ServerTransportPlugin && !server_mode(options)) {
3304 log_notice(LD_GENERAL, "Tor is not configured as a relay but you specified"
3305 " a ServerTransportPlugin line (%s). The ServerTransportPlugin "
3306 "line will be ignored.",
3307 escaped(options->ServerTransportPlugin->value));
3310 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
3311 /** If get_bindaddr_from_transport_listen_line() fails with
3312 'transport' being NULL, it means that something went wrong
3313 while parsing the ServerTransportListenAddr line. */
3314 char *bindaddr = get_bindaddr_from_transport_listen_line(cl->value, NULL);
3315 if (!bindaddr)
3316 REJECT("ServerTransportListenAddr did not parse. See logs for details.");
3317 tor_free(bindaddr);
3320 if (options->ServerTransportListenAddr && !options->ServerTransportPlugin) {
3321 log_notice(LD_GENERAL, "You need at least a single managed-proxy to "
3322 "specify a transport listen address. The "
3323 "ServerTransportListenAddr line will be ignored.");
3326 for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
3327 /** If get_options_from_transport_options_line() fails with
3328 'transport' being NULL, it means that something went wrong
3329 while parsing the ServerTransportOptions line. */
3330 smartlist_t *options_sl =
3331 get_options_from_transport_options_line(cl->value, NULL);
3332 if (!options_sl)
3333 REJECT("ServerTransportOptions did not parse. See logs for details.");
3335 SMARTLIST_FOREACH(options_sl, char *, cp, tor_free(cp));
3336 smartlist_free(options_sl);
3339 if (options->ConstrainedSockets) {
3340 /* If the user wants to constrain socket buffer use, make sure the desired
3341 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3342 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3343 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3344 options->ConstrainedSockSize % 1024) {
3345 tor_asprintf(msg,
3346 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3347 "in 1024 byte increments.",
3348 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3349 return -1;
3351 if (options->DirPort_set) {
3352 /* Providing cached directory entries while system TCP buffers are scarce
3353 * will exacerbate the socket errors. Suggest that this be disabled. */
3354 COMPLAIN("You have requested constrained socket buffers while also "
3355 "serving directory entries via DirPort. It is strongly "
3356 "suggested that you disable serving directory requests when "
3357 "system TCP buffer resources are scarce.");
3361 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3362 options->V3AuthVotingInterval/2) {
3363 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3364 "V3AuthVotingInterval");
3366 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
3367 REJECT("V3AuthVoteDelay is way too low.");
3368 if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
3369 REJECT("V3AuthDistDelay is way too low.");
3371 if (options->V3AuthNIntervalsValid < 2)
3372 REJECT("V3AuthNIntervalsValid must be at least 2.");
3374 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3375 REJECT("V3AuthVotingInterval is insanely low.");
3376 } else if (options->V3AuthVotingInterval > 24*60*60) {
3377 REJECT("V3AuthVotingInterval is insanely high.");
3378 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3379 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3382 if (rend_config_services(options, 1) < 0)
3383 REJECT("Failed to configure rendezvous options. See logs for details.");
3385 /* Parse client-side authorization for hidden services. */
3386 if (rend_parse_service_authorization(options, 1) < 0)
3387 REJECT("Failed to configure client authorization for hidden services. "
3388 "See logs for details.");
3390 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv4,
3391 AF_INET, 1, msg)<0)
3392 return -1;
3393 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv6,
3394 AF_INET6, 1, msg)<0)
3395 return -1;
3397 if (options->AutomapHostsSuffixes) {
3398 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
3400 size_t len = strlen(suf);
3401 if (len && suf[len-1] == '.')
3402 suf[len-1] = '\0';
3406 if (options->TestingTorNetwork &&
3407 !(options->DirAuthorities ||
3408 (options->AlternateDirAuthority &&
3409 options->AlternateBridgeAuthority))) {
3410 REJECT("TestingTorNetwork may only be configured in combination with "
3411 "a non-default set of DirAuthority or both of "
3412 "AlternateDirAuthority and AlternateBridgeAuthority configured.");
3415 if (options->AllowSingleHopExits && !options->DirAuthorities) {
3416 COMPLAIN("You have set AllowSingleHopExits; now your relay will allow "
3417 "others to make one-hop exits. However, since by default most "
3418 "clients avoid relays that set this option, most clients will "
3419 "ignore you.");
3422 #define CHECK_DEFAULT(arg) \
3423 STMT_BEGIN \
3424 if (!options->TestingTorNetwork && \
3425 !options->UsingTestNetworkDefaults_ && \
3426 !config_is_same(&options_format,options, \
3427 default_options,#arg)) { \
3428 REJECT(#arg " may only be changed in testing Tor " \
3429 "networks!"); \
3430 } STMT_END
3431 CHECK_DEFAULT(TestingV3AuthInitialVotingInterval);
3432 CHECK_DEFAULT(TestingV3AuthInitialVoteDelay);
3433 CHECK_DEFAULT(TestingV3AuthInitialDistDelay);
3434 CHECK_DEFAULT(TestingV3AuthVotingStartOffset);
3435 CHECK_DEFAULT(TestingAuthDirTimeToLearnReachability);
3436 CHECK_DEFAULT(TestingEstimatedDescriptorPropagationTime);
3437 CHECK_DEFAULT(TestingServerDownloadSchedule);
3438 CHECK_DEFAULT(TestingClientDownloadSchedule);
3439 CHECK_DEFAULT(TestingServerConsensusDownloadSchedule);
3440 CHECK_DEFAULT(TestingClientConsensusDownloadSchedule);
3441 CHECK_DEFAULT(TestingBridgeDownloadSchedule);
3442 CHECK_DEFAULT(TestingClientMaxIntervalWithoutRequest);
3443 CHECK_DEFAULT(TestingDirConnectionMaxStall);
3444 CHECK_DEFAULT(TestingConsensusMaxDownloadTries);
3445 CHECK_DEFAULT(TestingDescriptorMaxDownloadTries);
3446 CHECK_DEFAULT(TestingMicrodescMaxDownloadTries);
3447 CHECK_DEFAULT(TestingCertMaxDownloadTries);
3448 #undef CHECK_DEFAULT
3450 if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
3451 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3452 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
3453 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3454 "30 minutes.");
3457 if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
3458 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3461 if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
3462 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3465 if (options->TestingV3AuthInitialVoteDelay +
3466 options->TestingV3AuthInitialDistDelay >=
3467 options->TestingV3AuthInitialVotingInterval/2) {
3468 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3469 "must be less than half TestingV3AuthInitialVotingInterval");
3472 if (options->TestingV3AuthVotingStartOffset >
3473 MIN(options->TestingV3AuthInitialVotingInterval,
3474 options->V3AuthVotingInterval)) {
3475 REJECT("TestingV3AuthVotingStartOffset is higher than the voting "
3476 "interval.");
3479 if (options->TestingAuthDirTimeToLearnReachability < 0) {
3480 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3481 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
3482 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3485 if (options->TestingEstimatedDescriptorPropagationTime < 0) {
3486 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3487 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
3488 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3491 if (options->TestingClientMaxIntervalWithoutRequest < 1) {
3492 REJECT("TestingClientMaxIntervalWithoutRequest is way too low.");
3493 } else if (options->TestingClientMaxIntervalWithoutRequest > 3600) {
3494 COMPLAIN("TestingClientMaxIntervalWithoutRequest is insanely high.");
3497 if (options->TestingDirConnectionMaxStall < 5) {
3498 REJECT("TestingDirConnectionMaxStall is way too low.");
3499 } else if (options->TestingDirConnectionMaxStall > 3600) {
3500 COMPLAIN("TestingDirConnectionMaxStall is insanely high.");
3503 if (options->TestingConsensusMaxDownloadTries < 2) {
3504 REJECT("TestingConsensusMaxDownloadTries must be greater than 1.");
3505 } else if (options->TestingConsensusMaxDownloadTries > 800) {
3506 COMPLAIN("TestingConsensusMaxDownloadTries is insanely high.");
3509 if (options->TestingDescriptorMaxDownloadTries < 2) {
3510 REJECT("TestingDescriptorMaxDownloadTries must be greater than 1.");
3511 } else if (options->TestingDescriptorMaxDownloadTries > 800) {
3512 COMPLAIN("TestingDescriptorMaxDownloadTries is insanely high.");
3515 if (options->TestingMicrodescMaxDownloadTries < 2) {
3516 REJECT("TestingMicrodescMaxDownloadTries must be greater than 1.");
3517 } else if (options->TestingMicrodescMaxDownloadTries > 800) {
3518 COMPLAIN("TestingMicrodescMaxDownloadTries is insanely high.");
3521 if (options->TestingCertMaxDownloadTries < 2) {
3522 REJECT("TestingCertMaxDownloadTries must be greater than 1.");
3523 } else if (options->TestingCertMaxDownloadTries > 800) {
3524 COMPLAIN("TestingCertMaxDownloadTries is insanely high.");
3527 if (options->TestingEnableConnBwEvent &&
3528 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
3529 REJECT("TestingEnableConnBwEvent may only be changed in testing "
3530 "Tor networks!");
3533 if (options->TestingEnableCellStatsEvent &&
3534 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
3535 REJECT("TestingEnableCellStatsEvent may only be changed in testing "
3536 "Tor networks!");
3539 if (options->TestingEnableTbEmptyEvent &&
3540 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
3541 REJECT("TestingEnableTbEmptyEvent may only be changed in testing "
3542 "Tor networks!");
3545 if (options->TestingTorNetwork) {
3546 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
3547 "almost unusable in the public Tor network, and is "
3548 "therefore only advised if you are building a "
3549 "testing Tor network!");
3552 if (options->AccelName && !options->HardwareAccel)
3553 options->HardwareAccel = 1;
3554 if (options->AccelDir && !options->AccelName)
3555 REJECT("Can't use hardware crypto accelerator dir without engine name.");
3557 if (options->PublishServerDescriptor)
3558 SMARTLIST_FOREACH(options->PublishServerDescriptor, const char *, pubdes, {
3559 if (!strcmp(pubdes, "1") || !strcmp(pubdes, "0"))
3560 if (smartlist_len(options->PublishServerDescriptor) > 1) {
3561 COMPLAIN("You have passed a list of multiple arguments to the "
3562 "PublishServerDescriptor option that includes 0 or 1. "
3563 "0 or 1 should only be used as the sole argument. "
3564 "This configuration will be rejected in a future release.");
3565 break;
3569 if (options->BridgeRelay == 1 && ! options->ORPort_set)
3570 REJECT("BridgeRelay is 1, ORPort is not set. This is an invalid "
3571 "combination.");
3573 return 0;
3574 #undef REJECT
3575 #undef COMPLAIN
3578 /* Given the value that the user has set for MaxMemInQueues, compute the
3579 * actual maximum value. We clip this value if it's too low, and autodetect
3580 * it if it's set to 0. */
3581 static uint64_t
3582 compute_real_max_mem_in_queues(const uint64_t val, int log_guess)
3584 uint64_t result;
3586 if (val == 0) {
3587 #define ONE_GIGABYTE (U64_LITERAL(1) << 30)
3588 #define ONE_MEGABYTE (U64_LITERAL(1) << 20)
3589 #if SIZEOF_VOID_P >= 8
3590 #define MAX_DEFAULT_MAXMEM (8*ONE_GIGABYTE)
3591 #else
3592 #define MAX_DEFAULT_MAXMEM (2*ONE_GIGABYTE)
3593 #endif
3594 /* The user didn't pick a memory limit. Choose a very large one
3595 * that is still smaller than the system memory */
3596 static int notice_sent = 0;
3597 size_t ram = 0;
3598 if (get_total_system_memory(&ram) < 0) {
3599 /* We couldn't determine our total system memory! */
3600 #if SIZEOF_VOID_P >= 8
3601 /* 64-bit system. Let's hope for 8 GB. */
3602 result = 8 * ONE_GIGABYTE;
3603 #else
3604 /* (presumably) 32-bit system. Let's hope for 1 GB. */
3605 result = ONE_GIGABYTE;
3606 #endif
3607 } else {
3608 /* We detected it, so let's pick 3/4 of the total RAM as our limit. */
3609 const uint64_t avail = (ram / 4) * 3;
3611 /* Make sure it's in range from 0.25 GB to 8 GB. */
3612 if (avail > MAX_DEFAULT_MAXMEM) {
3613 /* If you want to use more than this much RAM, you need to configure
3614 it yourself */
3615 result = MAX_DEFAULT_MAXMEM;
3616 } else if (avail < ONE_GIGABYTE / 4) {
3617 result = ONE_GIGABYTE / 4;
3618 } else {
3619 result = avail;
3622 if (log_guess && ! notice_sent) {
3623 log_notice(LD_CONFIG, "%sMaxMemInQueues is set to "U64_FORMAT" MB. "
3624 "You can override this by setting MaxMemInQueues by hand.",
3625 ram ? "Based on detected system memory, " : "",
3626 U64_PRINTF_ARG(result / ONE_MEGABYTE));
3627 notice_sent = 1;
3629 return result;
3630 } else if (val < ONE_GIGABYTE / 4) {
3631 log_warn(LD_CONFIG, "MaxMemInQueues must be at least 256 MB for now. "
3632 "Ideally, have it as large as you can afford.");
3633 return ONE_GIGABYTE / 4;
3634 } else {
3635 /* The value was fine all along */
3636 return val;
3640 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3641 * equal strings. */
3642 static int
3643 opt_streq(const char *s1, const char *s2)
3645 return 0 == strcmp_opt(s1, s2);
3648 /** Check if any of the previous options have changed but aren't allowed to. */
3649 static int
3650 options_transition_allowed(const or_options_t *old,
3651 const or_options_t *new_val,
3652 char **msg)
3654 if (!old)
3655 return 0;
3657 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3658 *msg = tor_strdup("PidFile is not allowed to change.");
3659 return -1;
3662 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3663 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3664 "is not allowed.");
3665 return -1;
3668 if (old->Sandbox != new_val->Sandbox) {
3669 *msg = tor_strdup("While Tor is running, changing Sandbox "
3670 "is not allowed.");
3671 return -1;
3674 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
3675 tor_asprintf(msg,
3676 "While Tor is running, changing DataDirectory "
3677 "(\"%s\"->\"%s\") is not allowed.",
3678 old->DataDirectory, new_val->DataDirectory);
3679 return -1;
3682 if (!opt_streq(old->User, new_val->User)) {
3683 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
3684 return -1;
3687 if ((old->HardwareAccel != new_val->HardwareAccel)
3688 || !opt_streq(old->AccelName, new_val->AccelName)
3689 || !opt_streq(old->AccelDir, new_val->AccelDir)) {
3690 *msg = tor_strdup("While Tor is running, changing OpenSSL hardware "
3691 "acceleration engine is not allowed.");
3692 return -1;
3695 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
3696 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
3697 "is not allowed.");
3698 return -1;
3701 if (old->DisableAllSwap != new_val->DisableAllSwap) {
3702 *msg = tor_strdup("While Tor is running, changing DisableAllSwap "
3703 "is not allowed.");
3704 return -1;
3707 if (old->TokenBucketRefillInterval != new_val->TokenBucketRefillInterval) {
3708 *msg = tor_strdup("While Tor is running, changing TokenBucketRefill"
3709 "Interval is not allowed");
3710 return -1;
3713 if (old->DisableIOCP != new_val->DisableIOCP) {
3714 *msg = tor_strdup("While Tor is running, changing DisableIOCP "
3715 "is not allowed.");
3716 return -1;
3719 if (old->DisableDebuggerAttachment &&
3720 !new_val->DisableDebuggerAttachment) {
3721 *msg = tor_strdup("While Tor is running, disabling "
3722 "DisableDebuggerAttachment is not allowed.");
3723 return -1;
3726 if (sandbox_is_active()) {
3727 if (! opt_streq(old->PidFile, new_val->PidFile)) {
3728 *msg = tor_strdup("Can't change PidFile while Sandbox is active");
3729 return -1;
3731 if (! config_lines_eq(old->Logs, new_val->Logs)) {
3732 *msg = tor_strdup("Can't change Logs while Sandbox is active");
3733 return -1;
3735 if (old->ConnLimit != new_val->ConnLimit) {
3736 *msg = tor_strdup("Can't change ConnLimit while Sandbox is active");
3737 return -1;
3739 if (! opt_streq(old->ServerDNSResolvConfFile,
3740 new_val->ServerDNSResolvConfFile)) {
3741 *msg = tor_strdup("Can't change ServerDNSResolvConfFile"
3742 " while Sandbox is active");
3743 return -1;
3745 if (server_mode(old) != server_mode(new_val)) {
3746 *msg = tor_strdup("Can't start/stop being a server while "
3747 "Sandbox is active");
3748 return -1;
3750 if (! opt_streq(old->DirPortFrontPage, new_val->DirPortFrontPage)) {
3751 *msg = tor_strdup("Can't change DirPortFrontPage"
3752 " while Sandbox is active");
3753 return -1;
3757 return 0;
3760 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3761 * will require us to rotate the CPU and DNS workers; else return 0. */
3762 static int
3763 options_transition_affects_workers(const or_options_t *old_options,
3764 const or_options_t *new_options)
3766 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3767 old_options->NumCPUs != new_options->NumCPUs ||
3768 !config_lines_eq(old_options->ORPort_lines, new_options->ORPort_lines) ||
3769 old_options->ServerDNSSearchDomains !=
3770 new_options->ServerDNSSearchDomains ||
3771 old_options->SafeLogging_ != new_options->SafeLogging_ ||
3772 old_options->ClientOnly != new_options->ClientOnly ||
3773 public_server_mode(old_options) != public_server_mode(new_options) ||
3774 !config_lines_eq(old_options->Logs, new_options->Logs) ||
3775 old_options->LogMessageDomains != new_options->LogMessageDomains)
3776 return 1;
3778 /* Check whether log options match. */
3780 /* Nothing that changed matters. */
3781 return 0;
3784 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3785 * will require us to generate a new descriptor; else return 0. */
3786 static int
3787 options_transition_affects_descriptor(const or_options_t *old_options,
3788 const or_options_t *new_options)
3790 /* XXX We can be smarter here. If your DirPort isn't being
3791 * published and you just turned it off, no need to republish. Etc. */
3792 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3793 !opt_streq(old_options->Nickname,new_options->Nickname) ||
3794 !opt_streq(old_options->Address,new_options->Address) ||
3795 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
3796 old_options->ExitPolicyRejectPrivate !=
3797 new_options->ExitPolicyRejectPrivate ||
3798 old_options->IPv6Exit != new_options->IPv6Exit ||
3799 !config_lines_eq(old_options->ORPort_lines,
3800 new_options->ORPort_lines) ||
3801 !config_lines_eq(old_options->DirPort_lines,
3802 new_options->DirPort_lines) ||
3803 old_options->ClientOnly != new_options->ClientOnly ||
3804 old_options->DisableNetwork != new_options->DisableNetwork ||
3805 old_options->PublishServerDescriptor_ !=
3806 new_options->PublishServerDescriptor_ ||
3807 get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
3808 get_effective_bwburst(old_options) !=
3809 get_effective_bwburst(new_options) ||
3810 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
3811 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
3812 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
3813 old_options->AccountingMax != new_options->AccountingMax ||
3814 public_server_mode(old_options) != public_server_mode(new_options))
3815 return 1;
3817 return 0;
3820 #ifdef _WIN32
3821 /** Return the directory on windows where we expect to find our application
3822 * data. */
3823 static char *
3824 get_windows_conf_root(void)
3826 static int is_set = 0;
3827 static char path[MAX_PATH*2+1];
3828 TCHAR tpath[MAX_PATH] = {0};
3830 LPITEMIDLIST idl;
3831 IMalloc *m;
3832 HRESULT result;
3834 if (is_set)
3835 return path;
3837 /* Find X:\documents and settings\username\application data\ .
3838 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3840 #ifdef ENABLE_LOCAL_APPDATA
3841 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
3842 #else
3843 #define APPDATA_PATH CSIDL_APPDATA
3844 #endif
3845 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
3846 getcwd(path,MAX_PATH);
3847 is_set = 1;
3848 log_warn(LD_CONFIG,
3849 "I couldn't find your application data folder: are you "
3850 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3851 path);
3852 return path;
3854 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3855 result = SHGetPathFromIDList(idl, tpath);
3856 #ifdef UNICODE
3857 wcstombs(path,tpath,sizeof(path));
3858 path[sizeof(path)-1] = '\0';
3859 #else
3860 strlcpy(path,tpath,sizeof(path));
3861 #endif
3863 /* Now we need to free the memory that the path-idl was stored in. In
3864 * typical Windows fashion, we can't just call 'free()' on it. */
3865 SHGetMalloc(&m);
3866 if (m) {
3867 m->lpVtbl->Free(m, idl);
3868 m->lpVtbl->Release(m);
3870 if (!SUCCEEDED(result)) {
3871 return NULL;
3873 strlcat(path,"\\tor",MAX_PATH);
3874 is_set = 1;
3875 return path;
3877 #endif
3879 /** Return the default location for our torrc file (if <b>defaults_file</b> is
3880 * false), or for the torrc-defaults file (if <b>defaults_file</b> is true). */
3881 static const char *
3882 get_default_conf_file(int defaults_file)
3884 #ifdef _WIN32
3885 if (defaults_file) {
3886 static char defaults_path[MAX_PATH+1];
3887 tor_snprintf(defaults_path, MAX_PATH, "%s\\torrc-defaults",
3888 get_windows_conf_root());
3889 return defaults_path;
3890 } else {
3891 static char path[MAX_PATH+1];
3892 tor_snprintf(path, MAX_PATH, "%s\\torrc",
3893 get_windows_conf_root());
3894 return path;
3896 #else
3897 return defaults_file ? CONFDIR "/torrc-defaults" : CONFDIR "/torrc";
3898 #endif
3901 /** Verify whether lst is a string containing valid-looking comma-separated
3902 * nicknames, or NULL. Will normalise <b>lst</b> to prefix '$' to any nickname
3903 * or fingerprint that needs it. Return 0 on success.
3904 * Warn and return -1 on failure.
3906 static int
3907 check_nickname_list(char **lst, const char *name, char **msg)
3909 int r = 0;
3910 smartlist_t *sl;
3911 int changes = 0;
3913 if (!*lst)
3914 return 0;
3915 sl = smartlist_new();
3917 smartlist_split_string(sl, *lst, ",",
3918 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
3920 SMARTLIST_FOREACH_BEGIN(sl, char *, s)
3922 if (!is_legal_nickname_or_hexdigest(s)) {
3923 // check if first char is dollar
3924 if (s[0] != '$') {
3925 // Try again but with a dollar symbol prepended
3926 char *prepended;
3927 tor_asprintf(&prepended, "$%s", s);
3929 if (is_legal_nickname_or_hexdigest(prepended)) {
3930 // The nickname is valid when it's prepended, swap the current
3931 // version with a prepended one
3932 tor_free(s);
3933 SMARTLIST_REPLACE_CURRENT(sl, s, prepended);
3934 changes = 1;
3935 continue;
3938 // Still not valid, free and fallback to error message
3939 tor_free(prepended);
3942 tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
3943 r = -1;
3944 break;
3947 SMARTLIST_FOREACH_END(s);
3949 // Replace the caller's nickname list with a fixed one
3950 if (changes && r == 0) {
3951 char *newNicknames = smartlist_join_strings(sl, ", ", 0, NULL);
3952 tor_free(*lst);
3953 *lst = newNicknames;
3956 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
3957 smartlist_free(sl);
3959 return r;
3962 /** Learn config file name from command line arguments, or use the default.
3964 * If <b>defaults_file</b> is true, we're looking for torrc-defaults;
3965 * otherwise, we're looking for the regular torrc_file.
3967 * Set *<b>using_default_fname</b> to true if we're using the default
3968 * configuration file name; or false if we've set it from the command line.
3970 * Set *<b>ignore_missing_torrc</b> to true if we should ignore the resulting
3971 * filename if it doesn't exist.
3973 static char *
3974 find_torrc_filename(config_line_t *cmd_arg,
3975 int defaults_file,
3976 int *using_default_fname, int *ignore_missing_torrc)
3978 char *fname=NULL;
3979 config_line_t *p_index;
3980 const char *fname_opt = defaults_file ? "--defaults-torrc" : "-f";
3981 const char *ignore_opt = defaults_file ? NULL : "--ignore-missing-torrc";
3983 if (defaults_file)
3984 *ignore_missing_torrc = 1;
3986 for (p_index = cmd_arg; p_index; p_index = p_index->next) {
3987 if (!strcmp(p_index->key, fname_opt)) {
3988 if (fname) {
3989 log_warn(LD_CONFIG, "Duplicate %s options on command line.",
3990 fname_opt);
3991 tor_free(fname);
3993 fname = expand_filename(p_index->value);
3996 char *absfname;
3997 absfname = make_path_absolute(fname);
3998 tor_free(fname);
3999 fname = absfname;
4002 *using_default_fname = 0;
4003 } else if (ignore_opt && !strcmp(p_index->key,ignore_opt)) {
4004 *ignore_missing_torrc = 1;
4008 if (*using_default_fname) {
4009 /* didn't find one, try CONFDIR */
4010 const char *dflt = get_default_conf_file(defaults_file);
4011 if (dflt && file_status(dflt) == FN_FILE) {
4012 fname = tor_strdup(dflt);
4013 } else {
4014 #ifndef _WIN32
4015 char *fn = NULL;
4016 if (!defaults_file)
4017 fn = expand_filename("~/.torrc");
4018 if (fn && file_status(fn) == FN_FILE) {
4019 fname = fn;
4020 } else {
4021 tor_free(fn);
4022 fname = tor_strdup(dflt);
4024 #else
4025 fname = tor_strdup(dflt);
4026 #endif
4029 return fname;
4032 /** Load a configuration file from disk, setting torrc_fname or
4033 * torrc_defaults_fname if successful.
4035 * If <b>defaults_file</b> is true, load torrc-defaults; otherwise load torrc.
4037 * Return the contents of the file on success, and NULL on failure.
4039 static char *
4040 load_torrc_from_disk(config_line_t *cmd_arg, int defaults_file)
4042 char *fname=NULL;
4043 char *cf = NULL;
4044 int using_default_torrc = 1;
4045 int ignore_missing_torrc = 0;
4046 char **fname_var = defaults_file ? &torrc_defaults_fname : &torrc_fname;
4048 fname = find_torrc_filename(cmd_arg, defaults_file,
4049 &using_default_torrc, &ignore_missing_torrc);
4050 tor_assert(fname);
4051 log_debug(LD_CONFIG, "Opening config file \"%s\"", fname);
4053 tor_free(*fname_var);
4054 *fname_var = fname;
4056 /* Open config file */
4057 if (file_status(fname) != FN_FILE ||
4058 !(cf = read_file_to_str(fname,0,NULL))) {
4059 if (using_default_torrc == 1 || ignore_missing_torrc) {
4060 if (!defaults_file)
4061 log_notice(LD_CONFIG, "Configuration file \"%s\" not present, "
4062 "using reasonable defaults.", fname);
4063 tor_free(fname); /* sets fname to NULL */
4064 *fname_var = NULL;
4065 cf = tor_strdup("");
4066 } else {
4067 log_warn(LD_CONFIG,
4068 "Unable to open configuration file \"%s\".", fname);
4069 goto err;
4071 } else {
4072 log_notice(LD_CONFIG, "Read configuration file \"%s\".", fname);
4075 return cf;
4076 err:
4077 tor_free(fname);
4078 *fname_var = NULL;
4079 return NULL;
4082 /** Read a configuration file into <b>options</b>, finding the configuration
4083 * file location based on the command line. After loading the file
4084 * call options_init_from_string() to load the config.
4085 * Return 0 if success, -1 if failure. */
4087 options_init_from_torrc(int argc, char **argv)
4089 char *cf=NULL, *cf_defaults=NULL;
4090 int command;
4091 int retval = -1;
4092 char *command_arg = NULL;
4093 char *errmsg=NULL;
4094 config_line_t *p_index = NULL;
4095 config_line_t *cmdline_only_options = NULL;
4097 /* Go through command-line variables */
4098 if (! have_parsed_cmdline) {
4099 /* Or we could redo the list every time we pass this place.
4100 * It does not really matter */
4101 if (config_parse_commandline(argc, argv, 0, &global_cmdline_options,
4102 &global_cmdline_only_options) < 0) {
4103 goto err;
4105 have_parsed_cmdline = 1;
4107 cmdline_only_options = global_cmdline_only_options;
4109 if (config_line_find(cmdline_only_options, "-h") ||
4110 config_line_find(cmdline_only_options, "--help")) {
4111 print_usage();
4112 exit(0);
4114 if (config_line_find(cmdline_only_options, "--list-torrc-options")) {
4115 /* For documenting validating whether we've documented everything. */
4116 list_torrc_options();
4117 exit(0);
4120 if (config_line_find(cmdline_only_options, "--version")) {
4121 printf("Tor version %s.\n",get_version());
4122 exit(0);
4125 if (config_line_find(cmdline_only_options, "--digests")) {
4126 printf("Tor version %s.\n",get_version());
4127 printf("%s", libor_get_digests());
4128 printf("%s", tor_get_digests());
4129 exit(0);
4132 if (config_line_find(cmdline_only_options, "--library-versions")) {
4133 printf("Tor version %s. \n", get_version());
4134 printf("Library versions\tCompiled\t\tRuntime\n");
4135 printf("Libevent\t\t%-15s\t\t%s\n",
4136 tor_libevent_get_header_version_str(),
4137 tor_libevent_get_version_str());
4138 printf("OpenSSL \t\t%-15s\t\t%s\n",
4139 crypto_openssl_get_header_version_str(),
4140 crypto_openssl_get_version_str());
4141 printf("Zlib \t\t%-15s\t\t%s\n",
4142 tor_zlib_get_header_version_str(),
4143 tor_zlib_get_version_str());
4144 //TODO: Hex versions?
4145 exit(0);
4148 command = CMD_RUN_TOR;
4149 for (p_index = cmdline_only_options; p_index; p_index = p_index->next) {
4150 if (!strcmp(p_index->key,"--list-fingerprint")) {
4151 command = CMD_LIST_FINGERPRINT;
4152 } else if (!strcmp(p_index->key, "--hash-password")) {
4153 command = CMD_HASH_PASSWORD;
4154 command_arg = p_index->value;
4155 } else if (!strcmp(p_index->key, "--dump-config")) {
4156 command = CMD_DUMP_CONFIG;
4157 command_arg = p_index->value;
4158 } else if (!strcmp(p_index->key, "--verify-config")) {
4159 command = CMD_VERIFY_CONFIG;
4163 if (command == CMD_HASH_PASSWORD) {
4164 cf_defaults = tor_strdup("");
4165 cf = tor_strdup("");
4166 } else {
4167 cf_defaults = load_torrc_from_disk(cmdline_only_options, 1);
4168 cf = load_torrc_from_disk(cmdline_only_options, 0);
4169 if (!cf) {
4170 if (config_line_find(cmdline_only_options, "--allow-missing-torrc")) {
4171 cf = tor_strdup("");
4172 } else {
4173 goto err;
4178 retval = options_init_from_string(cf_defaults, cf, command, command_arg,
4179 &errmsg);
4181 err:
4183 tor_free(cf);
4184 tor_free(cf_defaults);
4185 if (errmsg) {
4186 log_warn(LD_CONFIG,"%s", errmsg);
4187 tor_free(errmsg);
4189 return retval < 0 ? -1 : 0;
4192 /** Load the options from the configuration in <b>cf</b>, validate
4193 * them for consistency and take actions based on them.
4195 * Return 0 if success, negative on error:
4196 * * -1 for general errors.
4197 * * -2 for failure to parse/validate,
4198 * * -3 for transition not allowed
4199 * * -4 for error while setting the new options
4201 setopt_err_t
4202 options_init_from_string(const char *cf_defaults, const char *cf,
4203 int command, const char *command_arg,
4204 char **msg)
4206 or_options_t *oldoptions, *newoptions, *newdefaultoptions=NULL;
4207 config_line_t *cl;
4208 int retval, i;
4209 setopt_err_t err = SETOPT_ERR_MISC;
4210 tor_assert(msg);
4212 oldoptions = global_options; /* get_options unfortunately asserts if
4213 this is the first time we run*/
4215 newoptions = tor_malloc_zero(sizeof(or_options_t));
4216 newoptions->magic_ = OR_OPTIONS_MAGIC;
4217 options_init(newoptions);
4218 newoptions->command = command;
4219 newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
4221 for (i = 0; i < 2; ++i) {
4222 const char *body = i==0 ? cf_defaults : cf;
4223 if (!body)
4224 continue;
4225 /* get config lines, assign them */
4226 retval = config_get_lines(body, &cl, 1);
4227 if (retval < 0) {
4228 err = SETOPT_ERR_PARSE;
4229 goto err;
4231 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4232 config_free_lines(cl);
4233 if (retval < 0) {
4234 err = SETOPT_ERR_PARSE;
4235 goto err;
4237 if (i==0)
4238 newdefaultoptions = config_dup(&options_format, newoptions);
4241 if (newdefaultoptions == NULL) {
4242 newdefaultoptions = config_dup(&options_format, global_default_options);
4245 /* Go through command-line variables too */
4246 retval = config_assign(&options_format, newoptions,
4247 global_cmdline_options, 0, 0, msg);
4248 if (retval < 0) {
4249 err = SETOPT_ERR_PARSE;
4250 goto err;
4253 /* If this is a testing network configuration, change defaults
4254 * for a list of dependent config options, re-initialize newoptions
4255 * with the new defaults, and assign all options to it second time. */
4256 if (newoptions->TestingTorNetwork) {
4257 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4258 * this? We could, for example, make the parsing algorithm do two passes
4259 * over the configuration. If it finds any "suite" options like
4260 * TestingTorNetwork, it could change the defaults before its second pass.
4261 * Not urgent so long as this seems to work, but at any sign of trouble,
4262 * let's clean it up. -NM */
4264 /* Change defaults. */
4265 int i;
4266 for (i = 0; testing_tor_network_defaults[i].name; ++i) {
4267 const config_var_t *new_var = &testing_tor_network_defaults[i];
4268 config_var_t *old_var =
4269 config_find_option_mutable(&options_format, new_var->name);
4270 tor_assert(new_var);
4271 tor_assert(old_var);
4272 old_var->initvalue = new_var->initvalue;
4275 /* Clear newoptions and re-initialize them with new defaults. */
4276 config_free(&options_format, newoptions);
4277 config_free(&options_format, newdefaultoptions);
4278 newdefaultoptions = NULL;
4279 newoptions = tor_malloc_zero(sizeof(or_options_t));
4280 newoptions->magic_ = OR_OPTIONS_MAGIC;
4281 options_init(newoptions);
4282 newoptions->command = command;
4283 newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
4285 /* Assign all options a second time. */
4286 for (i = 0; i < 2; ++i) {
4287 const char *body = i==0 ? cf_defaults : cf;
4288 if (!body)
4289 continue;
4290 /* get config lines, assign them */
4291 retval = config_get_lines(body, &cl, 1);
4292 if (retval < 0) {
4293 err = SETOPT_ERR_PARSE;
4294 goto err;
4296 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4297 config_free_lines(cl);
4298 if (retval < 0) {
4299 err = SETOPT_ERR_PARSE;
4300 goto err;
4302 if (i==0)
4303 newdefaultoptions = config_dup(&options_format, newoptions);
4305 /* Assign command-line variables a second time too */
4306 retval = config_assign(&options_format, newoptions,
4307 global_cmdline_options, 0, 0, msg);
4308 if (retval < 0) {
4309 err = SETOPT_ERR_PARSE;
4310 goto err;
4314 /* Validate newoptions */
4315 if (options_validate(oldoptions, newoptions, newdefaultoptions,
4316 0, msg) < 0) {
4317 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
4318 goto err;
4321 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
4322 err = SETOPT_ERR_TRANSITION;
4323 goto err;
4326 if (set_options(newoptions, msg)) {
4327 err = SETOPT_ERR_SETTING;
4328 goto err; /* frees and replaces old options */
4330 config_free(&options_format, global_default_options);
4331 global_default_options = newdefaultoptions;
4333 return SETOPT_OK;
4335 err:
4336 config_free(&options_format, newoptions);
4337 config_free(&options_format, newdefaultoptions);
4338 if (*msg) {
4339 char *old_msg = *msg;
4340 tor_asprintf(msg, "Failed to parse/validate config: %s", old_msg);
4341 tor_free(old_msg);
4343 return err;
4346 /** Return the location for our configuration file.
4348 const char *
4349 get_torrc_fname(int defaults_fname)
4351 const char *fname = defaults_fname ? torrc_defaults_fname : torrc_fname;
4353 if (fname)
4354 return fname;
4355 else
4356 return get_default_conf_file(defaults_fname);
4359 /** Adjust the address map based on the MapAddress elements in the
4360 * configuration <b>options</b>
4362 void
4363 config_register_addressmaps(const or_options_t *options)
4365 smartlist_t *elts;
4366 config_line_t *opt;
4367 const char *from, *to, *msg;
4369 addressmap_clear_configured();
4370 elts = smartlist_new();
4371 for (opt = options->AddressMap; opt; opt = opt->next) {
4372 smartlist_split_string(elts, opt->value, NULL,
4373 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4374 if (smartlist_len(elts) < 2) {
4375 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
4376 opt->value);
4377 goto cleanup;
4380 from = smartlist_get(elts,0);
4381 to = smartlist_get(elts,1);
4383 if (to[0] == '.' || from[0] == '.') {
4384 log_warn(LD_CONFIG,"MapAddress '%s' is ambiguous - address starts with a"
4385 "'.'. Ignoring.",opt->value);
4386 goto cleanup;
4389 if (addressmap_register_auto(from, to, 0, ADDRMAPSRC_TORRC, &msg) < 0) {
4390 log_warn(LD_CONFIG,"MapAddress '%s' failed: %s. Ignoring.", opt->value,
4391 msg);
4392 goto cleanup;
4395 if (smartlist_len(elts) > 2)
4396 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
4398 cleanup:
4399 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4400 smartlist_clear(elts);
4402 smartlist_free(elts);
4405 /** As addressmap_register(), but detect the wildcarded status of "from" and
4406 * "to", and do not steal a reference to <b>to</b>. */
4407 /* XXXX024 move to connection_edge.c */
4409 addressmap_register_auto(const char *from, const char *to,
4410 time_t expires,
4411 addressmap_entry_source_t addrmap_source,
4412 const char **msg)
4414 int from_wildcard = 0, to_wildcard = 0;
4416 *msg = "whoops, forgot the error message";
4417 if (1) {
4418 if (!strcmp(to, "*") || !strcmp(from, "*")) {
4419 *msg = "can't remap from or to *";
4420 return -1;
4422 /* Detect asterisks in expressions of type: '*.example.com' */
4423 if (!strncmp(from,"*.",2)) {
4424 from += 2;
4425 from_wildcard = 1;
4427 if (!strncmp(to,"*.",2)) {
4428 to += 2;
4429 to_wildcard = 1;
4432 if (to_wildcard && !from_wildcard) {
4433 *msg = "can only use wildcard (i.e. '*.') if 'from' address "
4434 "uses wildcard also";
4435 return -1;
4438 if (address_is_invalid_destination(to, 1)) {
4439 *msg = "destination is invalid";
4440 return -1;
4443 addressmap_register(from, tor_strdup(to), expires, addrmap_source,
4444 from_wildcard, to_wildcard);
4446 return 0;
4450 * Initialize the logs based on the configuration file.
4452 static int
4453 options_init_logs(or_options_t *options, int validate_only)
4455 config_line_t *opt;
4456 int ok;
4457 smartlist_t *elts;
4458 int daemon =
4459 #ifdef _WIN32
4461 #else
4462 options->RunAsDaemon;
4463 #endif
4465 if (options->LogTimeGranularity <= 0) {
4466 log_warn(LD_CONFIG, "Log time granularity '%d' has to be positive.",
4467 options->LogTimeGranularity);
4468 return -1;
4469 } else if (1000 % options->LogTimeGranularity != 0 &&
4470 options->LogTimeGranularity % 1000 != 0) {
4471 int granularity = options->LogTimeGranularity;
4472 if (granularity < 40) {
4473 do granularity++;
4474 while (1000 % granularity != 0);
4475 } else if (granularity < 1000) {
4476 granularity = 1000 / granularity;
4477 while (1000 % granularity != 0)
4478 granularity--;
4479 granularity = 1000 / granularity;
4480 } else {
4481 granularity = 1000 * ((granularity / 1000) + 1);
4483 log_warn(LD_CONFIG, "Log time granularity '%d' has to be either a "
4484 "divisor or a multiple of 1 second. Changing to "
4485 "'%d'.",
4486 options->LogTimeGranularity, granularity);
4487 if (!validate_only)
4488 set_log_time_granularity(granularity);
4489 } else {
4490 if (!validate_only)
4491 set_log_time_granularity(options->LogTimeGranularity);
4494 ok = 1;
4495 elts = smartlist_new();
4497 for (opt = options->Logs; opt; opt = opt->next) {
4498 log_severity_list_t *severity;
4499 const char *cfg = opt->value;
4500 severity = tor_malloc_zero(sizeof(log_severity_list_t));
4501 if (parse_log_severity_config(&cfg, severity) < 0) {
4502 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
4503 opt->value);
4504 ok = 0; goto cleanup;
4507 smartlist_split_string(elts, cfg, NULL,
4508 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4510 if (smartlist_len(elts) == 0)
4511 smartlist_add(elts, tor_strdup("stdout"));
4513 if (smartlist_len(elts) == 1 &&
4514 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
4515 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
4516 int err = smartlist_len(elts) &&
4517 !strcasecmp(smartlist_get(elts,0), "stderr");
4518 if (!validate_only) {
4519 if (daemon) {
4520 log_warn(LD_CONFIG,
4521 "Can't log to %s with RunAsDaemon set; skipping stdout",
4522 err?"stderr":"stdout");
4523 } else {
4524 add_stream_log(severity, err?"<stderr>":"<stdout>",
4525 fileno(err?stderr:stdout));
4528 goto cleanup;
4530 if (smartlist_len(elts) == 1 &&
4531 !strcasecmp(smartlist_get(elts,0), "syslog")) {
4532 #ifdef HAVE_SYSLOG_H
4533 if (!validate_only) {
4534 add_syslog_log(severity);
4536 #else
4537 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
4538 #endif
4539 goto cleanup;
4542 if (smartlist_len(elts) == 2 &&
4543 !strcasecmp(smartlist_get(elts,0), "file")) {
4544 if (!validate_only) {
4545 char *fname = expand_filename(smartlist_get(elts, 1));
4546 if (add_file_log(severity, fname) < 0) {
4547 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
4548 opt->value, strerror(errno));
4549 ok = 0;
4551 tor_free(fname);
4553 goto cleanup;
4556 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
4557 opt->value);
4558 ok = 0; goto cleanup;
4560 cleanup:
4561 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4562 smartlist_clear(elts);
4563 tor_free(severity);
4565 smartlist_free(elts);
4567 if (ok && !validate_only)
4568 logs_set_domain_logging(options->LogMessageDomains);
4570 return ok?0:-1;
4573 /** Given a smartlist of SOCKS arguments to be passed to a transport
4574 * proxy in <b>args</b>, validate them and return -1 if they are
4575 * corrupted. Return 0 if they seem OK. */
4576 static int
4577 validate_transport_socks_arguments(const smartlist_t *args)
4579 char *socks_string = NULL;
4580 size_t socks_string_len;
4582 tor_assert(args);
4583 tor_assert(smartlist_len(args) > 0);
4585 SMARTLIST_FOREACH_BEGIN(args, const char *, s) {
4586 if (!string_is_key_value(LOG_WARN, s)) { /* items should be k=v items */
4587 log_warn(LD_CONFIG, "'%s' is not a k=v item.", s);
4588 return -1;
4590 } SMARTLIST_FOREACH_END(s);
4592 socks_string = pt_stringify_socks_args(args);
4593 if (!socks_string)
4594 return -1;
4596 socks_string_len = strlen(socks_string);
4597 tor_free(socks_string);
4599 if (socks_string_len > MAX_SOCKS5_AUTH_SIZE_TOTAL) {
4600 log_warn(LD_CONFIG, "SOCKS arguments can't be more than %u bytes (%lu).",
4601 MAX_SOCKS5_AUTH_SIZE_TOTAL,
4602 (unsigned long) socks_string_len);
4603 return -1;
4606 return 0;
4609 /** Deallocate a bridge_line_t structure. */
4610 /* private */ void
4611 bridge_line_free(bridge_line_t *bridge_line)
4613 if (!bridge_line)
4614 return;
4616 if (bridge_line->socks_args) {
4617 SMARTLIST_FOREACH(bridge_line->socks_args, char*, s, tor_free(s));
4618 smartlist_free(bridge_line->socks_args);
4620 tor_free(bridge_line->transport_name);
4621 tor_free(bridge_line);
4624 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4625 * if the line is well-formed, and -1 if it isn't. If
4626 * <b>validate_only</b> is 0, and the line is well-formed, then add
4627 * the bridge described in the line to our internal bridge list.
4629 * Bridge line format:
4630 * Bridge [transport] IP:PORT [id-fingerprint] [k=v] [k=v] ...
4632 /* private */ bridge_line_t *
4633 parse_bridge_line(const char *line)
4635 smartlist_t *items = NULL;
4636 char *addrport=NULL, *fingerprint=NULL;
4637 char *field=NULL;
4638 bridge_line_t *bridge_line = tor_malloc_zero(sizeof(bridge_line_t));
4640 items = smartlist_new();
4641 smartlist_split_string(items, line, NULL,
4642 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4643 if (smartlist_len(items) < 1) {
4644 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
4645 goto err;
4648 /* first field is either a transport name or addrport */
4649 field = smartlist_get(items, 0);
4650 smartlist_del_keeporder(items, 0);
4652 if (string_is_C_identifier(field)) {
4653 /* It's a transport name. */
4654 bridge_line->transport_name = field;
4655 if (smartlist_len(items) < 1) {
4656 log_warn(LD_CONFIG, "Too few items to Bridge line.");
4657 goto err;
4659 addrport = smartlist_get(items, 0); /* Next field is addrport then. */
4660 smartlist_del_keeporder(items, 0);
4661 } else {
4662 addrport = field;
4665 if (tor_addr_port_parse(LOG_INFO, addrport,
4666 &bridge_line->addr, &bridge_line->port, 443)<0) {
4667 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
4668 goto err;
4671 /* If transports are enabled, next field could be a fingerprint or a
4672 socks argument. If transports are disabled, next field must be
4673 a fingerprint. */
4674 if (smartlist_len(items)) {
4675 if (bridge_line->transport_name) { /* transports enabled: */
4676 field = smartlist_get(items, 0);
4677 smartlist_del_keeporder(items, 0);
4679 /* If it's a key=value pair, then it's a SOCKS argument for the
4680 transport proxy... */
4681 if (string_is_key_value(LOG_DEBUG, field)) {
4682 bridge_line->socks_args = smartlist_new();
4683 smartlist_add(bridge_line->socks_args, field);
4684 } else { /* ...otherwise, it's the bridge fingerprint. */
4685 fingerprint = field;
4688 } else { /* transports disabled: */
4689 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4693 /* Handle fingerprint, if it was provided. */
4694 if (fingerprint) {
4695 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4696 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
4697 goto err;
4699 if (base16_decode(bridge_line->digest, DIGEST_LEN,
4700 fingerprint, HEX_DIGEST_LEN)<0) {
4701 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
4702 goto err;
4706 /* If we are using transports, any remaining items in the smartlist
4707 should be k=v values. */
4708 if (bridge_line->transport_name && smartlist_len(items)) {
4709 if (!bridge_line->socks_args)
4710 bridge_line->socks_args = smartlist_new();
4712 /* append remaining items of 'items' to 'socks_args' */
4713 smartlist_add_all(bridge_line->socks_args, items);
4714 smartlist_clear(items);
4716 tor_assert(smartlist_len(bridge_line->socks_args) > 0);
4719 if (bridge_line->socks_args) {
4720 if (validate_transport_socks_arguments(bridge_line->socks_args) < 0)
4721 goto err;
4724 goto done;
4726 err:
4727 bridge_line_free(bridge_line);
4728 bridge_line = NULL;
4730 done:
4731 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4732 smartlist_free(items);
4733 tor_free(addrport);
4734 tor_free(fingerprint);
4736 return bridge_line;
4739 /** Read the contents of a ClientTransportPlugin line from
4740 * <b>line</b>. Return 0 if the line is well-formed, and -1 if it
4741 * isn't.
4743 * If <b>validate_only</b> is 0, the line is well-formed, and the
4744 * transport is needed by some bridge:
4745 * - If it's an external proxy line, add the transport described in the line to
4746 * our internal transport list.
4747 * - If it's a managed proxy line, launch the managed proxy. */
4748 static int
4749 parse_client_transport_line(const or_options_t *options,
4750 const char *line, int validate_only)
4752 smartlist_t *items = NULL;
4753 int r;
4754 char *field2=NULL;
4756 const char *transports=NULL;
4757 smartlist_t *transport_list=NULL;
4758 char *addrport=NULL;
4759 tor_addr_t addr;
4760 uint16_t port = 0;
4761 int socks_ver=PROXY_NONE;
4763 /* managed proxy options */
4764 int is_managed=0;
4765 char **proxy_argv=NULL;
4766 char **tmp=NULL;
4767 int proxy_argc, i;
4768 int is_useless_proxy=1;
4770 int line_length;
4772 items = smartlist_new();
4773 smartlist_split_string(items, line, NULL,
4774 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4776 line_length = smartlist_len(items);
4777 if (line_length < 3) {
4778 log_warn(LD_CONFIG, "Too few arguments on ClientTransportPlugin line.");
4779 goto err;
4782 /* Get the first line element, split it to commas into
4783 transport_list (in case it's multiple transports) and validate
4784 the transport names. */
4785 transports = smartlist_get(items, 0);
4786 transport_list = smartlist_new();
4787 smartlist_split_string(transport_list, transports, ",",
4788 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
4789 SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
4790 /* validate transport names */
4791 if (!string_is_C_identifier(transport_name)) {
4792 log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
4793 transport_name);
4794 goto err;
4797 /* see if we actually need the transports provided by this proxy */
4798 if (!validate_only && transport_is_needed(transport_name))
4799 is_useless_proxy = 0;
4800 } SMARTLIST_FOREACH_END(transport_name);
4802 /* field2 is either a SOCKS version or "exec" */
4803 field2 = smartlist_get(items, 1);
4805 if (!strcmp(field2,"socks4")) {
4806 socks_ver = PROXY_SOCKS4;
4807 } else if (!strcmp(field2,"socks5")) {
4808 socks_ver = PROXY_SOCKS5;
4809 } else if (!strcmp(field2,"exec")) {
4810 is_managed=1;
4811 } else {
4812 log_warn(LD_CONFIG, "Strange ClientTransportPlugin field '%s'.",
4813 field2);
4814 goto err;
4817 if (is_managed && options->Sandbox) {
4818 log_warn(LD_CONFIG, "Managed proxies are not compatible with Sandbox mode."
4819 "(ClientTransportPlugin line was %s)", escaped(line));
4820 goto err;
4823 if (is_managed) { /* managed */
4824 if (!validate_only && is_useless_proxy) {
4825 log_notice(LD_GENERAL, "Pluggable transport proxy (%s) does not provide "
4826 "any needed transports and will not be launched.", line);
4829 /* If we are not just validating, use the rest of the line as the
4830 argv of the proxy to be launched. Also, make sure that we are
4831 only launching proxies that contribute useful transports. */
4832 if (!validate_only && !is_useless_proxy) {
4833 proxy_argc = line_length-2;
4834 tor_assert(proxy_argc > 0);
4835 proxy_argv = tor_malloc_zero(sizeof(char*)*(proxy_argc+1));
4836 tmp = proxy_argv;
4837 for (i=0;i<proxy_argc;i++) { /* store arguments */
4838 *tmp++ = smartlist_get(items, 2);
4839 smartlist_del_keeporder(items, 2);
4841 *tmp = NULL; /*terminated with NULL, just like execve() likes it*/
4843 /* kickstart the thing */
4844 pt_kickstart_client_proxy(transport_list, proxy_argv);
4846 } else { /* external */
4847 if (smartlist_len(transport_list) != 1) {
4848 log_warn(LD_CONFIG, "You can't have an external proxy with "
4849 "more than one transports.");
4850 goto err;
4853 addrport = smartlist_get(items, 2);
4855 if (tor_addr_port_lookup(addrport, &addr, &port)<0) {
4856 log_warn(LD_CONFIG, "Error parsing transport "
4857 "address '%s'", addrport);
4858 goto err;
4860 if (!port) {
4861 log_warn(LD_CONFIG,
4862 "Transport address '%s' has no port.", addrport);
4863 goto err;
4866 if (!validate_only) {
4867 transport_add_from_config(&addr, port, smartlist_get(transport_list, 0),
4868 socks_ver);
4870 log_info(LD_DIR, "Transport '%s' found at %s",
4871 transports, fmt_addrport(&addr, port));
4875 r = 0;
4876 goto done;
4878 err:
4879 r = -1;
4881 done:
4882 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4883 smartlist_free(items);
4884 if (transport_list) {
4885 SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
4886 smartlist_free(transport_list);
4889 return r;
4892 /** Given a ServerTransportListenAddr <b>line</b>, return its
4893 * <address:port> string. Return NULL if the line was not
4894 * well-formed.
4896 * If <b>transport</b> is set, return NULL if the line is not
4897 * referring to <b>transport</b>.
4899 * The returned string is allocated on the heap and it's the
4900 * responsibility of the caller to free it. */
4901 static char *
4902 get_bindaddr_from_transport_listen_line(const char *line,const char *transport)
4904 smartlist_t *items = NULL;
4905 const char *parsed_transport = NULL;
4906 char *addrport = NULL;
4907 tor_addr_t addr;
4908 uint16_t port = 0;
4910 items = smartlist_new();
4911 smartlist_split_string(items, line, NULL,
4912 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4914 if (smartlist_len(items) < 2) {
4915 log_warn(LD_CONFIG,"Too few arguments on ServerTransportListenAddr line.");
4916 goto err;
4919 parsed_transport = smartlist_get(items, 0);
4920 addrport = tor_strdup(smartlist_get(items, 1));
4922 /* If 'transport' is given, check if it matches the one on the line */
4923 if (transport && strcmp(transport, parsed_transport))
4924 goto err;
4926 /* Validate addrport */
4927 if (tor_addr_port_parse(LOG_WARN, addrport, &addr, &port, -1)<0) {
4928 log_warn(LD_CONFIG, "Error parsing ServerTransportListenAddr "
4929 "address '%s'", addrport);
4930 goto err;
4933 goto done;
4935 err:
4936 tor_free(addrport);
4937 addrport = NULL;
4939 done:
4940 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4941 smartlist_free(items);
4943 return addrport;
4946 /** Given a ServerTransportOptions <b>line</b>, return a smartlist
4947 * with the options. Return NULL if the line was not well-formed.
4949 * If <b>transport</b> is set, return NULL if the line is not
4950 * referring to <b>transport</b>.
4952 * The returned smartlist and its strings are allocated on the heap
4953 * and it's the responsibility of the caller to free it. */
4954 smartlist_t *
4955 get_options_from_transport_options_line(const char *line,const char *transport)
4957 smartlist_t *items = smartlist_new();
4958 smartlist_t *options = smartlist_new();
4959 const char *parsed_transport = NULL;
4961 smartlist_split_string(items, line, NULL,
4962 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4964 if (smartlist_len(items) < 2) {
4965 log_warn(LD_CONFIG,"Too few arguments on ServerTransportOptions line.");
4966 goto err;
4969 parsed_transport = smartlist_get(items, 0);
4970 /* If 'transport' is given, check if it matches the one on the line */
4971 if (transport && strcmp(transport, parsed_transport))
4972 goto err;
4974 SMARTLIST_FOREACH_BEGIN(items, const char *, option) {
4975 if (option_sl_idx == 0) /* skip the transport field (first field)*/
4976 continue;
4978 /* validate that it's a k=v value */
4979 if (!string_is_key_value(LOG_WARN, option)) {
4980 log_warn(LD_CONFIG, "%s is not a k=v value.", escaped(option));
4981 goto err;
4984 /* add it to the options smartlist */
4985 smartlist_add(options, tor_strdup(option));
4986 log_debug(LD_CONFIG, "Added %s to the list of options", escaped(option));
4987 } SMARTLIST_FOREACH_END(option);
4989 goto done;
4991 err:
4992 SMARTLIST_FOREACH(options, char*, s, tor_free(s));
4993 smartlist_free(options);
4994 options = NULL;
4996 done:
4997 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4998 smartlist_free(items);
5000 return options;
5003 /** Given the name of a pluggable transport in <b>transport</b>, check
5004 * the configuration file to see if the user has explicitly asked for
5005 * it to listen on a specific port. Return a <address:port> string if
5006 * so, otherwise NULL. */
5007 char *
5008 get_transport_bindaddr_from_config(const char *transport)
5010 config_line_t *cl;
5011 const or_options_t *options = get_options();
5013 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
5014 char *bindaddr =
5015 get_bindaddr_from_transport_listen_line(cl->value, transport);
5016 if (bindaddr)
5017 return bindaddr;
5020 return NULL;
5023 /** Given the name of a pluggable transport in <b>transport</b>, check
5024 * the configuration file to see if the user has asked us to pass any
5025 * parameters to the pluggable transport. Return a smartlist
5026 * containing the parameters, otherwise NULL. */
5027 smartlist_t *
5028 get_options_for_server_transport(const char *transport)
5030 config_line_t *cl;
5031 const or_options_t *options = get_options();
5033 for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
5034 smartlist_t *options_sl =
5035 get_options_from_transport_options_line(cl->value, transport);
5036 if (options_sl)
5037 return options_sl;
5040 return NULL;
5043 /** Read the contents of a ServerTransportPlugin line from
5044 * <b>line</b>. Return 0 if the line is well-formed, and -1 if it
5045 * isn't.
5046 * If <b>validate_only</b> is 0, the line is well-formed, and it's a
5047 * managed proxy line, launch the managed proxy. */
5048 static int
5049 parse_server_transport_line(const or_options_t *options,
5050 const char *line, int validate_only)
5052 smartlist_t *items = NULL;
5053 int r;
5054 const char *transports=NULL;
5055 smartlist_t *transport_list=NULL;
5056 char *type=NULL;
5057 char *addrport=NULL;
5058 tor_addr_t addr;
5059 uint16_t port = 0;
5061 /* managed proxy options */
5062 int is_managed=0;
5063 char **proxy_argv=NULL;
5064 char **tmp=NULL;
5065 int proxy_argc,i;
5067 int line_length;
5069 items = smartlist_new();
5070 smartlist_split_string(items, line, NULL,
5071 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5073 line_length = smartlist_len(items);
5074 if (line_length < 3) {
5075 log_warn(LD_CONFIG, "Too few arguments on ServerTransportPlugin line.");
5076 goto err;
5079 /* Get the first line element, split it to commas into
5080 transport_list (in case it's multiple transports) and validate
5081 the transport names. */
5082 transports = smartlist_get(items, 0);
5083 transport_list = smartlist_new();
5084 smartlist_split_string(transport_list, transports, ",",
5085 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
5086 SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
5087 if (!string_is_C_identifier(transport_name)) {
5088 log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
5089 transport_name);
5090 goto err;
5092 } SMARTLIST_FOREACH_END(transport_name);
5094 type = smartlist_get(items, 1);
5096 if (!strcmp(type, "exec")) {
5097 is_managed=1;
5098 } else if (!strcmp(type, "proxy")) {
5099 is_managed=0;
5100 } else {
5101 log_warn(LD_CONFIG, "Strange ServerTransportPlugin type '%s'", type);
5102 goto err;
5105 if (is_managed && options->Sandbox) {
5106 log_warn(LD_CONFIG, "Managed proxies are not compatible with Sandbox mode."
5107 "(ServerTransportPlugin line was %s)", escaped(line));
5108 goto err;
5111 if (is_managed) { /* managed */
5112 if (!validate_only) {
5113 proxy_argc = line_length-2;
5114 tor_assert(proxy_argc > 0);
5115 proxy_argv = tor_malloc_zero(sizeof(char*)*(proxy_argc+1));
5116 tmp = proxy_argv;
5118 for (i=0;i<proxy_argc;i++) { /* store arguments */
5119 *tmp++ = smartlist_get(items, 2);
5120 smartlist_del_keeporder(items, 2);
5122 *tmp = NULL; /*terminated with NULL, just like execve() likes it*/
5124 /* kickstart the thing */
5125 pt_kickstart_server_proxy(transport_list, proxy_argv);
5127 } else { /* external */
5128 if (smartlist_len(transport_list) != 1) {
5129 log_warn(LD_CONFIG, "You can't have an external proxy with "
5130 "more than one transports.");
5131 goto err;
5134 addrport = smartlist_get(items, 2);
5136 if (tor_addr_port_lookup(addrport, &addr, &port)<0) {
5137 log_warn(LD_CONFIG, "Error parsing transport "
5138 "address '%s'", addrport);
5139 goto err;
5141 if (!port) {
5142 log_warn(LD_CONFIG,
5143 "Transport address '%s' has no port.", addrport);
5144 goto err;
5147 if (!validate_only) {
5148 log_info(LD_DIR, "Server transport '%s' at %s.",
5149 transports, fmt_addrport(&addr, port));
5153 r = 0;
5154 goto done;
5156 err:
5157 r = -1;
5159 done:
5160 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5161 smartlist_free(items);
5162 if (transport_list) {
5163 SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
5164 smartlist_free(transport_list);
5167 return r;
5170 /** Read the contents of a DirAuthority line from <b>line</b>. If
5171 * <b>validate_only</b> is 0, and the line is well-formed, and it
5172 * shares any bits with <b>required_type</b> or <b>required_type</b>
5173 * is 0, then add the dirserver described in the line (minus whatever
5174 * bits it's missing) as a valid authority. Return 0 on success,
5175 * or -1 if the line isn't well-formed or if we can't add it. */
5176 static int
5177 parse_dir_authority_line(const char *line, dirinfo_type_t required_type,
5178 int validate_only)
5180 smartlist_t *items = NULL;
5181 int r;
5182 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
5183 uint16_t dir_port = 0, or_port = 0;
5184 char digest[DIGEST_LEN];
5185 char v3_digest[DIGEST_LEN];
5186 dirinfo_type_t type = 0;
5187 double weight = 1.0;
5189 items = smartlist_new();
5190 smartlist_split_string(items, line, NULL,
5191 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5192 if (smartlist_len(items) < 1) {
5193 log_warn(LD_CONFIG, "No arguments on DirAuthority line.");
5194 goto err;
5197 if (is_legal_nickname(smartlist_get(items, 0))) {
5198 nickname = smartlist_get(items, 0);
5199 smartlist_del_keeporder(items, 0);
5202 while (smartlist_len(items)) {
5203 char *flag = smartlist_get(items, 0);
5204 if (TOR_ISDIGIT(flag[0]))
5205 break;
5206 if (!strcasecmp(flag, "hs") ||
5207 !strcasecmp(flag, "no-hs")) {
5208 log_warn(LD_CONFIG, "The DirAuthority options 'hs' and 'no-hs' are "
5209 "obsolete; you don't need them any more.");
5210 } else if (!strcasecmp(flag, "bridge")) {
5211 type |= BRIDGE_DIRINFO;
5212 } else if (!strcasecmp(flag, "no-v2")) {
5213 /* obsolete, but may still be contained in DirAuthority lines generated
5214 by various tools */;
5215 } else if (!strcasecmpstart(flag, "orport=")) {
5216 int ok;
5217 char *portstring = flag + strlen("orport=");
5218 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
5219 if (!ok)
5220 log_warn(LD_CONFIG, "Invalid orport '%s' on DirAuthority line.",
5221 portstring);
5222 } else if (!strcmpstart(flag, "weight=")) {
5223 int ok;
5224 const char *wstring = flag + strlen("weight=");
5225 weight = tor_parse_double(wstring, 0, UINT64_MAX, &ok, NULL);
5226 if (!ok) {
5227 log_warn(LD_CONFIG, "Invalid weight '%s' on DirAuthority line.",flag);
5228 weight=1.0;
5230 } else if (!strcasecmpstart(flag, "v3ident=")) {
5231 char *idstr = flag + strlen("v3ident=");
5232 if (strlen(idstr) != HEX_DIGEST_LEN ||
5233 base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
5234 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirAuthority line",
5235 flag);
5236 } else {
5237 type |= V3_DIRINFO|EXTRAINFO_DIRINFO|MICRODESC_DIRINFO;
5239 } else {
5240 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirAuthority line",
5241 flag);
5243 tor_free(flag);
5244 smartlist_del_keeporder(items, 0);
5247 if (smartlist_len(items) < 2) {
5248 log_warn(LD_CONFIG, "Too few arguments to DirAuthority line.");
5249 goto err;
5251 addrport = smartlist_get(items, 0);
5252 smartlist_del_keeporder(items, 0);
5253 if (addr_port_lookup(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
5254 log_warn(LD_CONFIG, "Error parsing DirAuthority address '%s'", addrport);
5255 goto err;
5257 if (!dir_port) {
5258 log_warn(LD_CONFIG, "Missing port in DirAuthority address '%s'",addrport);
5259 goto err;
5262 fingerprint = smartlist_join_strings(items, "", 0, NULL);
5263 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
5264 log_warn(LD_CONFIG, "Key digest '%s' for DirAuthority is wrong length %d.",
5265 fingerprint, (int)strlen(fingerprint));
5266 goto err;
5268 if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
5269 /* a known bad fingerprint. refuse to use it. We can remove this
5270 * clause once Tor 0.1.2.17 is obsolete. */
5271 log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
5272 "torrc file (%s), or reinstall Tor and use the default torrc.",
5273 get_torrc_fname(0));
5274 goto err;
5276 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
5277 log_warn(LD_CONFIG, "Unable to decode DirAuthority key digest.");
5278 goto err;
5281 if (!validate_only && (!required_type || required_type & type)) {
5282 dir_server_t *ds;
5283 if (required_type)
5284 type &= required_type; /* pare down what we think of them as an
5285 * authority for. */
5286 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
5287 address, (int)dir_port, (char*)smartlist_get(items,0));
5288 if (!(ds = trusted_dir_server_new(nickname, address, dir_port, or_port,
5289 digest, v3_digest, type, weight)))
5290 goto err;
5291 dir_server_add(ds);
5294 r = 0;
5295 goto done;
5297 err:
5298 r = -1;
5300 done:
5301 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5302 smartlist_free(items);
5303 tor_free(addrport);
5304 tor_free(address);
5305 tor_free(nickname);
5306 tor_free(fingerprint);
5307 return r;
5310 /** Read the contents of a FallbackDir line from <b>line</b>. If
5311 * <b>validate_only</b> is 0, and the line is well-formed, then add the
5312 * dirserver described in the line as a fallback directory. Return 0 on
5313 * success, or -1 if the line isn't well-formed or if we can't add it. */
5314 static int
5315 parse_dir_fallback_line(const char *line,
5316 int validate_only)
5318 int r = -1;
5319 smartlist_t *items = smartlist_new(), *positional = smartlist_new();
5320 int orport = -1;
5321 uint16_t dirport;
5322 tor_addr_t addr;
5323 int ok;
5324 char id[DIGEST_LEN];
5325 char *address=NULL;
5326 double weight=1.0;
5328 memset(id, 0, sizeof(id));
5329 smartlist_split_string(items, line, NULL,
5330 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5331 SMARTLIST_FOREACH_BEGIN(items, const char *, cp) {
5332 const char *eq = strchr(cp, '=');
5333 ok = 1;
5334 if (! eq) {
5335 smartlist_add(positional, (char*)cp);
5336 continue;
5338 if (!strcmpstart(cp, "orport=")) {
5339 orport = (int)tor_parse_long(cp+strlen("orport="), 10,
5340 1, 65535, &ok, NULL);
5341 } else if (!strcmpstart(cp, "id=")) {
5342 ok = !base16_decode(id, DIGEST_LEN,
5343 cp+strlen("id="), strlen(cp)-strlen("id="));
5344 } else if (!strcmpstart(cp, "weight=")) {
5345 int ok;
5346 const char *wstring = cp + strlen("weight=");
5347 weight = tor_parse_double(wstring, 0, UINT64_MAX, &ok, NULL);
5348 if (!ok) {
5349 log_warn(LD_CONFIG, "Invalid weight '%s' on FallbackDir line.", cp);
5350 weight=1.0;
5354 if (!ok) {
5355 log_warn(LD_CONFIG, "Bad FallbackDir option %s", escaped(cp));
5356 goto end;
5358 } SMARTLIST_FOREACH_END(cp);
5360 if (smartlist_len(positional) != 1) {
5361 log_warn(LD_CONFIG, "Couldn't parse FallbackDir line %s", escaped(line));
5362 goto end;
5365 if (tor_digest_is_zero(id)) {
5366 log_warn(LD_CONFIG, "Missing identity on FallbackDir line");
5367 goto end;
5370 if (orport <= 0) {
5371 log_warn(LD_CONFIG, "Missing orport on FallbackDir line");
5372 goto end;
5375 if (tor_addr_port_split(LOG_INFO, smartlist_get(positional, 0),
5376 &address, &dirport) < 0 ||
5377 tor_addr_parse(&addr, address)<0) {
5378 log_warn(LD_CONFIG, "Couldn't parse address:port %s on FallbackDir line",
5379 (const char*)smartlist_get(positional, 0));
5380 goto end;
5383 if (!validate_only) {
5384 dir_server_t *ds;
5385 ds = fallback_dir_server_new(&addr, dirport, orport, id, weight);
5386 if (!ds) {
5387 log_warn(LD_CONFIG, "Couldn't create FallbackDir %s", escaped(line));
5388 goto end;
5390 dir_server_add(ds);
5393 r = 0;
5395 end:
5396 SMARTLIST_FOREACH(items, char *, cp, tor_free(cp));
5397 smartlist_free(items);
5398 smartlist_free(positional);
5399 tor_free(address);
5400 return r;
5403 /** Allocate and return a new port_cfg_t with reasonable defaults. */
5404 static port_cfg_t *
5405 port_cfg_new(void)
5407 port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t));
5408 cfg->ipv4_traffic = 1;
5409 cfg->cache_ipv4_answers = 1;
5410 cfg->prefer_ipv6_virtaddr = 1;
5411 return cfg;
5414 /** Free all storage held in <b>port</b> */
5415 static void
5416 port_cfg_free(port_cfg_t *port)
5418 tor_free(port);
5421 /** Warn for every port in <b>ports</b> of type <b>listener_type</b> that is
5422 * on a publicly routable address. */
5423 static void
5424 warn_nonlocal_client_ports(const smartlist_t *ports, const char *portname,
5425 int listener_type)
5427 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
5428 if (port->type != listener_type)
5429 continue;
5430 if (port->is_unix_addr) {
5431 /* Unix sockets aren't accessible over a network. */
5432 } else if (!tor_addr_is_internal(&port->addr, 1)) {
5433 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
5434 "Other people on the Internet might find your computer and "
5435 "use it as an open proxy. Please don't allow this unless you "
5436 "have a good reason.",
5437 fmt_addrport(&port->addr, port->port), portname);
5438 } else if (!tor_addr_is_loopback(&port->addr)) {
5439 log_notice(LD_CONFIG, "You configured a non-loopback address '%s' "
5440 "for %sPort. This allows everybody on your local network to "
5441 "use your machine as a proxy. Make sure this is what you "
5442 "wanted.",
5443 fmt_addrport(&port->addr, port->port), portname);
5445 } SMARTLIST_FOREACH_END(port);
5448 /** Warn for every Extended ORPort port in <b>ports</b> that is on a
5449 * publicly routable address. */
5450 static void
5451 warn_nonlocal_ext_orports(const smartlist_t *ports, const char *portname)
5453 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
5454 if (port->type != CONN_TYPE_EXT_OR_LISTENER)
5455 continue;
5456 if (port->is_unix_addr)
5457 continue;
5458 /* XXX maybe warn even if address is RFC1918? */
5459 if (!tor_addr_is_internal(&port->addr, 1)) {
5460 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
5461 "This is not advised; this address is supposed to only be "
5462 "exposed on localhost so that your pluggable transport "
5463 "proxies can connect to it.",
5464 fmt_addrport(&port->addr, port->port), portname);
5466 } SMARTLIST_FOREACH_END(port);
5469 /** Given a list of port_cfg_t in <b>ports</b>, warn any controller port there
5470 * is listening on any non-loopback address. If <b>forbid</b> is true,
5471 * then emit a stronger warning and remove the port from the list.
5473 static void
5474 warn_nonlocal_controller_ports(smartlist_t *ports, unsigned forbid)
5476 int warned = 0;
5477 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
5478 if (port->type != CONN_TYPE_CONTROL_LISTENER)
5479 continue;
5480 if (port->is_unix_addr)
5481 continue;
5482 if (!tor_addr_is_loopback(&port->addr)) {
5483 if (forbid) {
5484 if (!warned)
5485 log_warn(LD_CONFIG,
5486 "You have a ControlPort set to accept "
5487 "unauthenticated connections from a non-local address. "
5488 "This means that programs not running on your computer "
5489 "can reconfigure your Tor, without even having to guess a "
5490 "password. That's so bad that I'm closing your ControlPort "
5491 "for you. If you need to control your Tor remotely, try "
5492 "enabling authentication and using a tool like stunnel or "
5493 "ssh to encrypt remote access.");
5494 warned = 1;
5495 port_cfg_free(port);
5496 SMARTLIST_DEL_CURRENT(ports, port);
5497 } else {
5498 log_warn(LD_CONFIG, "You have a ControlPort set to accept "
5499 "connections from a non-local address. This means that "
5500 "programs not running on your computer can reconfigure your "
5501 "Tor. That's pretty bad, since the controller "
5502 "protocol isn't encrypted! Maybe you should just listen on "
5503 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
5504 "remote connections to your control port.");
5505 return; /* No point in checking the rest */
5508 } SMARTLIST_FOREACH_END(port);
5511 #define CL_PORT_NO_OPTIONS (1u<<0)
5512 #define CL_PORT_WARN_NONLOCAL (1u<<1)
5513 #define CL_PORT_ALLOW_EXTRA_LISTENADDR (1u<<2)
5514 #define CL_PORT_SERVER_OPTIONS (1u<<3)
5515 #define CL_PORT_FORBID_NONLOCAL (1u<<4)
5516 #define CL_PORT_TAKES_HOSTNAMES (1u<<5)
5519 * Parse port configuration for a single port type.
5521 * Read entries of the "FooPort" type from the list <b>ports</b>, and
5522 * entries of the "FooListenAddress" type from the list
5523 * <b>listenaddrs</b>. Two syntaxes are supported: a legacy syntax
5524 * where FooPort is at most a single entry containing a port number and
5525 * where FooListenAddress has any number of address:port combinations;
5526 * and a new syntax where there are no FooListenAddress entries and
5527 * where FooPort can have any number of entries of the format
5528 * "[Address:][Port] IsolationOptions".
5530 * In log messages, describe the port type as <b>portname</b>.
5532 * If no address is specified, default to <b>defaultaddr</b>. If no
5533 * FooPort is given, default to defaultport (if 0, there is no default).
5535 * If CL_PORT_NO_OPTIONS is set in <b>flags</b>, do not allow stream
5536 * isolation options in the FooPort entries.
5538 * If CL_PORT_WARN_NONLOCAL is set in <b>flags</b>, warn if any of the
5539 * ports are not on a local address. If CL_PORT_FORBID_NONLOCAL is set,
5540 * this is a contrl port with no password set: don't even allow it.
5542 * Unless CL_PORT_ALLOW_EXTRA_LISTENADDR is set in <b>flags</b>, warn
5543 * if FooListenAddress is set but FooPort is 0.
5545 * If CL_PORT_SERVER_OPTIONS is set in <b>flags</b>, do not allow stream
5546 * isolation options in the FooPort entries; instead allow the
5547 * server-port option set.
5549 * If CL_PORT_TAKES_HOSTNAMES is set in <b>flags</b>, allow the options
5550 * {No,}IPv{4,6}Traffic.
5552 * On success, if <b>out</b> is given, add a new port_cfg_t entry to
5553 * <b>out</b> for every port that the client should listen on. Return 0
5554 * on success, -1 on failure.
5556 static int
5557 parse_port_config(smartlist_t *out,
5558 const config_line_t *ports,
5559 const config_line_t *listenaddrs,
5560 const char *portname,
5561 int listener_type,
5562 const char *defaultaddr,
5563 int defaultport,
5564 unsigned flags)
5566 smartlist_t *elts;
5567 int retval = -1;
5568 const unsigned is_control = (listener_type == CONN_TYPE_CONTROL_LISTENER);
5569 const unsigned is_ext_orport = (listener_type == CONN_TYPE_EXT_OR_LISTENER);
5570 const unsigned allow_no_options = flags & CL_PORT_NO_OPTIONS;
5571 const unsigned use_server_options = flags & CL_PORT_SERVER_OPTIONS;
5572 const unsigned warn_nonlocal = flags & CL_PORT_WARN_NONLOCAL;
5573 const unsigned forbid_nonlocal = flags & CL_PORT_FORBID_NONLOCAL;
5574 const unsigned allow_spurious_listenaddr =
5575 flags & CL_PORT_ALLOW_EXTRA_LISTENADDR;
5576 const unsigned takes_hostnames = flags & CL_PORT_TAKES_HOSTNAMES;
5577 int got_zero_port=0, got_nonzero_port=0;
5579 /* FooListenAddress is deprecated; let's make it work like it used to work,
5580 * though. */
5581 if (listenaddrs) {
5582 int mainport = defaultport;
5584 if (ports && ports->next) {
5585 log_warn(LD_CONFIG, "%sListenAddress can't be used when there are "
5586 "multiple %sPort lines", portname, portname);
5587 return -1;
5588 } else if (ports) {
5589 if (!strcmp(ports->value, "auto")) {
5590 mainport = CFG_AUTO_PORT;
5591 } else {
5592 int ok;
5593 mainport = (int)tor_parse_long(ports->value, 10, 0, 65535, &ok, NULL);
5594 if (!ok) {
5595 log_warn(LD_CONFIG, "%sListenAddress can only be used with a single "
5596 "%sPort with value \"auto\" or 1-65535 and no options set.",
5597 portname, portname);
5598 return -1;
5603 if (mainport == 0) {
5604 if (allow_spurious_listenaddr)
5605 return 1; /*DOCDOC*/
5606 log_warn(LD_CONFIG, "%sPort must be defined if %sListenAddress is used",
5607 portname, portname);
5608 return -1;
5611 if (use_server_options && out) {
5612 /* Add a no_listen port. */
5613 port_cfg_t *cfg = port_cfg_new();
5614 cfg->type = listener_type;
5615 cfg->port = mainport;
5616 tor_addr_make_unspec(&cfg->addr); /* Server ports default to 0.0.0.0 */
5617 cfg->no_listen = 1;
5618 cfg->bind_ipv4_only = 1;
5619 cfg->ipv4_traffic = 1;
5620 cfg->prefer_ipv6_virtaddr = 1;
5621 smartlist_add(out, cfg);
5624 for (; listenaddrs; listenaddrs = listenaddrs->next) {
5625 tor_addr_t addr;
5626 uint16_t port = 0;
5627 if (tor_addr_port_lookup(listenaddrs->value, &addr, &port) < 0) {
5628 log_warn(LD_CONFIG, "Unable to parse %sListenAddress '%s'",
5629 portname, listenaddrs->value);
5630 return -1;
5632 if (out) {
5633 port_cfg_t *cfg = port_cfg_new();
5634 cfg->type = listener_type;
5635 cfg->port = port ? port : mainport;
5636 tor_addr_copy(&cfg->addr, &addr);
5637 cfg->session_group = SESSION_GROUP_UNSET;
5638 cfg->isolation_flags = ISO_DEFAULT;
5639 cfg->no_advertise = 1;
5640 smartlist_add(out, cfg);
5644 if (warn_nonlocal && out) {
5645 if (is_control)
5646 warn_nonlocal_controller_ports(out, forbid_nonlocal);
5647 else if (is_ext_orport)
5648 warn_nonlocal_ext_orports(out, portname);
5649 else
5650 warn_nonlocal_client_ports(out, portname, listener_type);
5652 return 0;
5653 } /* end if (listenaddrs) */
5655 /* No ListenAddress lines. If there's no FooPort, then maybe make a default
5656 * one. */
5657 if (! ports) {
5658 if (defaultport && out) {
5659 port_cfg_t *cfg = port_cfg_new();
5660 cfg->type = listener_type;
5661 cfg->port = defaultport;
5662 tor_addr_parse(&cfg->addr, defaultaddr);
5663 cfg->session_group = SESSION_GROUP_UNSET;
5664 cfg->isolation_flags = ISO_DEFAULT;
5665 smartlist_add(out, cfg);
5667 return 0;
5670 /* At last we can actually parse the FooPort lines. The syntax is:
5671 * [Addr:](Port|auto) [Options].*/
5672 elts = smartlist_new();
5674 for (; ports; ports = ports->next) {
5675 tor_addr_t addr;
5676 int port;
5677 int sessiongroup = SESSION_GROUP_UNSET;
5678 unsigned isolation = ISO_DEFAULT;
5679 int prefer_no_auth = 0;
5681 char *addrport;
5682 uint16_t ptmp=0;
5683 int ok;
5684 int no_listen = 0, no_advertise = 0, all_addrs = 0,
5685 bind_ipv4_only = 0, bind_ipv6_only = 0,
5686 ipv4_traffic = 1, ipv6_traffic = 0, prefer_ipv6 = 0,
5687 cache_ipv4 = 1, use_cached_ipv4 = 0,
5688 cache_ipv6 = 0, use_cached_ipv6 = 0,
5689 prefer_ipv6_automap = 1;
5691 smartlist_split_string(elts, ports->value, NULL,
5692 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
5693 if (smartlist_len(elts) == 0) {
5694 log_warn(LD_CONFIG, "Invalid %sPort line with no value", portname);
5695 goto err;
5698 if (allow_no_options && smartlist_len(elts) > 1) {
5699 log_warn(LD_CONFIG, "Too many options on %sPort line", portname);
5700 goto err;
5703 /* Now parse the addr/port value */
5704 addrport = smartlist_get(elts, 0);
5705 if (!strcmp(addrport, "auto")) {
5706 port = CFG_AUTO_PORT;
5707 tor_addr_parse(&addr, defaultaddr);
5708 } else if (!strcasecmpend(addrport, ":auto")) {
5709 char *addrtmp = tor_strndup(addrport, strlen(addrport)-5);
5710 port = CFG_AUTO_PORT;
5711 if (tor_addr_port_lookup(addrtmp, &addr, &ptmp)<0 || ptmp) {
5712 log_warn(LD_CONFIG, "Invalid address '%s' for %sPort",
5713 escaped(addrport), portname);
5714 tor_free(addrtmp);
5715 goto err;
5717 } else {
5718 /* Try parsing integer port before address, because, who knows?
5719 "9050" might be a valid address. */
5720 port = (int) tor_parse_long(addrport, 10, 0, 65535, &ok, NULL);
5721 if (ok) {
5722 tor_addr_parse(&addr, defaultaddr);
5723 } else if (tor_addr_port_lookup(addrport, &addr, &ptmp) == 0) {
5724 if (ptmp == 0) {
5725 log_warn(LD_CONFIG, "%sPort line has address but no port", portname);
5726 goto err;
5728 port = ptmp;
5729 } else {
5730 log_warn(LD_CONFIG, "Couldn't parse address '%s' for %sPort",
5731 escaped(addrport), portname);
5732 goto err;
5736 /* Now parse the rest of the options, if any. */
5737 if (use_server_options) {
5738 /* This is a server port; parse advertising options */
5739 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
5740 if (elt_sl_idx == 0)
5741 continue; /* Skip addr:port */
5743 if (!strcasecmp(elt, "NoAdvertise")) {
5744 no_advertise = 1;
5745 } else if (!strcasecmp(elt, "NoListen")) {
5746 no_listen = 1;
5747 #if 0
5748 /* not implemented yet. */
5749 } else if (!strcasecmp(elt, "AllAddrs")) {
5751 all_addrs = 1;
5752 #endif
5753 } else if (!strcasecmp(elt, "IPv4Only")) {
5754 bind_ipv4_only = 1;
5755 } else if (!strcasecmp(elt, "IPv6Only")) {
5756 bind_ipv6_only = 1;
5757 } else {
5758 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
5759 portname, escaped(elt));
5761 } SMARTLIST_FOREACH_END(elt);
5763 if (no_advertise && no_listen) {
5764 log_warn(LD_CONFIG, "Tried to set both NoListen and NoAdvertise "
5765 "on %sPort line '%s'",
5766 portname, escaped(ports->value));
5767 goto err;
5769 if (bind_ipv4_only && bind_ipv6_only) {
5770 log_warn(LD_CONFIG, "Tried to set both IPv4Only and IPv6Only "
5771 "on %sPort line '%s'",
5772 portname, escaped(ports->value));
5773 goto err;
5775 if (bind_ipv4_only && tor_addr_family(&addr) == AF_INET6) {
5776 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv6",
5777 portname);
5778 goto err;
5780 if (bind_ipv6_only && tor_addr_family(&addr) == AF_INET) {
5781 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv4",
5782 portname);
5783 goto err;
5785 } else {
5786 /* This is a client port; parse isolation options */
5787 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
5788 int no = 0, isoflag = 0;
5789 const char *elt_orig = elt;
5790 if (elt_sl_idx == 0)
5791 continue; /* Skip addr:port */
5792 if (!strcasecmpstart(elt, "SessionGroup=")) {
5793 int group = (int)tor_parse_long(elt+strlen("SessionGroup="),
5794 10, 0, INT_MAX, &ok, NULL);
5795 if (!ok) {
5796 log_warn(LD_CONFIG, "Invalid %sPort option '%s'",
5797 portname, escaped(elt));
5798 goto err;
5800 if (sessiongroup >= 0) {
5801 log_warn(LD_CONFIG, "Multiple SessionGroup options on %sPort",
5802 portname);
5803 goto err;
5805 sessiongroup = group;
5806 continue;
5809 if (!strcasecmpstart(elt, "No")) {
5810 no = 1;
5811 elt += 2;
5814 if (takes_hostnames) {
5815 if (!strcasecmp(elt, "IPv4Traffic")) {
5816 ipv4_traffic = ! no;
5817 continue;
5818 } else if (!strcasecmp(elt, "IPv6Traffic")) {
5819 ipv6_traffic = ! no;
5820 continue;
5821 } else if (!strcasecmp(elt, "PreferIPv6")) {
5822 prefer_ipv6 = ! no;
5823 continue;
5826 if (!strcasecmp(elt, "CacheIPv4DNS")) {
5827 cache_ipv4 = ! no;
5828 continue;
5829 } else if (!strcasecmp(elt, "CacheIPv6DNS")) {
5830 cache_ipv6 = ! no;
5831 continue;
5832 } else if (!strcasecmp(elt, "CacheDNS")) {
5833 cache_ipv4 = cache_ipv6 = ! no;
5834 continue;
5835 } else if (!strcasecmp(elt, "UseIPv4Cache")) {
5836 use_cached_ipv4 = ! no;
5837 continue;
5838 } else if (!strcasecmp(elt, "UseIPv6Cache")) {
5839 use_cached_ipv6 = ! no;
5840 continue;
5841 } else if (!strcasecmp(elt, "UseDNSCache")) {
5842 use_cached_ipv4 = use_cached_ipv6 = ! no;
5843 continue;
5844 } else if (!strcasecmp(elt, "PreferIPv6Automap")) {
5845 prefer_ipv6_automap = ! no;
5846 continue;
5847 } else if (!strcasecmp(elt, "PreferSOCKSNoAuth")) {
5848 prefer_no_auth = ! no;
5849 continue;
5852 if (!strcasecmpend(elt, "s"))
5853 elt[strlen(elt)-1] = '\0'; /* kill plurals. */
5855 if (!strcasecmp(elt, "IsolateDestPort")) {
5856 isoflag = ISO_DESTPORT;
5857 } else if (!strcasecmp(elt, "IsolateDestAddr")) {
5858 isoflag = ISO_DESTADDR;
5859 } else if (!strcasecmp(elt, "IsolateSOCKSAuth")) {
5860 isoflag = ISO_SOCKSAUTH;
5861 } else if (!strcasecmp(elt, "IsolateClientProtocol")) {
5862 isoflag = ISO_CLIENTPROTO;
5863 } else if (!strcasecmp(elt, "IsolateClientAddr")) {
5864 isoflag = ISO_CLIENTADDR;
5865 } else {
5866 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
5867 portname, escaped(elt_orig));
5870 if (no) {
5871 isolation &= ~isoflag;
5872 } else {
5873 isolation |= isoflag;
5875 } SMARTLIST_FOREACH_END(elt);
5878 if (port)
5879 got_nonzero_port = 1;
5880 else
5881 got_zero_port = 1;
5883 if (ipv4_traffic == 0 && ipv6_traffic == 0) {
5884 log_warn(LD_CONFIG, "You have a %sPort entry with both IPv4 and "
5885 "IPv6 disabled; that won't work.", portname);
5886 goto err;
5889 if (out && port) {
5890 port_cfg_t *cfg = port_cfg_new();
5891 tor_addr_copy(&cfg->addr, &addr);
5892 cfg->port = port;
5893 cfg->type = listener_type;
5894 cfg->isolation_flags = isolation;
5895 cfg->session_group = sessiongroup;
5896 cfg->no_advertise = no_advertise;
5897 cfg->no_listen = no_listen;
5898 cfg->all_addrs = all_addrs;
5899 cfg->bind_ipv4_only = bind_ipv4_only;
5900 cfg->bind_ipv6_only = bind_ipv6_only;
5901 cfg->ipv4_traffic = ipv4_traffic;
5902 cfg->ipv6_traffic = ipv6_traffic;
5903 cfg->prefer_ipv6 = prefer_ipv6;
5904 cfg->cache_ipv4_answers = cache_ipv4;
5905 cfg->cache_ipv6_answers = cache_ipv6;
5906 cfg->use_cached_ipv4_answers = use_cached_ipv4;
5907 cfg->use_cached_ipv6_answers = use_cached_ipv6;
5908 cfg->prefer_ipv6_virtaddr = prefer_ipv6_automap;
5909 cfg->socks_prefer_no_auth = prefer_no_auth;
5910 if (! (isolation & ISO_SOCKSAUTH))
5911 cfg->socks_prefer_no_auth = 1;
5913 smartlist_add(out, cfg);
5915 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
5916 smartlist_clear(elts);
5919 if (warn_nonlocal && out) {
5920 if (is_control)
5921 warn_nonlocal_controller_ports(out, forbid_nonlocal);
5922 else if (is_ext_orport)
5923 warn_nonlocal_ext_orports(out, portname);
5924 else
5925 warn_nonlocal_client_ports(out, portname, listener_type);
5928 if (got_zero_port && got_nonzero_port) {
5929 log_warn(LD_CONFIG, "You specified a nonzero %sPort along with '%sPort 0' "
5930 "in the same configuration. Did you mean to disable %sPort or "
5931 "not?", portname, portname, portname);
5932 goto err;
5935 retval = 0;
5936 err:
5937 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
5938 smartlist_free(elts);
5939 return retval;
5942 /** Parse a list of config_line_t for an AF_UNIX unix socket listener option
5943 * from <b>cfg</b> and add them to <b>out</b>. No fancy options are
5944 * supported: the line contains nothing but the path to the AF_UNIX socket. */
5945 static int
5946 parse_unix_socket_config(smartlist_t *out, const config_line_t *cfg,
5947 int listener_type)
5950 if (!out)
5951 return 0;
5953 for ( ; cfg; cfg = cfg->next) {
5954 size_t len = strlen(cfg->value);
5955 port_cfg_t *port = tor_malloc_zero(sizeof(port_cfg_t) + len + 1);
5956 port->is_unix_addr = 1;
5957 memcpy(port->unix_addr, cfg->value, len+1);
5958 port->type = listener_type;
5959 smartlist_add(out, port);
5962 return 0;
5965 /** Return the number of ports which are actually going to listen with type
5966 * <b>listenertype</b>. Do not count no_listen ports. Do not count unix
5967 * sockets. */
5968 static int
5969 count_real_listeners(const smartlist_t *ports, int listenertype)
5971 int n = 0;
5972 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
5973 if (port->no_listen || port->is_unix_addr)
5974 continue;
5975 if (port->type != listenertype)
5976 continue;
5977 ++n;
5978 } SMARTLIST_FOREACH_END(port);
5979 return n;
5982 /** Parse all client port types (Socks, DNS, Trans, NATD) from
5983 * <b>options</b>. On success, set *<b>n_ports_out</b> to the number
5984 * of ports that are listed, update the *Port_set values in
5985 * <b>options</b>, and return 0. On failure, set *<b>msg</b> to a
5986 * description of the problem and return -1.
5988 * If <b>validate_only</b> is false, set configured_client_ports to the
5989 * new list of ports parsed from <b>options</b>.
5991 static int
5992 parse_ports(or_options_t *options, int validate_only,
5993 char **msg, int *n_ports_out)
5995 smartlist_t *ports;
5996 int retval = -1;
5998 ports = smartlist_new();
6000 *n_ports_out = 0;
6002 if (parse_port_config(ports,
6003 options->SocksPort_lines, options->SocksListenAddress,
6004 "Socks", CONN_TYPE_AP_LISTENER,
6005 "127.0.0.1", 9050,
6006 CL_PORT_WARN_NONLOCAL|CL_PORT_ALLOW_EXTRA_LISTENADDR|
6007 CL_PORT_TAKES_HOSTNAMES) < 0) {
6008 *msg = tor_strdup("Invalid SocksPort/SocksListenAddress configuration");
6009 goto err;
6011 if (parse_port_config(ports,
6012 options->DNSPort_lines, options->DNSListenAddress,
6013 "DNS", CONN_TYPE_AP_DNS_LISTENER,
6014 "127.0.0.1", 0,
6015 CL_PORT_WARN_NONLOCAL|CL_PORT_TAKES_HOSTNAMES) < 0) {
6016 *msg = tor_strdup("Invalid DNSPort/DNSListenAddress configuration");
6017 goto err;
6019 if (parse_port_config(ports,
6020 options->TransPort_lines, options->TransListenAddress,
6021 "Trans", CONN_TYPE_AP_TRANS_LISTENER,
6022 "127.0.0.1", 0,
6023 CL_PORT_WARN_NONLOCAL) < 0) {
6024 *msg = tor_strdup("Invalid TransPort/TransListenAddress configuration");
6025 goto err;
6027 if (parse_port_config(ports,
6028 options->NATDPort_lines, options->NATDListenAddress,
6029 "NATD", CONN_TYPE_AP_NATD_LISTENER,
6030 "127.0.0.1", 0,
6031 CL_PORT_WARN_NONLOCAL) < 0) {
6032 *msg = tor_strdup("Invalid NatdPort/NatdListenAddress configuration");
6033 goto err;
6036 unsigned control_port_flags = CL_PORT_NO_OPTIONS | CL_PORT_WARN_NONLOCAL;
6037 const int any_passwords = (options->HashedControlPassword ||
6038 options->HashedControlSessionPassword ||
6039 options->CookieAuthentication);
6040 if (! any_passwords)
6041 control_port_flags |= CL_PORT_FORBID_NONLOCAL;
6043 if (parse_port_config(ports,
6044 options->ControlPort_lines,
6045 options->ControlListenAddress,
6046 "Control", CONN_TYPE_CONTROL_LISTENER,
6047 "127.0.0.1", 0,
6048 control_port_flags) < 0) {
6049 *msg = tor_strdup("Invalid ControlPort/ControlListenAddress "
6050 "configuration");
6051 goto err;
6053 if (parse_unix_socket_config(ports,
6054 options->ControlSocket,
6055 CONN_TYPE_CONTROL_LISTENER) < 0) {
6056 *msg = tor_strdup("Invalid ControlSocket configuration");
6057 goto err;
6060 if (! options->ClientOnly) {
6061 if (parse_port_config(ports,
6062 options->ORPort_lines, options->ORListenAddress,
6063 "OR", CONN_TYPE_OR_LISTENER,
6064 "0.0.0.0", 0,
6065 CL_PORT_SERVER_OPTIONS) < 0) {
6066 *msg = tor_strdup("Invalid ORPort/ORListenAddress configuration");
6067 goto err;
6069 if (parse_port_config(ports,
6070 options->ExtORPort_lines, NULL,
6071 "ExtOR", CONN_TYPE_EXT_OR_LISTENER,
6072 "127.0.0.1", 0,
6073 CL_PORT_SERVER_OPTIONS|CL_PORT_WARN_NONLOCAL) < 0) {
6074 *msg = tor_strdup("Invalid ExtORPort configuration");
6075 goto err;
6077 if (parse_port_config(ports,
6078 options->DirPort_lines, options->DirListenAddress,
6079 "Dir", CONN_TYPE_DIR_LISTENER,
6080 "0.0.0.0", 0,
6081 CL_PORT_SERVER_OPTIONS) < 0) {
6082 *msg = tor_strdup("Invalid DirPort/DirListenAddress configuration");
6083 goto err;
6087 if (check_server_ports(ports, options) < 0) {
6088 *msg = tor_strdup("Misconfigured server ports");
6089 goto err;
6092 *n_ports_out = smartlist_len(ports);
6094 retval = 0;
6096 /* Update the *Port_set options. The !! here is to force a boolean out of
6097 an integer. */
6098 options->ORPort_set =
6099 !! count_real_listeners(ports, CONN_TYPE_OR_LISTENER);
6100 options->SocksPort_set =
6101 !! count_real_listeners(ports, CONN_TYPE_AP_LISTENER);
6102 options->TransPort_set =
6103 !! count_real_listeners(ports, CONN_TYPE_AP_TRANS_LISTENER);
6104 options->NATDPort_set =
6105 !! count_real_listeners(ports, CONN_TYPE_AP_NATD_LISTENER);
6106 options->ControlPort_set =
6107 !! count_real_listeners(ports, CONN_TYPE_CONTROL_LISTENER);
6108 options->DirPort_set =
6109 !! count_real_listeners(ports, CONN_TYPE_DIR_LISTENER);
6110 options->DNSPort_set =
6111 !! count_real_listeners(ports, CONN_TYPE_AP_DNS_LISTENER);
6112 options->ExtORPort_set =
6113 !! count_real_listeners(ports, CONN_TYPE_EXT_OR_LISTENER);
6115 if (!validate_only) {
6116 if (configured_ports) {
6117 SMARTLIST_FOREACH(configured_ports,
6118 port_cfg_t *, p, port_cfg_free(p));
6119 smartlist_free(configured_ports);
6121 configured_ports = ports;
6122 ports = NULL; /* prevent free below. */
6125 err:
6126 if (ports) {
6127 SMARTLIST_FOREACH(ports, port_cfg_t *, p, port_cfg_free(p));
6128 smartlist_free(ports);
6130 return retval;
6133 /** Given a list of <b>port_cfg_t</b> in <b>ports</b>, check them for internal
6134 * consistency and warn as appropriate. */
6135 static int
6136 check_server_ports(const smartlist_t *ports,
6137 const or_options_t *options)
6139 int n_orport_advertised = 0;
6140 int n_orport_advertised_ipv4 = 0;
6141 int n_orport_listeners = 0;
6142 int n_dirport_advertised = 0;
6143 int n_dirport_listeners = 0;
6144 int n_low_port = 0;
6145 int r = 0;
6147 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
6148 if (port->type == CONN_TYPE_DIR_LISTENER) {
6149 if (! port->no_advertise)
6150 ++n_dirport_advertised;
6151 if (! port->no_listen)
6152 ++n_dirport_listeners;
6153 } else if (port->type == CONN_TYPE_OR_LISTENER) {
6154 if (! port->no_advertise) {
6155 ++n_orport_advertised;
6156 if (tor_addr_family(&port->addr) == AF_INET ||
6157 (tor_addr_family(&port->addr) == AF_UNSPEC &&
6158 !port->bind_ipv6_only))
6159 ++n_orport_advertised_ipv4;
6161 if (! port->no_listen)
6162 ++n_orport_listeners;
6163 } else {
6164 continue;
6166 #ifndef _WIN32
6167 if (!port->no_listen && port->port < 1024)
6168 ++n_low_port;
6169 #endif
6170 } SMARTLIST_FOREACH_END(port);
6172 if (n_orport_advertised && !n_orport_listeners) {
6173 log_warn(LD_CONFIG, "We are advertising an ORPort, but not actually "
6174 "listening on one.");
6175 r = -1;
6177 if (n_orport_listeners && !n_orport_advertised) {
6178 log_warn(LD_CONFIG, "We are listening on an ORPort, but not advertising "
6179 "any ORPorts. This will keep us from building a %s "
6180 "descriptor, and make us impossible to use.",
6181 options->BridgeRelay ? "bridge" : "router");
6182 r = -1;
6184 if (n_dirport_advertised && !n_dirport_listeners) {
6185 log_warn(LD_CONFIG, "We are advertising a DirPort, but not actually "
6186 "listening on one.");
6187 r = -1;
6189 if (n_dirport_advertised > 1) {
6190 log_warn(LD_CONFIG, "Can't advertise more than one DirPort.");
6191 r = -1;
6193 if (n_orport_advertised && !n_orport_advertised_ipv4 &&
6194 !options->BridgeRelay) {
6195 log_warn(LD_CONFIG, "Configured non-bridge only to listen on an IPv6 "
6196 "address.");
6197 r = -1;
6200 if (n_low_port && options->AccountingMax) {
6201 log_warn(LD_CONFIG,
6202 "You have set AccountingMax to use hibernation. You have also "
6203 "chosen a low DirPort or OrPort. This combination can make Tor stop "
6204 "working when it tries to re-attach the port after a period of "
6205 "hibernation. Please choose a different port or turn off "
6206 "hibernation unless you know this combination will work on your "
6207 "platform.");
6210 return r;
6213 /** Return a list of port_cfg_t for client ports parsed from the
6214 * options. */
6215 const smartlist_t *
6216 get_configured_ports(void)
6218 if (!configured_ports)
6219 configured_ports = smartlist_new();
6220 return configured_ports;
6223 /** Return an address:port string representation of the address
6224 * where the first <b>listener_type</b> listener waits for
6225 * connections. Return NULL if we couldn't find a listener. The
6226 * string is allocated on the heap and it's the responsibility of the
6227 * caller to free it after use.
6229 * This function is meant to be used by the pluggable transport proxy
6230 * spawning code, please make sure that it fits your purposes before
6231 * using it. */
6232 char *
6233 get_first_listener_addrport_string(int listener_type)
6235 static const char *ipv4_localhost = "127.0.0.1";
6236 static const char *ipv6_localhost = "[::1]";
6237 const char *address;
6238 uint16_t port;
6239 char *string = NULL;
6241 if (!configured_ports)
6242 return NULL;
6244 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
6245 if (cfg->no_listen)
6246 continue;
6248 if (cfg->type == listener_type &&
6249 tor_addr_family(&cfg->addr) != AF_UNSPEC) {
6251 /* We found the first listener of the type we are interested in! */
6253 /* If a listener is listening on INADDR_ANY, assume that it's
6254 also listening on 127.0.0.1, and point the transport proxy
6255 there: */
6256 if (tor_addr_is_null(&cfg->addr))
6257 address = tor_addr_is_v4(&cfg->addr) ? ipv4_localhost : ipv6_localhost;
6258 else
6259 address = fmt_and_decorate_addr(&cfg->addr);
6261 /* If a listener is configured with port 'auto', we are forced
6262 to iterate all listener connections and find out in which
6263 port it ended up listening: */
6264 if (cfg->port == CFG_AUTO_PORT) {
6265 port = router_get_active_listener_port_by_type_af(listener_type,
6266 tor_addr_family(&cfg->addr));
6267 if (!port)
6268 return NULL;
6269 } else {
6270 port = cfg->port;
6273 tor_asprintf(&string, "%s:%u", address, port);
6275 return string;
6278 } SMARTLIST_FOREACH_END(cfg);
6280 return NULL;
6283 /** Return the first advertised port of type <b>listener_type</b> in
6284 <b>address_family</b>. */
6286 get_first_advertised_port_by_type_af(int listener_type, int address_family)
6288 if (!configured_ports)
6289 return 0;
6290 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
6291 if (cfg->type == listener_type &&
6292 !cfg->no_advertise &&
6293 (tor_addr_family(&cfg->addr) == address_family ||
6294 tor_addr_family(&cfg->addr) == AF_UNSPEC)) {
6295 if (tor_addr_family(&cfg->addr) != AF_UNSPEC ||
6296 (address_family == AF_INET && !cfg->bind_ipv6_only) ||
6297 (address_family == AF_INET6 && !cfg->bind_ipv4_only)) {
6298 return cfg->port;
6301 } SMARTLIST_FOREACH_END(cfg);
6302 return 0;
6305 /** Adjust the value of options->DataDirectory, or fill it in if it's
6306 * absent. Return 0 on success, -1 on failure. */
6307 static int
6308 normalize_data_directory(or_options_t *options)
6310 #ifdef _WIN32
6311 char *p;
6312 if (options->DataDirectory)
6313 return 0; /* all set */
6314 p = tor_malloc(MAX_PATH);
6315 strlcpy(p,get_windows_conf_root(),MAX_PATH);
6316 options->DataDirectory = p;
6317 return 0;
6318 #else
6319 const char *d = options->DataDirectory;
6320 if (!d)
6321 d = "~/.tor";
6323 if (strncmp(d,"~/",2) == 0) {
6324 char *fn = expand_filename(d);
6325 if (!fn) {
6326 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
6327 return -1;
6329 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
6330 /* If our homedir is /, we probably don't want to use it. */
6331 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
6332 * want. */
6333 log_warn(LD_CONFIG,
6334 "Default DataDirectory is \"~/.tor\". This expands to "
6335 "\"%s\", which is probably not what you want. Using "
6336 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
6337 tor_free(fn);
6338 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
6340 tor_free(options->DataDirectory);
6341 options->DataDirectory = fn;
6343 return 0;
6344 #endif
6347 /** Check and normalize the value of options->DataDirectory; return 0 if it
6348 * is sane, -1 otherwise. */
6349 static int
6350 validate_data_directory(or_options_t *options)
6352 if (normalize_data_directory(options) < 0)
6353 return -1;
6354 tor_assert(options->DataDirectory);
6355 if (strlen(options->DataDirectory) > (512-128)) {
6356 log_warn(LD_CONFIG, "DataDirectory is too long.");
6357 return -1;
6359 return 0;
6362 /** This string must remain the same forevermore. It is how we
6363 * recognize that the torrc file doesn't need to be backed up. */
6364 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
6365 "if you edit it, comments will not be preserved"
6366 /** This string can change; it tries to give the reader an idea
6367 * that editing this file by hand is not a good plan. */
6368 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
6369 "to torrc.orig.1 or similar, and Tor will ignore it"
6371 /** Save a configuration file for the configuration in <b>options</b>
6372 * into the file <b>fname</b>. If the file already exists, and
6373 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
6374 * replace it. Return 0 on success, -1 on failure. */
6375 static int
6376 write_configuration_file(const char *fname, const or_options_t *options)
6378 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
6379 int rename_old = 0, r;
6381 tor_assert(fname);
6383 switch (file_status(fname)) {
6384 case FN_FILE:
6385 old_val = read_file_to_str(fname, 0, NULL);
6386 if (!old_val || strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
6387 rename_old = 1;
6389 tor_free(old_val);
6390 break;
6391 case FN_NOENT:
6392 break;
6393 case FN_ERROR:
6394 case FN_DIR:
6395 default:
6396 log_warn(LD_CONFIG,
6397 "Config file \"%s\" is not a file? Failing.", fname);
6398 return -1;
6401 if (!(new_conf = options_dump(options, OPTIONS_DUMP_MINIMAL))) {
6402 log_warn(LD_BUG, "Couldn't get configuration string");
6403 goto err;
6406 tor_asprintf(&new_val, "%s\n%s\n\n%s",
6407 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
6409 if (rename_old) {
6410 int i = 1;
6411 char *fn_tmp = NULL;
6412 while (1) {
6413 tor_asprintf(&fn_tmp, "%s.orig.%d", fname, i);
6414 if (file_status(fn_tmp) == FN_NOENT)
6415 break;
6416 tor_free(fn_tmp);
6417 ++i;
6419 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
6420 if (tor_rename(fname, fn_tmp) < 0) {//XXXX sandbox doesn't allow
6421 log_warn(LD_FS,
6422 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
6423 fname, fn_tmp, strerror(errno));
6424 tor_free(fn_tmp);
6425 goto err;
6427 tor_free(fn_tmp);
6430 if (write_str_to_file(fname, new_val, 0) < 0)
6431 goto err;
6433 r = 0;
6434 goto done;
6435 err:
6436 r = -1;
6437 done:
6438 tor_free(new_val);
6439 tor_free(new_conf);
6440 return r;
6444 * Save the current configuration file value to disk. Return 0 on
6445 * success, -1 on failure.
6448 options_save_current(void)
6450 /* This fails if we can't write to our configuration file.
6452 * If we try falling back to datadirectory or something, we have a better
6453 * chance of saving the configuration, but a better chance of doing
6454 * something the user never expected. */
6455 return write_configuration_file(get_torrc_fname(0), get_options());
6458 /** Return the number of cpus configured in <b>options</b>. If we are
6459 * told to auto-detect the number of cpus, return the auto-detected number. */
6461 get_num_cpus(const or_options_t *options)
6463 if (options->NumCPUs == 0) {
6464 int n = compute_num_cpus();
6465 return (n >= 1) ? n : 1;
6466 } else {
6467 return options->NumCPUs;
6472 * Initialize the libevent library.
6474 static void
6475 init_libevent(const or_options_t *options)
6477 const char *badness=NULL;
6478 tor_libevent_cfg cfg;
6480 tor_assert(options);
6482 configure_libevent_logging();
6483 /* If the kernel complains that some method (say, epoll) doesn't
6484 * exist, we don't care about it, since libevent will cope.
6486 suppress_libevent_log_msg("Function not implemented");
6488 tor_check_libevent_header_compatibility();
6490 memset(&cfg, 0, sizeof(cfg));
6491 cfg.disable_iocp = options->DisableIOCP;
6492 cfg.num_cpus = get_num_cpus(options);
6493 cfg.msec_per_tick = options->TokenBucketRefillInterval;
6495 tor_libevent_initialize(&cfg);
6497 suppress_libevent_log_msg(NULL);
6499 tor_check_libevent_version(tor_libevent_get_method(),
6500 server_mode(get_options()),
6501 &badness);
6502 if (badness) {
6503 const char *v = tor_libevent_get_version_str();
6504 const char *m = tor_libevent_get_method();
6505 control_event_general_status(LOG_WARN,
6506 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
6507 v, m, badness);
6511 /** Return a newly allocated string holding a filename relative to the data
6512 * directory. If <b>sub1</b> is present, it is the first path component after
6513 * the data directory. If <b>sub2</b> is also present, it is the second path
6514 * component after the data directory. If <b>suffix</b> is present, it
6515 * is appended to the filename.
6517 * Examples:
6518 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
6519 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
6520 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
6521 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
6523 * Note: Consider using the get_datadir_fname* macros in or.h.
6525 char *
6526 options_get_datadir_fname2_suffix(const or_options_t *options,
6527 const char *sub1, const char *sub2,
6528 const char *suffix)
6530 char *fname = NULL;
6531 size_t len;
6532 tor_assert(options);
6533 tor_assert(options->DataDirectory);
6534 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
6535 len = strlen(options->DataDirectory);
6536 if (sub1) {
6537 len += strlen(sub1)+1;
6538 if (sub2)
6539 len += strlen(sub2)+1;
6541 if (suffix)
6542 len += strlen(suffix);
6543 len++;
6544 fname = tor_malloc(len);
6545 if (sub1) {
6546 if (sub2) {
6547 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
6548 options->DataDirectory, sub1, sub2);
6549 } else {
6550 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
6551 options->DataDirectory, sub1);
6553 } else {
6554 strlcpy(fname, options->DataDirectory, len);
6556 if (suffix)
6557 strlcat(fname, suffix, len);
6558 return fname;
6561 /** Check wether the data directory has a private subdirectory
6562 * <b>subdir</b>. If not, try to create it. Return 0 on success,
6563 * -1 otherwise. */
6565 check_or_create_data_subdir(const char *subdir)
6567 char *statsdir = get_datadir_fname(subdir);
6568 int return_val = 0;
6570 if (check_private_dir(statsdir, CPD_CREATE, get_options()->User) < 0) {
6571 log_warn(LD_HIST, "Unable to create %s/ directory!", subdir);
6572 return_val = -1;
6574 tor_free(statsdir);
6575 return return_val;
6578 /** Create a file named <b>fname</b> with contents <b>str</b> in the
6579 * subdirectory <b>subdir</b> of the data directory. <b>descr</b>
6580 * should be a short description of the file's content and will be
6581 * used for the warning message, if it's present and the write process
6582 * fails. Return 0 on success, -1 otherwise.*/
6584 write_to_data_subdir(const char* subdir, const char* fname,
6585 const char* str, const char* descr)
6587 char *filename = get_datadir_fname2(subdir, fname);
6588 int return_val = 0;
6590 if (write_str_to_file(filename, str, 0) < 0) {
6591 log_warn(LD_HIST, "Unable to write %s to disk!", descr ? descr : fname);
6592 return_val = -1;
6594 tor_free(filename);
6595 return return_val;
6598 /** Given a file name check to see whether the file exists but has not been
6599 * modified for a very long time. If so, remove it. */
6600 void
6601 remove_file_if_very_old(const char *fname, time_t now)
6603 #define VERY_OLD_FILE_AGE (28*24*60*60)
6604 struct stat st;
6606 log_debug(LD_FS, "stat()ing %s", fname);
6607 if (stat(sandbox_intern_string(fname), &st)==0 &&
6608 st.st_mtime < now-VERY_OLD_FILE_AGE) {
6609 char buf[ISO_TIME_LEN+1];
6610 format_local_iso_time(buf, st.st_mtime);
6611 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
6612 "Removing it.", fname, buf);
6613 if (unlink(fname) != 0) {
6614 log_warn(LD_FS, "Failed to unlink %s: %s",
6615 fname, strerror(errno));
6620 /** Return a smartlist of ports that must be forwarded by
6621 * tor-fw-helper. The smartlist contains the ports in a string format
6622 * that is understandable by tor-fw-helper. */
6623 smartlist_t *
6624 get_list_of_ports_to_forward(void)
6626 smartlist_t *ports_to_forward = smartlist_new();
6627 int port = 0;
6629 /** XXX TODO tor-fw-helper does not support forwarding ports to
6630 other hosts than the local one. If the user is binding to a
6631 different IP address, tor-fw-helper won't work. */
6632 port = router_get_advertised_or_port(get_options()); /* Get ORPort */
6633 if (port)
6634 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
6636 port = router_get_advertised_dir_port(get_options(), 0); /* Get DirPort */
6637 if (port)
6638 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
6640 /* Get ports of transport proxies */
6642 smartlist_t *transport_ports = get_transport_proxy_ports();
6643 if (transport_ports) {
6644 smartlist_add_all(ports_to_forward, transport_ports);
6645 smartlist_free(transport_ports);
6649 if (!smartlist_len(ports_to_forward)) {
6650 smartlist_free(ports_to_forward);
6651 ports_to_forward = NULL;
6654 return ports_to_forward;
6657 /** Helper to implement GETINFO functions about configuration variables (not
6658 * their values). Given a "config/names" question, set *<b>answer</b> to a
6659 * new string describing the supported configuration variables and their
6660 * types. */
6662 getinfo_helper_config(control_connection_t *conn,
6663 const char *question, char **answer,
6664 const char **errmsg)
6666 (void) conn;
6667 (void) errmsg;
6668 if (!strcmp(question, "config/names")) {
6669 smartlist_t *sl = smartlist_new();
6670 int i;
6671 for (i = 0; option_vars_[i].name; ++i) {
6672 const config_var_t *var = &option_vars_[i];
6673 const char *type;
6674 /* don't tell controller about triple-underscore options */
6675 if (!strncmp(option_vars_[i].name, "___", 3))
6676 continue;
6677 switch (var->type) {
6678 case CONFIG_TYPE_STRING: type = "String"; break;
6679 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
6680 case CONFIG_TYPE_UINT: type = "Integer"; break;
6681 case CONFIG_TYPE_INT: type = "SignedInteger"; break;
6682 case CONFIG_TYPE_PORT: type = "Port"; break;
6683 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
6684 case CONFIG_TYPE_MSEC_INTERVAL: type = "TimeMsecInterval"; break;
6685 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
6686 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
6687 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
6688 case CONFIG_TYPE_AUTOBOOL: type = "Boolean+Auto"; break;
6689 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
6690 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
6691 case CONFIG_TYPE_CSV: type = "CommaList"; break;
6692 case CONFIG_TYPE_CSV_INTERVAL: type = "TimeIntervalCommaList"; break;
6693 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
6694 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
6695 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
6696 default:
6697 case CONFIG_TYPE_OBSOLETE:
6698 type = NULL; break;
6700 if (!type)
6701 continue;
6702 smartlist_add_asprintf(sl, "%s %s\n",var->name,type);
6704 *answer = smartlist_join_strings(sl, "", 0, NULL);
6705 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
6706 smartlist_free(sl);
6707 } else if (!strcmp(question, "config/defaults")) {
6708 smartlist_t *sl = smartlist_new();
6709 int i;
6710 for (i = 0; option_vars_[i].name; ++i) {
6711 const config_var_t *var = &option_vars_[i];
6712 if (var->initvalue != NULL) {
6713 char *val = esc_for_log(var->initvalue);
6714 smartlist_add_asprintf(sl, "%s %s\n",var->name,val);
6715 tor_free(val);
6718 *answer = smartlist_join_strings(sl, "", 0, NULL);
6719 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
6720 smartlist_free(sl);
6722 return 0;
6725 /** Parse outbound bind address option lines. If <b>validate_only</b>
6726 * is not 0 update OutboundBindAddressIPv4_ and
6727 * OutboundBindAddressIPv6_ in <b>options</b>. On failure, set
6728 * <b>msg</b> (if provided) to a newly allocated string containing a
6729 * description of the problem and return -1. */
6730 static int
6731 parse_outbound_addresses(or_options_t *options, int validate_only, char **msg)
6733 const config_line_t *lines = options->OutboundBindAddress;
6734 int found_v4 = 0, found_v6 = 0;
6736 if (!validate_only) {
6737 memset(&options->OutboundBindAddressIPv4_, 0,
6738 sizeof(options->OutboundBindAddressIPv4_));
6739 memset(&options->OutboundBindAddressIPv6_, 0,
6740 sizeof(options->OutboundBindAddressIPv6_));
6742 while (lines) {
6743 tor_addr_t addr, *dst_addr = NULL;
6744 int af = tor_addr_parse(&addr, lines->value);
6745 switch (af) {
6746 case AF_INET:
6747 if (found_v4) {
6748 if (msg)
6749 tor_asprintf(msg, "Multiple IPv4 outbound bind addresses "
6750 "configured: %s", lines->value);
6751 return -1;
6753 found_v4 = 1;
6754 dst_addr = &options->OutboundBindAddressIPv4_;
6755 break;
6756 case AF_INET6:
6757 if (found_v6) {
6758 if (msg)
6759 tor_asprintf(msg, "Multiple IPv6 outbound bind addresses "
6760 "configured: %s", lines->value);
6761 return -1;
6763 found_v6 = 1;
6764 dst_addr = &options->OutboundBindAddressIPv6_;
6765 break;
6766 default:
6767 if (msg)
6768 tor_asprintf(msg, "Outbound bind address '%s' didn't parse.",
6769 lines->value);
6770 return -1;
6772 if (!validate_only)
6773 tor_addr_copy(dst_addr, &addr);
6774 lines = lines->next;
6776 return 0;
6779 /** Load one of the geoip files, <a>family</a> determining which
6780 * one. <a>default_fname</a> is used if on Windows and
6781 * <a>fname</a> equals "<default>". */
6782 static void
6783 config_load_geoip_file_(sa_family_t family,
6784 const char *fname,
6785 const char *default_fname)
6787 #ifdef _WIN32
6788 char *free_fname = NULL; /* Used to hold any temporary-allocated value */
6789 /* XXXX Don't use this "<default>" junk; make our filename options
6790 * understand prefixes somehow. -NM */
6791 if (!strcmp(fname, "<default>")) {
6792 const char *conf_root = get_windows_conf_root();
6793 tor_asprintf(&free_fname, "%s\\%s", conf_root, default_fname);
6794 fname = free_fname;
6796 geoip_load_file(family, fname);
6797 tor_free(free_fname);
6798 #else
6799 (void)default_fname;
6800 geoip_load_file(family, fname);
6801 #endif
6804 /** Load geoip files for IPv4 and IPv6 if <a>options</a> and
6805 * <a>old_options</a> indicate we should. */
6806 static void
6807 config_maybe_load_geoip_files_(const or_options_t *options,
6808 const or_options_t *old_options)
6810 /* XXXX024 Reload GeoIPFile on SIGHUP. -NM */
6812 if (options->GeoIPFile &&
6813 ((!old_options || !opt_streq(old_options->GeoIPFile,
6814 options->GeoIPFile))
6815 || !geoip_is_loaded(AF_INET)))
6816 config_load_geoip_file_(AF_INET, options->GeoIPFile, "geoip");
6817 if (options->GeoIPv6File &&
6818 ((!old_options || !opt_streq(old_options->GeoIPv6File,
6819 options->GeoIPv6File))
6820 || !geoip_is_loaded(AF_INET6)))
6821 config_load_geoip_file_(AF_INET6, options->GeoIPv6File, "geoip6");
6824 /** Initialize cookie authentication (used so far by the ControlPort
6825 * and Extended ORPort).
6827 * Allocate memory and create a cookie (of length <b>cookie_len</b>)
6828 * in <b>cookie_out</b>.
6829 * Then write it down to <b>fname</b> and prepend it with <b>header</b>.
6831 * If the whole procedure was successful, set
6832 * <b>cookie_is_set_out</b> to True. */
6834 init_cookie_authentication(const char *fname, const char *header,
6835 int cookie_len,
6836 uint8_t **cookie_out, int *cookie_is_set_out)
6838 char cookie_file_str_len = strlen(header) + cookie_len;
6839 char *cookie_file_str = tor_malloc(cookie_file_str_len);
6840 int retval = -1;
6842 /* We don't want to generate a new cookie every time we call
6843 * options_act(). One should be enough. */
6844 if (*cookie_is_set_out) {
6845 retval = 0; /* we are all set */
6846 goto done;
6849 /* If we've already set the cookie, free it before re-setting
6850 it. This can happen if we previously generated a cookie, but
6851 couldn't write it to a disk. */
6852 if (*cookie_out)
6853 tor_free(*cookie_out);
6855 /* Generate the cookie */
6856 *cookie_out = tor_malloc(cookie_len);
6857 if (crypto_rand((char *)*cookie_out, cookie_len) < 0)
6858 goto done;
6860 /* Create the string that should be written on the file. */
6861 memcpy(cookie_file_str, header, strlen(header));
6862 memcpy(cookie_file_str+strlen(header), *cookie_out, cookie_len);
6863 if (write_bytes_to_file(fname, cookie_file_str, cookie_file_str_len, 1)) {
6864 log_warn(LD_FS,"Error writing auth cookie to %s.", escaped(fname));
6865 goto done;
6868 /* Success! */
6869 log_info(LD_GENERAL, "Generated auth cookie file in '%s'.", escaped(fname));
6870 *cookie_is_set_out = 1;
6871 retval = 0;
6873 done:
6874 memwipe(cookie_file_str, 0, cookie_file_str_len);
6875 tor_free(cookie_file_str);
6876 return retval;