Merge branch 'maint-0.2.4' into maint-0.2.5
[tor.git] / src / or / config.c
blob60d3d7feb5be6e94da2ef9154cb084cf12307e3d
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, "2 MB"),
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(ExtORPortCookieAuthFileGroupReadable, BOOL, "0"),
242 V(ExtraInfoStatistics, BOOL, "1"),
243 V(FallbackDir, LINELIST, NULL),
245 OBSOLETE("FallbackNetworkstatusFile"),
246 V(FascistFirewall, BOOL, "0"),
247 V(FirewallPorts, CSV, ""),
248 V(FastFirstHopPK, AUTOBOOL, "auto"),
249 V(FetchDirInfoEarly, BOOL, "0"),
250 V(FetchDirInfoExtraEarly, BOOL, "0"),
251 V(FetchServerDescriptors, BOOL, "1"),
252 V(FetchHidServDescriptors, BOOL, "1"),
253 V(FetchUselessDescriptors, BOOL, "0"),
254 OBSOLETE("FetchV2Networkstatus"),
255 V(GeoIPExcludeUnknown, AUTOBOOL, "auto"),
256 #ifdef _WIN32
257 V(GeoIPFile, FILENAME, "<default>"),
258 V(GeoIPv6File, FILENAME, "<default>"),
259 #else
260 V(GeoIPFile, FILENAME,
261 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
262 V(GeoIPv6File, FILENAME,
263 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip6"),
264 #endif
265 OBSOLETE("GiveGuardFlagTo_CVE_2011_2768_VulnerableRelays"),
266 OBSOLETE("Group"),
267 V(GuardLifetime, INTERVAL, "0 minutes"),
268 V(HardwareAccel, BOOL, "0"),
269 V(HeartbeatPeriod, INTERVAL, "6 hours"),
270 V(AccelName, STRING, NULL),
271 V(AccelDir, FILENAME, NULL),
272 V(HashedControlPassword, LINELIST, NULL),
273 V(HidServDirectoryV2, BOOL, "1"),
274 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
275 OBSOLETE("HiddenServiceExcludeNodes"),
276 OBSOLETE("HiddenServiceNodes"),
277 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
278 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
279 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
280 VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
281 V(HidServAuth, LINELIST, NULL),
282 OBSOLETE("HSAuthoritativeDir"),
283 OBSOLETE("HSAuthorityRecordStats"),
284 V(CloseHSClientCircuitsImmediatelyOnTimeout, BOOL, "0"),
285 V(CloseHSServiceRendCircuitsImmediatelyOnTimeout, BOOL, "0"),
286 V(HTTPProxy, STRING, NULL),
287 V(HTTPProxyAuthenticator, STRING, NULL),
288 V(HTTPSProxy, STRING, NULL),
289 V(HTTPSProxyAuthenticator, STRING, NULL),
290 V(IPv6Exit, BOOL, "0"),
291 VAR("ServerTransportPlugin", LINELIST, ServerTransportPlugin, NULL),
292 V(ServerTransportListenAddr, LINELIST, NULL),
293 V(ServerTransportOptions, LINELIST, NULL),
294 V(Socks4Proxy, STRING, NULL),
295 V(Socks5Proxy, STRING, NULL),
296 V(Socks5ProxyUsername, STRING, NULL),
297 V(Socks5ProxyPassword, STRING, NULL),
298 OBSOLETE("IgnoreVersion"),
299 V(KeepalivePeriod, INTERVAL, "5 minutes"),
300 VAR("Log", LINELIST, Logs, NULL),
301 V(LogMessageDomains, BOOL, "0"),
302 OBSOLETE("LinkPadding"),
303 OBSOLETE("LogLevel"),
304 OBSOLETE("LogFile"),
305 V(LogTimeGranularity, MSEC_INTERVAL, "1 second"),
306 V(LongLivedPorts, CSV,
307 "21,22,706,1863,5050,5190,5222,5223,6523,6667,6697,8300"),
308 VAR("MapAddress", LINELIST, AddressMap, NULL),
309 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
310 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
311 V(MaxClientCircuitsPending, UINT, "32"),
312 VAR("MaxMemInQueues", MEMUNIT, MaxMemInQueues_raw, "0"),
313 OBSOLETE("MaxOnionsPending"),
314 V(MaxOnionQueueDelay, MSEC_INTERVAL, "1750 msec"),
315 V(MinMeasuredBWsForAuthToIgnoreAdvertised, INT, "500"),
316 OBSOLETE("MonthlyAccountingStart"),
317 V(MyFamily, STRING, NULL),
318 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
319 VAR("NamingAuthoritativeDirectory",BOOL, NamingAuthoritativeDir, "0"),
320 V(NATDListenAddress, LINELIST, NULL),
321 VPORT(NATDPort, LINELIST, NULL),
322 V(Nickname, STRING, NULL),
323 V(PredictedPortsRelevanceTime, INTERVAL, "1 hour"),
324 V(WarnUnsafeSocks, BOOL, "1"),
325 OBSOLETE("NoPublish"),
326 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
327 V(NumCPUs, UINT, "0"),
328 V(NumDirectoryGuards, UINT, "0"),
329 V(NumEntryGuards, UINT, "0"),
330 V(ORListenAddress, LINELIST, NULL),
331 VPORT(ORPort, LINELIST, NULL),
332 V(OutboundBindAddress, LINELIST, NULL),
334 OBSOLETE("PathBiasDisableRate"),
335 V(PathBiasCircThreshold, INT, "-1"),
336 V(PathBiasNoticeRate, DOUBLE, "-1"),
337 V(PathBiasWarnRate, DOUBLE, "-1"),
338 V(PathBiasExtremeRate, DOUBLE, "-1"),
339 V(PathBiasScaleThreshold, INT, "-1"),
340 OBSOLETE("PathBiasScaleFactor"),
341 OBSOLETE("PathBiasMultFactor"),
342 V(PathBiasDropGuards, AUTOBOOL, "0"),
343 OBSOLETE("PathBiasUseCloseCounts"),
345 V(PathBiasUseThreshold, INT, "-1"),
346 V(PathBiasNoticeUseRate, DOUBLE, "-1"),
347 V(PathBiasExtremeUseRate, DOUBLE, "-1"),
348 V(PathBiasScaleUseThreshold, INT, "-1"),
350 V(PathsNeededToBuildCircuits, DOUBLE, "-1"),
351 OBSOLETE("PathlenCoinWeight"),
352 V(PerConnBWBurst, MEMUNIT, "0"),
353 V(PerConnBWRate, MEMUNIT, "0"),
354 V(PidFile, STRING, NULL),
355 V(TestingTorNetwork, BOOL, "0"),
356 V(TestingMinExitFlagThreshold, MEMUNIT, "0"),
357 V(TestingMinFastFlagThreshold, MEMUNIT, "0"),
358 V(OptimisticData, AUTOBOOL, "auto"),
359 V(PortForwarding, BOOL, "0"),
360 V(PortForwardingHelper, FILENAME, "tor-fw-helper"),
361 OBSOLETE("PreferTunneledDirConns"),
362 V(ProtocolWarnings, BOOL, "0"),
363 V(PublishServerDescriptor, CSV, "1"),
364 V(PublishHidServDescriptors, BOOL, "1"),
365 V(ReachableAddresses, LINELIST, NULL),
366 V(ReachableDirAddresses, LINELIST, NULL),
367 V(ReachableORAddresses, LINELIST, NULL),
368 V(RecommendedVersions, LINELIST, NULL),
369 V(RecommendedClientVersions, LINELIST, NULL),
370 V(RecommendedServerVersions, LINELIST, NULL),
371 OBSOLETE("RedirectExit"),
372 V(RefuseUnknownExits, AUTOBOOL, "auto"),
373 V(RejectPlaintextPorts, CSV, ""),
374 V(RelayBandwidthBurst, MEMUNIT, "0"),
375 V(RelayBandwidthRate, MEMUNIT, "0"),
376 OBSOLETE("RendExcludeNodes"),
377 OBSOLETE("RendNodes"),
378 V(RendPostPeriod, INTERVAL, "1 hour"),
379 V(RephistTrackTime, INTERVAL, "24 hours"),
380 OBSOLETE("RouterFile"),
381 V(RunAsDaemon, BOOL, "0"),
382 // V(RunTesting, BOOL, "0"),
383 OBSOLETE("RunTesting"), // currently unused
384 V(Sandbox, BOOL, "0"),
385 V(SafeLogging, STRING, "1"),
386 V(SafeSocks, BOOL, "0"),
387 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
388 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
389 V(ServerDNSDetectHijacking, BOOL, "1"),
390 V(ServerDNSRandomizeCase, BOOL, "1"),
391 V(ServerDNSResolvConfFile, STRING, NULL),
392 V(ServerDNSSearchDomains, BOOL, "0"),
393 V(ServerDNSTestAddresses, CSV,
394 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
395 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
396 V(SocksListenAddress, LINELIST, NULL),
397 V(SocksPolicy, LINELIST, NULL),
398 VPORT(SocksPort, LINELIST, NULL),
399 V(SocksTimeout, INTERVAL, "2 minutes"),
400 V(SSLKeyLifetime, INTERVAL, "0"),
401 OBSOLETE("StatusFetchPeriod"),
402 V(StrictNodes, BOOL, "0"),
403 V(Support022HiddenServices, AUTOBOOL, "auto"),
404 OBSOLETE("SysLog"),
405 V(TestSocks, BOOL, "0"),
406 OBSOLETE("TestVia"),
407 V(TokenBucketRefillInterval, MSEC_INTERVAL, "100 msec"),
408 V(Tor2webMode, BOOL, "0"),
409 V(TLSECGroup, STRING, NULL),
410 V(TrackHostExits, CSV, NULL),
411 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
412 OBSOLETE("TrafficShaping"),
413 V(TransListenAddress, LINELIST, NULL),
414 VPORT(TransPort, LINELIST, NULL),
415 V(TransProxyType, STRING, "default"),
416 OBSOLETE("TunnelDirConns"),
417 V(UpdateBridgesFromAuthority, BOOL, "0"),
418 V(UseBridges, BOOL, "0"),
419 V(UseEntryGuards, BOOL, "1"),
420 V(UseEntryGuardsAsDirGuards, BOOL, "1"),
421 V(UseMicrodescriptors, AUTOBOOL, "auto"),
422 V(UseNTorHandshake, AUTOBOOL, "1"),
423 V(User, STRING, NULL),
424 V(UserspaceIOCPBuffers, BOOL, "0"),
425 OBSOLETE("V1AuthoritativeDirectory"),
426 OBSOLETE("V2AuthoritativeDirectory"),
427 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
428 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
429 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
430 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
431 V(TestingV3AuthVotingStartOffset, INTERVAL, "0"),
432 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
433 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
434 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
435 V(V3AuthNIntervalsValid, UINT, "3"),
436 V(V3AuthUseLegacyKey, BOOL, "0"),
437 V(V3BandwidthsFile, FILENAME, NULL),
438 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
439 V(VirtualAddrNetworkIPv4, STRING, "127.192.0.0/10"),
440 V(VirtualAddrNetworkIPv6, STRING, "[FE80::]/10"),
441 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
442 V(UseFilteringSSLBufferevents, BOOL, "0"),
443 VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
444 VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
445 VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
446 VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
447 VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
448 NULL),
449 VAR("__OwningControllerProcess",STRING,OwningControllerProcess, NULL),
450 V(MinUptimeHidServDirectoryV2, INTERVAL, "25 hours"),
451 V(VoteOnHidServDirectoriesV2, BOOL, "1"),
452 V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 60, 60, 120, "
453 "300, 900, 2147483647"),
454 V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 60, 300, 600, "
455 "2147483647"),
456 V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
457 "300, 600, 1800, 1800, 1800, 1800, "
458 "1800, 3600, 7200"),
459 V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
460 "300, 600, 1800, 3600, 3600, 3600, "
461 "10800, 21600, 43200"),
462 V(TestingBridgeDownloadSchedule, CSV_INTERVAL, "3600, 900, 900, 3600"),
463 V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "10 minutes"),
464 V(TestingDirConnectionMaxStall, INTERVAL, "5 minutes"),
465 V(TestingConsensusMaxDownloadTries, UINT, "8"),
466 V(TestingDescriptorMaxDownloadTries, UINT, "8"),
467 V(TestingMicrodescMaxDownloadTries, UINT, "8"),
468 V(TestingCertMaxDownloadTries, UINT, "8"),
469 V(TestingDirAuthVoteGuard, ROUTERSET, NULL),
470 VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "0"),
472 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
475 /** Override default values with these if the user sets the TestingTorNetwork
476 * option. */
477 static const config_var_t testing_tor_network_defaults[] = {
478 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
479 V(DirAllowPrivateAddresses, BOOL, "1"),
480 V(EnforceDistinctSubnets, BOOL, "0"),
481 V(AssumeReachable, BOOL, "1"),
482 V(AuthDirMaxServersPerAddr, UINT, "0"),
483 V(AuthDirMaxServersPerAuthAddr,UINT, "0"),
484 V(ClientDNSRejectInternalAddresses, BOOL,"0"),
485 V(ClientRejectInternalAddresses, BOOL, "0"),
486 V(CountPrivateBandwidth, BOOL, "1"),
487 V(ExitPolicyRejectPrivate, BOOL, "0"),
488 V(ExtendAllowPrivateAddresses, BOOL, "1"),
489 V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
490 V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
491 V(V3AuthDistDelay, INTERVAL, "20 seconds"),
492 V(TestingV3AuthInitialVotingInterval, INTERVAL, "5 minutes"),
493 V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
494 V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
495 V(TestingV3AuthVotingStartOffset, INTERVAL, "0"),
496 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
497 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
498 V(MinUptimeHidServDirectoryV2, INTERVAL, "0 minutes"),
499 V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 5, 10, 15, "
500 "20, 30, 60"),
501 V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, 15, 20, "
502 "30, 60"),
503 V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
504 "15, 20, 30, 60"),
505 V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
506 "15, 20, 30, 60"),
507 V(TestingBridgeDownloadSchedule, CSV_INTERVAL, "60, 30, 30, 60"),
508 V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "5 seconds"),
509 V(TestingDirConnectionMaxStall, INTERVAL, "30 seconds"),
510 V(TestingConsensusMaxDownloadTries, UINT, "80"),
511 V(TestingDescriptorMaxDownloadTries, UINT, "80"),
512 V(TestingMicrodescMaxDownloadTries, UINT, "80"),
513 V(TestingCertMaxDownloadTries, UINT, "80"),
514 V(TestingEnableConnBwEvent, BOOL, "1"),
515 V(TestingEnableCellStatsEvent, BOOL, "1"),
516 V(TestingEnableTbEmptyEvent, BOOL, "1"),
517 VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "1"),
519 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
522 #undef VAR
523 #undef V
524 #undef OBSOLETE
526 #ifdef _WIN32
527 static char *get_windows_conf_root(void);
528 #endif
529 static int options_act_reversible(const or_options_t *old_options, char **msg);
530 static int options_act(const or_options_t *old_options);
531 static int options_transition_allowed(const or_options_t *old,
532 const or_options_t *new,
533 char **msg);
534 static int options_transition_affects_workers(
535 const or_options_t *old_options, const or_options_t *new_options);
536 static int options_transition_affects_descriptor(
537 const or_options_t *old_options, const or_options_t *new_options);
538 static int check_nickname_list(char **lst, const char *name, char **msg);
540 static int parse_client_transport_line(const or_options_t *options,
541 const char *line, int validate_only);
543 static int parse_server_transport_line(const or_options_t *options,
544 const char *line, int validate_only);
545 static char *get_bindaddr_from_transport_listen_line(const char *line,
546 const char *transport);
547 static int parse_dir_authority_line(const char *line,
548 dirinfo_type_t required_type,
549 int validate_only);
550 static int parse_dir_fallback_line(const char *line,
551 int validate_only);
552 static void port_cfg_free(port_cfg_t *port);
553 static int parse_ports(or_options_t *options, int validate_only,
554 char **msg_out, int *n_ports_out);
555 static int check_server_ports(const smartlist_t *ports,
556 const or_options_t *options);
558 static int validate_data_directory(or_options_t *options);
559 static int write_configuration_file(const char *fname,
560 const or_options_t *options);
561 static int options_init_logs(or_options_t *options, int validate_only);
563 static void init_libevent(const or_options_t *options);
564 static int opt_streq(const char *s1, const char *s2);
565 static int parse_outbound_addresses(or_options_t *options, int validate_only,
566 char **msg);
567 static void config_maybe_load_geoip_files_(const or_options_t *options,
568 const or_options_t *old_options);
569 static int options_validate_cb(void *old_options, void *options,
570 void *default_options,
571 int from_setconf, char **msg);
572 static uint64_t compute_real_max_mem_in_queues(const uint64_t val,
573 int log_guess);
575 /** Magic value for or_options_t. */
576 #define OR_OPTIONS_MAGIC 9090909
578 /** Configuration format for or_options_t. */
579 STATIC config_format_t options_format = {
580 sizeof(or_options_t),
581 OR_OPTIONS_MAGIC,
582 STRUCT_OFFSET(or_options_t, magic_),
583 option_abbrevs_,
584 option_vars_,
585 options_validate_cb,
586 NULL
590 * Functions to read and write the global options pointer.
593 /** Command-line and config-file options. */
594 static or_options_t *global_options = NULL;
595 /** The fallback options_t object; this is where we look for options not
596 * in torrc before we fall back to Tor's defaults. */
597 static or_options_t *global_default_options = NULL;
598 /** Name of most recently read torrc file. */
599 static char *torrc_fname = NULL;
600 /** Name of the most recently read torrc-defaults file.*/
601 static char *torrc_defaults_fname;
602 /** Configuration options set by command line. */
603 static config_line_t *global_cmdline_options = NULL;
604 /** Non-configuration options set by the command line */
605 static config_line_t *global_cmdline_only_options = NULL;
606 /** Boolean: Have we parsed the command line? */
607 static int have_parsed_cmdline = 0;
608 /** Contents of most recently read DirPortFrontPage file. */
609 static char *global_dirfrontpagecontents = NULL;
610 /** List of port_cfg_t for all configured ports. */
611 static smartlist_t *configured_ports = NULL;
613 /** Return the contents of our frontpage string, or NULL if not configured. */
614 const char *
615 get_dirportfrontpage(void)
617 return global_dirfrontpagecontents;
620 /** Return the currently configured options. */
621 or_options_t *
622 get_options_mutable(void)
624 tor_assert(global_options);
625 return global_options;
628 /** Returns the currently configured options */
629 MOCK_IMPL(const or_options_t *,
630 get_options,(void))
632 return get_options_mutable();
635 /** Change the current global options to contain <b>new_val</b> instead of
636 * their current value; take action based on the new value; free the old value
637 * as necessary. Returns 0 on success, -1 on failure.
640 set_options(or_options_t *new_val, char **msg)
642 int i;
643 smartlist_t *elements;
644 config_line_t *line;
645 or_options_t *old_options = global_options;
646 global_options = new_val;
647 /* Note that we pass the *old* options below, for comparison. It
648 * pulls the new options directly out of global_options. */
649 if (options_act_reversible(old_options, msg)<0) {
650 tor_assert(*msg);
651 global_options = old_options;
652 return -1;
654 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
655 log_err(LD_BUG,
656 "Acting on config options left us in a broken state. Dying.");
657 exit(1);
659 /* Issues a CONF_CHANGED event to notify controller of the change. If Tor is
660 * just starting up then the old_options will be undefined. */
661 if (old_options && old_options != global_options) {
662 elements = smartlist_new();
663 for (i=0; options_format.vars[i].name; ++i) {
664 const config_var_t *var = &options_format.vars[i];
665 const char *var_name = var->name;
666 if (var->type == CONFIG_TYPE_LINELIST_S ||
667 var->type == CONFIG_TYPE_OBSOLETE) {
668 continue;
670 if (!config_is_same(&options_format, new_val, old_options, var_name)) {
671 line = config_get_assigned_option(&options_format, new_val,
672 var_name, 1);
674 if (line) {
675 config_line_t *next;
676 for (; line; line = next) {
677 next = line->next;
678 smartlist_add(elements, line->key);
679 smartlist_add(elements, line->value);
680 tor_free(line);
682 } else {
683 smartlist_add(elements, tor_strdup(options_format.vars[i].name));
684 smartlist_add(elements, NULL);
688 control_event_conf_changed(elements);
689 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
690 smartlist_free(elements);
693 if (old_options != global_options)
694 config_free(&options_format, old_options);
696 return 0;
699 extern const char tor_git_revision[]; /* from tor_main.c */
701 /** The version of this Tor process, as parsed. */
702 static char *the_tor_version = NULL;
703 /** A shorter version of this Tor process's version, for export in our router
704 * descriptor. (Does not include the git version, if any.) */
705 static char *the_short_tor_version = NULL;
707 /** Return the current Tor version. */
708 const char *
709 get_version(void)
711 if (the_tor_version == NULL) {
712 if (strlen(tor_git_revision)) {
713 tor_asprintf(&the_tor_version, "%s (git-%s)", get_short_version(),
714 tor_git_revision);
715 } else {
716 the_tor_version = tor_strdup(get_short_version());
719 return the_tor_version;
722 /** Return the current Tor version, without any git tag. */
723 const char *
724 get_short_version(void)
727 if (the_short_tor_version == NULL) {
728 #ifdef TOR_BUILD_TAG
729 tor_asprintf(&the_short_tor_version, "%s (%s)", VERSION, TOR_BUILD_TAG);
730 #else
731 the_short_tor_version = tor_strdup(VERSION);
732 #endif
734 return the_short_tor_version;
737 /** Release additional memory allocated in options
739 STATIC void
740 or_options_free(or_options_t *options)
742 if (!options)
743 return;
745 routerset_free(options->ExcludeExitNodesUnion_);
746 if (options->NodeFamilySets) {
747 SMARTLIST_FOREACH(options->NodeFamilySets, routerset_t *,
748 rs, routerset_free(rs));
749 smartlist_free(options->NodeFamilySets);
751 tor_free(options->BridgePassword_AuthDigest_);
752 tor_free(options->command_arg);
753 config_free(&options_format, options);
756 /** Release all memory and resources held by global configuration structures.
758 void
759 config_free_all(void)
761 or_options_free(global_options);
762 global_options = NULL;
763 or_options_free(global_default_options);
764 global_default_options = NULL;
766 config_free_lines(global_cmdline_options);
767 global_cmdline_options = NULL;
769 config_free_lines(global_cmdline_only_options);
770 global_cmdline_only_options = NULL;
772 if (configured_ports) {
773 SMARTLIST_FOREACH(configured_ports,
774 port_cfg_t *, p, port_cfg_free(p));
775 smartlist_free(configured_ports);
776 configured_ports = NULL;
779 tor_free(torrc_fname);
780 tor_free(torrc_defaults_fname);
781 tor_free(the_tor_version);
782 tor_free(global_dirfrontpagecontents);
784 tor_free(the_short_tor_version);
785 tor_free(the_tor_version);
788 /** Make <b>address</b> -- a piece of information related to our operation as
789 * a client -- safe to log according to the settings in options->SafeLogging,
790 * and return it.
792 * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
794 const char *
795 safe_str_client(const char *address)
797 tor_assert(address);
798 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
799 return "[scrubbed]";
800 else
801 return address;
804 /** Make <b>address</b> -- a piece of information of unspecified sensitivity
805 * -- safe to log according to the settings in options->SafeLogging, and
806 * return it.
808 * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
809 * otherwise.)
811 const char *
812 safe_str(const char *address)
814 tor_assert(address);
815 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
816 return "[scrubbed]";
817 else
818 return address;
821 /** Equivalent to escaped(safe_str_client(address)). See reentrancy note on
822 * escaped(): don't use this outside the main thread, or twice in the same
823 * log statement. */
824 const char *
825 escaped_safe_str_client(const char *address)
827 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
828 return "[scrubbed]";
829 else
830 return escaped(address);
833 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
834 * escaped(): don't use this outside the main thread, or twice in the same
835 * log statement. */
836 const char *
837 escaped_safe_str(const char *address)
839 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
840 return "[scrubbed]";
841 else
842 return escaped(address);
845 /** Add the default directory authorities directly into the trusted dir list,
846 * but only add them insofar as they share bits with <b>type</b>. */
847 static void
848 add_default_trusted_dir_authorities(dirinfo_type_t type)
850 int i;
851 const char *authorities[] = {
852 "moria1 orport=9101 "
853 "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
854 "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
855 "tor26 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
856 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
857 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
858 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
859 "Tonga orport=443 bridge 82.94.251.203:80 "
860 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
861 "gabelmoo orport=443 "
862 "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
863 "131.188.40.189:80 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
864 "dannenberg orport=443 "
865 "v3ident=0232AF901C31A04EE9848595AF9BB7620D4C5B2E "
866 "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
867 "urras orport=80 v3ident=80550987E1D626E3EBA5E5E75A458DE0626D088C "
868 "208.83.223.34:443 0AD3 FA88 4D18 F89E EA2D 89C0 1937 9E0E 7FD9 4417",
869 "maatuska orport=80 "
870 "v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
871 "171.25.193.9:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
872 "Faravahar orport=443 "
873 "v3ident=EFCBE720AB3A82B99F9E953CD5BF50F7EEFC7B97 "
874 "154.35.175.225:80 CF6D 0AAF B385 BE71 B8E1 11FC 5CFF 4B47 9237 33BC",
875 "longclaw orport=443 "
876 "v3ident=23D15D965BC35114467363C165C4F724B64B4F66 "
877 "199.254.238.52:80 74A9 1064 6BCE EFBC D2E8 74FC 1DC9 9743 0F96 8145",
878 NULL
880 for (i=0; authorities[i]; i++) {
881 if (parse_dir_authority_line(authorities[i], type, 0)<0) {
882 log_err(LD_BUG, "Couldn't parse internal DirAuthority line %s",
883 authorities[i]);
888 /** Add the default fallback directory servers into the fallback directory
889 * server list. */
890 static void
891 add_default_fallback_dir_servers(void)
893 int i;
894 const char *fallback[] = {
895 NULL
897 for (i=0; fallback[i]; i++) {
898 if (parse_dir_fallback_line(fallback[i], 0)<0) {
899 log_err(LD_BUG, "Couldn't parse internal FallbackDir line %s",
900 fallback[i]);
905 /** Look at all the config options for using alternate directory
906 * authorities, and make sure none of them are broken. Also, warn the
907 * user if we changed any dangerous ones.
909 static int
910 validate_dir_servers(or_options_t *options, or_options_t *old_options)
912 config_line_t *cl;
914 if (options->DirAuthorities &&
915 (options->AlternateDirAuthority || options->AlternateBridgeAuthority)) {
916 log_warn(LD_CONFIG,
917 "You cannot set both DirAuthority and Alternate*Authority.");
918 return -1;
921 /* do we want to complain to the user about being partitionable? */
922 if ((options->DirAuthorities &&
923 (!old_options ||
924 !config_lines_eq(options->DirAuthorities,
925 old_options->DirAuthorities))) ||
926 (options->AlternateDirAuthority &&
927 (!old_options ||
928 !config_lines_eq(options->AlternateDirAuthority,
929 old_options->AlternateDirAuthority)))) {
930 log_warn(LD_CONFIG,
931 "You have used DirAuthority or AlternateDirAuthority to "
932 "specify alternate directory authorities in "
933 "your configuration. This is potentially dangerous: it can "
934 "make you look different from all other Tor users, and hurt "
935 "your anonymity. Even if you've specified the same "
936 "authorities as Tor uses by default, the defaults could "
937 "change in the future. Be sure you know what you're doing.");
940 /* Now go through the four ways you can configure an alternate
941 * set of directory authorities, and make sure none are broken. */
942 for (cl = options->DirAuthorities; cl; cl = cl->next)
943 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
944 return -1;
945 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
946 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
947 return -1;
948 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
949 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
950 return -1;
951 for (cl = options->FallbackDir; cl; cl = cl->next)
952 if (parse_dir_fallback_line(cl->value, 1)<0)
953 return -1;
954 return 0;
957 /** Look at all the config options and assign new dir authorities
958 * as appropriate.
960 static int
961 consider_adding_dir_servers(const or_options_t *options,
962 const or_options_t *old_options)
964 config_line_t *cl;
965 int need_to_update =
966 !smartlist_len(router_get_trusted_dir_servers()) ||
967 !smartlist_len(router_get_fallback_dir_servers()) || !old_options ||
968 !config_lines_eq(options->DirAuthorities, old_options->DirAuthorities) ||
969 !config_lines_eq(options->FallbackDir, old_options->FallbackDir) ||
970 !config_lines_eq(options->AlternateBridgeAuthority,
971 old_options->AlternateBridgeAuthority) ||
972 !config_lines_eq(options->AlternateDirAuthority,
973 old_options->AlternateDirAuthority);
975 if (!need_to_update)
976 return 0; /* all done */
978 /* Start from a clean slate. */
979 clear_dir_servers();
981 if (!options->DirAuthorities) {
982 /* then we may want some of the defaults */
983 dirinfo_type_t type = NO_DIRINFO;
984 if (!options->AlternateBridgeAuthority)
985 type |= BRIDGE_DIRINFO;
986 if (!options->AlternateDirAuthority)
987 type |= V3_DIRINFO | EXTRAINFO_DIRINFO | MICRODESC_DIRINFO;
988 add_default_trusted_dir_authorities(type);
990 if (!options->FallbackDir)
991 add_default_fallback_dir_servers();
993 for (cl = options->DirAuthorities; cl; cl = cl->next)
994 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
995 return -1;
996 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
997 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
998 return -1;
999 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1000 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1001 return -1;
1002 for (cl = options->FallbackDir; cl; cl = cl->next)
1003 if (parse_dir_fallback_line(cl->value, 0)<0)
1004 return -1;
1005 return 0;
1008 /** Fetch the active option list, and take actions based on it. All of the
1009 * things we do should survive being done repeatedly. If present,
1010 * <b>old_options</b> contains the previous value of the options.
1012 * Return 0 if all goes well, return -1 if things went badly.
1014 static int
1015 options_act_reversible(const or_options_t *old_options, char **msg)
1017 smartlist_t *new_listeners = smartlist_new();
1018 smartlist_t *replaced_listeners = smartlist_new();
1019 static int libevent_initialized = 0;
1020 or_options_t *options = get_options_mutable();
1021 int running_tor = options->command == CMD_RUN_TOR;
1022 int set_conn_limit = 0;
1023 int r = -1;
1024 int logs_marked = 0;
1025 int old_min_log_level = get_min_log_level();
1027 /* Daemonize _first_, since we only want to open most of this stuff in
1028 * the subprocess. Libevent bases can't be reliably inherited across
1029 * processes. */
1030 if (running_tor && options->RunAsDaemon) {
1031 /* No need to roll back, since you can't change the value. */
1032 start_daemon();
1035 #ifndef HAVE_SYS_UN_H
1036 if (options->ControlSocket || options->ControlSocketsGroupWritable) {
1037 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported "
1038 "on this OS/with this build.");
1039 goto rollback;
1041 #else
1042 if (options->ControlSocketsGroupWritable && !options->ControlSocket) {
1043 *msg = tor_strdup("Setting ControlSocketGroupWritable without setting"
1044 "a ControlSocket makes no sense.");
1045 goto rollback;
1047 #endif
1049 if (running_tor) {
1050 int n_ports=0;
1051 /* We need to set the connection limit before we can open the listeners. */
1052 if (! sandbox_is_active()) {
1053 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1054 &options->ConnLimit_) < 0) {
1055 *msg = tor_strdup("Problem with ConnLimit value. "
1056 "See logs for details.");
1057 goto rollback;
1059 set_conn_limit = 1;
1060 } else {
1061 tor_assert(old_options);
1062 options->ConnLimit_ = old_options->ConnLimit_;
1065 /* Set up libevent. (We need to do this before we can register the
1066 * listeners as listeners.) */
1067 if (running_tor && !libevent_initialized) {
1068 init_libevent(options);
1069 libevent_initialized = 1;
1072 /* Adjust the port configuration so we can launch listeners. */
1073 if (parse_ports(options, 0, msg, &n_ports)) {
1074 if (!*msg)
1075 *msg = tor_strdup("Unexpected problem parsing port config");
1076 goto rollback;
1079 /* Set the hibernation state appropriately.*/
1080 consider_hibernation(time(NULL));
1082 /* Launch the listeners. (We do this before we setuid, so we can bind to
1083 * ports under 1024.) We don't want to rebind if we're hibernating. If
1084 * networking is disabled, this will close all but the control listeners,
1085 * but disable those. */
1086 if (!we_are_hibernating()) {
1087 if (retry_all_listeners(replaced_listeners, new_listeners,
1088 options->DisableNetwork) < 0) {
1089 *msg = tor_strdup("Failed to bind one of the listener ports.");
1090 goto rollback;
1093 if (options->DisableNetwork) {
1094 /* Aggressively close non-controller stuff, NOW */
1095 log_notice(LD_NET, "DisableNetwork is set. Tor will not make or accept "
1096 "non-control network connections. Shutting down all existing "
1097 "connections.");
1098 connection_mark_all_noncontrol_connections();
1102 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1103 /* Open /dev/pf before dropping privileges. */
1104 if (options->TransPort_set &&
1105 options->TransProxyType_parsed == TPT_DEFAULT) {
1106 if (get_pf_socket() < 0) {
1107 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1108 goto rollback;
1111 #endif
1113 /* Attempt to lock all current and future memory with mlockall() only once */
1114 if (options->DisableAllSwap) {
1115 if (tor_mlockall() == -1) {
1116 *msg = tor_strdup("DisableAllSwap failure. Do you have proper "
1117 "permissions?");
1118 goto done;
1122 /* Setuid/setgid as appropriate */
1123 if (options->User) {
1124 if (switch_id(options->User) != 0) {
1125 /* No need to roll back, since you can't change the value. */
1126 *msg = tor_strdup("Problem with User value. See logs for details.");
1127 goto done;
1131 /* Ensure data directory is private; create if possible. */
1132 if (check_private_dir(options->DataDirectory,
1133 running_tor ? CPD_CREATE : CPD_CHECK,
1134 options->User)<0) {
1135 tor_asprintf(msg,
1136 "Couldn't access/create private data directory \"%s\"",
1137 options->DataDirectory);
1138 goto done;
1139 /* No need to roll back, since you can't change the value. */
1142 /* Bail out at this point if we're not going to be a client or server:
1143 * we don't run Tor itself. */
1144 if (!running_tor)
1145 goto commit;
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;
1154 commit:
1155 r = 0;
1156 if (logs_marked) {
1157 log_severity_list_t *severity =
1158 tor_malloc_zero(sizeof(log_severity_list_t));
1159 close_temp_logs();
1160 add_callback_log(severity, control_event_logmsg);
1161 control_adjust_event_log_severity();
1162 tor_free(severity);
1163 tor_log_update_sigsafe_err_fds();
1167 const char *badness = NULL;
1168 int bad_safelog = 0, bad_severity = 0, new_badness = 0;
1169 if (options->SafeLogging_ != SAFELOG_SCRUB_ALL) {
1170 bad_safelog = 1;
1171 if (!old_options || old_options->SafeLogging_ != options->SafeLogging_)
1172 new_badness = 1;
1174 if (get_min_log_level() >= LOG_INFO) {
1175 bad_severity = 1;
1176 if (get_min_log_level() != old_min_log_level)
1177 new_badness = 1;
1179 if (bad_safelog && bad_severity)
1180 badness = "you disabled SafeLogging, and "
1181 "you're logging more than \"notice\"";
1182 else if (bad_safelog)
1183 badness = "you disabled SafeLogging";
1184 else
1185 badness = "you're logging more than \"notice\"";
1186 if (new_badness)
1187 log_warn(LD_GENERAL, "Your log may contain sensitive information - %s. "
1188 "Don't log unless it serves an important reason. "
1189 "Overwrite the log afterwards.", badness);
1192 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1194 int marked = conn->marked_for_close;
1195 log_notice(LD_NET, "Closing old %s on %s:%d",
1196 conn_type_to_string(conn->type), conn->address, conn->port);
1197 connection_close_immediate(conn);
1198 if (!marked) {
1199 connection_mark_for_close(conn);
1202 goto done;
1204 rollback:
1205 r = -1;
1206 tor_assert(*msg);
1208 if (logs_marked) {
1209 rollback_log_changes();
1210 control_adjust_event_log_severity();
1213 if (set_conn_limit && old_options)
1214 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1215 &options->ConnLimit_);
1217 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1219 log_notice(LD_NET, "Closing partially-constructed %s on %s:%d",
1220 conn_type_to_string(conn->type), conn->address, conn->port);
1221 connection_close_immediate(conn);
1222 connection_mark_for_close(conn);
1225 done:
1226 smartlist_free(new_listeners);
1227 smartlist_free(replaced_listeners);
1228 return r;
1231 /** If we need to have a GEOIP ip-to-country map to run with our configured
1232 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1234 options_need_geoip_info(const or_options_t *options, const char **reason_out)
1236 int bridge_usage =
1237 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1238 int routerset_usage =
1239 routerset_needs_geoip(options->EntryNodes) ||
1240 routerset_needs_geoip(options->ExitNodes) ||
1241 routerset_needs_geoip(options->ExcludeExitNodes) ||
1242 routerset_needs_geoip(options->ExcludeNodes);
1244 if (routerset_usage && reason_out) {
1245 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1246 "countries, and we need GEOIP information to figure out which ones they "
1247 "are.";
1248 } else if (bridge_usage && reason_out) {
1249 *reason_out = "We've been configured to see which countries can access "
1250 "us as a bridge, and we need GEOIP information to tell which countries "
1251 "clients are in.";
1253 return bridge_usage || routerset_usage;
1256 /** Return the bandwidthrate that we are going to report to the authorities
1257 * based on the config options. */
1258 uint32_t
1259 get_effective_bwrate(const or_options_t *options)
1261 uint64_t bw = options->BandwidthRate;
1262 if (bw > options->MaxAdvertisedBandwidth)
1263 bw = options->MaxAdvertisedBandwidth;
1264 if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1265 bw = options->RelayBandwidthRate;
1266 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1267 return (uint32_t)bw;
1270 /** Return the bandwidthburst that we are going to report to the authorities
1271 * based on the config options. */
1272 uint32_t
1273 get_effective_bwburst(const or_options_t *options)
1275 uint64_t bw = options->BandwidthBurst;
1276 if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1277 bw = options->RelayBandwidthBurst;
1278 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1279 return (uint32_t)bw;
1282 /** Return True if any changes from <b>old_options</b> to
1283 * <b>new_options</b> needs us to refresh our TLS context. */
1284 static int
1285 options_transition_requires_fresh_tls_context(const or_options_t *old_options,
1286 const or_options_t *new_options)
1288 tor_assert(new_options);
1290 if (!old_options)
1291 return 0;
1293 if ((old_options->DynamicDHGroups != new_options->DynamicDHGroups)) {
1294 return 1;
1297 if (!opt_streq(old_options->TLSECGroup, new_options->TLSECGroup))
1298 return 1;
1300 return 0;
1303 /** Fetch the active option list, and take actions based on it. All of the
1304 * things we do should survive being done repeatedly. If present,
1305 * <b>old_options</b> contains the previous value of the options.
1307 * Return 0 if all goes well, return -1 if it's time to die.
1309 * Note: We haven't moved all the "act on new configuration" logic
1310 * here yet. Some is still in do_hup() and other places.
1312 static int
1313 options_act(const or_options_t *old_options)
1315 config_line_t *cl;
1316 or_options_t *options = get_options_mutable();
1317 int running_tor = options->command == CMD_RUN_TOR;
1318 char *msg=NULL;
1319 const int transition_affects_workers =
1320 old_options && options_transition_affects_workers(old_options, options);
1321 int old_ewma_enabled;
1323 /* disable ptrace and later, other basic debugging techniques */
1325 /* Remember if we already disabled debugger attachment */
1326 static int disabled_debugger_attach = 0;
1327 /* Remember if we already warned about being configured not to disable
1328 * debugger attachment */
1329 static int warned_debugger_attach = 0;
1330 /* Don't disable debugger attachment when we're running the unit tests. */
1331 if (options->DisableDebuggerAttachment && !disabled_debugger_attach &&
1332 running_tor) {
1333 int ok = tor_disable_debugger_attach();
1334 if (warned_debugger_attach && ok == 1) {
1335 log_notice(LD_CONFIG, "Disabled attaching debuggers for unprivileged "
1336 "users.");
1338 disabled_debugger_attach = (ok == 1);
1339 } else if (!options->DisableDebuggerAttachment &&
1340 !warned_debugger_attach) {
1341 log_notice(LD_CONFIG, "Not disabling debugger attaching for "
1342 "unprivileged users.");
1343 warned_debugger_attach = 1;
1347 /* Write control ports to disk as appropriate */
1348 control_ports_write_to_file();
1350 if (running_tor && !have_lockfile()) {
1351 if (try_locking(options, 1) < 0)
1352 return -1;
1355 if (consider_adding_dir_servers(options, old_options) < 0)
1356 return -1;
1358 #ifdef NON_ANONYMOUS_MODE_ENABLED
1359 log_warn(LD_GENERAL, "This copy of Tor was compiled to run in a "
1360 "non-anonymous mode. It will provide NO ANONYMITY.");
1361 #endif
1363 #ifdef ENABLE_TOR2WEB_MODE
1364 if (!options->Tor2webMode) {
1365 log_err(LD_CONFIG, "This copy of Tor was compiled to run in "
1366 "'tor2web mode'. It can only be run with the Tor2webMode torrc "
1367 "option enabled.");
1368 return -1;
1370 #else
1371 if (options->Tor2webMode) {
1372 log_err(LD_CONFIG, "This copy of Tor was not compiled to run in "
1373 "'tor2web mode'. It cannot be run with the Tor2webMode torrc "
1374 "option enabled. To enable Tor2webMode recompile with the "
1375 "--enable-tor2webmode option.");
1376 return -1;
1378 #endif
1380 /* If we are a bridge with a pluggable transport proxy but no
1381 Extended ORPort, inform the user that she is missing out. */
1382 if (server_mode(options) && options->ServerTransportPlugin &&
1383 !options->ExtORPort_lines) {
1384 log_notice(LD_CONFIG, "We use pluggable transports but the Extended "
1385 "ORPort is disabled. Tor and your pluggable transports proxy "
1386 "communicate with each other via the Extended ORPort so it "
1387 "is suggested you enable it: it will also allow your Bridge "
1388 "to collect statistics about its clients that use pluggable "
1389 "transports. Please enable it using the ExtORPort torrc option "
1390 "(e.g. set 'ExtORPort auto').");
1393 if (options->Bridges) {
1394 mark_bridge_list();
1395 for (cl = options->Bridges; cl; cl = cl->next) {
1396 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
1397 if (!bridge_line) {
1398 log_warn(LD_BUG,
1399 "Previously validated Bridge line could not be added!");
1400 return -1;
1402 bridge_add_from_config(bridge_line);
1404 sweep_bridge_list();
1407 if (running_tor && rend_config_services(options, 0)<0) {
1408 log_warn(LD_BUG,
1409 "Previously validated hidden services line could not be added!");
1410 return -1;
1413 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1414 log_warn(LD_BUG, "Previously validated client authorization for "
1415 "hidden services could not be added!");
1416 return -1;
1419 /* Load state */
1420 if (! or_state_loaded() && running_tor) {
1421 if (or_state_load())
1422 return -1;
1423 rep_hist_load_mtbf_data(time(NULL));
1426 mark_transport_list();
1427 pt_prepare_proxy_list_for_config_read();
1428 if (options->ClientTransportPlugin) {
1429 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
1430 if (parse_client_transport_line(options, cl->value, 0)<0) {
1431 log_warn(LD_BUG,
1432 "Previously validated ClientTransportPlugin line "
1433 "could not be added!");
1434 return -1;
1439 if (options->ServerTransportPlugin && server_mode(options)) {
1440 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
1441 if (parse_server_transport_line(options, cl->value, 0)<0) {
1442 log_warn(LD_BUG,
1443 "Previously validated ServerTransportPlugin line "
1444 "could not be added!");
1445 return -1;
1449 sweep_transport_list();
1450 sweep_proxy_list();
1452 /* Start the PT proxy configuration. By doing this configuration
1453 here, we also figure out which proxies need to be restarted and
1454 which not. */
1455 if (pt_proxies_configuration_pending() && !net_is_disabled())
1456 pt_configure_remaining_proxies();
1458 /* Bail out at this point if we're not going to be a client or server:
1459 * we want to not fork, and to log stuff to stderr. */
1460 if (!running_tor)
1461 return 0;
1463 /* Finish backgrounding the process */
1464 if (options->RunAsDaemon) {
1465 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1466 finish_daemon(options->DataDirectory);
1469 /* If needed, generate a new TLS DH prime according to the current torrc. */
1470 if (server_mode(options) && options->DynamicDHGroups) {
1471 char *keydir = get_datadir_fname("keys");
1472 if (check_private_dir(keydir, CPD_CREATE, options->User)) {
1473 tor_free(keydir);
1474 return -1;
1476 tor_free(keydir);
1478 if (!old_options || !old_options->DynamicDHGroups) {
1479 char *fname = get_datadir_fname2("keys", "dynamic_dh_params");
1480 crypto_set_tls_dh_prime(fname);
1481 tor_free(fname);
1483 } else { /* clients don't need a dynamic DH prime. */
1484 crypto_set_tls_dh_prime(NULL);
1487 /* We want to reinit keys as needed before we do much of anything else:
1488 keys are important, and other things can depend on them. */
1489 if (transition_affects_workers ||
1490 (options->V3AuthoritativeDir && (!old_options ||
1491 !old_options->V3AuthoritativeDir))) {
1492 if (init_keys() < 0) {
1493 log_warn(LD_BUG,"Error initializing keys; exiting");
1494 return -1;
1496 } else if (old_options &&
1497 options_transition_requires_fresh_tls_context(old_options,
1498 options)) {
1499 if (router_initialize_tls_context() < 0) {
1500 log_warn(LD_BUG,"Error initializing TLS context.");
1501 return -1;
1505 /* Write our PID to the PID file. If we do not have write permissions we
1506 * will log a warning */
1507 if (options->PidFile && !sandbox_is_active()) {
1508 write_pidfile(options->PidFile);
1511 /* Register addressmap directives */
1512 config_register_addressmaps(options);
1513 parse_virtual_addr_network(options->VirtualAddrNetworkIPv4, AF_INET,0,NULL);
1514 parse_virtual_addr_network(options->VirtualAddrNetworkIPv6, AF_INET6,0,NULL);
1516 /* Update address policies. */
1517 if (policies_parse_from_options(options) < 0) {
1518 /* This should be impossible, but let's be sure. */
1519 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1520 return -1;
1523 if (init_control_cookie_authentication(options->CookieAuthentication) < 0) {
1524 log_warn(LD_CONFIG,"Error creating control cookie authentication file.");
1525 return -1;
1528 /* If we have an ExtORPort, initialize its auth cookie. */
1529 if (init_ext_or_cookie_authentication(!!options->ExtORPort_lines) < 0) {
1530 log_warn(LD_CONFIG,"Error creating Extended ORPort cookie file.");
1531 return -1;
1534 monitor_owning_controller_process(options->OwningControllerProcess);
1536 /* reload keys as needed for rendezvous services. */
1537 if (rend_service_load_all_keys()<0) {
1538 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1539 return -1;
1542 /* Set up accounting */
1543 if (accounting_parse_options(options, 0)<0) {
1544 log_warn(LD_CONFIG,"Error in accounting options");
1545 return -1;
1547 if (accounting_is_enabled(options))
1548 configure_accounting(time(NULL));
1550 #ifdef USE_BUFFEREVENTS
1551 /* If we're using the bufferevents implementation and our rate limits
1552 * changed, we need to tell the rate-limiting system about it. */
1553 if (!old_options ||
1554 old_options->BandwidthRate != options->BandwidthRate ||
1555 old_options->BandwidthBurst != options->BandwidthBurst ||
1556 old_options->RelayBandwidthRate != options->RelayBandwidthRate ||
1557 old_options->RelayBandwidthBurst != options->RelayBandwidthBurst)
1558 connection_bucket_init();
1559 #endif
1561 old_ewma_enabled = cell_ewma_enabled();
1562 /* Change the cell EWMA settings */
1563 cell_ewma_set_scale_factor(options, networkstatus_get_latest_consensus());
1564 /* If we just enabled ewma, set the cmux policy on all active channels */
1565 if (cell_ewma_enabled() && !old_ewma_enabled) {
1566 channel_set_cmux_policy_everywhere(&ewma_policy);
1567 } else if (!cell_ewma_enabled() && old_ewma_enabled) {
1568 /* Turn it off everywhere */
1569 channel_set_cmux_policy_everywhere(NULL);
1572 /* Update the BridgePassword's hashed version as needed. We store this as a
1573 * digest so that we can do side-channel-proof comparisons on it.
1575 if (options->BridgePassword) {
1576 char *http_authenticator;
1577 http_authenticator = alloc_http_authenticator(options->BridgePassword);
1578 if (!http_authenticator) {
1579 log_warn(LD_BUG, "Unable to allocate HTTP authenticator. Not setting "
1580 "BridgePassword.");
1581 return -1;
1583 options->BridgePassword_AuthDigest_ = tor_malloc(DIGEST256_LEN);
1584 crypto_digest256(options->BridgePassword_AuthDigest_,
1585 http_authenticator, strlen(http_authenticator),
1586 DIGEST_SHA256);
1587 tor_free(http_authenticator);
1590 if (parse_outbound_addresses(options, 0, &msg) < 0) {
1591 log_warn(LD_BUG, "Failed parsing oubound bind addresses: %s", msg);
1592 tor_free(msg);
1593 return -1;
1596 /* Check for transitions that need action. */
1597 if (old_options) {
1598 int revise_trackexithosts = 0;
1599 int revise_automap_entries = 0;
1600 if ((options->UseEntryGuards && !old_options->UseEntryGuards) ||
1601 options->UseBridges != old_options->UseBridges ||
1602 (options->UseBridges &&
1603 !config_lines_eq(options->Bridges, old_options->Bridges)) ||
1604 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes) ||
1605 !routerset_equal(old_options->ExcludeExitNodes,
1606 options->ExcludeExitNodes) ||
1607 !routerset_equal(old_options->EntryNodes, options->EntryNodes) ||
1608 !routerset_equal(old_options->ExitNodes, options->ExitNodes) ||
1609 options->StrictNodes != old_options->StrictNodes) {
1610 log_info(LD_CIRC,
1611 "Changed to using entry guards or bridges, or changed "
1612 "preferred or excluded node lists. "
1613 "Abandoning previous circuits.");
1614 circuit_mark_all_unused_circs();
1615 circuit_mark_all_dirty_circs_as_unusable();
1616 revise_trackexithosts = 1;
1619 if (!smartlist_strings_eq(old_options->TrackHostExits,
1620 options->TrackHostExits))
1621 revise_trackexithosts = 1;
1623 if (revise_trackexithosts)
1624 addressmap_clear_excluded_trackexithosts(options);
1626 if (!options->AutomapHostsOnResolve) {
1627 if (old_options->AutomapHostsOnResolve)
1628 revise_automap_entries = 1;
1629 } else {
1630 if (!smartlist_strings_eq(old_options->AutomapHostsSuffixes,
1631 options->AutomapHostsSuffixes))
1632 revise_automap_entries = 1;
1633 else if (!opt_streq(old_options->VirtualAddrNetworkIPv4,
1634 options->VirtualAddrNetworkIPv4) ||
1635 !opt_streq(old_options->VirtualAddrNetworkIPv6,
1636 options->VirtualAddrNetworkIPv6))
1637 revise_automap_entries = 1;
1640 if (revise_automap_entries)
1641 addressmap_clear_invalid_automaps(options);
1643 /* How long should we delay counting bridge stats after becoming a bridge?
1644 * We use this so we don't count people who used our bridge thinking it is
1645 * a relay. If you change this, don't forget to change the log message
1646 * below. It's 4 hours (the time it takes to stop being used by clients)
1647 * plus some extra time for clock skew. */
1648 #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
1650 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
1651 int was_relay = 0;
1652 if (options->BridgeRelay) {
1653 time_t int_start = time(NULL);
1654 if (config_lines_eq(old_options->ORPort_lines,options->ORPort_lines)) {
1655 int_start += RELAY_BRIDGE_STATS_DELAY;
1656 was_relay = 1;
1658 geoip_bridge_stats_init(int_start);
1659 log_info(LD_CONFIG, "We are acting as a bridge now. Starting new "
1660 "GeoIP stats interval%s.", was_relay ? " in 6 "
1661 "hours from now" : "");
1662 } else {
1663 geoip_bridge_stats_term();
1664 log_info(LD_GENERAL, "We are no longer acting as a bridge. "
1665 "Forgetting GeoIP stats.");
1669 if (transition_affects_workers) {
1670 log_info(LD_GENERAL,
1671 "Worker-related options changed. Rotating workers.");
1673 if (server_mode(options) && !server_mode(old_options)) {
1674 ip_address_changed(0);
1675 if (can_complete_circuit || !any_predicted_circuits(time(NULL)))
1676 inform_testing_reachability();
1678 cpuworkers_rotate();
1679 if (dns_reset())
1680 return -1;
1681 } else {
1682 if (dns_reset())
1683 return -1;
1686 if (options->PerConnBWRate != old_options->PerConnBWRate ||
1687 options->PerConnBWBurst != old_options->PerConnBWBurst)
1688 connection_or_update_token_buckets(get_connection_array(), options);
1691 config_maybe_load_geoip_files_(options, old_options);
1693 if (geoip_is_loaded(AF_INET) && options->GeoIPExcludeUnknown) {
1694 /* ExcludeUnknown is true or "auto" */
1695 const int is_auto = options->GeoIPExcludeUnknown == -1;
1696 int changed;
1698 changed = routerset_add_unknown_ccs(&options->ExcludeNodes, is_auto);
1699 changed += routerset_add_unknown_ccs(&options->ExcludeExitNodes, is_auto);
1701 if (changed)
1702 routerset_add_unknown_ccs(&options->ExcludeExitNodesUnion_, is_auto);
1705 if (options->CellStatistics || options->DirReqStatistics ||
1706 options->EntryStatistics || options->ExitPortStatistics ||
1707 options->ConnDirectionStatistics ||
1708 options->BridgeAuthoritativeDir) {
1709 time_t now = time(NULL);
1710 int print_notice = 0;
1712 /* Only collect directory-request statistics on relays and bridges. */
1713 if (!server_mode(options)) {
1714 options->DirReqStatistics = 0;
1717 /* Only collect other relay-only statistics on relays. */
1718 if (!public_server_mode(options)) {
1719 options->CellStatistics = 0;
1720 options->EntryStatistics = 0;
1721 options->ExitPortStatistics = 0;
1724 if ((!old_options || !old_options->CellStatistics) &&
1725 options->CellStatistics) {
1726 rep_hist_buffer_stats_init(now);
1727 print_notice = 1;
1729 if ((!old_options || !old_options->DirReqStatistics) &&
1730 options->DirReqStatistics) {
1731 if (geoip_is_loaded(AF_INET)) {
1732 geoip_dirreq_stats_init(now);
1733 print_notice = 1;
1734 } else {
1735 options->DirReqStatistics = 0;
1736 /* Don't warn Tor clients, they don't use statistics */
1737 if (options->ORPort_set)
1738 log_notice(LD_CONFIG, "Configured to measure directory request "
1739 "statistics, but no GeoIP database found. "
1740 "Please specify a GeoIP database using the "
1741 "GeoIPFile option.");
1744 if ((!old_options || !old_options->EntryStatistics) &&
1745 options->EntryStatistics && !should_record_bridge_info(options)) {
1746 if (geoip_is_loaded(AF_INET) || geoip_is_loaded(AF_INET6)) {
1747 geoip_entry_stats_init(now);
1748 print_notice = 1;
1749 } else {
1750 options->EntryStatistics = 0;
1751 log_notice(LD_CONFIG, "Configured to measure entry node "
1752 "statistics, but no GeoIP database found. "
1753 "Please specify a GeoIP database using the "
1754 "GeoIPFile option.");
1757 if ((!old_options || !old_options->ExitPortStatistics) &&
1758 options->ExitPortStatistics) {
1759 rep_hist_exit_stats_init(now);
1760 print_notice = 1;
1762 if ((!old_options || !old_options->ConnDirectionStatistics) &&
1763 options->ConnDirectionStatistics) {
1764 rep_hist_conn_stats_init(now);
1766 if ((!old_options || !old_options->BridgeAuthoritativeDir) &&
1767 options->BridgeAuthoritativeDir) {
1768 rep_hist_desc_stats_init(now);
1769 print_notice = 1;
1771 if (print_notice)
1772 log_notice(LD_CONFIG, "Configured to measure statistics. Look for "
1773 "the *-stats files that will first be written to the "
1774 "data directory in 24 hours from now.");
1777 if (old_options && old_options->CellStatistics &&
1778 !options->CellStatistics)
1779 rep_hist_buffer_stats_term();
1780 if (old_options && old_options->DirReqStatistics &&
1781 !options->DirReqStatistics)
1782 geoip_dirreq_stats_term();
1783 if (old_options && old_options->EntryStatistics &&
1784 !options->EntryStatistics)
1785 geoip_entry_stats_term();
1786 if (old_options && old_options->ExitPortStatistics &&
1787 !options->ExitPortStatistics)
1788 rep_hist_exit_stats_term();
1789 if (old_options && old_options->ConnDirectionStatistics &&
1790 !options->ConnDirectionStatistics)
1791 rep_hist_conn_stats_term();
1792 if (old_options && old_options->BridgeAuthoritativeDir &&
1793 !options->BridgeAuthoritativeDir)
1794 rep_hist_desc_stats_term();
1796 /* Check if we need to parse and add the EntryNodes config option. */
1797 if (options->EntryNodes &&
1798 (!old_options ||
1799 !routerset_equal(old_options->EntryNodes,options->EntryNodes) ||
1800 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes)))
1801 entry_nodes_should_be_added();
1803 /* Since our options changed, we might need to regenerate and upload our
1804 * server descriptor.
1806 if (!old_options ||
1807 options_transition_affects_descriptor(old_options, options))
1808 mark_my_descriptor_dirty("config change");
1810 /* We may need to reschedule some directory stuff if our status changed. */
1811 if (old_options) {
1812 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1813 dirvote_recalculate_timing(options, time(NULL));
1814 if (!bool_eq(directory_fetches_dir_info_early(options),
1815 directory_fetches_dir_info_early(old_options)) ||
1816 !bool_eq(directory_fetches_dir_info_later(options),
1817 directory_fetches_dir_info_later(old_options))) {
1818 /* Make sure update_router_have_min_dir_info gets called. */
1819 router_dir_info_changed();
1820 /* We might need to download a new consensus status later or sooner than
1821 * we had expected. */
1822 update_consensus_networkstatus_fetch_time(time(NULL));
1826 /* Load the webpage we're going to serve every time someone asks for '/' on
1827 our DirPort. */
1828 tor_free(global_dirfrontpagecontents);
1829 if (options->DirPortFrontPage) {
1830 global_dirfrontpagecontents =
1831 read_file_to_str(options->DirPortFrontPage, 0, NULL);
1832 if (!global_dirfrontpagecontents) {
1833 log_warn(LD_CONFIG,
1834 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1835 options->DirPortFrontPage);
1839 return 0;
1842 static const struct {
1843 const char *name;
1844 int takes_argument;
1845 } CMDLINE_ONLY_OPTIONS[] = {
1846 { "-f", 1 },
1847 { "--allow-missing-torrc", 0 },
1848 { "--defaults-torrc", 1 },
1849 { "--hash-password", 1 },
1850 { "--dump-config", 1 },
1851 { "--list-fingerprint", 0 },
1852 { "--verify-config", 0 },
1853 { "--ignore-missing-torrc", 0 },
1854 { "--quiet", 0 },
1855 { "--hush", 0 },
1856 { "--version", 0 },
1857 { "--library-versions", 0 },
1858 { "-h", 0 },
1859 { "--help", 0 },
1860 { "--list-torrc-options", 0 },
1861 { "--digests", 0 },
1862 { "--nt-service", 0 },
1863 { "-nt-service", 0 },
1864 { NULL, 0 },
1867 /** Helper: Read a list of configuration options from the command line. If
1868 * successful, or if ignore_errors is set, put them in *<b>result</b>, put the
1869 * commandline-only options in *<b>cmdline_result</b>, and return 0;
1870 * otherwise, return -1 and leave *<b>result</b> and <b>cmdline_result</b>
1871 * alone. */
1873 config_parse_commandline(int argc, char **argv, int ignore_errors,
1874 config_line_t **result,
1875 config_line_t **cmdline_result)
1877 config_line_t *param = NULL;
1879 config_line_t *front = NULL;
1880 config_line_t **new = &front;
1882 config_line_t *front_cmdline = NULL;
1883 config_line_t **new_cmdline = &front_cmdline;
1885 char *s, *arg;
1886 int i = 1;
1888 while (i < argc) {
1889 unsigned command = CONFIG_LINE_NORMAL;
1890 int want_arg = 1;
1891 int is_cmdline = 0;
1892 int j;
1894 for (j = 0; CMDLINE_ONLY_OPTIONS[j].name != NULL; ++j) {
1895 if (!strcmp(argv[i], CMDLINE_ONLY_OPTIONS[j].name)) {
1896 is_cmdline = 1;
1897 want_arg = CMDLINE_ONLY_OPTIONS[j].takes_argument;
1898 break;
1902 s = argv[i];
1904 /* Each keyword may be prefixed with one or two dashes. */
1905 if (*s == '-')
1906 s++;
1907 if (*s == '-')
1908 s++;
1909 /* Figure out the command, if any. */
1910 if (*s == '+') {
1911 s++;
1912 command = CONFIG_LINE_APPEND;
1913 } else if (*s == '/') {
1914 s++;
1915 command = CONFIG_LINE_CLEAR;
1916 /* A 'clear' command has no argument. */
1917 want_arg = 0;
1920 if (want_arg && i == argc-1) {
1921 if (ignore_errors) {
1922 arg = strdup("");
1923 } else {
1924 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1925 argv[i]);
1926 config_free_lines(front);
1927 config_free_lines(front_cmdline);
1928 return -1;
1930 } else {
1931 arg = want_arg ? tor_strdup(argv[i+1]) : strdup("");
1934 param = tor_malloc_zero(sizeof(config_line_t));
1935 param->key = is_cmdline ? tor_strdup(argv[i]) :
1936 tor_strdup(config_expand_abbrev(&options_format, s, 1, 1));
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 if (server_mode(options) && options->RendConfigLines)
2568 log_warn(LD_CONFIG,
2569 "Tor is currently configured as a relay and a hidden service. "
2570 "That's not very secure: you should probably run your hidden service "
2571 "in a separate Tor process, at least -- see "
2572 "https://trac.torproject.org/8742");
2574 /* XXXX require that the only port not be DirPort? */
2575 /* XXXX require that at least one port be listened-upon. */
2576 if (n_ports == 0 && !options->RendConfigLines)
2577 log_warn(LD_CONFIG,
2578 "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
2579 "undefined, and there aren't any hidden services configured. "
2580 "Tor will still run, but probably won't do anything.");
2582 options->TransProxyType_parsed = TPT_DEFAULT;
2583 #ifdef USE_TRANSPARENT
2584 if (options->TransProxyType) {
2585 if (!strcasecmp(options->TransProxyType, "default")) {
2586 options->TransProxyType_parsed = TPT_DEFAULT;
2587 } else if (!strcasecmp(options->TransProxyType, "pf-divert")) {
2588 #ifndef __OpenBSD__
2589 REJECT("pf-divert is a OpenBSD-specific feature.");
2590 #else
2591 options->TransProxyType_parsed = TPT_PF_DIVERT;
2592 #endif
2593 } else if (!strcasecmp(options->TransProxyType, "tproxy")) {
2594 #ifndef __linux__
2595 REJECT("TPROXY is a Linux-specific feature.");
2596 #else
2597 options->TransProxyType_parsed = TPT_TPROXY;
2598 #endif
2599 } else if (!strcasecmp(options->TransProxyType, "ipfw")) {
2600 #ifndef __FreeBSD__
2601 REJECT("ipfw is a FreeBSD-specific feature.");
2602 #else
2603 options->TransProxyType_parsed = TPT_IPFW;
2604 #endif
2605 } else {
2606 REJECT("Unrecognized value for TransProxyType");
2609 if (strcasecmp(options->TransProxyType, "default") &&
2610 !options->TransPort_set) {
2611 REJECT("Cannot use TransProxyType without any valid TransPort or "
2612 "TransListenAddress.");
2615 #else
2616 if (options->TransPort_set)
2617 REJECT("TransPort and TransListenAddress are disabled "
2618 "in this build.");
2619 #endif
2621 if (options->TokenBucketRefillInterval <= 0
2622 || options->TokenBucketRefillInterval > 1000) {
2623 REJECT("TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
2626 if (options->ExcludeExitNodes || options->ExcludeNodes) {
2627 options->ExcludeExitNodesUnion_ = routerset_new();
2628 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeExitNodes);
2629 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeNodes);
2632 if (options->NodeFamilies) {
2633 options->NodeFamilySets = smartlist_new();
2634 for (cl = options->NodeFamilies; cl; cl = cl->next) {
2635 routerset_t *rs = routerset_new();
2636 if (routerset_parse(rs, cl->value, cl->key) == 0) {
2637 smartlist_add(options->NodeFamilySets, rs);
2638 } else {
2639 routerset_free(rs);
2644 if (options->TLSECGroup && (strcasecmp(options->TLSECGroup, "P256") &&
2645 strcasecmp(options->TLSECGroup, "P224"))) {
2646 COMPLAIN("Unrecognized TLSECGroup: Falling back to the default.");
2647 tor_free(options->TLSECGroup);
2650 if (options->ExcludeNodes && options->StrictNodes) {
2651 COMPLAIN("You have asked to exclude certain relays from all positions "
2652 "in your circuits. Expect hidden services and other Tor "
2653 "features to be broken in unpredictable ways.");
2656 if (options->AuthoritativeDir) {
2657 if (!options->ContactInfo && !options->TestingTorNetwork)
2658 REJECT("Authoritative directory servers must set ContactInfo");
2659 if (!options->RecommendedClientVersions)
2660 options->RecommendedClientVersions =
2661 config_lines_dup(options->RecommendedVersions);
2662 if (!options->RecommendedServerVersions)
2663 options->RecommendedServerVersions =
2664 config_lines_dup(options->RecommendedVersions);
2665 if (options->VersioningAuthoritativeDir &&
2666 (!options->RecommendedClientVersions ||
2667 !options->RecommendedServerVersions))
2668 REJECT("Versioning authoritative dir servers must set "
2669 "Recommended*Versions.");
2670 if (options->UseEntryGuards) {
2671 log_info(LD_CONFIG, "Authoritative directory servers can't set "
2672 "UseEntryGuards. Disabling.");
2673 options->UseEntryGuards = 0;
2675 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
2676 log_info(LD_CONFIG, "Authoritative directories always try to download "
2677 "extra-info documents. Setting DownloadExtraInfo.");
2678 options->DownloadExtraInfo = 1;
2680 if (!(options->BridgeAuthoritativeDir ||
2681 options->V3AuthoritativeDir))
2682 REJECT("AuthoritativeDir is set, but none of "
2683 "(Bridge/V3)AuthoritativeDir is set.");
2684 /* If we have a v3bandwidthsfile and it's broken, complain on startup */
2685 if (options->V3BandwidthsFile && !old_options) {
2686 dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
2690 if (options->AuthoritativeDir && !options->DirPort_set)
2691 REJECT("Running as authoritative directory, but no DirPort set.");
2693 if (options->AuthoritativeDir && !options->ORPort_set)
2694 REJECT("Running as authoritative directory, but no ORPort set.");
2696 if (options->AuthoritativeDir && options->ClientOnly)
2697 REJECT("Running as authoritative directory, but ClientOnly also set.");
2699 if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
2700 REJECT("FetchDirInfoExtraEarly requires that you also set "
2701 "FetchDirInfoEarly");
2703 if (options->ConnLimit <= 0) {
2704 tor_asprintf(msg,
2705 "ConnLimit must be greater than 0, but was set to %d",
2706 options->ConnLimit);
2707 return -1;
2710 if (options->PathsNeededToBuildCircuits >= 0.0) {
2711 if (options->PathsNeededToBuildCircuits < 0.25) {
2712 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too low. Increasing "
2713 "to 0.25");
2714 options->PathsNeededToBuildCircuits = 0.25;
2715 } else if (options->PathsNeededToBuildCircuits > 0.95) {
2716 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too high. Decreasing "
2717 "to 0.95");
2718 options->PathsNeededToBuildCircuits = 0.95;
2722 if (options->MaxClientCircuitsPending <= 0 ||
2723 options->MaxClientCircuitsPending > MAX_MAX_CLIENT_CIRCUITS_PENDING) {
2724 tor_asprintf(msg,
2725 "MaxClientCircuitsPending must be between 1 and %d, but "
2726 "was set to %d", MAX_MAX_CLIENT_CIRCUITS_PENDING,
2727 options->MaxClientCircuitsPending);
2728 return -1;
2731 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
2732 return -1;
2734 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
2735 return -1;
2737 if (validate_ports_csv(options->RejectPlaintextPorts,
2738 "RejectPlaintextPorts", msg) < 0)
2739 return -1;
2741 if (validate_ports_csv(options->WarnPlaintextPorts,
2742 "WarnPlaintextPorts", msg) < 0)
2743 return -1;
2745 if (options->FascistFirewall && !options->ReachableAddresses) {
2746 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
2747 /* We already have firewall ports set, so migrate them to
2748 * ReachableAddresses, which will set ReachableORAddresses and
2749 * ReachableDirAddresses if they aren't set explicitly. */
2750 smartlist_t *instead = smartlist_new();
2751 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
2752 new_line->key = tor_strdup("ReachableAddresses");
2753 /* If we're configured with the old format, we need to prepend some
2754 * open ports. */
2755 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
2757 int p = atoi(portno);
2758 if (p<0) continue;
2759 smartlist_add_asprintf(instead, "*:%d", p);
2761 new_line->value = smartlist_join_strings(instead,",",0,NULL);
2762 /* These have been deprecated since 0.1.1.5-alpha-cvs */
2763 log_notice(LD_CONFIG,
2764 "Converting FascistFirewall and FirewallPorts "
2765 "config options to new format: \"ReachableAddresses %s\"",
2766 new_line->value);
2767 options->ReachableAddresses = new_line;
2768 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
2769 smartlist_free(instead);
2770 } else {
2771 /* We do not have FirewallPorts set, so add 80 to
2772 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
2773 if (!options->ReachableDirAddresses) {
2774 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
2775 new_line->key = tor_strdup("ReachableDirAddresses");
2776 new_line->value = tor_strdup("*:80");
2777 options->ReachableDirAddresses = new_line;
2778 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
2779 "to new format: \"ReachableDirAddresses *:80\"");
2781 if (!options->ReachableORAddresses) {
2782 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
2783 new_line->key = tor_strdup("ReachableORAddresses");
2784 new_line->value = tor_strdup("*:443");
2785 options->ReachableORAddresses = new_line;
2786 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
2787 "to new format: \"ReachableORAddresses *:443\"");
2792 for (i=0; i<3; i++) {
2793 config_line_t **linep =
2794 (i==0) ? &options->ReachableAddresses :
2795 (i==1) ? &options->ReachableORAddresses :
2796 &options->ReachableDirAddresses;
2797 if (!*linep)
2798 continue;
2799 /* We need to end with a reject *:*, not an implicit accept *:* */
2800 for (;;) {
2801 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
2802 break;
2803 linep = &((*linep)->next);
2804 if (!*linep) {
2805 *linep = tor_malloc_zero(sizeof(config_line_t));
2806 (*linep)->key = tor_strdup(
2807 (i==0) ? "ReachableAddresses" :
2808 (i==1) ? "ReachableORAddresses" :
2809 "ReachableDirAddresses");
2810 (*linep)->value = tor_strdup("reject *:*");
2811 break;
2816 if ((options->ReachableAddresses ||
2817 options->ReachableORAddresses ||
2818 options->ReachableDirAddresses) &&
2819 server_mode(options))
2820 REJECT("Servers must be able to freely connect to the rest "
2821 "of the Internet, so they must not set Reachable*Addresses "
2822 "or FascistFirewall.");
2824 if (options->UseBridges &&
2825 server_mode(options))
2826 REJECT("Servers must be able to freely connect to the rest "
2827 "of the Internet, so they must not set UseBridges.");
2829 /* If both of these are set, we'll end up with funny behavior where we
2830 * demand enough entrynodes be up and running else we won't build
2831 * circuits, yet we never actually use them. */
2832 if (options->UseBridges && options->EntryNodes)
2833 REJECT("You cannot set both UseBridges and EntryNodes.");
2835 if (options->EntryNodes && !options->UseEntryGuards) {
2836 REJECT("If EntryNodes is set, UseEntryGuards must be enabled.");
2839 options->MaxMemInQueues =
2840 compute_real_max_mem_in_queues(options->MaxMemInQueues_raw,
2841 server_mode(options));
2843 options->AllowInvalid_ = 0;
2845 if (options->AllowInvalidNodes) {
2846 SMARTLIST_FOREACH_BEGIN(options->AllowInvalidNodes, const char *, cp) {
2847 if (!strcasecmp(cp, "entry"))
2848 options->AllowInvalid_ |= ALLOW_INVALID_ENTRY;
2849 else if (!strcasecmp(cp, "exit"))
2850 options->AllowInvalid_ |= ALLOW_INVALID_EXIT;
2851 else if (!strcasecmp(cp, "middle"))
2852 options->AllowInvalid_ |= ALLOW_INVALID_MIDDLE;
2853 else if (!strcasecmp(cp, "introduction"))
2854 options->AllowInvalid_ |= ALLOW_INVALID_INTRODUCTION;
2855 else if (!strcasecmp(cp, "rendezvous"))
2856 options->AllowInvalid_ |= ALLOW_INVALID_RENDEZVOUS;
2857 else {
2858 tor_asprintf(msg,
2859 "Unrecognized value '%s' in AllowInvalidNodes", cp);
2860 return -1;
2862 } SMARTLIST_FOREACH_END(cp);
2865 if (!options->SafeLogging ||
2866 !strcasecmp(options->SafeLogging, "0")) {
2867 options->SafeLogging_ = SAFELOG_SCRUB_NONE;
2868 } else if (!strcasecmp(options->SafeLogging, "relay")) {
2869 options->SafeLogging_ = SAFELOG_SCRUB_RELAY;
2870 } else if (!strcasecmp(options->SafeLogging, "1")) {
2871 options->SafeLogging_ = SAFELOG_SCRUB_ALL;
2872 } else {
2873 tor_asprintf(msg,
2874 "Unrecognized value '%s' in SafeLogging",
2875 escaped(options->SafeLogging));
2876 return -1;
2879 if (compute_publishserverdescriptor(options) < 0) {
2880 tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
2881 return -1;
2884 if ((options->BridgeRelay
2885 || options->PublishServerDescriptor_ & BRIDGE_DIRINFO)
2886 && (options->PublishServerDescriptor_ & V3_DIRINFO)) {
2887 REJECT("Bridges are not supposed to publish router descriptors to the "
2888 "directory authorities. Please correct your "
2889 "PublishServerDescriptor line.");
2892 if (options->BridgeRelay && options->DirPort_set) {
2893 log_warn(LD_CONFIG, "Can't set a DirPort on a bridge relay; disabling "
2894 "DirPort");
2895 config_free_lines(options->DirPort_lines);
2896 options->DirPort_lines = NULL;
2897 options->DirPort_set = 0;
2900 if (options->MinUptimeHidServDirectoryV2 < 0) {
2901 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
2902 "least 0 seconds. Changing to 0.");
2903 options->MinUptimeHidServDirectoryV2 = 0;
2906 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
2907 log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
2908 "raising to %d seconds.", MIN_REND_POST_PERIOD);
2909 options->RendPostPeriod = MIN_REND_POST_PERIOD;
2912 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
2913 log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
2914 MAX_DIR_PERIOD);
2915 options->RendPostPeriod = MAX_DIR_PERIOD;
2918 if (options->PredictedPortsRelevanceTime >
2919 MAX_PREDICTED_CIRCS_RELEVANCE) {
2920 log_warn(LD_CONFIG, "PredictedPortsRelevanceTime is too large; "
2921 "clipping to %ds.", MAX_PREDICTED_CIRCS_RELEVANCE);
2922 options->PredictedPortsRelevanceTime = MAX_PREDICTED_CIRCS_RELEVANCE;
2925 if (options->Tor2webMode && options->LearnCircuitBuildTimeout) {
2926 /* LearnCircuitBuildTimeout and Tor2webMode are incompatible in
2927 * two ways:
2929 * - LearnCircuitBuildTimeout results in a low CBT, which
2930 * Tor2webMode's use of one-hop rendezvous circuits lowers
2931 * much further, producing *far* too many timeouts.
2933 * - The adaptive CBT code does not update its timeout estimate
2934 * using build times for single-hop circuits.
2936 * If we fix both of these issues someday, we should test
2937 * Tor2webMode with LearnCircuitBuildTimeout on again. */
2938 log_notice(LD_CONFIG,"Tor2webMode is enabled; turning "
2939 "LearnCircuitBuildTimeout off.");
2940 options->LearnCircuitBuildTimeout = 0;
2943 if (options->Tor2webMode && options->UseEntryGuards) {
2944 /* tor2web mode clients do not (and should not) use entry guards
2945 * in any meaningful way. Further, tor2web mode causes the hidden
2946 * service client code to do things which break the path bias
2947 * detector, and it's far easier to turn off entry guards (and
2948 * thus the path bias detector with it) than to figure out how to
2949 * make a piece of code which cannot possibly help tor2web mode
2950 * users compatible with tor2web mode.
2952 log_notice(LD_CONFIG,
2953 "Tor2WebMode is enabled; disabling UseEntryGuards.");
2954 options->UseEntryGuards = 0;
2957 if (!(options->UseEntryGuards) &&
2958 (options->RendConfigLines != NULL)) {
2959 log_warn(LD_CONFIG,
2960 "UseEntryGuards is disabled, but you have configured one or more "
2961 "hidden services on this Tor instance. Your hidden services "
2962 "will be very easy to locate using a well-known attack -- see "
2963 "http://freehaven.net/anonbib/#hs-attack06 for details.");
2966 if (!options->LearnCircuitBuildTimeout && options->CircuitBuildTimeout &&
2967 options->CircuitBuildTimeout < RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT) {
2968 log_warn(LD_CONFIG,
2969 "CircuitBuildTimeout is shorter (%d seconds) than the recommended "
2970 "minimum (%d seconds), and LearnCircuitBuildTimeout is disabled. "
2971 "If tor isn't working, raise this value or enable "
2972 "LearnCircuitBuildTimeout.",
2973 options->CircuitBuildTimeout,
2974 RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT );
2975 } else if (!options->LearnCircuitBuildTimeout &&
2976 !options->CircuitBuildTimeout) {
2977 log_notice(LD_CONFIG, "You disabled LearnCircuitBuildTimeout, but didn't "
2978 "a CircuitBuildTimeout. I'll pick a plausible default.");
2981 if (options->PathBiasNoticeRate > 1.0) {
2982 tor_asprintf(msg,
2983 "PathBiasNoticeRate is too high. "
2984 "It must be between 0 and 1.0");
2985 return -1;
2987 if (options->PathBiasWarnRate > 1.0) {
2988 tor_asprintf(msg,
2989 "PathBiasWarnRate is too high. "
2990 "It must be between 0 and 1.0");
2991 return -1;
2993 if (options->PathBiasExtremeRate > 1.0) {
2994 tor_asprintf(msg,
2995 "PathBiasExtremeRate is too high. "
2996 "It must be between 0 and 1.0");
2997 return -1;
2999 if (options->PathBiasNoticeUseRate > 1.0) {
3000 tor_asprintf(msg,
3001 "PathBiasNoticeUseRate is too high. "
3002 "It must be between 0 and 1.0");
3003 return -1;
3005 if (options->PathBiasExtremeUseRate > 1.0) {
3006 tor_asprintf(msg,
3007 "PathBiasExtremeUseRate is too high. "
3008 "It must be between 0 and 1.0");
3009 return -1;
3012 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3013 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3014 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3015 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3018 if (options->MaxCircuitDirtiness > MAX_MAX_CIRCUIT_DIRTINESS) {
3019 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too high; "
3020 "setting to %d days.", MAX_MAX_CIRCUIT_DIRTINESS/86400);
3021 options->MaxCircuitDirtiness = MAX_MAX_CIRCUIT_DIRTINESS;
3024 if (options->CircuitStreamTimeout &&
3025 options->CircuitStreamTimeout < MIN_CIRCUIT_STREAM_TIMEOUT) {
3026 log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
3027 "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
3028 options->CircuitStreamTimeout = MIN_CIRCUIT_STREAM_TIMEOUT;
3031 if (options->HeartbeatPeriod &&
3032 options->HeartbeatPeriod < MIN_HEARTBEAT_PERIOD) {
3033 log_warn(LD_CONFIG, "HeartbeatPeriod option is too short; "
3034 "raising to %d seconds.", MIN_HEARTBEAT_PERIOD);
3035 options->HeartbeatPeriod = MIN_HEARTBEAT_PERIOD;
3038 if (options->KeepalivePeriod < 1)
3039 REJECT("KeepalivePeriod option must be positive.");
3041 if (options->PortForwarding && options->Sandbox) {
3042 REJECT("PortForwarding is not compatible with Sandbox; at most one can "
3043 "be set");
3046 if (ensure_bandwidth_cap(&options->BandwidthRate,
3047 "BandwidthRate", msg) < 0)
3048 return -1;
3049 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3050 "BandwidthBurst", msg) < 0)
3051 return -1;
3052 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3053 "MaxAdvertisedBandwidth", msg) < 0)
3054 return -1;
3055 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3056 "RelayBandwidthRate", msg) < 0)
3057 return -1;
3058 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3059 "RelayBandwidthBurst", msg) < 0)
3060 return -1;
3061 if (ensure_bandwidth_cap(&options->PerConnBWRate,
3062 "PerConnBWRate", msg) < 0)
3063 return -1;
3064 if (ensure_bandwidth_cap(&options->PerConnBWBurst,
3065 "PerConnBWBurst", msg) < 0)
3066 return -1;
3067 if (ensure_bandwidth_cap(&options->AuthDirFastGuarantee,
3068 "AuthDirFastGuarantee", msg) < 0)
3069 return -1;
3070 if (ensure_bandwidth_cap(&options->AuthDirGuardBWGuarantee,
3071 "AuthDirGuardBWGuarantee", msg) < 0)
3072 return -1;
3074 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3075 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3076 if (options->RelayBandwidthBurst && !options->RelayBandwidthRate)
3077 options->RelayBandwidthRate = options->RelayBandwidthBurst;
3079 if (server_mode(options)) {
3080 if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3081 tor_asprintf(msg,
3082 "BandwidthRate is set to %d bytes/second. "
3083 "For servers, it must be at least %d.",
3084 (int)options->BandwidthRate,
3085 ROUTER_REQUIRED_MIN_BANDWIDTH);
3086 return -1;
3087 } else if (options->MaxAdvertisedBandwidth <
3088 ROUTER_REQUIRED_MIN_BANDWIDTH/2) {
3089 tor_asprintf(msg,
3090 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3091 "For servers, it must be at least %d.",
3092 (int)options->MaxAdvertisedBandwidth,
3093 ROUTER_REQUIRED_MIN_BANDWIDTH/2);
3094 return -1;
3096 if (options->RelayBandwidthRate &&
3097 options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3098 tor_asprintf(msg,
3099 "RelayBandwidthRate is set to %d bytes/second. "
3100 "For servers, it must be at least %d.",
3101 (int)options->RelayBandwidthRate,
3102 ROUTER_REQUIRED_MIN_BANDWIDTH);
3103 return -1;
3107 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3108 REJECT("RelayBandwidthBurst must be at least equal "
3109 "to RelayBandwidthRate.");
3111 if (options->BandwidthRate > options->BandwidthBurst)
3112 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3114 /* if they set relaybandwidth* really high but left bandwidth*
3115 * at the default, raise the defaults. */
3116 if (options->RelayBandwidthRate > options->BandwidthRate)
3117 options->BandwidthRate = options->RelayBandwidthRate;
3118 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3119 options->BandwidthBurst = options->RelayBandwidthBurst;
3121 if (accounting_parse_options(options, 1)<0)
3122 REJECT("Failed to parse accounting options. See logs for details.");
3124 if (options->AccountingMax) {
3125 if (options->RendConfigLines && server_mode(options)) {
3126 log_warn(LD_CONFIG, "Using accounting with a hidden service and an "
3127 "ORPort is risky: your hidden service(s) and your public "
3128 "address will all turn off at the same time, which may alert "
3129 "observers that they are being run by the same party.");
3130 } else if (config_count_key(options->RendConfigLines,
3131 "HiddenServiceDir") > 1) {
3132 log_warn(LD_CONFIG, "Using accounting with multiple hidden services is "
3133 "risky: they will all turn off at the same time, which may "
3134 "alert observers that they are being run by the same party.");
3138 if (options->HTTPProxy) { /* parse it now */
3139 if (tor_addr_port_lookup(options->HTTPProxy,
3140 &options->HTTPProxyAddr, &options->HTTPProxyPort) < 0)
3141 REJECT("HTTPProxy failed to parse or resolve. Please fix.");
3142 if (options->HTTPProxyPort == 0) { /* give it a default */
3143 options->HTTPProxyPort = 80;
3147 if (options->HTTPProxyAuthenticator) {
3148 if (strlen(options->HTTPProxyAuthenticator) >= 512)
3149 REJECT("HTTPProxyAuthenticator is too long (>= 512 chars).");
3152 if (options->HTTPSProxy) { /* parse it now */
3153 if (tor_addr_port_lookup(options->HTTPSProxy,
3154 &options->HTTPSProxyAddr, &options->HTTPSProxyPort) <0)
3155 REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
3156 if (options->HTTPSProxyPort == 0) { /* give it a default */
3157 options->HTTPSProxyPort = 443;
3161 if (options->HTTPSProxyAuthenticator) {
3162 if (strlen(options->HTTPSProxyAuthenticator) >= 512)
3163 REJECT("HTTPSProxyAuthenticator is too long (>= 512 chars).");
3166 if (options->Socks4Proxy) { /* parse it now */
3167 if (tor_addr_port_lookup(options->Socks4Proxy,
3168 &options->Socks4ProxyAddr,
3169 &options->Socks4ProxyPort) <0)
3170 REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
3171 if (options->Socks4ProxyPort == 0) { /* give it a default */
3172 options->Socks4ProxyPort = 1080;
3176 if (options->Socks5Proxy) { /* parse it now */
3177 if (tor_addr_port_lookup(options->Socks5Proxy,
3178 &options->Socks5ProxyAddr,
3179 &options->Socks5ProxyPort) <0)
3180 REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
3181 if (options->Socks5ProxyPort == 0) { /* give it a default */
3182 options->Socks5ProxyPort = 1080;
3186 /* Check if more than one proxy type has been enabled. */
3187 if (!!options->Socks4Proxy + !!options->Socks5Proxy +
3188 !!options->HTTPSProxy + !!options->ClientTransportPlugin > 1)
3189 REJECT("You have configured more than one proxy type. "
3190 "(Socks4Proxy|Socks5Proxy|HTTPSProxy|ClientTransportPlugin)");
3192 /* Check if the proxies will give surprising behavior. */
3193 if (options->HTTPProxy && !(options->Socks4Proxy ||
3194 options->Socks5Proxy ||
3195 options->HTTPSProxy)) {
3196 log_warn(LD_CONFIG, "HTTPProxy configured, but no SOCKS proxy or "
3197 "HTTPS proxy configured. Watch out: this configuration will "
3198 "proxy unencrypted directory connections only.");
3201 if (options->Socks5ProxyUsername) {
3202 size_t len;
3204 len = strlen(options->Socks5ProxyUsername);
3205 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
3206 REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
3208 if (!options->Socks5ProxyPassword)
3209 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3211 len = strlen(options->Socks5ProxyPassword);
3212 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
3213 REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
3214 } else if (options->Socks5ProxyPassword)
3215 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3217 if (options->HashedControlPassword) {
3218 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3219 if (!sl) {
3220 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3221 } else {
3222 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3223 smartlist_free(sl);
3227 if (options->HashedControlSessionPassword) {
3228 smartlist_t *sl = decode_hashed_passwords(
3229 options->HashedControlSessionPassword);
3230 if (!sl) {
3231 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3232 } else {
3233 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3234 smartlist_free(sl);
3238 if (options->OwningControllerProcess) {
3239 const char *validate_pspec_msg = NULL;
3240 if (tor_validate_process_specifier(options->OwningControllerProcess,
3241 &validate_pspec_msg)) {
3242 tor_asprintf(msg, "Bad OwningControllerProcess: %s",
3243 validate_pspec_msg);
3244 return -1;
3248 if (options->ControlPort_set && !options->HashedControlPassword &&
3249 !options->HashedControlSessionPassword &&
3250 !options->CookieAuthentication) {
3251 log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
3252 "has been configured. This means that any program on your "
3253 "computer can reconfigure your Tor. That's bad! You should "
3254 "upgrade your Tor controller as soon as possible.");
3257 if (options->CookieAuthFileGroupReadable && !options->CookieAuthFile) {
3258 log_warn(LD_CONFIG, "CookieAuthFileGroupReadable is set, but will have "
3259 "no effect: you must specify an explicit CookieAuthFile to "
3260 "have it group-readable.");
3263 if (options->MyFamily && options->BridgeRelay) {
3264 log_warn(LD_CONFIG, "Listing a family for a bridge relay is not "
3265 "supported: it can reveal bridge fingerprints to censors. "
3266 "You should also make sure you aren't listing this bridge's "
3267 "fingerprint in any other MyFamily.");
3269 if (check_nickname_list(&options->MyFamily, "MyFamily", msg))
3270 return -1;
3271 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3272 routerset_t *rs = routerset_new();
3273 if (routerset_parse(rs, cl->value, cl->key)) {
3274 routerset_free(rs);
3275 return -1;
3277 routerset_free(rs);
3280 if (validate_addr_policies(options, msg) < 0)
3281 return -1;
3283 if (validate_dir_servers(options, old_options) < 0)
3284 REJECT("Directory authority/fallback line did not parse. See logs "
3285 "for details.");
3287 if (options->UseBridges && !options->Bridges)
3288 REJECT("If you set UseBridges, you must specify at least one bridge.");
3290 for (cl = options->Bridges; cl; cl = cl->next) {
3291 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
3292 if (!bridge_line)
3293 REJECT("Bridge line did not parse. See logs for details.");
3294 bridge_line_free(bridge_line);
3297 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
3298 if (parse_client_transport_line(options, cl->value, 1)<0)
3299 REJECT("Invalid client transport line. See logs for details.");
3302 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
3303 if (parse_server_transport_line(options, cl->value, 1)<0)
3304 REJECT("Invalid server transport line. See logs for details.");
3307 if (options->ServerTransportPlugin && !server_mode(options)) {
3308 log_notice(LD_GENERAL, "Tor is not configured as a relay but you specified"
3309 " a ServerTransportPlugin line (%s). The ServerTransportPlugin "
3310 "line will be ignored.",
3311 escaped(options->ServerTransportPlugin->value));
3314 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
3315 /** If get_bindaddr_from_transport_listen_line() fails with
3316 'transport' being NULL, it means that something went wrong
3317 while parsing the ServerTransportListenAddr line. */
3318 char *bindaddr = get_bindaddr_from_transport_listen_line(cl->value, NULL);
3319 if (!bindaddr)
3320 REJECT("ServerTransportListenAddr did not parse. See logs for details.");
3321 tor_free(bindaddr);
3324 if (options->ServerTransportListenAddr && !options->ServerTransportPlugin) {
3325 log_notice(LD_GENERAL, "You need at least a single managed-proxy to "
3326 "specify a transport listen address. The "
3327 "ServerTransportListenAddr line will be ignored.");
3330 for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
3331 /** If get_options_from_transport_options_line() fails with
3332 'transport' being NULL, it means that something went wrong
3333 while parsing the ServerTransportOptions line. */
3334 smartlist_t *options_sl =
3335 get_options_from_transport_options_line(cl->value, NULL);
3336 if (!options_sl)
3337 REJECT("ServerTransportOptions did not parse. See logs for details.");
3339 SMARTLIST_FOREACH(options_sl, char *, cp, tor_free(cp));
3340 smartlist_free(options_sl);
3343 if (options->ConstrainedSockets) {
3344 /* If the user wants to constrain socket buffer use, make sure the desired
3345 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3346 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3347 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3348 options->ConstrainedSockSize % 1024) {
3349 tor_asprintf(msg,
3350 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3351 "in 1024 byte increments.",
3352 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3353 return -1;
3355 if (options->DirPort_set) {
3356 /* Providing cached directory entries while system TCP buffers are scarce
3357 * will exacerbate the socket errors. Suggest that this be disabled. */
3358 COMPLAIN("You have requested constrained socket buffers while also "
3359 "serving directory entries via DirPort. It is strongly "
3360 "suggested that you disable serving directory requests when "
3361 "system TCP buffer resources are scarce.");
3365 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3366 options->V3AuthVotingInterval/2) {
3367 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3368 "V3AuthVotingInterval");
3370 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
3371 REJECT("V3AuthVoteDelay is way too low.");
3372 if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
3373 REJECT("V3AuthDistDelay is way too low.");
3375 if (options->V3AuthNIntervalsValid < 2)
3376 REJECT("V3AuthNIntervalsValid must be at least 2.");
3378 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3379 REJECT("V3AuthVotingInterval is insanely low.");
3380 } else if (options->V3AuthVotingInterval > 24*60*60) {
3381 REJECT("V3AuthVotingInterval is insanely high.");
3382 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3383 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3386 if (rend_config_services(options, 1) < 0)
3387 REJECT("Failed to configure rendezvous options. See logs for details.");
3389 /* Parse client-side authorization for hidden services. */
3390 if (rend_parse_service_authorization(options, 1) < 0)
3391 REJECT("Failed to configure client authorization for hidden services. "
3392 "See logs for details.");
3394 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv4,
3395 AF_INET, 1, msg)<0)
3396 return -1;
3397 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv6,
3398 AF_INET6, 1, msg)<0)
3399 return -1;
3401 if (options->AutomapHostsSuffixes) {
3402 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
3404 size_t len = strlen(suf);
3405 if (len && suf[len-1] == '.')
3406 suf[len-1] = '\0';
3410 if (options->TestingTorNetwork &&
3411 !(options->DirAuthorities ||
3412 (options->AlternateDirAuthority &&
3413 options->AlternateBridgeAuthority))) {
3414 REJECT("TestingTorNetwork may only be configured in combination with "
3415 "a non-default set of DirAuthority or both of "
3416 "AlternateDirAuthority and AlternateBridgeAuthority configured.");
3419 if (options->AllowSingleHopExits && !options->DirAuthorities) {
3420 COMPLAIN("You have set AllowSingleHopExits; now your relay will allow "
3421 "others to make one-hop exits. However, since by default most "
3422 "clients avoid relays that set this option, most clients will "
3423 "ignore you.");
3426 #define CHECK_DEFAULT(arg) \
3427 STMT_BEGIN \
3428 if (!options->TestingTorNetwork && \
3429 !options->UsingTestNetworkDefaults_ && \
3430 !config_is_same(&options_format,options, \
3431 default_options,#arg)) { \
3432 REJECT(#arg " may only be changed in testing Tor " \
3433 "networks!"); \
3434 } STMT_END
3435 CHECK_DEFAULT(TestingV3AuthInitialVotingInterval);
3436 CHECK_DEFAULT(TestingV3AuthInitialVoteDelay);
3437 CHECK_DEFAULT(TestingV3AuthInitialDistDelay);
3438 CHECK_DEFAULT(TestingV3AuthVotingStartOffset);
3439 CHECK_DEFAULT(TestingAuthDirTimeToLearnReachability);
3440 CHECK_DEFAULT(TestingEstimatedDescriptorPropagationTime);
3441 CHECK_DEFAULT(TestingServerDownloadSchedule);
3442 CHECK_DEFAULT(TestingClientDownloadSchedule);
3443 CHECK_DEFAULT(TestingServerConsensusDownloadSchedule);
3444 CHECK_DEFAULT(TestingClientConsensusDownloadSchedule);
3445 CHECK_DEFAULT(TestingBridgeDownloadSchedule);
3446 CHECK_DEFAULT(TestingClientMaxIntervalWithoutRequest);
3447 CHECK_DEFAULT(TestingDirConnectionMaxStall);
3448 CHECK_DEFAULT(TestingConsensusMaxDownloadTries);
3449 CHECK_DEFAULT(TestingDescriptorMaxDownloadTries);
3450 CHECK_DEFAULT(TestingMicrodescMaxDownloadTries);
3451 CHECK_DEFAULT(TestingCertMaxDownloadTries);
3452 #undef CHECK_DEFAULT
3454 if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
3455 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3456 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
3457 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3458 "30 minutes.");
3461 if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
3462 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3465 if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
3466 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3469 if (options->TestingV3AuthInitialVoteDelay +
3470 options->TestingV3AuthInitialDistDelay >=
3471 options->TestingV3AuthInitialVotingInterval/2) {
3472 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3473 "must be less than half TestingV3AuthInitialVotingInterval");
3476 if (options->TestingV3AuthVotingStartOffset >
3477 MIN(options->TestingV3AuthInitialVotingInterval,
3478 options->V3AuthVotingInterval)) {
3479 REJECT("TestingV3AuthVotingStartOffset is higher than the voting "
3480 "interval.");
3483 if (options->TestingAuthDirTimeToLearnReachability < 0) {
3484 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3485 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
3486 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3489 if (options->TestingEstimatedDescriptorPropagationTime < 0) {
3490 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3491 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
3492 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3495 if (options->TestingClientMaxIntervalWithoutRequest < 1) {
3496 REJECT("TestingClientMaxIntervalWithoutRequest is way too low.");
3497 } else if (options->TestingClientMaxIntervalWithoutRequest > 3600) {
3498 COMPLAIN("TestingClientMaxIntervalWithoutRequest is insanely high.");
3501 if (options->TestingDirConnectionMaxStall < 5) {
3502 REJECT("TestingDirConnectionMaxStall is way too low.");
3503 } else if (options->TestingDirConnectionMaxStall > 3600) {
3504 COMPLAIN("TestingDirConnectionMaxStall is insanely high.");
3507 if (options->TestingConsensusMaxDownloadTries < 2) {
3508 REJECT("TestingConsensusMaxDownloadTries must be greater than 1.");
3509 } else if (options->TestingConsensusMaxDownloadTries > 800) {
3510 COMPLAIN("TestingConsensusMaxDownloadTries is insanely high.");
3513 if (options->TestingDescriptorMaxDownloadTries < 2) {
3514 REJECT("TestingDescriptorMaxDownloadTries must be greater than 1.");
3515 } else if (options->TestingDescriptorMaxDownloadTries > 800) {
3516 COMPLAIN("TestingDescriptorMaxDownloadTries is insanely high.");
3519 if (options->TestingMicrodescMaxDownloadTries < 2) {
3520 REJECT("TestingMicrodescMaxDownloadTries must be greater than 1.");
3521 } else if (options->TestingMicrodescMaxDownloadTries > 800) {
3522 COMPLAIN("TestingMicrodescMaxDownloadTries is insanely high.");
3525 if (options->TestingCertMaxDownloadTries < 2) {
3526 REJECT("TestingCertMaxDownloadTries must be greater than 1.");
3527 } else if (options->TestingCertMaxDownloadTries > 800) {
3528 COMPLAIN("TestingCertMaxDownloadTries is insanely high.");
3531 if (options->TestingEnableConnBwEvent &&
3532 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
3533 REJECT("TestingEnableConnBwEvent may only be changed in testing "
3534 "Tor networks!");
3537 if (options->TestingEnableCellStatsEvent &&
3538 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
3539 REJECT("TestingEnableCellStatsEvent may only be changed in testing "
3540 "Tor networks!");
3543 if (options->TestingEnableTbEmptyEvent &&
3544 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
3545 REJECT("TestingEnableTbEmptyEvent may only be changed in testing "
3546 "Tor networks!");
3549 if (options->TestingTorNetwork) {
3550 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
3551 "almost unusable in the public Tor network, and is "
3552 "therefore only advised if you are building a "
3553 "testing Tor network!");
3556 if (options->AccelName && !options->HardwareAccel)
3557 options->HardwareAccel = 1;
3558 if (options->AccelDir && !options->AccelName)
3559 REJECT("Can't use hardware crypto accelerator dir without engine name.");
3561 if (options->PublishServerDescriptor)
3562 SMARTLIST_FOREACH(options->PublishServerDescriptor, const char *, pubdes, {
3563 if (!strcmp(pubdes, "1") || !strcmp(pubdes, "0"))
3564 if (smartlist_len(options->PublishServerDescriptor) > 1) {
3565 COMPLAIN("You have passed a list of multiple arguments to the "
3566 "PublishServerDescriptor option that includes 0 or 1. "
3567 "0 or 1 should only be used as the sole argument. "
3568 "This configuration will be rejected in a future release.");
3569 break;
3573 if (options->BridgeRelay == 1 && ! options->ORPort_set)
3574 REJECT("BridgeRelay is 1, ORPort is not set. This is an invalid "
3575 "combination.");
3577 return 0;
3578 #undef REJECT
3579 #undef COMPLAIN
3582 /* Given the value that the user has set for MaxMemInQueues, compute the
3583 * actual maximum value. We clip this value if it's too low, and autodetect
3584 * it if it's set to 0. */
3585 static uint64_t
3586 compute_real_max_mem_in_queues(const uint64_t val, int log_guess)
3588 uint64_t result;
3590 if (val == 0) {
3591 #define ONE_GIGABYTE (U64_LITERAL(1) << 30)
3592 #define ONE_MEGABYTE (U64_LITERAL(1) << 20)
3593 #if SIZEOF_VOID_P >= 8
3594 #define MAX_DEFAULT_MAXMEM (8*ONE_GIGABYTE)
3595 #else
3596 #define MAX_DEFAULT_MAXMEM (2*ONE_GIGABYTE)
3597 #endif
3598 /* The user didn't pick a memory limit. Choose a very large one
3599 * that is still smaller than the system memory */
3600 static int notice_sent = 0;
3601 size_t ram = 0;
3602 if (get_total_system_memory(&ram) < 0) {
3603 /* We couldn't determine our total system memory! */
3604 #if SIZEOF_VOID_P >= 8
3605 /* 64-bit system. Let's hope for 8 GB. */
3606 result = 8 * ONE_GIGABYTE;
3607 #else
3608 /* (presumably) 32-bit system. Let's hope for 1 GB. */
3609 result = ONE_GIGABYTE;
3610 #endif
3611 } else {
3612 /* We detected it, so let's pick 3/4 of the total RAM as our limit. */
3613 const uint64_t avail = (ram / 4) * 3;
3615 /* Make sure it's in range from 0.25 GB to 8 GB. */
3616 if (avail > MAX_DEFAULT_MAXMEM) {
3617 /* If you want to use more than this much RAM, you need to configure
3618 it yourself */
3619 result = MAX_DEFAULT_MAXMEM;
3620 } else if (avail < ONE_GIGABYTE / 4) {
3621 result = ONE_GIGABYTE / 4;
3622 } else {
3623 result = avail;
3626 if (log_guess && ! notice_sent) {
3627 log_notice(LD_CONFIG, "%sMaxMemInQueues is set to "U64_FORMAT" MB. "
3628 "You can override this by setting MaxMemInQueues by hand.",
3629 ram ? "Based on detected system memory, " : "",
3630 U64_PRINTF_ARG(result / ONE_MEGABYTE));
3631 notice_sent = 1;
3633 return result;
3634 } else if (val < ONE_GIGABYTE / 4) {
3635 log_warn(LD_CONFIG, "MaxMemInQueues must be at least 256 MB for now. "
3636 "Ideally, have it as large as you can afford.");
3637 return ONE_GIGABYTE / 4;
3638 } else {
3639 /* The value was fine all along */
3640 return val;
3644 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3645 * equal strings. */
3646 static int
3647 opt_streq(const char *s1, const char *s2)
3649 return 0 == strcmp_opt(s1, s2);
3652 /** Check if any of the previous options have changed but aren't allowed to. */
3653 static int
3654 options_transition_allowed(const or_options_t *old,
3655 const or_options_t *new_val,
3656 char **msg)
3658 if (!old)
3659 return 0;
3661 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3662 *msg = tor_strdup("PidFile is not allowed to change.");
3663 return -1;
3666 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3667 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3668 "is not allowed.");
3669 return -1;
3672 if (old->Sandbox != new_val->Sandbox) {
3673 *msg = tor_strdup("While Tor is running, changing Sandbox "
3674 "is not allowed.");
3675 return -1;
3678 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
3679 tor_asprintf(msg,
3680 "While Tor is running, changing DataDirectory "
3681 "(\"%s\"->\"%s\") is not allowed.",
3682 old->DataDirectory, new_val->DataDirectory);
3683 return -1;
3686 if (!opt_streq(old->User, new_val->User)) {
3687 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
3688 return -1;
3691 if ((old->HardwareAccel != new_val->HardwareAccel)
3692 || !opt_streq(old->AccelName, new_val->AccelName)
3693 || !opt_streq(old->AccelDir, new_val->AccelDir)) {
3694 *msg = tor_strdup("While Tor is running, changing OpenSSL hardware "
3695 "acceleration engine is not allowed.");
3696 return -1;
3699 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
3700 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
3701 "is not allowed.");
3702 return -1;
3705 if (old->DisableAllSwap != new_val->DisableAllSwap) {
3706 *msg = tor_strdup("While Tor is running, changing DisableAllSwap "
3707 "is not allowed.");
3708 return -1;
3711 if (old->TokenBucketRefillInterval != new_val->TokenBucketRefillInterval) {
3712 *msg = tor_strdup("While Tor is running, changing TokenBucketRefill"
3713 "Interval is not allowed");
3714 return -1;
3717 if (old->DisableIOCP != new_val->DisableIOCP) {
3718 *msg = tor_strdup("While Tor is running, changing DisableIOCP "
3719 "is not allowed.");
3720 return -1;
3723 if (old->DisableDebuggerAttachment &&
3724 !new_val->DisableDebuggerAttachment) {
3725 *msg = tor_strdup("While Tor is running, disabling "
3726 "DisableDebuggerAttachment is not allowed.");
3727 return -1;
3730 if (sandbox_is_active()) {
3731 #define SB_NOCHANGE_STR(opt) \
3732 do { \
3733 if (! opt_streq(old->opt, new_val->opt)) { \
3734 *msg = tor_strdup("Can't change " #opt " while Sandbox is active"); \
3735 return -1; \
3737 } while (0)
3739 SB_NOCHANGE_STR(PidFile);
3740 SB_NOCHANGE_STR(ServerDNSResolvConfFile);
3741 SB_NOCHANGE_STR(DirPortFrontPage);
3742 SB_NOCHANGE_STR(CookieAuthFile);
3743 SB_NOCHANGE_STR(ExtORPortCookieAuthFile);
3745 #undef SB_NOCHANGE_STR
3747 if (! config_lines_eq(old->Logs, new_val->Logs)) {
3748 *msg = tor_strdup("Can't change Logs while Sandbox is active");
3749 return -1;
3751 if (old->ConnLimit != new_val->ConnLimit) {
3752 *msg = tor_strdup("Can't change ConnLimit while Sandbox is active");
3753 return -1;
3755 if (server_mode(old) != server_mode(new_val)) {
3756 *msg = tor_strdup("Can't start/stop being a server while "
3757 "Sandbox is active");
3758 return -1;
3762 return 0;
3765 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3766 * will require us to rotate the CPU and DNS workers; else return 0. */
3767 static int
3768 options_transition_affects_workers(const or_options_t *old_options,
3769 const or_options_t *new_options)
3771 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3772 old_options->NumCPUs != new_options->NumCPUs ||
3773 !config_lines_eq(old_options->ORPort_lines, new_options->ORPort_lines) ||
3774 old_options->ServerDNSSearchDomains !=
3775 new_options->ServerDNSSearchDomains ||
3776 old_options->SafeLogging_ != new_options->SafeLogging_ ||
3777 old_options->ClientOnly != new_options->ClientOnly ||
3778 public_server_mode(old_options) != public_server_mode(new_options) ||
3779 !config_lines_eq(old_options->Logs, new_options->Logs) ||
3780 old_options->LogMessageDomains != new_options->LogMessageDomains)
3781 return 1;
3783 /* Check whether log options match. */
3785 /* Nothing that changed matters. */
3786 return 0;
3789 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3790 * will require us to generate a new descriptor; else return 0. */
3791 static int
3792 options_transition_affects_descriptor(const or_options_t *old_options,
3793 const or_options_t *new_options)
3795 /* XXX We can be smarter here. If your DirPort isn't being
3796 * published and you just turned it off, no need to republish. Etc. */
3797 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3798 !opt_streq(old_options->Nickname,new_options->Nickname) ||
3799 !opt_streq(old_options->Address,new_options->Address) ||
3800 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
3801 old_options->ExitPolicyRejectPrivate !=
3802 new_options->ExitPolicyRejectPrivate ||
3803 old_options->IPv6Exit != new_options->IPv6Exit ||
3804 !config_lines_eq(old_options->ORPort_lines,
3805 new_options->ORPort_lines) ||
3806 !config_lines_eq(old_options->DirPort_lines,
3807 new_options->DirPort_lines) ||
3808 old_options->ClientOnly != new_options->ClientOnly ||
3809 old_options->DisableNetwork != new_options->DisableNetwork ||
3810 old_options->PublishServerDescriptor_ !=
3811 new_options->PublishServerDescriptor_ ||
3812 get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
3813 get_effective_bwburst(old_options) !=
3814 get_effective_bwburst(new_options) ||
3815 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
3816 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
3817 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
3818 old_options->AccountingMax != new_options->AccountingMax ||
3819 public_server_mode(old_options) != public_server_mode(new_options))
3820 return 1;
3822 return 0;
3825 #ifdef _WIN32
3826 /** Return the directory on windows where we expect to find our application
3827 * data. */
3828 static char *
3829 get_windows_conf_root(void)
3831 static int is_set = 0;
3832 static char path[MAX_PATH*2+1];
3833 TCHAR tpath[MAX_PATH] = {0};
3835 LPITEMIDLIST idl;
3836 IMalloc *m;
3837 HRESULT result;
3839 if (is_set)
3840 return path;
3842 /* Find X:\documents and settings\username\application data\ .
3843 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3845 #ifdef ENABLE_LOCAL_APPDATA
3846 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
3847 #else
3848 #define APPDATA_PATH CSIDL_APPDATA
3849 #endif
3850 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
3851 getcwd(path,MAX_PATH);
3852 is_set = 1;
3853 log_warn(LD_CONFIG,
3854 "I couldn't find your application data folder: are you "
3855 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3856 path);
3857 return path;
3859 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3860 result = SHGetPathFromIDList(idl, tpath);
3861 #ifdef UNICODE
3862 wcstombs(path,tpath,sizeof(path));
3863 path[sizeof(path)-1] = '\0';
3864 #else
3865 strlcpy(path,tpath,sizeof(path));
3866 #endif
3868 /* Now we need to free the memory that the path-idl was stored in. In
3869 * typical Windows fashion, we can't just call 'free()' on it. */
3870 SHGetMalloc(&m);
3871 if (m) {
3872 m->lpVtbl->Free(m, idl);
3873 m->lpVtbl->Release(m);
3875 if (!SUCCEEDED(result)) {
3876 return NULL;
3878 strlcat(path,"\\tor",MAX_PATH);
3879 is_set = 1;
3880 return path;
3882 #endif
3884 /** Return the default location for our torrc file (if <b>defaults_file</b> is
3885 * false), or for the torrc-defaults file (if <b>defaults_file</b> is true). */
3886 static const char *
3887 get_default_conf_file(int defaults_file)
3889 #ifdef _WIN32
3890 if (defaults_file) {
3891 static char defaults_path[MAX_PATH+1];
3892 tor_snprintf(defaults_path, MAX_PATH, "%s\\torrc-defaults",
3893 get_windows_conf_root());
3894 return defaults_path;
3895 } else {
3896 static char path[MAX_PATH+1];
3897 tor_snprintf(path, MAX_PATH, "%s\\torrc",
3898 get_windows_conf_root());
3899 return path;
3901 #else
3902 return defaults_file ? CONFDIR "/torrc-defaults" : CONFDIR "/torrc";
3903 #endif
3906 /** Verify whether lst is a string containing valid-looking comma-separated
3907 * nicknames, or NULL. Will normalise <b>lst</b> to prefix '$' to any nickname
3908 * or fingerprint that needs it. Return 0 on success.
3909 * Warn and return -1 on failure.
3911 static int
3912 check_nickname_list(char **lst, const char *name, char **msg)
3914 int r = 0;
3915 smartlist_t *sl;
3916 int changes = 0;
3918 if (!*lst)
3919 return 0;
3920 sl = smartlist_new();
3922 smartlist_split_string(sl, *lst, ",",
3923 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
3925 SMARTLIST_FOREACH_BEGIN(sl, char *, s)
3927 if (!is_legal_nickname_or_hexdigest(s)) {
3928 // check if first char is dollar
3929 if (s[0] != '$') {
3930 // Try again but with a dollar symbol prepended
3931 char *prepended;
3932 tor_asprintf(&prepended, "$%s", s);
3934 if (is_legal_nickname_or_hexdigest(prepended)) {
3935 // The nickname is valid when it's prepended, swap the current
3936 // version with a prepended one
3937 tor_free(s);
3938 SMARTLIST_REPLACE_CURRENT(sl, s, prepended);
3939 changes = 1;
3940 continue;
3943 // Still not valid, free and fallback to error message
3944 tor_free(prepended);
3947 tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
3948 r = -1;
3949 break;
3952 SMARTLIST_FOREACH_END(s);
3954 // Replace the caller's nickname list with a fixed one
3955 if (changes && r == 0) {
3956 char *newNicknames = smartlist_join_strings(sl, ", ", 0, NULL);
3957 tor_free(*lst);
3958 *lst = newNicknames;
3961 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
3962 smartlist_free(sl);
3964 return r;
3967 /** Learn config file name from command line arguments, or use the default.
3969 * If <b>defaults_file</b> is true, we're looking for torrc-defaults;
3970 * otherwise, we're looking for the regular torrc_file.
3972 * Set *<b>using_default_fname</b> to true if we're using the default
3973 * configuration file name; or false if we've set it from the command line.
3975 * Set *<b>ignore_missing_torrc</b> to true if we should ignore the resulting
3976 * filename if it doesn't exist.
3978 static char *
3979 find_torrc_filename(config_line_t *cmd_arg,
3980 int defaults_file,
3981 int *using_default_fname, int *ignore_missing_torrc)
3983 char *fname=NULL;
3984 config_line_t *p_index;
3985 const char *fname_opt = defaults_file ? "--defaults-torrc" : "-f";
3986 const char *ignore_opt = defaults_file ? NULL : "--ignore-missing-torrc";
3988 if (defaults_file)
3989 *ignore_missing_torrc = 1;
3991 for (p_index = cmd_arg; p_index; p_index = p_index->next) {
3992 if (!strcmp(p_index->key, fname_opt)) {
3993 if (fname) {
3994 log_warn(LD_CONFIG, "Duplicate %s options on command line.",
3995 fname_opt);
3996 tor_free(fname);
3998 fname = expand_filename(p_index->value);
4001 char *absfname;
4002 absfname = make_path_absolute(fname);
4003 tor_free(fname);
4004 fname = absfname;
4007 *using_default_fname = 0;
4008 } else if (ignore_opt && !strcmp(p_index->key,ignore_opt)) {
4009 *ignore_missing_torrc = 1;
4013 if (*using_default_fname) {
4014 /* didn't find one, try CONFDIR */
4015 const char *dflt = get_default_conf_file(defaults_file);
4016 if (dflt && file_status(dflt) == FN_FILE) {
4017 fname = tor_strdup(dflt);
4018 } else {
4019 #ifndef _WIN32
4020 char *fn = NULL;
4021 if (!defaults_file)
4022 fn = expand_filename("~/.torrc");
4023 if (fn && file_status(fn) == FN_FILE) {
4024 fname = fn;
4025 } else {
4026 tor_free(fn);
4027 fname = tor_strdup(dflt);
4029 #else
4030 fname = tor_strdup(dflt);
4031 #endif
4034 return fname;
4037 /** Load a configuration file from disk, setting torrc_fname or
4038 * torrc_defaults_fname if successful.
4040 * If <b>defaults_file</b> is true, load torrc-defaults; otherwise load torrc.
4042 * Return the contents of the file on success, and NULL on failure.
4044 static char *
4045 load_torrc_from_disk(config_line_t *cmd_arg, int defaults_file)
4047 char *fname=NULL;
4048 char *cf = NULL;
4049 int using_default_torrc = 1;
4050 int ignore_missing_torrc = 0;
4051 char **fname_var = defaults_file ? &torrc_defaults_fname : &torrc_fname;
4053 fname = find_torrc_filename(cmd_arg, defaults_file,
4054 &using_default_torrc, &ignore_missing_torrc);
4055 tor_assert(fname);
4056 log_debug(LD_CONFIG, "Opening config file \"%s\"", fname);
4058 tor_free(*fname_var);
4059 *fname_var = fname;
4061 /* Open config file */
4062 if (file_status(fname) != FN_FILE ||
4063 !(cf = read_file_to_str(fname,0,NULL))) {
4064 if (using_default_torrc == 1 || ignore_missing_torrc) {
4065 if (!defaults_file)
4066 log_notice(LD_CONFIG, "Configuration file \"%s\" not present, "
4067 "using reasonable defaults.", fname);
4068 tor_free(fname); /* sets fname to NULL */
4069 *fname_var = NULL;
4070 cf = tor_strdup("");
4071 } else {
4072 log_warn(LD_CONFIG,
4073 "Unable to open configuration file \"%s\".", fname);
4074 goto err;
4076 } else {
4077 log_notice(LD_CONFIG, "Read configuration file \"%s\".", fname);
4080 return cf;
4081 err:
4082 tor_free(fname);
4083 *fname_var = NULL;
4084 return NULL;
4087 /** Read a configuration file into <b>options</b>, finding the configuration
4088 * file location based on the command line. After loading the file
4089 * call options_init_from_string() to load the config.
4090 * Return 0 if success, -1 if failure. */
4092 options_init_from_torrc(int argc, char **argv)
4094 char *cf=NULL, *cf_defaults=NULL;
4095 int command;
4096 int retval = -1;
4097 char *command_arg = NULL;
4098 char *errmsg=NULL;
4099 config_line_t *p_index = NULL;
4100 config_line_t *cmdline_only_options = NULL;
4102 /* Go through command-line variables */
4103 if (! have_parsed_cmdline) {
4104 /* Or we could redo the list every time we pass this place.
4105 * It does not really matter */
4106 if (config_parse_commandline(argc, argv, 0, &global_cmdline_options,
4107 &global_cmdline_only_options) < 0) {
4108 goto err;
4110 have_parsed_cmdline = 1;
4112 cmdline_only_options = global_cmdline_only_options;
4114 if (config_line_find(cmdline_only_options, "-h") ||
4115 config_line_find(cmdline_only_options, "--help")) {
4116 print_usage();
4117 exit(0);
4119 if (config_line_find(cmdline_only_options, "--list-torrc-options")) {
4120 /* For documenting validating whether we've documented everything. */
4121 list_torrc_options();
4122 exit(0);
4125 if (config_line_find(cmdline_only_options, "--version")) {
4126 printf("Tor version %s.\n",get_version());
4127 exit(0);
4130 if (config_line_find(cmdline_only_options, "--digests")) {
4131 printf("Tor version %s.\n",get_version());
4132 printf("%s", libor_get_digests());
4133 printf("%s", tor_get_digests());
4134 exit(0);
4137 if (config_line_find(cmdline_only_options, "--library-versions")) {
4138 printf("Tor version %s. \n", get_version());
4139 printf("Library versions\tCompiled\t\tRuntime\n");
4140 printf("Libevent\t\t%-15s\t\t%s\n",
4141 tor_libevent_get_header_version_str(),
4142 tor_libevent_get_version_str());
4143 printf("OpenSSL \t\t%-15s\t\t%s\n",
4144 crypto_openssl_get_header_version_str(),
4145 crypto_openssl_get_version_str());
4146 printf("Zlib \t\t%-15s\t\t%s\n",
4147 tor_zlib_get_header_version_str(),
4148 tor_zlib_get_version_str());
4149 //TODO: Hex versions?
4150 exit(0);
4153 command = CMD_RUN_TOR;
4154 for (p_index = cmdline_only_options; p_index; p_index = p_index->next) {
4155 if (!strcmp(p_index->key,"--list-fingerprint")) {
4156 command = CMD_LIST_FINGERPRINT;
4157 } else if (!strcmp(p_index->key, "--hash-password")) {
4158 command = CMD_HASH_PASSWORD;
4159 command_arg = p_index->value;
4160 } else if (!strcmp(p_index->key, "--dump-config")) {
4161 command = CMD_DUMP_CONFIG;
4162 command_arg = p_index->value;
4163 } else if (!strcmp(p_index->key, "--verify-config")) {
4164 command = CMD_VERIFY_CONFIG;
4168 if (command == CMD_HASH_PASSWORD) {
4169 cf_defaults = tor_strdup("");
4170 cf = tor_strdup("");
4171 } else {
4172 cf_defaults = load_torrc_from_disk(cmdline_only_options, 1);
4173 cf = load_torrc_from_disk(cmdline_only_options, 0);
4174 if (!cf) {
4175 if (config_line_find(cmdline_only_options, "--allow-missing-torrc")) {
4176 cf = tor_strdup("");
4177 } else {
4178 goto err;
4183 retval = options_init_from_string(cf_defaults, cf, command, command_arg,
4184 &errmsg);
4186 err:
4188 tor_free(cf);
4189 tor_free(cf_defaults);
4190 if (errmsg) {
4191 log_warn(LD_CONFIG,"%s", errmsg);
4192 tor_free(errmsg);
4194 return retval < 0 ? -1 : 0;
4197 /** Load the options from the configuration in <b>cf</b>, validate
4198 * them for consistency and take actions based on them.
4200 * Return 0 if success, negative on error:
4201 * * -1 for general errors.
4202 * * -2 for failure to parse/validate,
4203 * * -3 for transition not allowed
4204 * * -4 for error while setting the new options
4206 setopt_err_t
4207 options_init_from_string(const char *cf_defaults, const char *cf,
4208 int command, const char *command_arg,
4209 char **msg)
4211 or_options_t *oldoptions, *newoptions, *newdefaultoptions=NULL;
4212 config_line_t *cl;
4213 int retval, i;
4214 setopt_err_t err = SETOPT_ERR_MISC;
4215 tor_assert(msg);
4217 oldoptions = global_options; /* get_options unfortunately asserts if
4218 this is the first time we run*/
4220 newoptions = tor_malloc_zero(sizeof(or_options_t));
4221 newoptions->magic_ = OR_OPTIONS_MAGIC;
4222 options_init(newoptions);
4223 newoptions->command = command;
4224 newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
4226 for (i = 0; i < 2; ++i) {
4227 const char *body = i==0 ? cf_defaults : cf;
4228 if (!body)
4229 continue;
4230 /* get config lines, assign them */
4231 retval = config_get_lines(body, &cl, 1);
4232 if (retval < 0) {
4233 err = SETOPT_ERR_PARSE;
4234 goto err;
4236 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4237 config_free_lines(cl);
4238 if (retval < 0) {
4239 err = SETOPT_ERR_PARSE;
4240 goto err;
4242 if (i==0)
4243 newdefaultoptions = config_dup(&options_format, newoptions);
4246 if (newdefaultoptions == NULL) {
4247 newdefaultoptions = config_dup(&options_format, global_default_options);
4250 /* Go through command-line variables too */
4251 retval = config_assign(&options_format, newoptions,
4252 global_cmdline_options, 0, 0, msg);
4253 if (retval < 0) {
4254 err = SETOPT_ERR_PARSE;
4255 goto err;
4258 /* If this is a testing network configuration, change defaults
4259 * for a list of dependent config options, re-initialize newoptions
4260 * with the new defaults, and assign all options to it second time. */
4261 if (newoptions->TestingTorNetwork) {
4262 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4263 * this? We could, for example, make the parsing algorithm do two passes
4264 * over the configuration. If it finds any "suite" options like
4265 * TestingTorNetwork, it could change the defaults before its second pass.
4266 * Not urgent so long as this seems to work, but at any sign of trouble,
4267 * let's clean it up. -NM */
4269 /* Change defaults. */
4270 int i;
4271 for (i = 0; testing_tor_network_defaults[i].name; ++i) {
4272 const config_var_t *new_var = &testing_tor_network_defaults[i];
4273 config_var_t *old_var =
4274 config_find_option_mutable(&options_format, new_var->name);
4275 tor_assert(new_var);
4276 tor_assert(old_var);
4277 old_var->initvalue = new_var->initvalue;
4280 /* Clear newoptions and re-initialize them with new defaults. */
4281 config_free(&options_format, newoptions);
4282 config_free(&options_format, newdefaultoptions);
4283 newdefaultoptions = NULL;
4284 newoptions = tor_malloc_zero(sizeof(or_options_t));
4285 newoptions->magic_ = OR_OPTIONS_MAGIC;
4286 options_init(newoptions);
4287 newoptions->command = command;
4288 newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
4290 /* Assign all options a second time. */
4291 for (i = 0; i < 2; ++i) {
4292 const char *body = i==0 ? cf_defaults : cf;
4293 if (!body)
4294 continue;
4295 /* get config lines, assign them */
4296 retval = config_get_lines(body, &cl, 1);
4297 if (retval < 0) {
4298 err = SETOPT_ERR_PARSE;
4299 goto err;
4301 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4302 config_free_lines(cl);
4303 if (retval < 0) {
4304 err = SETOPT_ERR_PARSE;
4305 goto err;
4307 if (i==0)
4308 newdefaultoptions = config_dup(&options_format, newoptions);
4310 /* Assign command-line variables a second time too */
4311 retval = config_assign(&options_format, newoptions,
4312 global_cmdline_options, 0, 0, msg);
4313 if (retval < 0) {
4314 err = SETOPT_ERR_PARSE;
4315 goto err;
4319 /* Validate newoptions */
4320 if (options_validate(oldoptions, newoptions, newdefaultoptions,
4321 0, msg) < 0) {
4322 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
4323 goto err;
4326 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
4327 err = SETOPT_ERR_TRANSITION;
4328 goto err;
4331 if (set_options(newoptions, msg)) {
4332 err = SETOPT_ERR_SETTING;
4333 goto err; /* frees and replaces old options */
4335 config_free(&options_format, global_default_options);
4336 global_default_options = newdefaultoptions;
4338 return SETOPT_OK;
4340 err:
4341 config_free(&options_format, newoptions);
4342 config_free(&options_format, newdefaultoptions);
4343 if (*msg) {
4344 char *old_msg = *msg;
4345 tor_asprintf(msg, "Failed to parse/validate config: %s", old_msg);
4346 tor_free(old_msg);
4348 return err;
4351 /** Return the location for our configuration file.
4353 const char *
4354 get_torrc_fname(int defaults_fname)
4356 const char *fname = defaults_fname ? torrc_defaults_fname : torrc_fname;
4358 if (fname)
4359 return fname;
4360 else
4361 return get_default_conf_file(defaults_fname);
4364 /** Adjust the address map based on the MapAddress elements in the
4365 * configuration <b>options</b>
4367 void
4368 config_register_addressmaps(const or_options_t *options)
4370 smartlist_t *elts;
4371 config_line_t *opt;
4372 const char *from, *to, *msg;
4374 addressmap_clear_configured();
4375 elts = smartlist_new();
4376 for (opt = options->AddressMap; opt; opt = opt->next) {
4377 smartlist_split_string(elts, opt->value, NULL,
4378 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4379 if (smartlist_len(elts) < 2) {
4380 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
4381 opt->value);
4382 goto cleanup;
4385 from = smartlist_get(elts,0);
4386 to = smartlist_get(elts,1);
4388 if (to[0] == '.' || from[0] == '.') {
4389 log_warn(LD_CONFIG,"MapAddress '%s' is ambiguous - address starts with a"
4390 "'.'. Ignoring.",opt->value);
4391 goto cleanup;
4394 if (addressmap_register_auto(from, to, 0, ADDRMAPSRC_TORRC, &msg) < 0) {
4395 log_warn(LD_CONFIG,"MapAddress '%s' failed: %s. Ignoring.", opt->value,
4396 msg);
4397 goto cleanup;
4400 if (smartlist_len(elts) > 2)
4401 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
4403 cleanup:
4404 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4405 smartlist_clear(elts);
4407 smartlist_free(elts);
4410 /** As addressmap_register(), but detect the wildcarded status of "from" and
4411 * "to", and do not steal a reference to <b>to</b>. */
4412 /* XXXX024 move to connection_edge.c */
4414 addressmap_register_auto(const char *from, const char *to,
4415 time_t expires,
4416 addressmap_entry_source_t addrmap_source,
4417 const char **msg)
4419 int from_wildcard = 0, to_wildcard = 0;
4421 *msg = "whoops, forgot the error message";
4422 if (1) {
4423 if (!strcmp(to, "*") || !strcmp(from, "*")) {
4424 *msg = "can't remap from or to *";
4425 return -1;
4427 /* Detect asterisks in expressions of type: '*.example.com' */
4428 if (!strncmp(from,"*.",2)) {
4429 from += 2;
4430 from_wildcard = 1;
4432 if (!strncmp(to,"*.",2)) {
4433 to += 2;
4434 to_wildcard = 1;
4437 if (to_wildcard && !from_wildcard) {
4438 *msg = "can only use wildcard (i.e. '*.') if 'from' address "
4439 "uses wildcard also";
4440 return -1;
4443 if (address_is_invalid_destination(to, 1)) {
4444 *msg = "destination is invalid";
4445 return -1;
4448 addressmap_register(from, tor_strdup(to), expires, addrmap_source,
4449 from_wildcard, to_wildcard);
4451 return 0;
4455 * Initialize the logs based on the configuration file.
4457 static int
4458 options_init_logs(or_options_t *options, int validate_only)
4460 config_line_t *opt;
4461 int ok;
4462 smartlist_t *elts;
4463 int daemon =
4464 #ifdef _WIN32
4466 #else
4467 options->RunAsDaemon;
4468 #endif
4470 if (options->LogTimeGranularity <= 0) {
4471 log_warn(LD_CONFIG, "Log time granularity '%d' has to be positive.",
4472 options->LogTimeGranularity);
4473 return -1;
4474 } else if (1000 % options->LogTimeGranularity != 0 &&
4475 options->LogTimeGranularity % 1000 != 0) {
4476 int granularity = options->LogTimeGranularity;
4477 if (granularity < 40) {
4478 do granularity++;
4479 while (1000 % granularity != 0);
4480 } else if (granularity < 1000) {
4481 granularity = 1000 / granularity;
4482 while (1000 % granularity != 0)
4483 granularity--;
4484 granularity = 1000 / granularity;
4485 } else {
4486 granularity = 1000 * ((granularity / 1000) + 1);
4488 log_warn(LD_CONFIG, "Log time granularity '%d' has to be either a "
4489 "divisor or a multiple of 1 second. Changing to "
4490 "'%d'.",
4491 options->LogTimeGranularity, granularity);
4492 if (!validate_only)
4493 set_log_time_granularity(granularity);
4494 } else {
4495 if (!validate_only)
4496 set_log_time_granularity(options->LogTimeGranularity);
4499 ok = 1;
4500 elts = smartlist_new();
4502 for (opt = options->Logs; opt; opt = opt->next) {
4503 log_severity_list_t *severity;
4504 const char *cfg = opt->value;
4505 severity = tor_malloc_zero(sizeof(log_severity_list_t));
4506 if (parse_log_severity_config(&cfg, severity) < 0) {
4507 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
4508 opt->value);
4509 ok = 0; goto cleanup;
4512 smartlist_split_string(elts, cfg, NULL,
4513 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4515 if (smartlist_len(elts) == 0)
4516 smartlist_add(elts, tor_strdup("stdout"));
4518 if (smartlist_len(elts) == 1 &&
4519 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
4520 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
4521 int err = smartlist_len(elts) &&
4522 !strcasecmp(smartlist_get(elts,0), "stderr");
4523 if (!validate_only) {
4524 if (daemon) {
4525 log_warn(LD_CONFIG,
4526 "Can't log to %s with RunAsDaemon set; skipping stdout",
4527 err?"stderr":"stdout");
4528 } else {
4529 add_stream_log(severity, err?"<stderr>":"<stdout>",
4530 fileno(err?stderr:stdout));
4533 goto cleanup;
4535 if (smartlist_len(elts) == 1 &&
4536 !strcasecmp(smartlist_get(elts,0), "syslog")) {
4537 #ifdef HAVE_SYSLOG_H
4538 if (!validate_only) {
4539 add_syslog_log(severity);
4541 #else
4542 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
4543 #endif
4544 goto cleanup;
4547 if (smartlist_len(elts) == 2 &&
4548 !strcasecmp(smartlist_get(elts,0), "file")) {
4549 if (!validate_only) {
4550 char *fname = expand_filename(smartlist_get(elts, 1));
4551 if (add_file_log(severity, fname) < 0) {
4552 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
4553 opt->value, strerror(errno));
4554 ok = 0;
4556 tor_free(fname);
4558 goto cleanup;
4561 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
4562 opt->value);
4563 ok = 0; goto cleanup;
4565 cleanup:
4566 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4567 smartlist_clear(elts);
4568 tor_free(severity);
4570 smartlist_free(elts);
4572 if (ok && !validate_only)
4573 logs_set_domain_logging(options->LogMessageDomains);
4575 return ok?0:-1;
4578 /** Given a smartlist of SOCKS arguments to be passed to a transport
4579 * proxy in <b>args</b>, validate them and return -1 if they are
4580 * corrupted. Return 0 if they seem OK. */
4581 static int
4582 validate_transport_socks_arguments(const smartlist_t *args)
4584 char *socks_string = NULL;
4585 size_t socks_string_len;
4587 tor_assert(args);
4588 tor_assert(smartlist_len(args) > 0);
4590 SMARTLIST_FOREACH_BEGIN(args, const char *, s) {
4591 if (!string_is_key_value(LOG_WARN, s)) { /* items should be k=v items */
4592 log_warn(LD_CONFIG, "'%s' is not a k=v item.", s);
4593 return -1;
4595 } SMARTLIST_FOREACH_END(s);
4597 socks_string = pt_stringify_socks_args(args);
4598 if (!socks_string)
4599 return -1;
4601 socks_string_len = strlen(socks_string);
4602 tor_free(socks_string);
4604 if (socks_string_len > MAX_SOCKS5_AUTH_SIZE_TOTAL) {
4605 log_warn(LD_CONFIG, "SOCKS arguments can't be more than %u bytes (%lu).",
4606 MAX_SOCKS5_AUTH_SIZE_TOTAL,
4607 (unsigned long) socks_string_len);
4608 return -1;
4611 return 0;
4614 /** Deallocate a bridge_line_t structure. */
4615 /* private */ void
4616 bridge_line_free(bridge_line_t *bridge_line)
4618 if (!bridge_line)
4619 return;
4621 if (bridge_line->socks_args) {
4622 SMARTLIST_FOREACH(bridge_line->socks_args, char*, s, tor_free(s));
4623 smartlist_free(bridge_line->socks_args);
4625 tor_free(bridge_line->transport_name);
4626 tor_free(bridge_line);
4629 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4630 * if the line is well-formed, and -1 if it isn't. If
4631 * <b>validate_only</b> is 0, and the line is well-formed, then add
4632 * the bridge described in the line to our internal bridge list.
4634 * Bridge line format:
4635 * Bridge [transport] IP:PORT [id-fingerprint] [k=v] [k=v] ...
4637 /* private */ bridge_line_t *
4638 parse_bridge_line(const char *line)
4640 smartlist_t *items = NULL;
4641 char *addrport=NULL, *fingerprint=NULL;
4642 char *field=NULL;
4643 bridge_line_t *bridge_line = tor_malloc_zero(sizeof(bridge_line_t));
4645 items = smartlist_new();
4646 smartlist_split_string(items, line, NULL,
4647 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4648 if (smartlist_len(items) < 1) {
4649 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
4650 goto err;
4653 /* first field is either a transport name or addrport */
4654 field = smartlist_get(items, 0);
4655 smartlist_del_keeporder(items, 0);
4657 if (string_is_C_identifier(field)) {
4658 /* It's a transport name. */
4659 bridge_line->transport_name = field;
4660 if (smartlist_len(items) < 1) {
4661 log_warn(LD_CONFIG, "Too few items to Bridge line.");
4662 goto err;
4664 addrport = smartlist_get(items, 0); /* Next field is addrport then. */
4665 smartlist_del_keeporder(items, 0);
4666 } else {
4667 addrport = field;
4670 if (tor_addr_port_parse(LOG_INFO, addrport,
4671 &bridge_line->addr, &bridge_line->port, 443)<0) {
4672 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
4673 goto err;
4676 /* If transports are enabled, next field could be a fingerprint or a
4677 socks argument. If transports are disabled, next field must be
4678 a fingerprint. */
4679 if (smartlist_len(items)) {
4680 if (bridge_line->transport_name) { /* transports enabled: */
4681 field = smartlist_get(items, 0);
4682 smartlist_del_keeporder(items, 0);
4684 /* If it's a key=value pair, then it's a SOCKS argument for the
4685 transport proxy... */
4686 if (string_is_key_value(LOG_DEBUG, field)) {
4687 bridge_line->socks_args = smartlist_new();
4688 smartlist_add(bridge_line->socks_args, field);
4689 } else { /* ...otherwise, it's the bridge fingerprint. */
4690 fingerprint = field;
4693 } else { /* transports disabled: */
4694 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4698 /* Handle fingerprint, if it was provided. */
4699 if (fingerprint) {
4700 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4701 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
4702 goto err;
4704 if (base16_decode(bridge_line->digest, DIGEST_LEN,
4705 fingerprint, HEX_DIGEST_LEN)<0) {
4706 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
4707 goto err;
4711 /* If we are using transports, any remaining items in the smartlist
4712 should be k=v values. */
4713 if (bridge_line->transport_name && smartlist_len(items)) {
4714 if (!bridge_line->socks_args)
4715 bridge_line->socks_args = smartlist_new();
4717 /* append remaining items of 'items' to 'socks_args' */
4718 smartlist_add_all(bridge_line->socks_args, items);
4719 smartlist_clear(items);
4721 tor_assert(smartlist_len(bridge_line->socks_args) > 0);
4724 if (bridge_line->socks_args) {
4725 if (validate_transport_socks_arguments(bridge_line->socks_args) < 0)
4726 goto err;
4729 goto done;
4731 err:
4732 bridge_line_free(bridge_line);
4733 bridge_line = NULL;
4735 done:
4736 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4737 smartlist_free(items);
4738 tor_free(addrport);
4739 tor_free(fingerprint);
4741 return bridge_line;
4744 /** Read the contents of a ClientTransportPlugin line from
4745 * <b>line</b>. Return 0 if the line is well-formed, and -1 if it
4746 * isn't.
4748 * If <b>validate_only</b> is 0, the line is well-formed, and the
4749 * transport is needed by some bridge:
4750 * - If it's an external proxy line, add the transport described in the line to
4751 * our internal transport list.
4752 * - If it's a managed proxy line, launch the managed proxy. */
4753 static int
4754 parse_client_transport_line(const or_options_t *options,
4755 const char *line, int validate_only)
4757 smartlist_t *items = NULL;
4758 int r;
4759 char *field2=NULL;
4761 const char *transports=NULL;
4762 smartlist_t *transport_list=NULL;
4763 char *addrport=NULL;
4764 tor_addr_t addr;
4765 uint16_t port = 0;
4766 int socks_ver=PROXY_NONE;
4768 /* managed proxy options */
4769 int is_managed=0;
4770 char **proxy_argv=NULL;
4771 char **tmp=NULL;
4772 int proxy_argc, i;
4773 int is_useless_proxy=1;
4775 int line_length;
4777 items = smartlist_new();
4778 smartlist_split_string(items, line, NULL,
4779 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4781 line_length = smartlist_len(items);
4782 if (line_length < 3) {
4783 log_warn(LD_CONFIG, "Too few arguments on ClientTransportPlugin line.");
4784 goto err;
4787 /* Get the first line element, split it to commas into
4788 transport_list (in case it's multiple transports) and validate
4789 the transport names. */
4790 transports = smartlist_get(items, 0);
4791 transport_list = smartlist_new();
4792 smartlist_split_string(transport_list, transports, ",",
4793 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
4794 SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
4795 /* validate transport names */
4796 if (!string_is_C_identifier(transport_name)) {
4797 log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
4798 transport_name);
4799 goto err;
4802 /* see if we actually need the transports provided by this proxy */
4803 if (!validate_only && transport_is_needed(transport_name))
4804 is_useless_proxy = 0;
4805 } SMARTLIST_FOREACH_END(transport_name);
4807 /* field2 is either a SOCKS version or "exec" */
4808 field2 = smartlist_get(items, 1);
4810 if (!strcmp(field2,"socks4")) {
4811 socks_ver = PROXY_SOCKS4;
4812 } else if (!strcmp(field2,"socks5")) {
4813 socks_ver = PROXY_SOCKS5;
4814 } else if (!strcmp(field2,"exec")) {
4815 is_managed=1;
4816 } else {
4817 log_warn(LD_CONFIG, "Strange ClientTransportPlugin field '%s'.",
4818 field2);
4819 goto err;
4822 if (is_managed && options->Sandbox) {
4823 log_warn(LD_CONFIG, "Managed proxies are not compatible with Sandbox mode."
4824 "(ClientTransportPlugin line was %s)", escaped(line));
4825 goto err;
4828 if (is_managed) { /* managed */
4829 if (!validate_only && is_useless_proxy) {
4830 log_info(LD_GENERAL, "Pluggable transport proxy (%s) does not provide "
4831 "any needed transports and will not be launched.", line);
4834 /* If we are not just validating, use the rest of the line as the
4835 argv of the proxy to be launched. Also, make sure that we are
4836 only launching proxies that contribute useful transports. */
4837 if (!validate_only && !is_useless_proxy) {
4838 proxy_argc = line_length-2;
4839 tor_assert(proxy_argc > 0);
4840 proxy_argv = tor_malloc_zero(sizeof(char*)*(proxy_argc+1));
4841 tmp = proxy_argv;
4842 for (i=0;i<proxy_argc;i++) { /* store arguments */
4843 *tmp++ = smartlist_get(items, 2);
4844 smartlist_del_keeporder(items, 2);
4846 *tmp = NULL; /*terminated with NULL, just like execve() likes it*/
4848 /* kickstart the thing */
4849 pt_kickstart_client_proxy(transport_list, proxy_argv);
4851 } else { /* external */
4852 if (smartlist_len(transport_list) != 1) {
4853 log_warn(LD_CONFIG, "You can't have an external proxy with "
4854 "more than one transports.");
4855 goto err;
4858 addrport = smartlist_get(items, 2);
4860 if (tor_addr_port_lookup(addrport, &addr, &port)<0) {
4861 log_warn(LD_CONFIG, "Error parsing transport "
4862 "address '%s'", addrport);
4863 goto err;
4865 if (!port) {
4866 log_warn(LD_CONFIG,
4867 "Transport address '%s' has no port.", addrport);
4868 goto err;
4871 if (!validate_only) {
4872 transport_add_from_config(&addr, port, smartlist_get(transport_list, 0),
4873 socks_ver);
4875 log_info(LD_DIR, "Transport '%s' found at %s",
4876 transports, fmt_addrport(&addr, port));
4880 r = 0;
4881 goto done;
4883 err:
4884 r = -1;
4886 done:
4887 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4888 smartlist_free(items);
4889 if (transport_list) {
4890 SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
4891 smartlist_free(transport_list);
4894 return r;
4897 /** Given a ServerTransportListenAddr <b>line</b>, return its
4898 * <address:port> string. Return NULL if the line was not
4899 * well-formed.
4901 * If <b>transport</b> is set, return NULL if the line is not
4902 * referring to <b>transport</b>.
4904 * The returned string is allocated on the heap and it's the
4905 * responsibility of the caller to free it. */
4906 static char *
4907 get_bindaddr_from_transport_listen_line(const char *line,const char *transport)
4909 smartlist_t *items = NULL;
4910 const char *parsed_transport = NULL;
4911 char *addrport = NULL;
4912 tor_addr_t addr;
4913 uint16_t port = 0;
4915 items = smartlist_new();
4916 smartlist_split_string(items, line, NULL,
4917 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4919 if (smartlist_len(items) < 2) {
4920 log_warn(LD_CONFIG,"Too few arguments on ServerTransportListenAddr line.");
4921 goto err;
4924 parsed_transport = smartlist_get(items, 0);
4925 addrport = tor_strdup(smartlist_get(items, 1));
4927 /* If 'transport' is given, check if it matches the one on the line */
4928 if (transport && strcmp(transport, parsed_transport))
4929 goto err;
4931 /* Validate addrport */
4932 if (tor_addr_port_parse(LOG_WARN, addrport, &addr, &port, -1)<0) {
4933 log_warn(LD_CONFIG, "Error parsing ServerTransportListenAddr "
4934 "address '%s'", addrport);
4935 goto err;
4938 goto done;
4940 err:
4941 tor_free(addrport);
4942 addrport = NULL;
4944 done:
4945 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4946 smartlist_free(items);
4948 return addrport;
4951 /** Given a ServerTransportOptions <b>line</b>, return a smartlist
4952 * with the options. Return NULL if the line was not well-formed.
4954 * If <b>transport</b> is set, return NULL if the line is not
4955 * referring to <b>transport</b>.
4957 * The returned smartlist and its strings are allocated on the heap
4958 * and it's the responsibility of the caller to free it. */
4959 smartlist_t *
4960 get_options_from_transport_options_line(const char *line,const char *transport)
4962 smartlist_t *items = smartlist_new();
4963 smartlist_t *options = smartlist_new();
4964 const char *parsed_transport = NULL;
4966 smartlist_split_string(items, line, NULL,
4967 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4969 if (smartlist_len(items) < 2) {
4970 log_warn(LD_CONFIG,"Too few arguments on ServerTransportOptions line.");
4971 goto err;
4974 parsed_transport = smartlist_get(items, 0);
4975 /* If 'transport' is given, check if it matches the one on the line */
4976 if (transport && strcmp(transport, parsed_transport))
4977 goto err;
4979 SMARTLIST_FOREACH_BEGIN(items, const char *, option) {
4980 if (option_sl_idx == 0) /* skip the transport field (first field)*/
4981 continue;
4983 /* validate that it's a k=v value */
4984 if (!string_is_key_value(LOG_WARN, option)) {
4985 log_warn(LD_CONFIG, "%s is not a k=v value.", escaped(option));
4986 goto err;
4989 /* add it to the options smartlist */
4990 smartlist_add(options, tor_strdup(option));
4991 log_debug(LD_CONFIG, "Added %s to the list of options", escaped(option));
4992 } SMARTLIST_FOREACH_END(option);
4994 goto done;
4996 err:
4997 SMARTLIST_FOREACH(options, char*, s, tor_free(s));
4998 smartlist_free(options);
4999 options = NULL;
5001 done:
5002 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5003 smartlist_free(items);
5005 return options;
5008 /** Given the name of a pluggable transport in <b>transport</b>, check
5009 * the configuration file to see if the user has explicitly asked for
5010 * it to listen on a specific port. Return a <address:port> string if
5011 * so, otherwise NULL. */
5012 char *
5013 get_transport_bindaddr_from_config(const char *transport)
5015 config_line_t *cl;
5016 const or_options_t *options = get_options();
5018 for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
5019 char *bindaddr =
5020 get_bindaddr_from_transport_listen_line(cl->value, transport);
5021 if (bindaddr)
5022 return bindaddr;
5025 return NULL;
5028 /** Given the name of a pluggable transport in <b>transport</b>, check
5029 * the configuration file to see if the user has asked us to pass any
5030 * parameters to the pluggable transport. Return a smartlist
5031 * containing the parameters, otherwise NULL. */
5032 smartlist_t *
5033 get_options_for_server_transport(const char *transport)
5035 config_line_t *cl;
5036 const or_options_t *options = get_options();
5038 for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
5039 smartlist_t *options_sl =
5040 get_options_from_transport_options_line(cl->value, transport);
5041 if (options_sl)
5042 return options_sl;
5045 return NULL;
5048 /** Read the contents of a ServerTransportPlugin line from
5049 * <b>line</b>. Return 0 if the line is well-formed, and -1 if it
5050 * isn't.
5051 * If <b>validate_only</b> is 0, the line is well-formed, and it's a
5052 * managed proxy line, launch the managed proxy. */
5053 static int
5054 parse_server_transport_line(const or_options_t *options,
5055 const char *line, int validate_only)
5057 smartlist_t *items = NULL;
5058 int r;
5059 const char *transports=NULL;
5060 smartlist_t *transport_list=NULL;
5061 char *type=NULL;
5062 char *addrport=NULL;
5063 tor_addr_t addr;
5064 uint16_t port = 0;
5066 /* managed proxy options */
5067 int is_managed=0;
5068 char **proxy_argv=NULL;
5069 char **tmp=NULL;
5070 int proxy_argc,i;
5072 int line_length;
5074 items = smartlist_new();
5075 smartlist_split_string(items, line, NULL,
5076 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5078 line_length = smartlist_len(items);
5079 if (line_length < 3) {
5080 log_warn(LD_CONFIG, "Too few arguments on ServerTransportPlugin line.");
5081 goto err;
5084 /* Get the first line element, split it to commas into
5085 transport_list (in case it's multiple transports) and validate
5086 the transport names. */
5087 transports = smartlist_get(items, 0);
5088 transport_list = smartlist_new();
5089 smartlist_split_string(transport_list, transports, ",",
5090 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
5091 SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
5092 if (!string_is_C_identifier(transport_name)) {
5093 log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
5094 transport_name);
5095 goto err;
5097 } SMARTLIST_FOREACH_END(transport_name);
5099 type = smartlist_get(items, 1);
5101 if (!strcmp(type, "exec")) {
5102 is_managed=1;
5103 } else if (!strcmp(type, "proxy")) {
5104 is_managed=0;
5105 } else {
5106 log_warn(LD_CONFIG, "Strange ServerTransportPlugin type '%s'", type);
5107 goto err;
5110 if (is_managed && options->Sandbox) {
5111 log_warn(LD_CONFIG, "Managed proxies are not compatible with Sandbox mode."
5112 "(ServerTransportPlugin line was %s)", escaped(line));
5113 goto err;
5116 if (is_managed) { /* managed */
5117 if (!validate_only) {
5118 proxy_argc = line_length-2;
5119 tor_assert(proxy_argc > 0);
5120 proxy_argv = tor_malloc_zero(sizeof(char*)*(proxy_argc+1));
5121 tmp = proxy_argv;
5123 for (i=0;i<proxy_argc;i++) { /* store arguments */
5124 *tmp++ = smartlist_get(items, 2);
5125 smartlist_del_keeporder(items, 2);
5127 *tmp = NULL; /*terminated with NULL, just like execve() likes it*/
5129 /* kickstart the thing */
5130 pt_kickstart_server_proxy(transport_list, proxy_argv);
5132 } else { /* external */
5133 if (smartlist_len(transport_list) != 1) {
5134 log_warn(LD_CONFIG, "You can't have an external proxy with "
5135 "more than one transports.");
5136 goto err;
5139 addrport = smartlist_get(items, 2);
5141 if (tor_addr_port_lookup(addrport, &addr, &port)<0) {
5142 log_warn(LD_CONFIG, "Error parsing transport "
5143 "address '%s'", addrport);
5144 goto err;
5146 if (!port) {
5147 log_warn(LD_CONFIG,
5148 "Transport address '%s' has no port.", addrport);
5149 goto err;
5152 if (!validate_only) {
5153 log_info(LD_DIR, "Server transport '%s' at %s.",
5154 transports, fmt_addrport(&addr, port));
5158 r = 0;
5159 goto done;
5161 err:
5162 r = -1;
5164 done:
5165 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5166 smartlist_free(items);
5167 if (transport_list) {
5168 SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
5169 smartlist_free(transport_list);
5172 return r;
5175 /** Read the contents of a DirAuthority line from <b>line</b>. If
5176 * <b>validate_only</b> is 0, and the line is well-formed, and it
5177 * shares any bits with <b>required_type</b> or <b>required_type</b>
5178 * is 0, then add the dirserver described in the line (minus whatever
5179 * bits it's missing) as a valid authority. Return 0 on success,
5180 * or -1 if the line isn't well-formed or if we can't add it. */
5181 static int
5182 parse_dir_authority_line(const char *line, dirinfo_type_t required_type,
5183 int validate_only)
5185 smartlist_t *items = NULL;
5186 int r;
5187 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
5188 uint16_t dir_port = 0, or_port = 0;
5189 char digest[DIGEST_LEN];
5190 char v3_digest[DIGEST_LEN];
5191 dirinfo_type_t type = 0;
5192 double weight = 1.0;
5194 items = smartlist_new();
5195 smartlist_split_string(items, line, NULL,
5196 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5197 if (smartlist_len(items) < 1) {
5198 log_warn(LD_CONFIG, "No arguments on DirAuthority line.");
5199 goto err;
5202 if (is_legal_nickname(smartlist_get(items, 0))) {
5203 nickname = smartlist_get(items, 0);
5204 smartlist_del_keeporder(items, 0);
5207 while (smartlist_len(items)) {
5208 char *flag = smartlist_get(items, 0);
5209 if (TOR_ISDIGIT(flag[0]))
5210 break;
5211 if (!strcasecmp(flag, "hs") ||
5212 !strcasecmp(flag, "no-hs")) {
5213 log_warn(LD_CONFIG, "The DirAuthority options 'hs' and 'no-hs' are "
5214 "obsolete; you don't need them any more.");
5215 } else if (!strcasecmp(flag, "bridge")) {
5216 type |= BRIDGE_DIRINFO;
5217 } else if (!strcasecmp(flag, "no-v2")) {
5218 /* obsolete, but may still be contained in DirAuthority lines generated
5219 by various tools */;
5220 } else if (!strcasecmpstart(flag, "orport=")) {
5221 int ok;
5222 char *portstring = flag + strlen("orport=");
5223 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
5224 if (!ok)
5225 log_warn(LD_CONFIG, "Invalid orport '%s' on DirAuthority line.",
5226 portstring);
5227 } else if (!strcmpstart(flag, "weight=")) {
5228 int ok;
5229 const char *wstring = flag + strlen("weight=");
5230 weight = tor_parse_double(wstring, 0, UINT64_MAX, &ok, NULL);
5231 if (!ok) {
5232 log_warn(LD_CONFIG, "Invalid weight '%s' on DirAuthority line.",flag);
5233 weight=1.0;
5235 } else if (!strcasecmpstart(flag, "v3ident=")) {
5236 char *idstr = flag + strlen("v3ident=");
5237 if (strlen(idstr) != HEX_DIGEST_LEN ||
5238 base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
5239 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirAuthority line",
5240 flag);
5241 } else {
5242 type |= V3_DIRINFO|EXTRAINFO_DIRINFO|MICRODESC_DIRINFO;
5244 } else {
5245 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirAuthority line",
5246 flag);
5248 tor_free(flag);
5249 smartlist_del_keeporder(items, 0);
5252 if (smartlist_len(items) < 2) {
5253 log_warn(LD_CONFIG, "Too few arguments to DirAuthority line.");
5254 goto err;
5256 addrport = smartlist_get(items, 0);
5257 smartlist_del_keeporder(items, 0);
5258 if (addr_port_lookup(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
5259 log_warn(LD_CONFIG, "Error parsing DirAuthority address '%s'", addrport);
5260 goto err;
5262 if (!dir_port) {
5263 log_warn(LD_CONFIG, "Missing port in DirAuthority address '%s'",addrport);
5264 goto err;
5267 fingerprint = smartlist_join_strings(items, "", 0, NULL);
5268 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
5269 log_warn(LD_CONFIG, "Key digest '%s' for DirAuthority is wrong length %d.",
5270 fingerprint, (int)strlen(fingerprint));
5271 goto err;
5273 if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
5274 /* a known bad fingerprint. refuse to use it. We can remove this
5275 * clause once Tor 0.1.2.17 is obsolete. */
5276 log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
5277 "torrc file (%s), or reinstall Tor and use the default torrc.",
5278 get_torrc_fname(0));
5279 goto err;
5281 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
5282 log_warn(LD_CONFIG, "Unable to decode DirAuthority key digest.");
5283 goto err;
5286 if (!validate_only && (!required_type || required_type & type)) {
5287 dir_server_t *ds;
5288 if (required_type)
5289 type &= required_type; /* pare down what we think of them as an
5290 * authority for. */
5291 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
5292 address, (int)dir_port, (char*)smartlist_get(items,0));
5293 if (!(ds = trusted_dir_server_new(nickname, address, dir_port, or_port,
5294 digest, v3_digest, type, weight)))
5295 goto err;
5296 dir_server_add(ds);
5299 r = 0;
5300 goto done;
5302 err:
5303 r = -1;
5305 done:
5306 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5307 smartlist_free(items);
5308 tor_free(addrport);
5309 tor_free(address);
5310 tor_free(nickname);
5311 tor_free(fingerprint);
5312 return r;
5315 /** Read the contents of a FallbackDir line from <b>line</b>. If
5316 * <b>validate_only</b> is 0, and the line is well-formed, then add the
5317 * dirserver described in the line as a fallback directory. Return 0 on
5318 * success, or -1 if the line isn't well-formed or if we can't add it. */
5319 static int
5320 parse_dir_fallback_line(const char *line,
5321 int validate_only)
5323 int r = -1;
5324 smartlist_t *items = smartlist_new(), *positional = smartlist_new();
5325 int orport = -1;
5326 uint16_t dirport;
5327 tor_addr_t addr;
5328 int ok;
5329 char id[DIGEST_LEN];
5330 char *address=NULL;
5331 double weight=1.0;
5333 memset(id, 0, sizeof(id));
5334 smartlist_split_string(items, line, NULL,
5335 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5336 SMARTLIST_FOREACH_BEGIN(items, const char *, cp) {
5337 const char *eq = strchr(cp, '=');
5338 ok = 1;
5339 if (! eq) {
5340 smartlist_add(positional, (char*)cp);
5341 continue;
5343 if (!strcmpstart(cp, "orport=")) {
5344 orport = (int)tor_parse_long(cp+strlen("orport="), 10,
5345 1, 65535, &ok, NULL);
5346 } else if (!strcmpstart(cp, "id=")) {
5347 ok = !base16_decode(id, DIGEST_LEN,
5348 cp+strlen("id="), strlen(cp)-strlen("id="));
5349 } else if (!strcmpstart(cp, "weight=")) {
5350 int ok;
5351 const char *wstring = cp + strlen("weight=");
5352 weight = tor_parse_double(wstring, 0, UINT64_MAX, &ok, NULL);
5353 if (!ok) {
5354 log_warn(LD_CONFIG, "Invalid weight '%s' on FallbackDir line.", cp);
5355 weight=1.0;
5359 if (!ok) {
5360 log_warn(LD_CONFIG, "Bad FallbackDir option %s", escaped(cp));
5361 goto end;
5363 } SMARTLIST_FOREACH_END(cp);
5365 if (smartlist_len(positional) != 1) {
5366 log_warn(LD_CONFIG, "Couldn't parse FallbackDir line %s", escaped(line));
5367 goto end;
5370 if (tor_digest_is_zero(id)) {
5371 log_warn(LD_CONFIG, "Missing identity on FallbackDir line");
5372 goto end;
5375 if (orport <= 0) {
5376 log_warn(LD_CONFIG, "Missing orport on FallbackDir line");
5377 goto end;
5380 if (tor_addr_port_split(LOG_INFO, smartlist_get(positional, 0),
5381 &address, &dirport) < 0 ||
5382 tor_addr_parse(&addr, address)<0) {
5383 log_warn(LD_CONFIG, "Couldn't parse address:port %s on FallbackDir line",
5384 (const char*)smartlist_get(positional, 0));
5385 goto end;
5388 if (!validate_only) {
5389 dir_server_t *ds;
5390 ds = fallback_dir_server_new(&addr, dirport, orport, id, weight);
5391 if (!ds) {
5392 log_warn(LD_CONFIG, "Couldn't create FallbackDir %s", escaped(line));
5393 goto end;
5395 dir_server_add(ds);
5398 r = 0;
5400 end:
5401 SMARTLIST_FOREACH(items, char *, cp, tor_free(cp));
5402 smartlist_free(items);
5403 smartlist_free(positional);
5404 tor_free(address);
5405 return r;
5408 /** Allocate and return a new port_cfg_t with reasonable defaults. */
5409 static port_cfg_t *
5410 port_cfg_new(void)
5412 port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t));
5413 cfg->ipv4_traffic = 1;
5414 cfg->cache_ipv4_answers = 1;
5415 cfg->prefer_ipv6_virtaddr = 1;
5416 return cfg;
5419 /** Free all storage held in <b>port</b> */
5420 static void
5421 port_cfg_free(port_cfg_t *port)
5423 tor_free(port);
5426 /** Warn for every port in <b>ports</b> of type <b>listener_type</b> that is
5427 * on a publicly routable address. */
5428 static void
5429 warn_nonlocal_client_ports(const smartlist_t *ports, const char *portname,
5430 int listener_type)
5432 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
5433 if (port->type != listener_type)
5434 continue;
5435 if (port->is_unix_addr) {
5436 /* Unix sockets aren't accessible over a network. */
5437 } else if (!tor_addr_is_internal(&port->addr, 1)) {
5438 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
5439 "Other people on the Internet might find your computer and "
5440 "use it as an open proxy. Please don't allow this unless you "
5441 "have a good reason.",
5442 fmt_addrport(&port->addr, port->port), portname);
5443 } else if (!tor_addr_is_loopback(&port->addr)) {
5444 log_notice(LD_CONFIG, "You configured a non-loopback address '%s' "
5445 "for %sPort. This allows everybody on your local network to "
5446 "use your machine as a proxy. Make sure this is what you "
5447 "wanted.",
5448 fmt_addrport(&port->addr, port->port), portname);
5450 } SMARTLIST_FOREACH_END(port);
5453 /** Warn for every Extended ORPort port in <b>ports</b> that is on a
5454 * publicly routable address. */
5455 static void
5456 warn_nonlocal_ext_orports(const smartlist_t *ports, const char *portname)
5458 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
5459 if (port->type != CONN_TYPE_EXT_OR_LISTENER)
5460 continue;
5461 if (port->is_unix_addr)
5462 continue;
5463 /* XXX maybe warn even if address is RFC1918? */
5464 if (!tor_addr_is_internal(&port->addr, 1)) {
5465 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
5466 "This is not advised; this address is supposed to only be "
5467 "exposed on localhost so that your pluggable transport "
5468 "proxies can connect to it.",
5469 fmt_addrport(&port->addr, port->port), portname);
5471 } SMARTLIST_FOREACH_END(port);
5474 /** Given a list of port_cfg_t in <b>ports</b>, warn any controller port there
5475 * is listening on any non-loopback address. If <b>forbid</b> is true,
5476 * then emit a stronger warning and remove the port from the list.
5478 static void
5479 warn_nonlocal_controller_ports(smartlist_t *ports, unsigned forbid)
5481 int warned = 0;
5482 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
5483 if (port->type != CONN_TYPE_CONTROL_LISTENER)
5484 continue;
5485 if (port->is_unix_addr)
5486 continue;
5487 if (!tor_addr_is_loopback(&port->addr)) {
5488 if (forbid) {
5489 if (!warned)
5490 log_warn(LD_CONFIG,
5491 "You have a ControlPort set to accept "
5492 "unauthenticated connections from a non-local address. "
5493 "This means that programs not running on your computer "
5494 "can reconfigure your Tor, without even having to guess a "
5495 "password. That's so bad that I'm closing your ControlPort "
5496 "for you. If you need to control your Tor remotely, try "
5497 "enabling authentication and using a tool like stunnel or "
5498 "ssh to encrypt remote access.");
5499 warned = 1;
5500 port_cfg_free(port);
5501 SMARTLIST_DEL_CURRENT(ports, port);
5502 } else {
5503 log_warn(LD_CONFIG, "You have a ControlPort set to accept "
5504 "connections from a non-local address. This means that "
5505 "programs not running on your computer can reconfigure your "
5506 "Tor. That's pretty bad, since the controller "
5507 "protocol isn't encrypted! Maybe you should just listen on "
5508 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
5509 "remote connections to your control port.");
5510 return; /* No point in checking the rest */
5513 } SMARTLIST_FOREACH_END(port);
5516 #define CL_PORT_NO_OPTIONS (1u<<0)
5517 #define CL_PORT_WARN_NONLOCAL (1u<<1)
5518 #define CL_PORT_ALLOW_EXTRA_LISTENADDR (1u<<2)
5519 #define CL_PORT_SERVER_OPTIONS (1u<<3)
5520 #define CL_PORT_FORBID_NONLOCAL (1u<<4)
5521 #define CL_PORT_TAKES_HOSTNAMES (1u<<5)
5524 * Parse port configuration for a single port type.
5526 * Read entries of the "FooPort" type from the list <b>ports</b>, and
5527 * entries of the "FooListenAddress" type from the list
5528 * <b>listenaddrs</b>. Two syntaxes are supported: a legacy syntax
5529 * where FooPort is at most a single entry containing a port number and
5530 * where FooListenAddress has any number of address:port combinations;
5531 * and a new syntax where there are no FooListenAddress entries and
5532 * where FooPort can have any number of entries of the format
5533 * "[Address:][Port] IsolationOptions".
5535 * In log messages, describe the port type as <b>portname</b>.
5537 * If no address is specified, default to <b>defaultaddr</b>. If no
5538 * FooPort is given, default to defaultport (if 0, there is no default).
5540 * If CL_PORT_NO_OPTIONS is set in <b>flags</b>, do not allow stream
5541 * isolation options in the FooPort entries.
5543 * If CL_PORT_WARN_NONLOCAL is set in <b>flags</b>, warn if any of the
5544 * ports are not on a local address. If CL_PORT_FORBID_NONLOCAL is set,
5545 * this is a contrl port with no password set: don't even allow it.
5547 * Unless CL_PORT_ALLOW_EXTRA_LISTENADDR is set in <b>flags</b>, warn
5548 * if FooListenAddress is set but FooPort is 0.
5550 * If CL_PORT_SERVER_OPTIONS is set in <b>flags</b>, do not allow stream
5551 * isolation options in the FooPort entries; instead allow the
5552 * server-port option set.
5554 * If CL_PORT_TAKES_HOSTNAMES is set in <b>flags</b>, allow the options
5555 * {No,}IPv{4,6}Traffic.
5557 * On success, if <b>out</b> is given, add a new port_cfg_t entry to
5558 * <b>out</b> for every port that the client should listen on. Return 0
5559 * on success, -1 on failure.
5561 static int
5562 parse_port_config(smartlist_t *out,
5563 const config_line_t *ports,
5564 const config_line_t *listenaddrs,
5565 const char *portname,
5566 int listener_type,
5567 const char *defaultaddr,
5568 int defaultport,
5569 unsigned flags)
5571 smartlist_t *elts;
5572 int retval = -1;
5573 const unsigned is_control = (listener_type == CONN_TYPE_CONTROL_LISTENER);
5574 const unsigned is_ext_orport = (listener_type == CONN_TYPE_EXT_OR_LISTENER);
5575 const unsigned allow_no_options = flags & CL_PORT_NO_OPTIONS;
5576 const unsigned use_server_options = flags & CL_PORT_SERVER_OPTIONS;
5577 const unsigned warn_nonlocal = flags & CL_PORT_WARN_NONLOCAL;
5578 const unsigned forbid_nonlocal = flags & CL_PORT_FORBID_NONLOCAL;
5579 const unsigned allow_spurious_listenaddr =
5580 flags & CL_PORT_ALLOW_EXTRA_LISTENADDR;
5581 const unsigned takes_hostnames = flags & CL_PORT_TAKES_HOSTNAMES;
5582 int got_zero_port=0, got_nonzero_port=0;
5584 /* FooListenAddress is deprecated; let's make it work like it used to work,
5585 * though. */
5586 if (listenaddrs) {
5587 int mainport = defaultport;
5589 if (ports && ports->next) {
5590 log_warn(LD_CONFIG, "%sListenAddress can't be used when there are "
5591 "multiple %sPort lines", portname, portname);
5592 return -1;
5593 } else if (ports) {
5594 if (!strcmp(ports->value, "auto")) {
5595 mainport = CFG_AUTO_PORT;
5596 } else {
5597 int ok;
5598 mainport = (int)tor_parse_long(ports->value, 10, 0, 65535, &ok, NULL);
5599 if (!ok) {
5600 log_warn(LD_CONFIG, "%sListenAddress can only be used with a single "
5601 "%sPort with value \"auto\" or 1-65535 and no options set.",
5602 portname, portname);
5603 return -1;
5608 if (mainport == 0) {
5609 if (allow_spurious_listenaddr)
5610 return 1; /*DOCDOC*/
5611 log_warn(LD_CONFIG, "%sPort must be defined if %sListenAddress is used",
5612 portname, portname);
5613 return -1;
5616 if (use_server_options && out) {
5617 /* Add a no_listen port. */
5618 port_cfg_t *cfg = port_cfg_new();
5619 cfg->type = listener_type;
5620 cfg->port = mainport;
5621 tor_addr_make_unspec(&cfg->addr); /* Server ports default to 0.0.0.0 */
5622 cfg->no_listen = 1;
5623 cfg->bind_ipv4_only = 1;
5624 cfg->ipv4_traffic = 1;
5625 cfg->prefer_ipv6_virtaddr = 1;
5626 smartlist_add(out, cfg);
5629 for (; listenaddrs; listenaddrs = listenaddrs->next) {
5630 tor_addr_t addr;
5631 uint16_t port = 0;
5632 if (tor_addr_port_lookup(listenaddrs->value, &addr, &port) < 0) {
5633 log_warn(LD_CONFIG, "Unable to parse %sListenAddress '%s'",
5634 portname, listenaddrs->value);
5635 return -1;
5637 if (out) {
5638 port_cfg_t *cfg = port_cfg_new();
5639 cfg->type = listener_type;
5640 cfg->port = port ? port : mainport;
5641 tor_addr_copy(&cfg->addr, &addr);
5642 cfg->session_group = SESSION_GROUP_UNSET;
5643 cfg->isolation_flags = ISO_DEFAULT;
5644 cfg->no_advertise = 1;
5645 smartlist_add(out, cfg);
5649 if (warn_nonlocal && out) {
5650 if (is_control)
5651 warn_nonlocal_controller_ports(out, forbid_nonlocal);
5652 else if (is_ext_orport)
5653 warn_nonlocal_ext_orports(out, portname);
5654 else
5655 warn_nonlocal_client_ports(out, portname, listener_type);
5657 return 0;
5658 } /* end if (listenaddrs) */
5660 /* No ListenAddress lines. If there's no FooPort, then maybe make a default
5661 * one. */
5662 if (! ports) {
5663 if (defaultport && out) {
5664 port_cfg_t *cfg = port_cfg_new();
5665 cfg->type = listener_type;
5666 cfg->port = defaultport;
5667 tor_addr_parse(&cfg->addr, defaultaddr);
5668 cfg->session_group = SESSION_GROUP_UNSET;
5669 cfg->isolation_flags = ISO_DEFAULT;
5670 smartlist_add(out, cfg);
5672 return 0;
5675 /* At last we can actually parse the FooPort lines. The syntax is:
5676 * [Addr:](Port|auto) [Options].*/
5677 elts = smartlist_new();
5679 for (; ports; ports = ports->next) {
5680 tor_addr_t addr;
5681 int port;
5682 int sessiongroup = SESSION_GROUP_UNSET;
5683 unsigned isolation = ISO_DEFAULT;
5684 int prefer_no_auth = 0;
5686 char *addrport;
5687 uint16_t ptmp=0;
5688 int ok;
5689 int no_listen = 0, no_advertise = 0, all_addrs = 0,
5690 bind_ipv4_only = 0, bind_ipv6_only = 0,
5691 ipv4_traffic = 1, ipv6_traffic = 0, prefer_ipv6 = 0,
5692 cache_ipv4 = 1, use_cached_ipv4 = 0,
5693 cache_ipv6 = 0, use_cached_ipv6 = 0,
5694 prefer_ipv6_automap = 1;
5696 smartlist_split_string(elts, ports->value, NULL,
5697 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
5698 if (smartlist_len(elts) == 0) {
5699 log_warn(LD_CONFIG, "Invalid %sPort line with no value", portname);
5700 goto err;
5703 if (allow_no_options && smartlist_len(elts) > 1) {
5704 log_warn(LD_CONFIG, "Too many options on %sPort line", portname);
5705 goto err;
5708 /* Now parse the addr/port value */
5709 addrport = smartlist_get(elts, 0);
5710 if (!strcmp(addrport, "auto")) {
5711 port = CFG_AUTO_PORT;
5712 tor_addr_parse(&addr, defaultaddr);
5713 } else if (!strcasecmpend(addrport, ":auto")) {
5714 char *addrtmp = tor_strndup(addrport, strlen(addrport)-5);
5715 port = CFG_AUTO_PORT;
5716 if (tor_addr_port_lookup(addrtmp, &addr, &ptmp)<0 || ptmp) {
5717 log_warn(LD_CONFIG, "Invalid address '%s' for %sPort",
5718 escaped(addrport), portname);
5719 tor_free(addrtmp);
5720 goto err;
5722 } else {
5723 /* Try parsing integer port before address, because, who knows?
5724 "9050" might be a valid address. */
5725 port = (int) tor_parse_long(addrport, 10, 0, 65535, &ok, NULL);
5726 if (ok) {
5727 tor_addr_parse(&addr, defaultaddr);
5728 } else if (tor_addr_port_lookup(addrport, &addr, &ptmp) == 0) {
5729 if (ptmp == 0) {
5730 log_warn(LD_CONFIG, "%sPort line has address but no port", portname);
5731 goto err;
5733 port = ptmp;
5734 } else {
5735 log_warn(LD_CONFIG, "Couldn't parse address '%s' for %sPort",
5736 escaped(addrport), portname);
5737 goto err;
5741 /* Now parse the rest of the options, if any. */
5742 if (use_server_options) {
5743 /* This is a server port; parse advertising options */
5744 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
5745 if (elt_sl_idx == 0)
5746 continue; /* Skip addr:port */
5748 if (!strcasecmp(elt, "NoAdvertise")) {
5749 no_advertise = 1;
5750 } else if (!strcasecmp(elt, "NoListen")) {
5751 no_listen = 1;
5752 #if 0
5753 /* not implemented yet. */
5754 } else if (!strcasecmp(elt, "AllAddrs")) {
5756 all_addrs = 1;
5757 #endif
5758 } else if (!strcasecmp(elt, "IPv4Only")) {
5759 bind_ipv4_only = 1;
5760 } else if (!strcasecmp(elt, "IPv6Only")) {
5761 bind_ipv6_only = 1;
5762 } else {
5763 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
5764 portname, escaped(elt));
5766 } SMARTLIST_FOREACH_END(elt);
5768 if (no_advertise && no_listen) {
5769 log_warn(LD_CONFIG, "Tried to set both NoListen and NoAdvertise "
5770 "on %sPort line '%s'",
5771 portname, escaped(ports->value));
5772 goto err;
5774 if (bind_ipv4_only && bind_ipv6_only) {
5775 log_warn(LD_CONFIG, "Tried to set both IPv4Only and IPv6Only "
5776 "on %sPort line '%s'",
5777 portname, escaped(ports->value));
5778 goto err;
5780 if (bind_ipv4_only && tor_addr_family(&addr) == AF_INET6) {
5781 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv6",
5782 portname);
5783 goto err;
5785 if (bind_ipv6_only && tor_addr_family(&addr) == AF_INET) {
5786 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv4",
5787 portname);
5788 goto err;
5790 } else {
5791 /* This is a client port; parse isolation options */
5792 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
5793 int no = 0, isoflag = 0;
5794 const char *elt_orig = elt;
5795 if (elt_sl_idx == 0)
5796 continue; /* Skip addr:port */
5797 if (!strcasecmpstart(elt, "SessionGroup=")) {
5798 int group = (int)tor_parse_long(elt+strlen("SessionGroup="),
5799 10, 0, INT_MAX, &ok, NULL);
5800 if (!ok) {
5801 log_warn(LD_CONFIG, "Invalid %sPort option '%s'",
5802 portname, escaped(elt));
5803 goto err;
5805 if (sessiongroup >= 0) {
5806 log_warn(LD_CONFIG, "Multiple SessionGroup options on %sPort",
5807 portname);
5808 goto err;
5810 sessiongroup = group;
5811 continue;
5814 if (!strcasecmpstart(elt, "No")) {
5815 no = 1;
5816 elt += 2;
5819 if (takes_hostnames) {
5820 if (!strcasecmp(elt, "IPv4Traffic")) {
5821 ipv4_traffic = ! no;
5822 continue;
5823 } else if (!strcasecmp(elt, "IPv6Traffic")) {
5824 ipv6_traffic = ! no;
5825 continue;
5826 } else if (!strcasecmp(elt, "PreferIPv6")) {
5827 prefer_ipv6 = ! no;
5828 continue;
5831 if (!strcasecmp(elt, "CacheIPv4DNS")) {
5832 cache_ipv4 = ! no;
5833 continue;
5834 } else if (!strcasecmp(elt, "CacheIPv6DNS")) {
5835 cache_ipv6 = ! no;
5836 continue;
5837 } else if (!strcasecmp(elt, "CacheDNS")) {
5838 cache_ipv4 = cache_ipv6 = ! no;
5839 continue;
5840 } else if (!strcasecmp(elt, "UseIPv4Cache")) {
5841 use_cached_ipv4 = ! no;
5842 continue;
5843 } else if (!strcasecmp(elt, "UseIPv6Cache")) {
5844 use_cached_ipv6 = ! no;
5845 continue;
5846 } else if (!strcasecmp(elt, "UseDNSCache")) {
5847 use_cached_ipv4 = use_cached_ipv6 = ! no;
5848 continue;
5849 } else if (!strcasecmp(elt, "PreferIPv6Automap")) {
5850 prefer_ipv6_automap = ! no;
5851 continue;
5852 } else if (!strcasecmp(elt, "PreferSOCKSNoAuth")) {
5853 prefer_no_auth = ! no;
5854 continue;
5857 if (!strcasecmpend(elt, "s"))
5858 elt[strlen(elt)-1] = '\0'; /* kill plurals. */
5860 if (!strcasecmp(elt, "IsolateDestPort")) {
5861 isoflag = ISO_DESTPORT;
5862 } else if (!strcasecmp(elt, "IsolateDestAddr")) {
5863 isoflag = ISO_DESTADDR;
5864 } else if (!strcasecmp(elt, "IsolateSOCKSAuth")) {
5865 isoflag = ISO_SOCKSAUTH;
5866 } else if (!strcasecmp(elt, "IsolateClientProtocol")) {
5867 isoflag = ISO_CLIENTPROTO;
5868 } else if (!strcasecmp(elt, "IsolateClientAddr")) {
5869 isoflag = ISO_CLIENTADDR;
5870 } else {
5871 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
5872 portname, escaped(elt_orig));
5875 if (no) {
5876 isolation &= ~isoflag;
5877 } else {
5878 isolation |= isoflag;
5880 } SMARTLIST_FOREACH_END(elt);
5883 if (port)
5884 got_nonzero_port = 1;
5885 else
5886 got_zero_port = 1;
5888 if (ipv4_traffic == 0 && ipv6_traffic == 0) {
5889 log_warn(LD_CONFIG, "You have a %sPort entry with both IPv4 and "
5890 "IPv6 disabled; that won't work.", portname);
5891 goto err;
5894 if (out && port) {
5895 port_cfg_t *cfg = port_cfg_new();
5896 tor_addr_copy(&cfg->addr, &addr);
5897 cfg->port = port;
5898 cfg->type = listener_type;
5899 cfg->isolation_flags = isolation;
5900 cfg->session_group = sessiongroup;
5901 cfg->no_advertise = no_advertise;
5902 cfg->no_listen = no_listen;
5903 cfg->all_addrs = all_addrs;
5904 cfg->bind_ipv4_only = bind_ipv4_only;
5905 cfg->bind_ipv6_only = bind_ipv6_only;
5906 cfg->ipv4_traffic = ipv4_traffic;
5907 cfg->ipv6_traffic = ipv6_traffic;
5908 cfg->prefer_ipv6 = prefer_ipv6;
5909 cfg->cache_ipv4_answers = cache_ipv4;
5910 cfg->cache_ipv6_answers = cache_ipv6;
5911 cfg->use_cached_ipv4_answers = use_cached_ipv4;
5912 cfg->use_cached_ipv6_answers = use_cached_ipv6;
5913 cfg->prefer_ipv6_virtaddr = prefer_ipv6_automap;
5914 cfg->socks_prefer_no_auth = prefer_no_auth;
5915 if (! (isolation & ISO_SOCKSAUTH))
5916 cfg->socks_prefer_no_auth = 1;
5918 smartlist_add(out, cfg);
5920 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
5921 smartlist_clear(elts);
5924 if (warn_nonlocal && out) {
5925 if (is_control)
5926 warn_nonlocal_controller_ports(out, forbid_nonlocal);
5927 else if (is_ext_orport)
5928 warn_nonlocal_ext_orports(out, portname);
5929 else
5930 warn_nonlocal_client_ports(out, portname, listener_type);
5933 if (got_zero_port && got_nonzero_port) {
5934 log_warn(LD_CONFIG, "You specified a nonzero %sPort along with '%sPort 0' "
5935 "in the same configuration. Did you mean to disable %sPort or "
5936 "not?", portname, portname, portname);
5937 goto err;
5940 retval = 0;
5941 err:
5942 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
5943 smartlist_free(elts);
5944 return retval;
5947 /** Parse a list of config_line_t for an AF_UNIX unix socket listener option
5948 * from <b>cfg</b> and add them to <b>out</b>. No fancy options are
5949 * supported: the line contains nothing but the path to the AF_UNIX socket. */
5950 static int
5951 parse_unix_socket_config(smartlist_t *out, const config_line_t *cfg,
5952 int listener_type)
5955 if (!out)
5956 return 0;
5958 for ( ; cfg; cfg = cfg->next) {
5959 size_t len = strlen(cfg->value);
5960 port_cfg_t *port = tor_malloc_zero(sizeof(port_cfg_t) + len + 1);
5961 port->is_unix_addr = 1;
5962 memcpy(port->unix_addr, cfg->value, len+1);
5963 port->type = listener_type;
5964 smartlist_add(out, port);
5967 return 0;
5970 /** Return the number of ports which are actually going to listen with type
5971 * <b>listenertype</b>. Do not count no_listen ports. Do not count unix
5972 * sockets. */
5973 static int
5974 count_real_listeners(const smartlist_t *ports, int listenertype)
5976 int n = 0;
5977 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
5978 if (port->no_listen || port->is_unix_addr)
5979 continue;
5980 if (port->type != listenertype)
5981 continue;
5982 ++n;
5983 } SMARTLIST_FOREACH_END(port);
5984 return n;
5987 /** Parse all client port types (Socks, DNS, Trans, NATD) from
5988 * <b>options</b>. On success, set *<b>n_ports_out</b> to the number
5989 * of ports that are listed, update the *Port_set values in
5990 * <b>options</b>, and return 0. On failure, set *<b>msg</b> to a
5991 * description of the problem and return -1.
5993 * If <b>validate_only</b> is false, set configured_client_ports to the
5994 * new list of ports parsed from <b>options</b>.
5996 static int
5997 parse_ports(or_options_t *options, int validate_only,
5998 char **msg, int *n_ports_out)
6000 smartlist_t *ports;
6001 int retval = -1;
6003 ports = smartlist_new();
6005 *n_ports_out = 0;
6007 if (parse_port_config(ports,
6008 options->SocksPort_lines, options->SocksListenAddress,
6009 "Socks", CONN_TYPE_AP_LISTENER,
6010 "127.0.0.1", 9050,
6011 CL_PORT_WARN_NONLOCAL|CL_PORT_ALLOW_EXTRA_LISTENADDR|
6012 CL_PORT_TAKES_HOSTNAMES) < 0) {
6013 *msg = tor_strdup("Invalid SocksPort/SocksListenAddress configuration");
6014 goto err;
6016 if (parse_port_config(ports,
6017 options->DNSPort_lines, options->DNSListenAddress,
6018 "DNS", CONN_TYPE_AP_DNS_LISTENER,
6019 "127.0.0.1", 0,
6020 CL_PORT_WARN_NONLOCAL|CL_PORT_TAKES_HOSTNAMES) < 0) {
6021 *msg = tor_strdup("Invalid DNSPort/DNSListenAddress configuration");
6022 goto err;
6024 if (parse_port_config(ports,
6025 options->TransPort_lines, options->TransListenAddress,
6026 "Trans", CONN_TYPE_AP_TRANS_LISTENER,
6027 "127.0.0.1", 0,
6028 CL_PORT_WARN_NONLOCAL) < 0) {
6029 *msg = tor_strdup("Invalid TransPort/TransListenAddress configuration");
6030 goto err;
6032 if (parse_port_config(ports,
6033 options->NATDPort_lines, options->NATDListenAddress,
6034 "NATD", CONN_TYPE_AP_NATD_LISTENER,
6035 "127.0.0.1", 0,
6036 CL_PORT_WARN_NONLOCAL) < 0) {
6037 *msg = tor_strdup("Invalid NatdPort/NatdListenAddress configuration");
6038 goto err;
6041 unsigned control_port_flags = CL_PORT_NO_OPTIONS | CL_PORT_WARN_NONLOCAL;
6042 const int any_passwords = (options->HashedControlPassword ||
6043 options->HashedControlSessionPassword ||
6044 options->CookieAuthentication);
6045 if (! any_passwords)
6046 control_port_flags |= CL_PORT_FORBID_NONLOCAL;
6048 if (parse_port_config(ports,
6049 options->ControlPort_lines,
6050 options->ControlListenAddress,
6051 "Control", CONN_TYPE_CONTROL_LISTENER,
6052 "127.0.0.1", 0,
6053 control_port_flags) < 0) {
6054 *msg = tor_strdup("Invalid ControlPort/ControlListenAddress "
6055 "configuration");
6056 goto err;
6058 if (parse_unix_socket_config(ports,
6059 options->ControlSocket,
6060 CONN_TYPE_CONTROL_LISTENER) < 0) {
6061 *msg = tor_strdup("Invalid ControlSocket configuration");
6062 goto err;
6065 if (! options->ClientOnly) {
6066 if (parse_port_config(ports,
6067 options->ORPort_lines, options->ORListenAddress,
6068 "OR", CONN_TYPE_OR_LISTENER,
6069 "0.0.0.0", 0,
6070 CL_PORT_SERVER_OPTIONS) < 0) {
6071 *msg = tor_strdup("Invalid ORPort/ORListenAddress configuration");
6072 goto err;
6074 if (parse_port_config(ports,
6075 options->ExtORPort_lines, NULL,
6076 "ExtOR", CONN_TYPE_EXT_OR_LISTENER,
6077 "127.0.0.1", 0,
6078 CL_PORT_SERVER_OPTIONS|CL_PORT_WARN_NONLOCAL) < 0) {
6079 *msg = tor_strdup("Invalid ExtORPort configuration");
6080 goto err;
6082 if (parse_port_config(ports,
6083 options->DirPort_lines, options->DirListenAddress,
6084 "Dir", CONN_TYPE_DIR_LISTENER,
6085 "0.0.0.0", 0,
6086 CL_PORT_SERVER_OPTIONS) < 0) {
6087 *msg = tor_strdup("Invalid DirPort/DirListenAddress configuration");
6088 goto err;
6092 if (check_server_ports(ports, options) < 0) {
6093 *msg = tor_strdup("Misconfigured server ports");
6094 goto err;
6097 *n_ports_out = smartlist_len(ports);
6099 retval = 0;
6101 /* Update the *Port_set options. The !! here is to force a boolean out of
6102 an integer. */
6103 options->ORPort_set =
6104 !! count_real_listeners(ports, CONN_TYPE_OR_LISTENER);
6105 options->SocksPort_set =
6106 !! count_real_listeners(ports, CONN_TYPE_AP_LISTENER);
6107 options->TransPort_set =
6108 !! count_real_listeners(ports, CONN_TYPE_AP_TRANS_LISTENER);
6109 options->NATDPort_set =
6110 !! count_real_listeners(ports, CONN_TYPE_AP_NATD_LISTENER);
6111 options->ControlPort_set =
6112 !! count_real_listeners(ports, CONN_TYPE_CONTROL_LISTENER);
6113 options->DirPort_set =
6114 !! count_real_listeners(ports, CONN_TYPE_DIR_LISTENER);
6115 options->DNSPort_set =
6116 !! count_real_listeners(ports, CONN_TYPE_AP_DNS_LISTENER);
6117 options->ExtORPort_set =
6118 !! count_real_listeners(ports, CONN_TYPE_EXT_OR_LISTENER);
6120 if (!validate_only) {
6121 if (configured_ports) {
6122 SMARTLIST_FOREACH(configured_ports,
6123 port_cfg_t *, p, port_cfg_free(p));
6124 smartlist_free(configured_ports);
6126 configured_ports = ports;
6127 ports = NULL; /* prevent free below. */
6130 err:
6131 if (ports) {
6132 SMARTLIST_FOREACH(ports, port_cfg_t *, p, port_cfg_free(p));
6133 smartlist_free(ports);
6135 return retval;
6138 /** Given a list of <b>port_cfg_t</b> in <b>ports</b>, check them for internal
6139 * consistency and warn as appropriate. */
6140 static int
6141 check_server_ports(const smartlist_t *ports,
6142 const or_options_t *options)
6144 int n_orport_advertised = 0;
6145 int n_orport_advertised_ipv4 = 0;
6146 int n_orport_listeners = 0;
6147 int n_dirport_advertised = 0;
6148 int n_dirport_listeners = 0;
6149 int n_low_port = 0;
6150 int r = 0;
6152 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
6153 if (port->type == CONN_TYPE_DIR_LISTENER) {
6154 if (! port->no_advertise)
6155 ++n_dirport_advertised;
6156 if (! port->no_listen)
6157 ++n_dirport_listeners;
6158 } else if (port->type == CONN_TYPE_OR_LISTENER) {
6159 if (! port->no_advertise) {
6160 ++n_orport_advertised;
6161 if (tor_addr_family(&port->addr) == AF_INET ||
6162 (tor_addr_family(&port->addr) == AF_UNSPEC &&
6163 !port->bind_ipv6_only))
6164 ++n_orport_advertised_ipv4;
6166 if (! port->no_listen)
6167 ++n_orport_listeners;
6168 } else {
6169 continue;
6171 #ifndef _WIN32
6172 if (!port->no_listen && port->port < 1024)
6173 ++n_low_port;
6174 #endif
6175 } SMARTLIST_FOREACH_END(port);
6177 if (n_orport_advertised && !n_orport_listeners) {
6178 log_warn(LD_CONFIG, "We are advertising an ORPort, but not actually "
6179 "listening on one.");
6180 r = -1;
6182 if (n_orport_listeners && !n_orport_advertised) {
6183 log_warn(LD_CONFIG, "We are listening on an ORPort, but not advertising "
6184 "any ORPorts. This will keep us from building a %s "
6185 "descriptor, and make us impossible to use.",
6186 options->BridgeRelay ? "bridge" : "router");
6187 r = -1;
6189 if (n_dirport_advertised && !n_dirport_listeners) {
6190 log_warn(LD_CONFIG, "We are advertising a DirPort, but not actually "
6191 "listening on one.");
6192 r = -1;
6194 if (n_dirport_advertised > 1) {
6195 log_warn(LD_CONFIG, "Can't advertise more than one DirPort.");
6196 r = -1;
6198 if (n_orport_advertised && !n_orport_advertised_ipv4 &&
6199 !options->BridgeRelay) {
6200 log_warn(LD_CONFIG, "Configured non-bridge only to listen on an IPv6 "
6201 "address.");
6202 r = -1;
6205 if (n_low_port && options->AccountingMax) {
6206 log_warn(LD_CONFIG,
6207 "You have set AccountingMax to use hibernation. You have also "
6208 "chosen a low DirPort or OrPort. This combination can make Tor stop "
6209 "working when it tries to re-attach the port after a period of "
6210 "hibernation. Please choose a different port or turn off "
6211 "hibernation unless you know this combination will work on your "
6212 "platform.");
6215 return r;
6218 /** Return a list of port_cfg_t for client ports parsed from the
6219 * options. */
6220 const smartlist_t *
6221 get_configured_ports(void)
6223 if (!configured_ports)
6224 configured_ports = smartlist_new();
6225 return configured_ports;
6228 /** Return an address:port string representation of the address
6229 * where the first <b>listener_type</b> listener waits for
6230 * connections. Return NULL if we couldn't find a listener. The
6231 * string is allocated on the heap and it's the responsibility of the
6232 * caller to free it after use.
6234 * This function is meant to be used by the pluggable transport proxy
6235 * spawning code, please make sure that it fits your purposes before
6236 * using it. */
6237 char *
6238 get_first_listener_addrport_string(int listener_type)
6240 static const char *ipv4_localhost = "127.0.0.1";
6241 static const char *ipv6_localhost = "[::1]";
6242 const char *address;
6243 uint16_t port;
6244 char *string = NULL;
6246 if (!configured_ports)
6247 return NULL;
6249 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
6250 if (cfg->no_listen)
6251 continue;
6253 if (cfg->type == listener_type &&
6254 tor_addr_family(&cfg->addr) != AF_UNSPEC) {
6256 /* We found the first listener of the type we are interested in! */
6258 /* If a listener is listening on INADDR_ANY, assume that it's
6259 also listening on 127.0.0.1, and point the transport proxy
6260 there: */
6261 if (tor_addr_is_null(&cfg->addr))
6262 address = tor_addr_is_v4(&cfg->addr) ? ipv4_localhost : ipv6_localhost;
6263 else
6264 address = fmt_and_decorate_addr(&cfg->addr);
6266 /* If a listener is configured with port 'auto', we are forced
6267 to iterate all listener connections and find out in which
6268 port it ended up listening: */
6269 if (cfg->port == CFG_AUTO_PORT) {
6270 port = router_get_active_listener_port_by_type_af(listener_type,
6271 tor_addr_family(&cfg->addr));
6272 if (!port)
6273 return NULL;
6274 } else {
6275 port = cfg->port;
6278 tor_asprintf(&string, "%s:%u", address, port);
6280 return string;
6283 } SMARTLIST_FOREACH_END(cfg);
6285 return NULL;
6288 /** Return the first advertised port of type <b>listener_type</b> in
6289 <b>address_family</b>. */
6291 get_first_advertised_port_by_type_af(int listener_type, int address_family)
6293 if (!configured_ports)
6294 return 0;
6295 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
6296 if (cfg->type == listener_type &&
6297 !cfg->no_advertise &&
6298 (tor_addr_family(&cfg->addr) == address_family ||
6299 tor_addr_family(&cfg->addr) == AF_UNSPEC)) {
6300 if (tor_addr_family(&cfg->addr) != AF_UNSPEC ||
6301 (address_family == AF_INET && !cfg->bind_ipv6_only) ||
6302 (address_family == AF_INET6 && !cfg->bind_ipv4_only)) {
6303 return cfg->port;
6306 } SMARTLIST_FOREACH_END(cfg);
6307 return 0;
6310 /** Adjust the value of options->DataDirectory, or fill it in if it's
6311 * absent. Return 0 on success, -1 on failure. */
6312 static int
6313 normalize_data_directory(or_options_t *options)
6315 #ifdef _WIN32
6316 char *p;
6317 if (options->DataDirectory)
6318 return 0; /* all set */
6319 p = tor_malloc(MAX_PATH);
6320 strlcpy(p,get_windows_conf_root(),MAX_PATH);
6321 options->DataDirectory = p;
6322 return 0;
6323 #else
6324 const char *d = options->DataDirectory;
6325 if (!d)
6326 d = "~/.tor";
6328 if (strncmp(d,"~/",2) == 0) {
6329 char *fn = expand_filename(d);
6330 if (!fn) {
6331 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
6332 return -1;
6334 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
6335 /* If our homedir is /, we probably don't want to use it. */
6336 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
6337 * want. */
6338 log_warn(LD_CONFIG,
6339 "Default DataDirectory is \"~/.tor\". This expands to "
6340 "\"%s\", which is probably not what you want. Using "
6341 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
6342 tor_free(fn);
6343 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
6345 tor_free(options->DataDirectory);
6346 options->DataDirectory = fn;
6348 return 0;
6349 #endif
6352 /** Check and normalize the value of options->DataDirectory; return 0 if it
6353 * is sane, -1 otherwise. */
6354 static int
6355 validate_data_directory(or_options_t *options)
6357 if (normalize_data_directory(options) < 0)
6358 return -1;
6359 tor_assert(options->DataDirectory);
6360 if (strlen(options->DataDirectory) > (512-128)) {
6361 log_warn(LD_CONFIG, "DataDirectory is too long.");
6362 return -1;
6364 return 0;
6367 /** This string must remain the same forevermore. It is how we
6368 * recognize that the torrc file doesn't need to be backed up. */
6369 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
6370 "if you edit it, comments will not be preserved"
6371 /** This string can change; it tries to give the reader an idea
6372 * that editing this file by hand is not a good plan. */
6373 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
6374 "to torrc.orig.1 or similar, and Tor will ignore it"
6376 /** Save a configuration file for the configuration in <b>options</b>
6377 * into the file <b>fname</b>. If the file already exists, and
6378 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
6379 * replace it. Return 0 on success, -1 on failure. */
6380 static int
6381 write_configuration_file(const char *fname, const or_options_t *options)
6383 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
6384 int rename_old = 0, r;
6386 tor_assert(fname);
6388 switch (file_status(fname)) {
6389 case FN_FILE:
6390 old_val = read_file_to_str(fname, 0, NULL);
6391 if (!old_val || strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
6392 rename_old = 1;
6394 tor_free(old_val);
6395 break;
6396 case FN_NOENT:
6397 break;
6398 case FN_ERROR:
6399 case FN_DIR:
6400 default:
6401 log_warn(LD_CONFIG,
6402 "Config file \"%s\" is not a file? Failing.", fname);
6403 return -1;
6406 if (!(new_conf = options_dump(options, OPTIONS_DUMP_MINIMAL))) {
6407 log_warn(LD_BUG, "Couldn't get configuration string");
6408 goto err;
6411 tor_asprintf(&new_val, "%s\n%s\n\n%s",
6412 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
6414 if (rename_old) {
6415 int i = 1;
6416 char *fn_tmp = NULL;
6417 while (1) {
6418 tor_asprintf(&fn_tmp, "%s.orig.%d", fname, i);
6419 if (file_status(fn_tmp) == FN_NOENT)
6420 break;
6421 tor_free(fn_tmp);
6422 ++i;
6424 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
6425 if (tor_rename(fname, fn_tmp) < 0) {//XXXX sandbox doesn't allow
6426 log_warn(LD_FS,
6427 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
6428 fname, fn_tmp, strerror(errno));
6429 tor_free(fn_tmp);
6430 goto err;
6432 tor_free(fn_tmp);
6435 if (write_str_to_file(fname, new_val, 0) < 0)
6436 goto err;
6438 r = 0;
6439 goto done;
6440 err:
6441 r = -1;
6442 done:
6443 tor_free(new_val);
6444 tor_free(new_conf);
6445 return r;
6449 * Save the current configuration file value to disk. Return 0 on
6450 * success, -1 on failure.
6453 options_save_current(void)
6455 /* This fails if we can't write to our configuration file.
6457 * If we try falling back to datadirectory or something, we have a better
6458 * chance of saving the configuration, but a better chance of doing
6459 * something the user never expected. */
6460 return write_configuration_file(get_torrc_fname(0), get_options());
6463 /** Return the number of cpus configured in <b>options</b>. If we are
6464 * told to auto-detect the number of cpus, return the auto-detected number. */
6466 get_num_cpus(const or_options_t *options)
6468 if (options->NumCPUs == 0) {
6469 int n = compute_num_cpus();
6470 return (n >= 1) ? n : 1;
6471 } else {
6472 return options->NumCPUs;
6477 * Initialize the libevent library.
6479 static void
6480 init_libevent(const or_options_t *options)
6482 const char *badness=NULL;
6483 tor_libevent_cfg cfg;
6485 tor_assert(options);
6487 configure_libevent_logging();
6488 /* If the kernel complains that some method (say, epoll) doesn't
6489 * exist, we don't care about it, since libevent will cope.
6491 suppress_libevent_log_msg("Function not implemented");
6493 tor_check_libevent_header_compatibility();
6495 memset(&cfg, 0, sizeof(cfg));
6496 cfg.disable_iocp = options->DisableIOCP;
6497 cfg.num_cpus = get_num_cpus(options);
6498 cfg.msec_per_tick = options->TokenBucketRefillInterval;
6500 tor_libevent_initialize(&cfg);
6502 suppress_libevent_log_msg(NULL);
6504 tor_check_libevent_version(tor_libevent_get_method(),
6505 server_mode(get_options()),
6506 &badness);
6507 if (badness) {
6508 const char *v = tor_libevent_get_version_str();
6509 const char *m = tor_libevent_get_method();
6510 control_event_general_status(LOG_WARN,
6511 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
6512 v, m, badness);
6516 /** Return a newly allocated string holding a filename relative to the data
6517 * directory. If <b>sub1</b> is present, it is the first path component after
6518 * the data directory. If <b>sub2</b> is also present, it is the second path
6519 * component after the data directory. If <b>suffix</b> is present, it
6520 * is appended to the filename.
6522 * Examples:
6523 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
6524 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
6525 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
6526 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
6528 * Note: Consider using the get_datadir_fname* macros in or.h.
6530 char *
6531 options_get_datadir_fname2_suffix(const or_options_t *options,
6532 const char *sub1, const char *sub2,
6533 const char *suffix)
6535 char *fname = NULL;
6536 size_t len;
6537 tor_assert(options);
6538 tor_assert(options->DataDirectory);
6539 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
6540 len = strlen(options->DataDirectory);
6541 if (sub1) {
6542 len += strlen(sub1)+1;
6543 if (sub2)
6544 len += strlen(sub2)+1;
6546 if (suffix)
6547 len += strlen(suffix);
6548 len++;
6549 fname = tor_malloc(len);
6550 if (sub1) {
6551 if (sub2) {
6552 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
6553 options->DataDirectory, sub1, sub2);
6554 } else {
6555 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
6556 options->DataDirectory, sub1);
6558 } else {
6559 strlcpy(fname, options->DataDirectory, len);
6561 if (suffix)
6562 strlcat(fname, suffix, len);
6563 return fname;
6566 /** Check wether the data directory has a private subdirectory
6567 * <b>subdir</b>. If not, try to create it. Return 0 on success,
6568 * -1 otherwise. */
6570 check_or_create_data_subdir(const char *subdir)
6572 char *statsdir = get_datadir_fname(subdir);
6573 int return_val = 0;
6575 if (check_private_dir(statsdir, CPD_CREATE, get_options()->User) < 0) {
6576 log_warn(LD_HIST, "Unable to create %s/ directory!", subdir);
6577 return_val = -1;
6579 tor_free(statsdir);
6580 return return_val;
6583 /** Create a file named <b>fname</b> with contents <b>str</b> in the
6584 * subdirectory <b>subdir</b> of the data directory. <b>descr</b>
6585 * should be a short description of the file's content and will be
6586 * used for the warning message, if it's present and the write process
6587 * fails. Return 0 on success, -1 otherwise.*/
6589 write_to_data_subdir(const char* subdir, const char* fname,
6590 const char* str, const char* descr)
6592 char *filename = get_datadir_fname2(subdir, fname);
6593 int return_val = 0;
6595 if (write_str_to_file(filename, str, 0) < 0) {
6596 log_warn(LD_HIST, "Unable to write %s to disk!", descr ? descr : fname);
6597 return_val = -1;
6599 tor_free(filename);
6600 return return_val;
6603 /** Given a file name check to see whether the file exists but has not been
6604 * modified for a very long time. If so, remove it. */
6605 void
6606 remove_file_if_very_old(const char *fname, time_t now)
6608 #define VERY_OLD_FILE_AGE (28*24*60*60)
6609 struct stat st;
6611 log_debug(LD_FS, "stat()ing %s", fname);
6612 if (stat(sandbox_intern_string(fname), &st)==0 &&
6613 st.st_mtime < now-VERY_OLD_FILE_AGE) {
6614 char buf[ISO_TIME_LEN+1];
6615 format_local_iso_time(buf, st.st_mtime);
6616 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
6617 "Removing it.", fname, buf);
6618 if (unlink(fname) != 0) {
6619 log_warn(LD_FS, "Failed to unlink %s: %s",
6620 fname, strerror(errno));
6625 /** Return a smartlist of ports that must be forwarded by
6626 * tor-fw-helper. The smartlist contains the ports in a string format
6627 * that is understandable by tor-fw-helper. */
6628 smartlist_t *
6629 get_list_of_ports_to_forward(void)
6631 smartlist_t *ports_to_forward = smartlist_new();
6632 int port = 0;
6634 /** XXX TODO tor-fw-helper does not support forwarding ports to
6635 other hosts than the local one. If the user is binding to a
6636 different IP address, tor-fw-helper won't work. */
6637 port = router_get_advertised_or_port(get_options()); /* Get ORPort */
6638 if (port)
6639 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
6641 port = router_get_advertised_dir_port(get_options(), 0); /* Get DirPort */
6642 if (port)
6643 smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
6645 /* Get ports of transport proxies */
6647 smartlist_t *transport_ports = get_transport_proxy_ports();
6648 if (transport_ports) {
6649 smartlist_add_all(ports_to_forward, transport_ports);
6650 smartlist_free(transport_ports);
6654 if (!smartlist_len(ports_to_forward)) {
6655 smartlist_free(ports_to_forward);
6656 ports_to_forward = NULL;
6659 return ports_to_forward;
6662 /** Helper to implement GETINFO functions about configuration variables (not
6663 * their values). Given a "config/names" question, set *<b>answer</b> to a
6664 * new string describing the supported configuration variables and their
6665 * types. */
6667 getinfo_helper_config(control_connection_t *conn,
6668 const char *question, char **answer,
6669 const char **errmsg)
6671 (void) conn;
6672 (void) errmsg;
6673 if (!strcmp(question, "config/names")) {
6674 smartlist_t *sl = smartlist_new();
6675 int i;
6676 for (i = 0; option_vars_[i].name; ++i) {
6677 const config_var_t *var = &option_vars_[i];
6678 const char *type;
6679 /* don't tell controller about triple-underscore options */
6680 if (!strncmp(option_vars_[i].name, "___", 3))
6681 continue;
6682 switch (var->type) {
6683 case CONFIG_TYPE_STRING: type = "String"; break;
6684 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
6685 case CONFIG_TYPE_UINT: type = "Integer"; break;
6686 case CONFIG_TYPE_INT: type = "SignedInteger"; break;
6687 case CONFIG_TYPE_PORT: type = "Port"; break;
6688 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
6689 case CONFIG_TYPE_MSEC_INTERVAL: type = "TimeMsecInterval"; break;
6690 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
6691 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
6692 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
6693 case CONFIG_TYPE_AUTOBOOL: type = "Boolean+Auto"; break;
6694 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
6695 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
6696 case CONFIG_TYPE_CSV: type = "CommaList"; break;
6697 case CONFIG_TYPE_CSV_INTERVAL: type = "TimeIntervalCommaList"; break;
6698 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
6699 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
6700 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
6701 default:
6702 case CONFIG_TYPE_OBSOLETE:
6703 type = NULL; break;
6705 if (!type)
6706 continue;
6707 smartlist_add_asprintf(sl, "%s %s\n",var->name,type);
6709 *answer = smartlist_join_strings(sl, "", 0, NULL);
6710 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
6711 smartlist_free(sl);
6712 } else if (!strcmp(question, "config/defaults")) {
6713 smartlist_t *sl = smartlist_new();
6714 int i;
6715 for (i = 0; option_vars_[i].name; ++i) {
6716 const config_var_t *var = &option_vars_[i];
6717 if (var->initvalue != NULL) {
6718 char *val = esc_for_log(var->initvalue);
6719 smartlist_add_asprintf(sl, "%s %s\n",var->name,val);
6720 tor_free(val);
6723 *answer = smartlist_join_strings(sl, "", 0, NULL);
6724 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
6725 smartlist_free(sl);
6727 return 0;
6730 /** Parse outbound bind address option lines. If <b>validate_only</b>
6731 * is not 0 update OutboundBindAddressIPv4_ and
6732 * OutboundBindAddressIPv6_ in <b>options</b>. On failure, set
6733 * <b>msg</b> (if provided) to a newly allocated string containing a
6734 * description of the problem and return -1. */
6735 static int
6736 parse_outbound_addresses(or_options_t *options, int validate_only, char **msg)
6738 const config_line_t *lines = options->OutboundBindAddress;
6739 int found_v4 = 0, found_v6 = 0;
6741 if (!validate_only) {
6742 memset(&options->OutboundBindAddressIPv4_, 0,
6743 sizeof(options->OutboundBindAddressIPv4_));
6744 memset(&options->OutboundBindAddressIPv6_, 0,
6745 sizeof(options->OutboundBindAddressIPv6_));
6747 while (lines) {
6748 tor_addr_t addr, *dst_addr = NULL;
6749 int af = tor_addr_parse(&addr, lines->value);
6750 switch (af) {
6751 case AF_INET:
6752 if (found_v4) {
6753 if (msg)
6754 tor_asprintf(msg, "Multiple IPv4 outbound bind addresses "
6755 "configured: %s", lines->value);
6756 return -1;
6758 found_v4 = 1;
6759 dst_addr = &options->OutboundBindAddressIPv4_;
6760 break;
6761 case AF_INET6:
6762 if (found_v6) {
6763 if (msg)
6764 tor_asprintf(msg, "Multiple IPv6 outbound bind addresses "
6765 "configured: %s", lines->value);
6766 return -1;
6768 found_v6 = 1;
6769 dst_addr = &options->OutboundBindAddressIPv6_;
6770 break;
6771 default:
6772 if (msg)
6773 tor_asprintf(msg, "Outbound bind address '%s' didn't parse.",
6774 lines->value);
6775 return -1;
6777 if (!validate_only)
6778 tor_addr_copy(dst_addr, &addr);
6779 lines = lines->next;
6781 return 0;
6784 /** Load one of the geoip files, <a>family</a> determining which
6785 * one. <a>default_fname</a> is used if on Windows and
6786 * <a>fname</a> equals "<default>". */
6787 static void
6788 config_load_geoip_file_(sa_family_t family,
6789 const char *fname,
6790 const char *default_fname)
6792 #ifdef _WIN32
6793 char *free_fname = NULL; /* Used to hold any temporary-allocated value */
6794 /* XXXX Don't use this "<default>" junk; make our filename options
6795 * understand prefixes somehow. -NM */
6796 if (!strcmp(fname, "<default>")) {
6797 const char *conf_root = get_windows_conf_root();
6798 tor_asprintf(&free_fname, "%s\\%s", conf_root, default_fname);
6799 fname = free_fname;
6801 geoip_load_file(family, fname);
6802 tor_free(free_fname);
6803 #else
6804 (void)default_fname;
6805 geoip_load_file(family, fname);
6806 #endif
6809 /** Load geoip files for IPv4 and IPv6 if <a>options</a> and
6810 * <a>old_options</a> indicate we should. */
6811 static void
6812 config_maybe_load_geoip_files_(const or_options_t *options,
6813 const or_options_t *old_options)
6815 /* XXXX024 Reload GeoIPFile on SIGHUP. -NM */
6817 if (options->GeoIPFile &&
6818 ((!old_options || !opt_streq(old_options->GeoIPFile,
6819 options->GeoIPFile))
6820 || !geoip_is_loaded(AF_INET)))
6821 config_load_geoip_file_(AF_INET, options->GeoIPFile, "geoip");
6822 if (options->GeoIPv6File &&
6823 ((!old_options || !opt_streq(old_options->GeoIPv6File,
6824 options->GeoIPv6File))
6825 || !geoip_is_loaded(AF_INET6)))
6826 config_load_geoip_file_(AF_INET6, options->GeoIPv6File, "geoip6");
6829 /** Initialize cookie authentication (used so far by the ControlPort
6830 * and Extended ORPort).
6832 * Allocate memory and create a cookie (of length <b>cookie_len</b>)
6833 * in <b>cookie_out</b>.
6834 * Then write it down to <b>fname</b> and prepend it with <b>header</b>.
6836 * If <b>group_readable</b> is set, set <b>fname</b> to be readable
6837 * by the default GID.
6839 * If the whole procedure was successful, set
6840 * <b>cookie_is_set_out</b> to True. */
6842 init_cookie_authentication(const char *fname, const char *header,
6843 int cookie_len, int group_readable,
6844 uint8_t **cookie_out, int *cookie_is_set_out)
6846 char cookie_file_str_len = strlen(header) + cookie_len;
6847 char *cookie_file_str = tor_malloc(cookie_file_str_len);
6848 int retval = -1;
6850 /* We don't want to generate a new cookie every time we call
6851 * options_act(). One should be enough. */
6852 if (*cookie_is_set_out) {
6853 retval = 0; /* we are all set */
6854 goto done;
6857 /* If we've already set the cookie, free it before re-setting
6858 it. This can happen if we previously generated a cookie, but
6859 couldn't write it to a disk. */
6860 if (*cookie_out)
6861 tor_free(*cookie_out);
6863 /* Generate the cookie */
6864 *cookie_out = tor_malloc(cookie_len);
6865 if (crypto_rand((char *)*cookie_out, cookie_len) < 0)
6866 goto done;
6868 /* Create the string that should be written on the file. */
6869 memcpy(cookie_file_str, header, strlen(header));
6870 memcpy(cookie_file_str+strlen(header), *cookie_out, cookie_len);
6871 if (write_bytes_to_file(fname, cookie_file_str, cookie_file_str_len, 1)) {
6872 log_warn(LD_FS,"Error writing auth cookie to %s.", escaped(fname));
6873 goto done;
6876 #ifndef _WIN32
6877 if (group_readable) {
6878 if (chmod(fname, 0640)) {
6879 log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
6882 #else
6883 (void) group_readable;
6884 #endif
6886 /* Success! */
6887 log_info(LD_GENERAL, "Generated auth cookie file in '%s'.", escaped(fname));
6888 *cookie_is_set_out = 1;
6889 retval = 0;
6891 done:
6892 memwipe(cookie_file_str, 0, cookie_file_str_len);
6893 tor_free(cookie_file_str);
6894 return retval;