correct a point about logging
[tor.git] / src / or / config.c
blob90a5dfbda1c00399b141ef765470be6aeca42ad9
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-2012, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file config.c
9 * \brief Code to parse and interpret configuration files.
10 **/
12 #define CONFIG_PRIVATE
14 #include "or.h"
15 #include "circuitbuild.h"
16 #include "circuitlist.h"
17 #include "config.h"
18 #include "connection.h"
19 #include "connection_edge.h"
20 #include "connection_or.h"
21 #include "control.h"
22 #include "cpuworker.h"
23 #include "dirserv.h"
24 #include "dirvote.h"
25 #include "dns.h"
26 #include "geoip.h"
27 #include "hibernate.h"
28 #include "main.h"
29 #include "networkstatus.h"
30 #include "policies.h"
31 #include "relay.h"
32 #include "rendclient.h"
33 #include "rendservice.h"
34 #include "rephist.h"
35 #include "router.h"
36 #include "util.h"
37 #include "routerlist.h"
38 #include "transports.h"
39 #ifdef _WIN32
40 #include <shlobj.h>
41 #endif
43 #include "procmon.h"
45 /* From main.c */
46 extern int quiet_level;
48 /** Enumeration of types which option values can take */
49 typedef enum config_type_t {
50 CONFIG_TYPE_STRING = 0, /**< An arbitrary string. */
51 CONFIG_TYPE_FILENAME, /**< A filename: some prefixes get expanded. */
52 CONFIG_TYPE_UINT, /**< A non-negative integer less than MAX_INT */
53 CONFIG_TYPE_INT, /**< Any integer. */
54 CONFIG_TYPE_PORT, /**< A port from 1...65535, 0 for "not set", or
55 * "auto". */
56 CONFIG_TYPE_INTERVAL, /**< A number of seconds, with optional units*/
57 CONFIG_TYPE_MSEC_INTERVAL,/**< A number of milliseconds, with optional
58 * units */
59 CONFIG_TYPE_MEMUNIT, /**< A number of bytes, with optional units*/
60 CONFIG_TYPE_DOUBLE, /**< A floating-point value */
61 CONFIG_TYPE_BOOL, /**< A boolean value, expressed as 0 or 1. */
62 CONFIG_TYPE_AUTOBOOL, /**< A boolean+auto value, expressed 0 for false,
63 * 1 for true, and -1 for auto */
64 CONFIG_TYPE_ISOTIME, /**< An ISO-formatted time relative to GMT. */
65 CONFIG_TYPE_CSV, /**< A list of strings, separated by commas and
66 * optional whitespace. */
67 CONFIG_TYPE_LINELIST, /**< Uninterpreted config lines */
68 CONFIG_TYPE_LINELIST_S, /**< Uninterpreted, context-sensitive config lines,
69 * mixed with other keywords. */
70 CONFIG_TYPE_LINELIST_V, /**< Catch-all "virtual" option to summarize
71 * context-sensitive config lines when fetching.
73 CONFIG_TYPE_ROUTERSET, /**< A list of router names, addrs, and fps,
74 * parsed into a routerset_t. */
75 CONFIG_TYPE_OBSOLETE, /**< Obsolete (ignored) option. */
76 } config_type_t;
78 /** An abbreviation for a configuration option allowed on the command line. */
79 typedef struct config_abbrev_t {
80 const char *abbreviated;
81 const char *full;
82 int commandline_only;
83 int warn;
84 } config_abbrev_t;
86 /* Handy macro for declaring "In the config file or on the command line,
87 * you can abbreviate <b>tok</b>s as <b>tok</b>". */
88 #define PLURAL(tok) { #tok, #tok "s", 0, 0 }
90 /** A list of abbreviations and aliases to map command-line options, obsolete
91 * option names, or alternative option names, to their current values. */
92 static config_abbrev_t _option_abbrevs[] = {
93 PLURAL(AuthDirBadDirCC),
94 PLURAL(AuthDirBadExitCC),
95 PLURAL(AuthDirInvalidCC),
96 PLURAL(AuthDirRejectCC),
97 PLURAL(ExitNode),
98 PLURAL(EntryNode),
99 PLURAL(ExcludeNode),
100 PLURAL(FirewallPort),
101 PLURAL(LongLivedPort),
102 PLURAL(HiddenServiceNode),
103 PLURAL(HiddenServiceExcludeNode),
104 PLURAL(NumCPU),
105 PLURAL(RendNode),
106 PLURAL(RendExcludeNode),
107 PLURAL(StrictEntryNode),
108 PLURAL(StrictExitNode),
109 PLURAL(StrictNode),
110 { "l", "Log", 1, 0},
111 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
112 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
113 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
114 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
115 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
116 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
117 { "MaxConn", "ConnLimit", 0, 1},
118 { "ORBindAddress", "ORListenAddress", 0, 0},
119 { "DirBindAddress", "DirListenAddress", 0, 0},
120 { "SocksBindAddress", "SocksListenAddress", 0, 0},
121 { "UseHelperNodes", "UseEntryGuards", 0, 0},
122 { "NumHelperNodes", "NumEntryGuards", 0, 0},
123 { "UseEntryNodes", "UseEntryGuards", 0, 0},
124 { "NumEntryNodes", "NumEntryGuards", 0, 0},
125 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
126 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
127 { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0},
128 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
129 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
130 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
131 { "StrictEntryNodes", "StrictNodes", 0, 1},
132 { "StrictExitNodes", "StrictNodes", 0, 1},
133 { NULL, NULL, 0, 0},
136 /** A list of state-file "abbreviations," for compatibility. */
137 static config_abbrev_t _state_abbrevs[] = {
138 { "AccountingBytesReadInterval", "AccountingBytesReadInInterval", 0, 0 },
139 { "HelperNode", "EntryGuard", 0, 0 },
140 { "HelperNodeDownSince", "EntryGuardDownSince", 0, 0 },
141 { "HelperNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
142 { "EntryNode", "EntryGuard", 0, 0 },
143 { "EntryNodeDownSince", "EntryGuardDownSince", 0, 0 },
144 { "EntryNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
145 { NULL, NULL, 0, 0},
147 #undef PLURAL
149 /** A variable allowed in the configuration file or on the command line. */
150 typedef struct config_var_t {
151 const char *name; /**< The full keyword (case insensitive). */
152 config_type_t type; /**< How to interpret the type and turn it into a
153 * value. */
154 off_t var_offset; /**< Offset of the corresponding member of or_options_t. */
155 const char *initvalue; /**< String (or null) describing initial value. */
156 } config_var_t;
158 /** An entry for config_vars: "The option <b>name</b> has type
159 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
160 * or_options_t.<b>member</b>"
162 #define VAR(name,conftype,member,initvalue) \
163 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
164 initvalue }
165 /** As VAR, but the option name and member name are the same. */
166 #define V(member,conftype,initvalue) \
167 VAR(#member, conftype, member, initvalue)
168 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
169 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
171 #define VPORT(member,conftype,initvalue) \
172 VAR(#member, conftype, member ## _lines, initvalue)
174 /** Array of configuration options. Until we disallow nonstandard
175 * abbreviations, order is significant, since the first matching option will
176 * be chosen first.
178 static config_var_t _option_vars[] = {
179 OBSOLETE("AccountingMaxKB"),
180 V(AccountingMax, MEMUNIT, "0 bytes"),
181 V(AccountingStart, STRING, NULL),
182 V(Address, STRING, NULL),
183 V(AllowDotExit, BOOL, "0"),
184 V(AllowInvalidNodes, CSV, "middle,rendezvous"),
185 V(AllowNonRFC953Hostnames, BOOL, "0"),
186 V(AllowSingleHopCircuits, BOOL, "0"),
187 V(AllowSingleHopExits, BOOL, "0"),
188 V(AlternateBridgeAuthority, LINELIST, NULL),
189 V(AlternateDirAuthority, LINELIST, NULL),
190 V(AlternateHSAuthority, LINELIST, NULL),
191 V(AssumeReachable, BOOL, "0"),
192 V(AuthDirBadDir, LINELIST, NULL),
193 V(AuthDirBadDirCCs, CSV, ""),
194 V(AuthDirBadExit, LINELIST, NULL),
195 V(AuthDirBadExitCCs, CSV, ""),
196 V(AuthDirInvalid, LINELIST, NULL),
197 V(AuthDirInvalidCCs, CSV, ""),
198 V(AuthDirFastGuarantee, MEMUNIT, "100 KB"),
199 V(AuthDirGuardBWGuarantee, MEMUNIT, "250 KB"),
200 V(AuthDirReject, LINELIST, NULL),
201 V(AuthDirRejectCCs, CSV, ""),
202 V(AuthDirRejectUnlisted, BOOL, "0"),
203 V(AuthDirListBadDirs, BOOL, "0"),
204 V(AuthDirListBadExits, BOOL, "0"),
205 V(AuthDirMaxServersPerAddr, UINT, "2"),
206 V(AuthDirMaxServersPerAuthAddr,UINT, "5"),
207 VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
208 V(AutomapHostsOnResolve, BOOL, "0"),
209 V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
210 V(AvoidDiskWrites, BOOL, "0"),
211 V(BandwidthBurst, MEMUNIT, "10 MB"),
212 V(BandwidthRate, MEMUNIT, "5 MB"),
213 V(BridgeAuthoritativeDir, BOOL, "0"),
214 VAR("Bridge", LINELIST, Bridges, NULL),
215 V(BridgePassword, STRING, NULL),
216 V(BridgeRecordUsageByCountry, BOOL, "1"),
217 V(BridgeRelay, BOOL, "0"),
218 V(CellStatistics, BOOL, "0"),
219 V(LearnCircuitBuildTimeout, BOOL, "1"),
220 V(CircuitBuildTimeout, INTERVAL, "0"),
221 V(CircuitIdleTimeout, INTERVAL, "1 hour"),
222 V(CircuitStreamTimeout, INTERVAL, "0"),
223 V(CircuitPriorityHalflife, DOUBLE, "-100.0"), /*negative:'Use default'*/
224 V(ClientDNSRejectInternalAddresses, BOOL,"1"),
225 V(ClientOnly, BOOL, "0"),
226 V(ClientRejectInternalAddresses, BOOL, "1"),
227 V(ClientTransportPlugin, LINELIST, NULL),
228 V(ConsensusParams, STRING, NULL),
229 V(ConnLimit, UINT, "1000"),
230 V(ConnDirectionStatistics, BOOL, "0"),
231 V(ConstrainedSockets, BOOL, "0"),
232 V(ConstrainedSockSize, MEMUNIT, "8192"),
233 V(ContactInfo, STRING, NULL),
234 V(ControlListenAddress, LINELIST, NULL),
235 VPORT(ControlPort, LINELIST, NULL),
236 V(ControlPortFileGroupReadable,BOOL, "0"),
237 V(ControlPortWriteToFile, FILENAME, NULL),
238 V(ControlSocket, LINELIST, NULL),
239 V(ControlSocketsGroupWritable, BOOL, "0"),
240 V(CookieAuthentication, BOOL, "0"),
241 V(CookieAuthFileGroupReadable, BOOL, "0"),
242 V(CookieAuthFile, STRING, NULL),
243 V(CountPrivateBandwidth, BOOL, "0"),
244 V(DataDirectory, FILENAME, NULL),
245 OBSOLETE("DebugLogFile"),
246 V(DisableNetwork, BOOL, "0"),
247 V(DirAllowPrivateAddresses, BOOL, "0"),
248 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
249 V(DirListenAddress, LINELIST, NULL),
250 OBSOLETE("DirFetchPeriod"),
251 V(DirPolicy, LINELIST, NULL),
252 VPORT(DirPort, LINELIST, NULL),
253 V(DirPortFrontPage, FILENAME, NULL),
254 OBSOLETE("DirPostPeriod"),
255 OBSOLETE("DirRecordUsageByCountry"),
256 OBSOLETE("DirRecordUsageGranularity"),
257 OBSOLETE("DirRecordUsageRetainIPs"),
258 OBSOLETE("DirRecordUsageSaveInterval"),
259 V(DirReqStatistics, BOOL, "1"),
260 VAR("DirServer", LINELIST, DirServers, NULL),
261 V(DisableAllSwap, BOOL, "0"),
262 V(DisableDebuggerAttachment, BOOL, "1"),
263 V(DisableIOCP, BOOL, "1"),
264 V(DynamicDHGroups, BOOL, "0"),
265 VPORT(DNSPort, LINELIST, NULL),
266 V(DNSListenAddress, LINELIST, NULL),
267 V(DownloadExtraInfo, BOOL, "0"),
268 V(EnforceDistinctSubnets, BOOL, "1"),
269 V(EntryNodes, ROUTERSET, NULL),
270 V(EntryStatistics, BOOL, "0"),
271 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
272 V(ExcludeNodes, ROUTERSET, NULL),
273 V(ExcludeExitNodes, ROUTERSET, NULL),
274 V(ExcludeSingleHopRelays, BOOL, "1"),
275 V(ExitNodes, ROUTERSET, NULL),
276 V(ExitPolicy, LINELIST, NULL),
277 V(ExitPolicyRejectPrivate, BOOL, "1"),
278 V(ExitPortStatistics, BOOL, "0"),
279 V(ExtendAllowPrivateAddresses, BOOL, "0"),
280 V(ExtraInfoStatistics, BOOL, "1"),
282 #if defined (WINCE)
283 V(FallbackNetworkstatusFile, FILENAME, "fallback-consensus"),
284 #else
285 V(FallbackNetworkstatusFile, FILENAME,
286 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "fallback-consensus"),
287 #endif
288 V(FascistFirewall, BOOL, "0"),
289 V(FirewallPorts, CSV, ""),
290 V(FastFirstHopPK, BOOL, "1"),
291 V(FetchDirInfoEarly, BOOL, "0"),
292 V(FetchDirInfoExtraEarly, BOOL, "0"),
293 V(FetchServerDescriptors, BOOL, "1"),
294 V(FetchHidServDescriptors, BOOL, "1"),
295 V(FetchUselessDescriptors, BOOL, "0"),
296 V(FetchV2Networkstatus, BOOL, "0"),
297 #ifdef _WIN32
298 V(GeoIPFile, FILENAME, "<default>"),
299 #else
300 V(GeoIPFile, FILENAME,
301 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
302 #endif
303 OBSOLETE("GiveGuardFlagTo_CVE_2011_2768_VulnerableRelays"),
304 OBSOLETE("Group"),
305 V(HardwareAccel, BOOL, "0"),
306 V(HeartbeatPeriod, INTERVAL, "6 hours"),
307 V(AccelName, STRING, NULL),
308 V(AccelDir, FILENAME, NULL),
309 V(HashedControlPassword, LINELIST, NULL),
310 V(HidServDirectoryV2, BOOL, "1"),
311 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
312 OBSOLETE("HiddenServiceExcludeNodes"),
313 OBSOLETE("HiddenServiceNodes"),
314 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
315 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
316 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
317 VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
318 V(HidServAuth, LINELIST, NULL),
319 V(HSAuthoritativeDir, BOOL, "0"),
320 OBSOLETE("HSAuthorityRecordStats"),
321 V(CloseHSClientCircuitsImmediatelyOnTimeout, BOOL, "0"),
322 V(CloseHSServiceRendCircuitsImmediatelyOnTimeout, BOOL, "0"),
323 V(HTTPProxy, STRING, NULL),
324 V(HTTPProxyAuthenticator, STRING, NULL),
325 V(HTTPSProxy, STRING, NULL),
326 V(HTTPSProxyAuthenticator, STRING, NULL),
327 VAR("ServerTransportPlugin", LINELIST, ServerTransportPlugin, NULL),
328 V(Socks4Proxy, STRING, NULL),
329 V(Socks5Proxy, STRING, NULL),
330 V(Socks5ProxyUsername, STRING, NULL),
331 V(Socks5ProxyPassword, STRING, NULL),
332 OBSOLETE("IgnoreVersion"),
333 V(KeepalivePeriod, INTERVAL, "5 minutes"),
334 VAR("Log", LINELIST, Logs, NULL),
335 V(LogMessageDomains, BOOL, "0"),
336 OBSOLETE("LinkPadding"),
337 OBSOLETE("LogLevel"),
338 OBSOLETE("LogFile"),
339 V(LogTimeGranularity, MSEC_INTERVAL, "1 second"),
340 V(LongLivedPorts, CSV,
341 "21,22,706,1863,5050,5190,5222,5223,6523,6667,6697,8300"),
342 VAR("MapAddress", LINELIST, AddressMap, NULL),
343 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
344 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
345 V(MaxClientCircuitsPending, UINT, "32"),
346 V(MaxOnionsPending, UINT, "100"),
347 OBSOLETE("MonthlyAccountingStart"),
348 V(MyFamily, STRING, NULL),
349 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
350 VAR("NamingAuthoritativeDirectory",BOOL, NamingAuthoritativeDir, "0"),
351 V(NATDListenAddress, LINELIST, NULL),
352 VPORT(NATDPort, LINELIST, NULL),
353 V(Nickname, STRING, NULL),
354 V(WarnUnsafeSocks, BOOL, "1"),
355 OBSOLETE("NoPublish"),
356 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
357 V(NumCPUs, UINT, "0"),
358 V(NumEntryGuards, UINT, "3"),
359 V(ORListenAddress, LINELIST, NULL),
360 VPORT(ORPort, LINELIST, NULL),
361 V(OutboundBindAddress, STRING, NULL),
363 V(PathBiasCircThreshold, INT, "-1"),
364 V(PathBiasNoticeRate, DOUBLE, "-1"),
365 V(PathBiasDisableRate, DOUBLE, "-1"),
366 V(PathBiasScaleThreshold, INT, "-1"),
367 V(PathBiasScaleFactor, INT, "-1"),
369 OBSOLETE("PathlenCoinWeight"),
370 V(PerConnBWBurst, MEMUNIT, "0"),
371 V(PerConnBWRate, MEMUNIT, "0"),
372 V(PidFile, STRING, NULL),
373 V(TestingTorNetwork, BOOL, "0"),
374 V(OptimisticData, AUTOBOOL, "auto"),
375 V(PortForwarding, BOOL, "0"),
376 V(PortForwardingHelper, FILENAME, "tor-fw-helper"),
377 V(PreferTunneledDirConns, BOOL, "1"),
378 V(ProtocolWarnings, BOOL, "0"),
379 V(PublishServerDescriptor, CSV, "1"),
380 V(PublishHidServDescriptors, BOOL, "1"),
381 V(ReachableAddresses, LINELIST, NULL),
382 V(ReachableDirAddresses, LINELIST, NULL),
383 V(ReachableORAddresses, LINELIST, NULL),
384 V(RecommendedVersions, LINELIST, NULL),
385 V(RecommendedClientVersions, LINELIST, NULL),
386 V(RecommendedServerVersions, LINELIST, NULL),
387 OBSOLETE("RedirectExit"),
388 V(RefuseUnknownExits, AUTOBOOL, "auto"),
389 V(RejectPlaintextPorts, CSV, ""),
390 V(RelayBandwidthBurst, MEMUNIT, "0"),
391 V(RelayBandwidthRate, MEMUNIT, "0"),
392 OBSOLETE("RendExcludeNodes"),
393 OBSOLETE("RendNodes"),
394 V(RendPostPeriod, INTERVAL, "1 hour"),
395 V(RephistTrackTime, INTERVAL, "24 hours"),
396 OBSOLETE("RouterFile"),
397 V(RunAsDaemon, BOOL, "0"),
398 // V(RunTesting, BOOL, "0"),
399 OBSOLETE("RunTesting"), // currently unused
400 V(SafeLogging, STRING, "1"),
401 V(SafeSocks, BOOL, "0"),
402 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
403 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
404 V(ServerDNSDetectHijacking, BOOL, "1"),
405 V(ServerDNSRandomizeCase, BOOL, "1"),
406 V(ServerDNSResolvConfFile, STRING, NULL),
407 V(ServerDNSSearchDomains, BOOL, "0"),
408 V(ServerDNSTestAddresses, CSV,
409 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
410 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
411 V(SocksListenAddress, LINELIST, NULL),
412 V(SocksPolicy, LINELIST, NULL),
413 VPORT(SocksPort, LINELIST, NULL),
414 V(SocksTimeout, INTERVAL, "2 minutes"),
415 OBSOLETE("StatusFetchPeriod"),
416 V(StrictNodes, BOOL, "0"),
417 OBSOLETE("SysLog"),
418 V(TestSocks, BOOL, "0"),
419 OBSOLETE("TestVia"),
420 V(TokenBucketRefillInterval, MSEC_INTERVAL, "100 msec"),
421 V(Tor2webMode, BOOL, "0"),
422 V(TrackHostExits, CSV, NULL),
423 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
424 OBSOLETE("TrafficShaping"),
425 V(TransListenAddress, LINELIST, NULL),
426 VPORT(TransPort, LINELIST, NULL),
427 V(TunnelDirConns, BOOL, "1"),
428 V(UpdateBridgesFromAuthority, BOOL, "0"),
429 V(UseBridges, BOOL, "0"),
430 V(UseEntryGuards, BOOL, "1"),
431 V(UseMicrodescriptors, AUTOBOOL, "auto"),
432 V(User, STRING, NULL),
433 V(UserspaceIOCPBuffers, BOOL, "0"),
434 VAR("V1AuthoritativeDirectory",BOOL, V1AuthoritativeDir, "0"),
435 VAR("V2AuthoritativeDirectory",BOOL, V2AuthoritativeDir, "0"),
436 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
437 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
438 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
439 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
440 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
441 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
442 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
443 V(V3AuthNIntervalsValid, UINT, "3"),
444 V(V3AuthUseLegacyKey, BOOL, "0"),
445 V(V3BandwidthsFile, FILENAME, NULL),
446 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
447 V(VirtualAddrNetwork, STRING, "127.192.0.0/10"),
448 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
449 V(_UseFilteringSSLBufferevents, BOOL, "0"),
450 VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
451 VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
452 VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
453 VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
454 VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
455 NULL),
456 VAR("__OwningControllerProcess",STRING,OwningControllerProcess, NULL),
457 V(MinUptimeHidServDirectoryV2, INTERVAL, "25 hours"),
458 V(VoteOnHidServDirectoriesV2, BOOL, "1"),
459 V(_UsingTestNetworkDefaults, BOOL, "0"),
461 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
464 /** Override default values with these if the user sets the TestingTorNetwork
465 * option. */
466 static const config_var_t testing_tor_network_defaults[] = {
467 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
468 V(DirAllowPrivateAddresses, BOOL, "1"),
469 V(EnforceDistinctSubnets, BOOL, "0"),
470 V(AssumeReachable, BOOL, "1"),
471 V(AuthDirMaxServersPerAddr, UINT, "0"),
472 V(AuthDirMaxServersPerAuthAddr,UINT, "0"),
473 V(ClientDNSRejectInternalAddresses, BOOL,"0"),
474 V(ClientRejectInternalAddresses, BOOL, "0"),
475 V(CountPrivateBandwidth, BOOL, "1"),
476 V(ExitPolicyRejectPrivate, BOOL, "0"),
477 V(ExtendAllowPrivateAddresses, BOOL, "1"),
478 V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
479 V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
480 V(V3AuthDistDelay, INTERVAL, "20 seconds"),
481 V(TestingV3AuthInitialVotingInterval, INTERVAL, "5 minutes"),
482 V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
483 V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
484 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
485 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
486 V(MinUptimeHidServDirectoryV2, INTERVAL, "0 minutes"),
487 V(_UsingTestNetworkDefaults, BOOL, "1"),
489 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
491 #undef VAR
493 #define VAR(name,conftype,member,initvalue) \
494 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
495 initvalue }
497 /** Array of "state" variables saved to the ~/.tor/state file. */
498 static config_var_t _state_vars[] = {
499 /* Remember to document these in state-contents.txt ! */
501 V(AccountingBytesReadInInterval, MEMUNIT, NULL),
502 V(AccountingBytesWrittenInInterval, MEMUNIT, NULL),
503 V(AccountingExpectedUsage, MEMUNIT, NULL),
504 V(AccountingIntervalStart, ISOTIME, NULL),
505 V(AccountingSecondsActive, INTERVAL, NULL),
506 V(AccountingSecondsToReachSoftLimit,INTERVAL, NULL),
507 V(AccountingSoftLimitHitAt, ISOTIME, NULL),
508 V(AccountingBytesAtSoftLimit, MEMUNIT, NULL),
510 VAR("EntryGuard", LINELIST_S, EntryGuards, NULL),
511 VAR("EntryGuardDownSince", LINELIST_S, EntryGuards, NULL),
512 VAR("EntryGuardUnlistedSince", LINELIST_S, EntryGuards, NULL),
513 VAR("EntryGuardAddedBy", LINELIST_S, EntryGuards, NULL),
514 VAR("EntryGuardPathBias", LINELIST_S, EntryGuards, NULL),
515 V(EntryGuards, LINELIST_V, NULL),
517 VAR("TransportProxy", LINELIST_S, TransportProxies, NULL),
518 V(TransportProxies, LINELIST_V, NULL),
520 V(BWHistoryReadEnds, ISOTIME, NULL),
521 V(BWHistoryReadInterval, UINT, "900"),
522 V(BWHistoryReadValues, CSV, ""),
523 V(BWHistoryReadMaxima, CSV, ""),
524 V(BWHistoryWriteEnds, ISOTIME, NULL),
525 V(BWHistoryWriteInterval, UINT, "900"),
526 V(BWHistoryWriteValues, CSV, ""),
527 V(BWHistoryWriteMaxima, CSV, ""),
528 V(BWHistoryDirReadEnds, ISOTIME, NULL),
529 V(BWHistoryDirReadInterval, UINT, "900"),
530 V(BWHistoryDirReadValues, CSV, ""),
531 V(BWHistoryDirReadMaxima, CSV, ""),
532 V(BWHistoryDirWriteEnds, ISOTIME, NULL),
533 V(BWHistoryDirWriteInterval, UINT, "900"),
534 V(BWHistoryDirWriteValues, CSV, ""),
535 V(BWHistoryDirWriteMaxima, CSV, ""),
537 V(TorVersion, STRING, NULL),
539 V(LastRotatedOnionKey, ISOTIME, NULL),
540 V(LastWritten, ISOTIME, NULL),
542 V(TotalBuildTimes, UINT, NULL),
543 V(CircuitBuildAbandonedCount, UINT, "0"),
544 VAR("CircuitBuildTimeBin", LINELIST_S, BuildtimeHistogram, NULL),
545 VAR("BuildtimeHistogram", LINELIST_V, BuildtimeHistogram, NULL),
546 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
549 #undef VAR
550 #undef V
551 #undef OBSOLETE
553 /** Represents an English description of a configuration variable; used when
554 * generating configuration file comments. */
555 typedef struct config_var_description_t {
556 const char *name;
557 const char *description;
558 } config_var_description_t;
560 /** Type of a callback to validate whether a given configuration is
561 * well-formed and consistent. See options_trial_assign() for documentation
562 * of arguments. */
563 typedef int (*validate_fn_t)(void*,void*,int,char**);
565 /** Information on the keys, value types, key-to-struct-member mappings,
566 * variable descriptions, validation functions, and abbreviations for a
567 * configuration or storage format. */
568 typedef struct {
569 size_t size; /**< Size of the struct that everything gets parsed into. */
570 uint32_t magic; /**< Required 'magic value' to make sure we have a struct
571 * of the right type. */
572 off_t magic_offset; /**< Offset of the magic value within the struct. */
573 config_abbrev_t *abbrevs; /**< List of abbreviations that we expand when
574 * parsing this format. */
575 config_var_t *vars; /**< List of variables we recognize, their default
576 * values, and where we stick them in the structure. */
577 validate_fn_t validate_fn; /**< Function to validate config. */
578 /** If present, extra is a LINELIST variable for unrecognized
579 * lines. Otherwise, unrecognized lines are an error. */
580 config_var_t *extra;
581 } config_format_t;
583 /** Macro: assert that <b>cfg</b> has the right magic field for format
584 * <b>fmt</b>. */
585 #define CHECK(fmt, cfg) STMT_BEGIN \
586 tor_assert(fmt && cfg); \
587 tor_assert((fmt)->magic == \
588 *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
589 STMT_END
591 #ifdef _WIN32
592 static char *get_windows_conf_root(void);
593 #endif
594 static void config_line_append(config_line_t **lst,
595 const char *key, const char *val);
596 static void option_clear(const config_format_t *fmt, or_options_t *options,
597 const config_var_t *var);
598 static void option_reset(const config_format_t *fmt, or_options_t *options,
599 const config_var_t *var, int use_defaults);
600 static void config_free(const config_format_t *fmt, void *options);
601 static int config_lines_eq(config_line_t *a, config_line_t *b);
602 static int config_count_key(const config_line_t *a, const char *key);
603 static int option_is_same(const config_format_t *fmt,
604 const or_options_t *o1, const or_options_t *o2,
605 const char *name);
606 static or_options_t *options_dup(const config_format_t *fmt,
607 const or_options_t *old);
608 static int options_validate(or_options_t *old_options,
609 or_options_t *options,
610 int from_setconf, char **msg);
611 static int options_act_reversible(const or_options_t *old_options, char **msg);
612 static int options_act(const or_options_t *old_options);
613 static int options_transition_allowed(const or_options_t *old,
614 const or_options_t *new,
615 char **msg);
616 static int options_transition_affects_workers(
617 const or_options_t *old_options, const or_options_t *new_options);
618 static int options_transition_affects_descriptor(
619 const or_options_t *old_options, const or_options_t *new_options);
620 static int check_nickname_list(const char *lst, const char *name, char **msg);
622 static int parse_bridge_line(const char *line, int validate_only);
623 static int parse_client_transport_line(const char *line, int validate_only);
625 static int parse_server_transport_line(const char *line, int validate_only);
626 static int parse_dir_server_line(const char *line,
627 dirinfo_type_t required_type,
628 int validate_only);
629 static void port_cfg_free(port_cfg_t *port);
630 static int parse_ports(or_options_t *options, int validate_only,
631 char **msg_out, int *n_ports_out);
632 static int check_server_ports(const smartlist_t *ports,
633 const or_options_t *options);
635 static int validate_data_directory(or_options_t *options);
636 static int write_configuration_file(const char *fname,
637 const or_options_t *options);
638 static config_line_t *get_assigned_option(const config_format_t *fmt,
639 const void *options, const char *key,
640 int escape_val);
641 static void config_init(const config_format_t *fmt, void *options);
642 static int or_state_validate(or_state_t *old_options, or_state_t *options,
643 int from_setconf, char **msg);
644 static int or_state_load(void);
645 static int options_init_logs(or_options_t *options, int validate_only);
647 static uint64_t config_parse_memunit(const char *s, int *ok);
648 static int config_parse_msec_interval(const char *s, int *ok);
649 static int config_parse_interval(const char *s, int *ok);
650 static void init_libevent(const or_options_t *options);
651 static int opt_streq(const char *s1, const char *s2);
653 /** Magic value for or_options_t. */
654 #define OR_OPTIONS_MAGIC 9090909
656 /** Configuration format for or_options_t. */
657 static config_format_t options_format = {
658 sizeof(or_options_t),
659 OR_OPTIONS_MAGIC,
660 STRUCT_OFFSET(or_options_t, _magic),
661 _option_abbrevs,
662 _option_vars,
663 (validate_fn_t)options_validate,
664 NULL
667 /** Magic value for or_state_t. */
668 #define OR_STATE_MAGIC 0x57A73f57
670 /** "Extra" variable in the state that receives lines we can't parse. This
671 * lets us preserve options from versions of Tor newer than us. */
672 static config_var_t state_extra_var = {
673 "__extra", CONFIG_TYPE_LINELIST, STRUCT_OFFSET(or_state_t, ExtraLines), NULL
676 /** Configuration format for or_state_t. */
677 static const config_format_t state_format = {
678 sizeof(or_state_t),
679 OR_STATE_MAGIC,
680 STRUCT_OFFSET(or_state_t, _magic),
681 _state_abbrevs,
682 _state_vars,
683 (validate_fn_t)or_state_validate,
684 &state_extra_var,
688 * Functions to read and write the global options pointer.
691 /** Command-line and config-file options. */
692 static or_options_t *global_options = NULL;
693 /** The fallback options_t object; this is where we look for options not
694 * in torrc before we fall back to Tor's defaults. */
695 static or_options_t *global_default_options = NULL;
696 /** Name of most recently read torrc file. */
697 static char *torrc_fname = NULL;
698 /** Name of the most recently read torrc-defaults file.*/
699 static char *torrc_defaults_fname;
700 /** Persistent serialized state. */
701 static or_state_t *global_state = NULL;
702 /** Configuration Options set by command line. */
703 static config_line_t *global_cmdline_options = NULL;
704 /** Contents of most recently read DirPortFrontPage file. */
705 static char *global_dirfrontpagecontents = NULL;
706 /** List of port_cfg_t for all configured ports. */
707 static smartlist_t *configured_ports = NULL;
709 /** Return the contents of our frontpage string, or NULL if not configured. */
710 const char *
711 get_dirportfrontpage(void)
713 return global_dirfrontpagecontents;
716 /** Allocate an empty configuration object of a given format type. */
717 static void *
718 config_alloc(const config_format_t *fmt)
720 void *opts = tor_malloc_zero(fmt->size);
721 *(uint32_t*)STRUCT_VAR_P(opts, fmt->magic_offset) = fmt->magic;
722 CHECK(fmt, opts);
723 return opts;
726 /** Return the currently configured options. */
727 or_options_t *
728 get_options_mutable(void)
730 tor_assert(global_options);
731 return global_options;
734 /** Returns the currently configured options */
735 const or_options_t *
736 get_options(void)
738 return get_options_mutable();
741 /** Change the current global options to contain <b>new_val</b> instead of
742 * their current value; take action based on the new value; free the old value
743 * as necessary. Returns 0 on success, -1 on failure.
746 set_options(or_options_t *new_val, char **msg)
748 int i;
749 smartlist_t *elements;
750 config_line_t *line;
751 or_options_t *old_options = global_options;
752 global_options = new_val;
753 /* Note that we pass the *old* options below, for comparison. It
754 * pulls the new options directly out of global_options. */
755 if (options_act_reversible(old_options, msg)<0) {
756 tor_assert(*msg);
757 global_options = old_options;
758 return -1;
760 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
761 log_err(LD_BUG,
762 "Acting on config options left us in a broken state. Dying.");
763 exit(1);
765 /* Issues a CONF_CHANGED event to notify controller of the change. If Tor is
766 * just starting up then the old_options will be undefined. */
767 if (old_options && old_options != global_options) {
768 elements = smartlist_new();
769 for (i=0; options_format.vars[i].name; ++i) {
770 const config_var_t *var = &options_format.vars[i];
771 const char *var_name = var->name;
772 if (var->type == CONFIG_TYPE_LINELIST_S ||
773 var->type == CONFIG_TYPE_OBSOLETE) {
774 continue;
776 if (!option_is_same(&options_format, new_val, old_options, var_name)) {
777 line = get_assigned_option(&options_format, new_val, var_name, 1);
779 if (line) {
780 for (; line; line = line->next) {
781 smartlist_add(elements, line->key);
782 smartlist_add(elements, line->value);
784 } else {
785 smartlist_add(elements, (char*)options_format.vars[i].name);
786 smartlist_add(elements, NULL);
790 control_event_conf_changed(elements);
791 smartlist_free(elements);
794 if (old_options != global_options)
795 config_free(&options_format, old_options);
797 return 0;
800 extern const char tor_git_revision[]; /* from tor_main.c */
802 /** The version of this Tor process, as parsed. */
803 static char *the_tor_version = NULL;
804 /** A shorter version of this Tor process's version, for export in our router
805 * descriptor. (Does not include the git version, if any.) */
806 static char *the_short_tor_version = NULL;
808 /** Return the current Tor version. */
809 const char *
810 get_version(void)
812 if (the_tor_version == NULL) {
813 if (strlen(tor_git_revision)) {
814 tor_asprintf(&the_tor_version, "%s (git-%s)", get_short_version(),
815 tor_git_revision);
816 } else {
817 the_tor_version = tor_strdup(get_short_version());
820 return the_tor_version;
823 /** Return the current Tor version, without any git tag. */
824 const char *
825 get_short_version(void)
828 if (the_short_tor_version == NULL) {
829 #ifdef TOR_BUILD_TAG
830 tor_asprintf(&the_short_tor_version, "%s (%s)", VERSION, TOR_BUILD_TAG);
831 #else
832 the_short_tor_version = tor_strdup(VERSION);
833 #endif
835 return the_short_tor_version;
838 /** Release additional memory allocated in options
840 static void
841 or_options_free(or_options_t *options)
843 if (!options)
844 return;
846 routerset_free(options->_ExcludeExitNodesUnion);
847 if (options->NodeFamilySets) {
848 SMARTLIST_FOREACH(options->NodeFamilySets, routerset_t *,
849 rs, routerset_free(rs));
850 smartlist_free(options->NodeFamilySets);
852 tor_free(options->_BridgePassword_AuthDigest);
853 config_free(&options_format, options);
856 /** Release all memory and resources held by global configuration structures.
858 void
859 config_free_all(void)
861 or_options_free(global_options);
862 global_options = NULL;
863 or_options_free(global_default_options);
864 global_default_options = NULL;
866 config_free(&state_format, global_state);
867 global_state = NULL;
869 config_free_lines(global_cmdline_options);
870 global_cmdline_options = NULL;
872 if (configured_ports) {
873 SMARTLIST_FOREACH(configured_ports,
874 port_cfg_t *, p, tor_free(p));
875 smartlist_free(configured_ports);
876 configured_ports = NULL;
879 tor_free(torrc_fname);
880 tor_free(torrc_defaults_fname);
881 tor_free(the_tor_version);
882 tor_free(global_dirfrontpagecontents);
885 /** Make <b>address</b> -- a piece of information related to our operation as
886 * a client -- safe to log according to the settings in options->SafeLogging,
887 * and return it.
889 * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
891 const char *
892 safe_str_client(const char *address)
894 tor_assert(address);
895 if (get_options()->_SafeLogging == SAFELOG_SCRUB_ALL)
896 return "[scrubbed]";
897 else
898 return address;
901 /** Make <b>address</b> -- a piece of information of unspecified sensitivity
902 * -- safe to log according to the settings in options->SafeLogging, and
903 * return it.
905 * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
906 * otherwise.)
908 const char *
909 safe_str(const char *address)
911 tor_assert(address);
912 if (get_options()->_SafeLogging != SAFELOG_SCRUB_NONE)
913 return "[scrubbed]";
914 else
915 return address;
918 /** Equivalent to escaped(safe_str_client(address)). See reentrancy note on
919 * escaped(): don't use this outside the main thread, or twice in the same
920 * log statement. */
921 const char *
922 escaped_safe_str_client(const char *address)
924 if (get_options()->_SafeLogging == SAFELOG_SCRUB_ALL)
925 return "[scrubbed]";
926 else
927 return escaped(address);
930 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
931 * escaped(): don't use this outside the main thread, or twice in the same
932 * log statement. */
933 const char *
934 escaped_safe_str(const char *address)
936 if (get_options()->_SafeLogging != SAFELOG_SCRUB_NONE)
937 return "[scrubbed]";
938 else
939 return escaped(address);
942 /** Add the default directory authorities directly into the trusted dir list,
943 * but only add them insofar as they share bits with <b>type</b>. */
944 static void
945 add_default_trusted_dir_authorities(dirinfo_type_t type)
947 int i;
948 const char *dirservers[] = {
949 "moria1 orport=9101 no-v2 "
950 "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
951 "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
952 "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
953 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
954 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
955 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
956 "Tonga orport=443 bridge no-v2 82.94.251.203:80 "
957 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
958 "turtles orport=9090 no-v2 "
959 "v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
960 "76.73.17.194:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
961 "gabelmoo orport=443 no-v2 "
962 "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
963 "212.112.245.170:80 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
964 "dannenberg orport=443 no-v2 "
965 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
966 "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
967 "urras orport=80 no-v2 v3ident=80550987E1D626E3EBA5E5E75A458DE0626D088C "
968 "208.83.223.34:443 0AD3 FA88 4D18 F89E EA2D 89C0 1937 9E0E 7FD9 4417",
969 "maatuska orport=80 no-v2 "
970 "v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
971 "171.25.193.9:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
972 "Faravahar orport=443 no-v2 "
973 "v3ident=EFCBE720AB3A82B99F9E953CD5BF50F7EEFC7B97 "
974 "154.35.32.5:80 CF6D 0AAF B385 BE71 B8E1 11FC 5CFF 4B47 9237 33BC",
975 NULL
977 for (i=0; dirservers[i]; i++) {
978 if (parse_dir_server_line(dirservers[i], type, 0)<0) {
979 log_err(LD_BUG, "Couldn't parse internal dirserver line %s",
980 dirservers[i]);
985 /** Look at all the config options for using alternate directory
986 * authorities, and make sure none of them are broken. Also, warn the
987 * user if we changed any dangerous ones.
989 static int
990 validate_dir_authorities(or_options_t *options, or_options_t *old_options)
992 config_line_t *cl;
994 if (options->DirServers &&
995 (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
996 options->AlternateHSAuthority)) {
997 log_warn(LD_CONFIG,
998 "You cannot set both DirServers and Alternate*Authority.");
999 return -1;
1002 /* do we want to complain to the user about being partitionable? */
1003 if ((options->DirServers &&
1004 (!old_options ||
1005 !config_lines_eq(options->DirServers, old_options->DirServers))) ||
1006 (options->AlternateDirAuthority &&
1007 (!old_options ||
1008 !config_lines_eq(options->AlternateDirAuthority,
1009 old_options->AlternateDirAuthority)))) {
1010 log_warn(LD_CONFIG,
1011 "You have used DirServer or AlternateDirAuthority to "
1012 "specify alternate directory authorities in "
1013 "your configuration. This is potentially dangerous: it can "
1014 "make you look different from all other Tor users, and hurt "
1015 "your anonymity. Even if you've specified the same "
1016 "authorities as Tor uses by default, the defaults could "
1017 "change in the future. Be sure you know what you're doing.");
1020 /* Now go through the four ways you can configure an alternate
1021 * set of directory authorities, and make sure none are broken. */
1022 for (cl = options->DirServers; cl; cl = cl->next)
1023 if (parse_dir_server_line(cl->value, NO_DIRINFO, 1)<0)
1024 return -1;
1025 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1026 if (parse_dir_server_line(cl->value, NO_DIRINFO, 1)<0)
1027 return -1;
1028 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1029 if (parse_dir_server_line(cl->value, NO_DIRINFO, 1)<0)
1030 return -1;
1031 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
1032 if (parse_dir_server_line(cl->value, NO_DIRINFO, 1)<0)
1033 return -1;
1034 return 0;
1037 /** Look at all the config options and assign new dir authorities
1038 * as appropriate.
1040 static int
1041 consider_adding_dir_authorities(const or_options_t *options,
1042 const or_options_t *old_options)
1044 config_line_t *cl;
1045 int need_to_update =
1046 !smartlist_len(router_get_trusted_dir_servers()) || !old_options ||
1047 !config_lines_eq(options->DirServers, old_options->DirServers) ||
1048 !config_lines_eq(options->AlternateBridgeAuthority,
1049 old_options->AlternateBridgeAuthority) ||
1050 !config_lines_eq(options->AlternateDirAuthority,
1051 old_options->AlternateDirAuthority) ||
1052 !config_lines_eq(options->AlternateHSAuthority,
1053 old_options->AlternateHSAuthority);
1055 if (!need_to_update)
1056 return 0; /* all done */
1058 /* Start from a clean slate. */
1059 clear_trusted_dir_servers();
1061 if (!options->DirServers) {
1062 /* then we may want some of the defaults */
1063 dirinfo_type_t type = NO_DIRINFO;
1064 if (!options->AlternateBridgeAuthority)
1065 type |= BRIDGE_DIRINFO;
1066 if (!options->AlternateDirAuthority)
1067 type |= V1_DIRINFO | V2_DIRINFO | V3_DIRINFO | EXTRAINFO_DIRINFO |
1068 MICRODESC_DIRINFO;
1069 if (!options->AlternateHSAuthority)
1070 type |= HIDSERV_DIRINFO;
1071 add_default_trusted_dir_authorities(type);
1074 for (cl = options->DirServers; cl; cl = cl->next)
1075 if (parse_dir_server_line(cl->value, NO_DIRINFO, 0)<0)
1076 return -1;
1077 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1078 if (parse_dir_server_line(cl->value, NO_DIRINFO, 0)<0)
1079 return -1;
1080 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1081 if (parse_dir_server_line(cl->value, NO_DIRINFO, 0)<0)
1082 return -1;
1083 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
1084 if (parse_dir_server_line(cl->value, NO_DIRINFO, 0)<0)
1085 return -1;
1086 return 0;
1089 /** Fetch the active option list, and take actions based on it. All of the
1090 * things we do should survive being done repeatedly. If present,
1091 * <b>old_options</b> contains the previous value of the options.
1093 * Return 0 if all goes well, return -1 if things went badly.
1095 static int
1096 options_act_reversible(const or_options_t *old_options, char **msg)
1098 smartlist_t *new_listeners = smartlist_new();
1099 smartlist_t *replaced_listeners = smartlist_new();
1100 static int libevent_initialized = 0;
1101 or_options_t *options = get_options_mutable();
1102 int running_tor = options->command == CMD_RUN_TOR;
1103 int set_conn_limit = 0;
1104 int r = -1;
1105 int logs_marked = 0;
1107 /* Daemonize _first_, since we only want to open most of this stuff in
1108 * the subprocess. Libevent bases can't be reliably inherited across
1109 * processes. */
1110 if (running_tor && options->RunAsDaemon) {
1111 /* No need to roll back, since you can't change the value. */
1112 start_daemon();
1115 #ifndef HAVE_SYS_UN_H
1116 if (options->ControlSocket || options->ControlSocketsGroupWritable) {
1117 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported "
1118 "on this OS/with this build.");
1119 goto rollback;
1121 #else
1122 if (options->ControlSocketsGroupWritable && !options->ControlSocket) {
1123 *msg = tor_strdup("Setting ControlSocketGroupWritable without setting"
1124 "a ControlSocket makes no sense.");
1125 goto rollback;
1127 #endif
1129 if (running_tor) {
1130 int n_ports=0;
1131 /* We need to set the connection limit before we can open the listeners. */
1132 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1133 &options->_ConnLimit) < 0) {
1134 *msg = tor_strdup("Problem with ConnLimit value. See logs for details.");
1135 goto rollback;
1137 set_conn_limit = 1;
1139 /* Set up libevent. (We need to do this before we can register the
1140 * listeners as listeners.) */
1141 if (running_tor && !libevent_initialized) {
1142 init_libevent(options);
1143 libevent_initialized = 1;
1146 /* Adjust the port configuration so we can launch listeners. */
1147 if (parse_ports(options, 0, msg, &n_ports)) {
1148 if (!*msg)
1149 *msg = tor_strdup("Unexpected problem parsing port config");
1150 goto rollback;
1153 /* Set the hibernation state appropriately.*/
1154 consider_hibernation(time(NULL));
1156 /* Launch the listeners. (We do this before we setuid, so we can bind to
1157 * ports under 1024.) We don't want to rebind if we're hibernating. If
1158 * networking is disabled, this will close all but the control listeners,
1159 * but disable those. */
1160 if (!we_are_hibernating()) {
1161 if (retry_all_listeners(replaced_listeners, new_listeners,
1162 options->DisableNetwork) < 0) {
1163 *msg = tor_strdup("Failed to bind one of the listener ports.");
1164 goto rollback;
1167 if (options->DisableNetwork) {
1168 /* Aggressively close non-controller stuff, NOW */
1169 log_notice(LD_NET, "DisableNetwork is set. Tor will not make or accept "
1170 "non-control network connections. Shutting down all existing "
1171 "connections.");
1172 connection_mark_all_noncontrol_connections();
1176 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1177 /* Open /dev/pf before dropping privileges. */
1178 if (options->TransPort_set) {
1179 if (get_pf_socket() < 0) {
1180 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1181 goto rollback;
1184 #endif
1186 /* Attempt to lock all current and future memory with mlockall() only once */
1187 if (options->DisableAllSwap) {
1188 if (tor_mlockall() == -1) {
1189 *msg = tor_strdup("DisableAllSwap failure. Do you have proper "
1190 "permissions?");
1191 goto done;
1195 /* Setuid/setgid as appropriate */
1196 if (options->User) {
1197 if (switch_id(options->User) != 0) {
1198 /* No need to roll back, since you can't change the value. */
1199 *msg = tor_strdup("Problem with User value. See logs for details.");
1200 goto done;
1204 /* Ensure data directory is private; create if possible. */
1205 if (check_private_dir(options->DataDirectory,
1206 running_tor ? CPD_CREATE : CPD_CHECK,
1207 options->User)<0) {
1208 tor_asprintf(msg,
1209 "Couldn't access/create private data directory \"%s\"",
1210 options->DataDirectory);
1211 goto done;
1212 /* No need to roll back, since you can't change the value. */
1215 /* Write control ports to disk as appropriate */
1216 control_ports_write_to_file();
1218 if (directory_caches_v2_dir_info(options)) {
1219 char *fn = NULL;
1220 tor_asprintf(&fn, "%s"PATH_SEPARATOR"cached-status",
1221 options->DataDirectory);
1222 if (check_private_dir(fn, running_tor ? CPD_CREATE : CPD_CHECK,
1223 options->User) < 0) {
1224 tor_asprintf(msg,
1225 "Couldn't access/create private data directory \"%s\"", fn);
1226 tor_free(fn);
1227 goto done;
1229 tor_free(fn);
1232 /* Bail out at this point if we're not going to be a client or server:
1233 * we don't run Tor itself. */
1234 if (!running_tor)
1235 goto commit;
1237 mark_logs_temp(); /* Close current logs once new logs are open. */
1238 logs_marked = 1;
1239 if (options_init_logs(options, 0)<0) { /* Configure the log(s) */
1240 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1241 goto rollback;
1244 commit:
1245 r = 0;
1246 if (logs_marked) {
1247 log_severity_list_t *severity =
1248 tor_malloc_zero(sizeof(log_severity_list_t));
1249 close_temp_logs();
1250 add_callback_log(severity, control_event_logmsg);
1251 control_adjust_event_log_severity();
1252 tor_free(severity);
1254 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1256 log_notice(LD_NET, "Closing old %s on %s:%d",
1257 conn_type_to_string(conn->type), conn->address, conn->port);
1258 connection_close_immediate(conn);
1259 connection_mark_for_close(conn);
1261 goto done;
1263 rollback:
1264 r = -1;
1265 tor_assert(*msg);
1267 if (logs_marked) {
1268 rollback_log_changes();
1269 control_adjust_event_log_severity();
1272 if (set_conn_limit && old_options)
1273 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1274 &options->_ConnLimit);
1276 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1278 log_notice(LD_NET, "Closing partially-constructed %s on %s:%d",
1279 conn_type_to_string(conn->type), conn->address, conn->port);
1280 connection_close_immediate(conn);
1281 connection_mark_for_close(conn);
1284 done:
1285 smartlist_free(new_listeners);
1286 smartlist_free(replaced_listeners);
1287 return r;
1290 /** If we need to have a GEOIP ip-to-country map to run with our configured
1291 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1293 options_need_geoip_info(const or_options_t *options, const char **reason_out)
1295 int bridge_usage =
1296 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1297 int routerset_usage =
1298 routerset_needs_geoip(options->EntryNodes) ||
1299 routerset_needs_geoip(options->ExitNodes) ||
1300 routerset_needs_geoip(options->ExcludeExitNodes) ||
1301 routerset_needs_geoip(options->ExcludeNodes);
1303 if (routerset_usage && reason_out) {
1304 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1305 "countries, and we need GEOIP information to figure out which ones they "
1306 "are.";
1307 } else if (bridge_usage && reason_out) {
1308 *reason_out = "We've been configured to see which countries can access "
1309 "us as a bridge, and we need GEOIP information to tell which countries "
1310 "clients are in.";
1312 return bridge_usage || routerset_usage;
1315 /** Return the bandwidthrate that we are going to report to the authorities
1316 * based on the config options. */
1317 uint32_t
1318 get_effective_bwrate(const or_options_t *options)
1320 uint64_t bw = options->BandwidthRate;
1321 if (bw > options->MaxAdvertisedBandwidth)
1322 bw = options->MaxAdvertisedBandwidth;
1323 if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1324 bw = options->RelayBandwidthRate;
1325 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1326 return (uint32_t)bw;
1329 /** Return the bandwidthburst that we are going to report to the authorities
1330 * based on the config options. */
1331 uint32_t
1332 get_effective_bwburst(const or_options_t *options)
1334 uint64_t bw = options->BandwidthBurst;
1335 if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1336 bw = options->RelayBandwidthBurst;
1337 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1338 return (uint32_t)bw;
1341 /** Return True if any changes from <b>old_options</b> to
1342 * <b>new_options</b> needs us to refresh our TLS context. */
1343 static int
1344 options_transition_requires_fresh_tls_context(const or_options_t *old_options,
1345 const or_options_t *new_options)
1347 tor_assert(new_options);
1349 if (!old_options)
1350 return 0;
1352 if ((old_options->DynamicDHGroups != new_options->DynamicDHGroups)) {
1353 return 1;
1356 return 0;
1359 /** Fetch the active option list, and take actions based on it. All of the
1360 * things we do should survive being done repeatedly. If present,
1361 * <b>old_options</b> contains the previous value of the options.
1363 * Return 0 if all goes well, return -1 if it's time to die.
1365 * Note: We haven't moved all the "act on new configuration" logic
1366 * here yet. Some is still in do_hup() and other places.
1368 static int
1369 options_act(const or_options_t *old_options)
1371 config_line_t *cl;
1372 or_options_t *options = get_options_mutable();
1373 int running_tor = options->command == CMD_RUN_TOR;
1374 char *msg;
1375 const int transition_affects_workers =
1376 old_options && options_transition_affects_workers(old_options, options);
1378 /* disable ptrace and later, other basic debugging techniques */
1380 /* Remember if we already disabled debugger attachment */
1381 static int disabled_debugger_attach = 0;
1382 /* Remember if we already warned about being configured not to disable
1383 * debugger attachment */
1384 static int warned_debugger_attach = 0;
1385 /* Don't disable debugger attachment when we're running the unit tests. */
1386 if (options->DisableDebuggerAttachment && !disabled_debugger_attach &&
1387 running_tor) {
1388 int ok = tor_disable_debugger_attach();
1389 if (warned_debugger_attach && ok == 1) {
1390 log_notice(LD_CONFIG, "Disabled attaching debuggers for unprivileged "
1391 "users.");
1393 disabled_debugger_attach = (ok == 1);
1394 } else if (!options->DisableDebuggerAttachment &&
1395 !warned_debugger_attach) {
1396 log_notice(LD_CONFIG, "Not disabling debugger attaching for "
1397 "unprivileged users.");
1398 warned_debugger_attach = 1;
1402 if (running_tor && !have_lockfile()) {
1403 if (try_locking(options, 1) < 0)
1404 return -1;
1407 if (consider_adding_dir_authorities(options, old_options) < 0)
1408 return -1;
1410 #ifdef NON_ANONYMOUS_MODE_ENABLED
1411 log(LOG_WARN, LD_GENERAL, "This copy of Tor was compiled to run in a "
1412 "non-anonymous mode. It will provide NO ANONYMITY.");
1413 #endif
1415 #ifdef ENABLE_TOR2WEB_MODE
1416 if (!options->Tor2webMode) {
1417 log_err(LD_CONFIG, "This copy of Tor was compiled to run in "
1418 "'tor2web mode'. It can only be run with the Tor2webMode torrc "
1419 "option enabled.");
1420 return -1;
1422 #else
1423 if (options->Tor2webMode) {
1424 log_err(LD_CONFIG, "This copy of Tor was not compiled to run in "
1425 "'tor2web mode'. It cannot be run with the Tor2webMode torrc "
1426 "option enabled. To enable Tor2webMode recompile with the "
1427 "--enable-tor2webmode option.");
1428 return -1;
1430 #endif
1432 if (options->Bridges) {
1433 mark_bridge_list();
1434 for (cl = options->Bridges; cl; cl = cl->next) {
1435 if (parse_bridge_line(cl->value, 0)<0) {
1436 log_warn(LD_BUG,
1437 "Previously validated Bridge line could not be added!");
1438 return -1;
1441 sweep_bridge_list();
1444 if (running_tor && rend_config_services(options, 0)<0) {
1445 log_warn(LD_BUG,
1446 "Previously validated hidden services line could not be added!");
1447 return -1;
1450 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1451 log_warn(LD_BUG, "Previously validated client authorization for "
1452 "hidden services could not be added!");
1453 return -1;
1456 /* Load state */
1457 if (! global_state && running_tor) {
1458 if (or_state_load())
1459 return -1;
1460 rep_hist_load_mtbf_data(time(NULL));
1463 mark_transport_list();
1464 pt_prepare_proxy_list_for_config_read();
1465 if (options->ClientTransportPlugin) {
1466 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
1467 if (parse_client_transport_line(cl->value, 0)<0) {
1468 log_warn(LD_BUG,
1469 "Previously validated ClientTransportPlugin line "
1470 "could not be added!");
1471 return -1;
1476 if (options->ServerTransportPlugin && server_mode(options)) {
1477 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
1478 if (parse_server_transport_line(cl->value, 0)<0) {
1479 log_warn(LD_BUG,
1480 "Previously validated ServerTransportPlugin line "
1481 "could not be added!");
1482 return -1;
1486 sweep_transport_list();
1487 sweep_proxy_list();
1489 /* Bail out at this point if we're not going to be a client or server:
1490 * we want to not fork, and to log stuff to stderr. */
1491 if (!running_tor)
1492 return 0;
1494 /* Finish backgrounding the process */
1495 if (options->RunAsDaemon) {
1496 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1497 finish_daemon(options->DataDirectory);
1500 /* If needed, generate a new TLS DH prime according to the current torrc. */
1501 if (server_mode(options) && options->DynamicDHGroups) {
1502 char *keydir = get_datadir_fname("keys");
1503 if (check_private_dir(keydir, CPD_CREATE, options->User)) {
1504 tor_free(keydir);
1505 return -1;
1507 tor_free(keydir);
1509 if (!old_options || !old_options->DynamicDHGroups) {
1510 char *fname = get_datadir_fname2("keys", "dynamic_dh_params");
1511 crypto_set_tls_dh_prime(fname);
1512 tor_free(fname);
1514 } else { /* clients don't need a dynamic DH prime. */
1515 crypto_set_tls_dh_prime(NULL);
1518 /* We want to reinit keys as needed before we do much of anything else:
1519 keys are important, and other things can depend on them. */
1520 if (transition_affects_workers ||
1521 (options->V3AuthoritativeDir && (!old_options ||
1522 !old_options->V3AuthoritativeDir))) {
1523 if (init_keys() < 0) {
1524 log_warn(LD_BUG,"Error initializing keys; exiting");
1525 return -1;
1527 } else if (old_options &&
1528 options_transition_requires_fresh_tls_context(old_options,
1529 options)) {
1530 if (router_initialize_tls_context() < 0) {
1531 log_warn(LD_BUG,"Error initializing TLS context.");
1532 return -1;
1536 /* Write our PID to the PID file. If we do not have write permissions we
1537 * will log a warning */
1538 if (options->PidFile)
1539 write_pidfile(options->PidFile);
1541 /* Register addressmap directives */
1542 config_register_addressmaps(options);
1543 parse_virtual_addr_network(options->VirtualAddrNetwork, 0, &msg);
1545 /* Update address policies. */
1546 if (policies_parse_from_options(options) < 0) {
1547 /* This should be impossible, but let's be sure. */
1548 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1549 return -1;
1552 if (init_cookie_authentication(options->CookieAuthentication) < 0) {
1553 log_warn(LD_CONFIG,"Error creating cookie authentication file.");
1554 return -1;
1557 monitor_owning_controller_process(options->OwningControllerProcess);
1559 /* reload keys as needed for rendezvous services. */
1560 if (rend_service_load_keys()<0) {
1561 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1562 return -1;
1565 /* Set up accounting */
1566 if (accounting_parse_options(options, 0)<0) {
1567 log_warn(LD_CONFIG,"Error in accounting options");
1568 return -1;
1570 if (accounting_is_enabled(options))
1571 configure_accounting(time(NULL));
1573 #ifdef USE_BUFFEREVENTS
1574 /* If we're using the bufferevents implementation and our rate limits
1575 * changed, we need to tell the rate-limiting system about it. */
1576 if (!old_options ||
1577 old_options->BandwidthRate != options->BandwidthRate ||
1578 old_options->BandwidthBurst != options->BandwidthBurst ||
1579 old_options->RelayBandwidthRate != options->RelayBandwidthRate ||
1580 old_options->RelayBandwidthBurst != options->RelayBandwidthBurst)
1581 connection_bucket_init();
1582 #endif
1584 /* Change the cell EWMA settings */
1585 cell_ewma_set_scale_factor(options, networkstatus_get_latest_consensus());
1587 /* Update the BridgePassword's hashed version as needed. We store this as a
1588 * digest so that we can do side-channel-proof comparisons on it.
1590 if (options->BridgePassword) {
1591 char *http_authenticator;
1592 http_authenticator = alloc_http_authenticator(options->BridgePassword);
1593 if (!http_authenticator) {
1594 log_warn(LD_BUG, "Unable to allocate HTTP authenticator. Not setting "
1595 "BridgePassword.");
1596 return -1;
1598 options->_BridgePassword_AuthDigest = tor_malloc(DIGEST256_LEN);
1599 crypto_digest256(options->_BridgePassword_AuthDigest,
1600 http_authenticator, strlen(http_authenticator),
1601 DIGEST_SHA256);
1602 tor_free(http_authenticator);
1605 /* Check for transitions that need action. */
1606 if (old_options) {
1607 int revise_trackexithosts = 0;
1608 int revise_automap_entries = 0;
1609 if ((options->UseEntryGuards && !old_options->UseEntryGuards) ||
1610 options->UseBridges != old_options->UseBridges ||
1611 (options->UseBridges &&
1612 !config_lines_eq(options->Bridges, old_options->Bridges)) ||
1613 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes) ||
1614 !routerset_equal(old_options->ExcludeExitNodes,
1615 options->ExcludeExitNodes) ||
1616 !routerset_equal(old_options->EntryNodes, options->EntryNodes) ||
1617 !routerset_equal(old_options->ExitNodes, options->ExitNodes) ||
1618 options->StrictNodes != old_options->StrictNodes) {
1619 log_info(LD_CIRC,
1620 "Changed to using entry guards or bridges, or changed "
1621 "preferred or excluded node lists. "
1622 "Abandoning previous circuits.");
1623 circuit_mark_all_unused_circs();
1624 circuit_expire_all_dirty_circs();
1625 revise_trackexithosts = 1;
1628 if (!smartlist_strings_eq(old_options->TrackHostExits,
1629 options->TrackHostExits))
1630 revise_trackexithosts = 1;
1632 if (revise_trackexithosts)
1633 addressmap_clear_excluded_trackexithosts(options);
1635 if (!options->AutomapHostsOnResolve) {
1636 if (old_options->AutomapHostsOnResolve)
1637 revise_automap_entries = 1;
1638 } else {
1639 if (!smartlist_strings_eq(old_options->AutomapHostsSuffixes,
1640 options->AutomapHostsSuffixes))
1641 revise_automap_entries = 1;
1642 else if (!opt_streq(old_options->VirtualAddrNetwork,
1643 options->VirtualAddrNetwork))
1644 revise_automap_entries = 1;
1647 if (revise_automap_entries)
1648 addressmap_clear_invalid_automaps(options);
1650 /* How long should we delay counting bridge stats after becoming a bridge?
1651 * We use this so we don't count people who used our bridge thinking it is
1652 * a relay. If you change this, don't forget to change the log message
1653 * below. It's 4 hours (the time it takes to stop being used by clients)
1654 * plus some extra time for clock skew. */
1655 #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
1657 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
1658 int was_relay = 0;
1659 if (options->BridgeRelay) {
1660 time_t int_start = time(NULL);
1661 if (config_lines_eq(old_options->ORPort_lines,options->ORPort_lines)) {
1662 int_start += RELAY_BRIDGE_STATS_DELAY;
1663 was_relay = 1;
1665 geoip_bridge_stats_init(int_start);
1666 log_info(LD_CONFIG, "We are acting as a bridge now. Starting new "
1667 "GeoIP stats interval%s.", was_relay ? " in 6 "
1668 "hours from now" : "");
1669 } else {
1670 geoip_bridge_stats_term();
1671 log_info(LD_GENERAL, "We are no longer acting as a bridge. "
1672 "Forgetting GeoIP stats.");
1676 if (transition_affects_workers) {
1677 log_info(LD_GENERAL,
1678 "Worker-related options changed. Rotating workers.");
1680 if (server_mode(options) && !server_mode(old_options)) {
1681 ip_address_changed(0);
1682 if (can_complete_circuit || !any_predicted_circuits(time(NULL)))
1683 inform_testing_reachability();
1685 cpuworkers_rotate();
1686 if (dns_reset())
1687 return -1;
1688 } else {
1689 if (dns_reset())
1690 return -1;
1693 if (options->PerConnBWRate != old_options->PerConnBWRate ||
1694 options->PerConnBWBurst != old_options->PerConnBWBurst)
1695 connection_or_update_token_buckets(get_connection_array(), options);
1698 /* Maybe load geoip file */
1699 if (options->GeoIPFile &&
1700 ((!old_options || !opt_streq(old_options->GeoIPFile, options->GeoIPFile))
1701 || !geoip_is_loaded())) {
1702 /* XXXX Don't use this "<default>" junk; make our filename options
1703 * understand prefixes somehow. -NM */
1704 /* XXXX024 Reload GeoIPFile on SIGHUP. -NM */
1705 char *actual_fname = tor_strdup(options->GeoIPFile);
1706 #ifdef _WIN32
1707 if (!strcmp(actual_fname, "<default>")) {
1708 const char *conf_root = get_windows_conf_root();
1709 tor_free(actual_fname);
1710 tor_asprintf(&actual_fname, "%s\\geoip", conf_root);
1712 #endif
1713 geoip_load_file(actual_fname, options);
1714 tor_free(actual_fname);
1717 if (options->CellStatistics || options->DirReqStatistics ||
1718 options->EntryStatistics || options->ExitPortStatistics ||
1719 options->ConnDirectionStatistics ||
1720 options->BridgeAuthoritativeDir) {
1721 time_t now = time(NULL);
1722 int print_notice = 0;
1724 /* If we aren't acting as a server, we can't collect stats anyway. */
1725 if (!server_mode(options)) {
1726 options->CellStatistics = 0;
1727 options->DirReqStatistics = 0;
1728 options->EntryStatistics = 0;
1729 options->ExitPortStatistics = 0;
1732 if ((!old_options || !old_options->CellStatistics) &&
1733 options->CellStatistics) {
1734 rep_hist_buffer_stats_init(now);
1735 print_notice = 1;
1737 if ((!old_options || !old_options->DirReqStatistics) &&
1738 options->DirReqStatistics) {
1739 if (geoip_is_loaded()) {
1740 geoip_dirreq_stats_init(now);
1741 print_notice = 1;
1742 } else {
1743 options->DirReqStatistics = 0;
1744 /* Don't warn Tor clients, they don't use statistics */
1745 if (options->ORPort_set)
1746 log_notice(LD_CONFIG, "Configured to measure directory request "
1747 "statistics, but no GeoIP database found. "
1748 "Please specify a GeoIP database using the "
1749 "GeoIPFile option.");
1752 if ((!old_options || !old_options->EntryStatistics) &&
1753 options->EntryStatistics && !should_record_bridge_info(options)) {
1754 if (geoip_is_loaded()) {
1755 geoip_entry_stats_init(now);
1756 print_notice = 1;
1757 } else {
1758 options->EntryStatistics = 0;
1759 log_notice(LD_CONFIG, "Configured to measure entry node "
1760 "statistics, but no GeoIP database found. "
1761 "Please specify a GeoIP database using the "
1762 "GeoIPFile option.");
1765 if ((!old_options || !old_options->ExitPortStatistics) &&
1766 options->ExitPortStatistics) {
1767 rep_hist_exit_stats_init(now);
1768 print_notice = 1;
1770 if ((!old_options || !old_options->ConnDirectionStatistics) &&
1771 options->ConnDirectionStatistics) {
1772 rep_hist_conn_stats_init(now);
1774 if ((!old_options || !old_options->BridgeAuthoritativeDir) &&
1775 options->BridgeAuthoritativeDir) {
1776 rep_hist_desc_stats_init(now);
1777 print_notice = 1;
1779 if (print_notice)
1780 log_notice(LD_CONFIG, "Configured to measure statistics. Look for "
1781 "the *-stats files that will first be written to the "
1782 "data directory in 24 hours from now.");
1785 if (old_options && old_options->CellStatistics &&
1786 !options->CellStatistics)
1787 rep_hist_buffer_stats_term();
1788 if (old_options && old_options->DirReqStatistics &&
1789 !options->DirReqStatistics)
1790 geoip_dirreq_stats_term();
1791 if (old_options && old_options->EntryStatistics &&
1792 !options->EntryStatistics)
1793 geoip_entry_stats_term();
1794 if (old_options && old_options->ExitPortStatistics &&
1795 !options->ExitPortStatistics)
1796 rep_hist_exit_stats_term();
1797 if (old_options && old_options->ConnDirectionStatistics &&
1798 !options->ConnDirectionStatistics)
1799 rep_hist_conn_stats_term();
1800 if (old_options && old_options->BridgeAuthoritativeDir &&
1801 !options->BridgeAuthoritativeDir)
1802 rep_hist_desc_stats_term();
1804 /* Check if we need to parse and add the EntryNodes config option. */
1805 if (options->EntryNodes &&
1806 (!old_options ||
1807 !routerset_equal(old_options->EntryNodes,options->EntryNodes) ||
1808 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes)))
1809 entry_nodes_should_be_added();
1811 /* Since our options changed, we might need to regenerate and upload our
1812 * server descriptor.
1814 if (!old_options ||
1815 options_transition_affects_descriptor(old_options, options))
1816 mark_my_descriptor_dirty("config change");
1818 /* We may need to reschedule some directory stuff if our status changed. */
1819 if (old_options) {
1820 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1821 dirvote_recalculate_timing(options, time(NULL));
1822 if (!bool_eq(directory_fetches_dir_info_early(options),
1823 directory_fetches_dir_info_early(old_options)) ||
1824 !bool_eq(directory_fetches_dir_info_later(options),
1825 directory_fetches_dir_info_later(old_options))) {
1826 /* Make sure update_router_have_min_dir_info gets called. */
1827 router_dir_info_changed();
1828 /* We might need to download a new consensus status later or sooner than
1829 * we had expected. */
1830 update_consensus_networkstatus_fetch_time(time(NULL));
1834 /* Load the webpage we're going to serve every time someone asks for '/' on
1835 our DirPort. */
1836 tor_free(global_dirfrontpagecontents);
1837 if (options->DirPortFrontPage) {
1838 global_dirfrontpagecontents =
1839 read_file_to_str(options->DirPortFrontPage, 0, NULL);
1840 if (!global_dirfrontpagecontents) {
1841 log_warn(LD_CONFIG,
1842 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1843 options->DirPortFrontPage);
1847 return 0;
1851 * Functions to parse config options
1854 /** If <b>option</b> is an official abbreviation for a longer option,
1855 * return the longer option. Otherwise return <b>option</b>.
1856 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1857 * apply abbreviations that work for the config file and the command line.
1858 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1859 static const char *
1860 expand_abbrev(const config_format_t *fmt, const char *option, int command_line,
1861 int warn_obsolete)
1863 int i;
1864 if (! fmt->abbrevs)
1865 return option;
1866 for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
1867 /* Abbreviations are case insensitive. */
1868 if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
1869 (command_line || !fmt->abbrevs[i].commandline_only)) {
1870 if (warn_obsolete && fmt->abbrevs[i].warn) {
1871 log_warn(LD_CONFIG,
1872 "The configuration option '%s' is deprecated; "
1873 "use '%s' instead.",
1874 fmt->abbrevs[i].abbreviated,
1875 fmt->abbrevs[i].full);
1877 /* Keep going through the list in case we want to rewrite it more.
1878 * (We could imagine recursing here, but I don't want to get the
1879 * user into an infinite loop if we craft our list wrong.) */
1880 option = fmt->abbrevs[i].full;
1883 return option;
1886 /** Helper: Read a list of configuration options from the command line.
1887 * If successful, put them in *<b>result</b> and return 0, and return
1888 * -1 and leave *<b>result</b> alone. */
1889 static int
1890 config_get_commandlines(int argc, char **argv, config_line_t **result)
1892 config_line_t *front = NULL;
1893 config_line_t **new = &front;
1894 char *s;
1895 int i = 1;
1897 while (i < argc) {
1898 unsigned command = CONFIG_LINE_NORMAL;
1899 int want_arg = 1;
1901 if (!strcmp(argv[i],"-f") ||
1902 !strcmp(argv[i],"--defaults-torrc") ||
1903 !strcmp(argv[i],"--hash-password")) {
1904 i += 2; /* command-line option with argument. ignore them. */
1905 continue;
1906 } else if (!strcmp(argv[i],"--list-fingerprint") ||
1907 !strcmp(argv[i],"--verify-config") ||
1908 !strcmp(argv[i],"--ignore-missing-torrc") ||
1909 !strcmp(argv[i],"--quiet") ||
1910 !strcmp(argv[i],"--hush")) {
1911 i += 1; /* command-line option. ignore it. */
1912 continue;
1913 } else if (!strcmp(argv[i],"--nt-service") ||
1914 !strcmp(argv[i],"-nt-service")) {
1915 i += 1;
1916 continue;
1919 *new = tor_malloc_zero(sizeof(config_line_t));
1920 s = argv[i];
1922 /* Each keyword may be prefixed with one or two dashes. */
1923 if (*s == '-')
1924 s++;
1925 if (*s == '-')
1926 s++;
1927 /* Figure out the command, if any. */
1928 if (*s == '+') {
1929 s++;
1930 command = CONFIG_LINE_APPEND;
1931 } else if (*s == '/') {
1932 s++;
1933 command = CONFIG_LINE_CLEAR;
1934 /* A 'clear' command has no argument. */
1935 want_arg = 0;
1938 if (want_arg && i == argc-1) {
1939 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1940 argv[i]);
1941 config_free_lines(front);
1942 return -1;
1945 (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1, 1));
1946 (*new)->value = want_arg ? tor_strdup(argv[i+1]) : tor_strdup("");
1947 (*new)->command = command;
1948 (*new)->next = NULL;
1949 log(LOG_DEBUG, LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
1950 (*new)->key, (*new)->value);
1952 new = &((*new)->next);
1953 i += want_arg ? 2 : 1;
1955 *result = front;
1956 return 0;
1959 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1960 * append it to *<b>lst</b>. */
1961 static void
1962 config_line_append(config_line_t **lst,
1963 const char *key,
1964 const char *val)
1966 config_line_t *newline;
1968 newline = tor_malloc_zero(sizeof(config_line_t));
1969 newline->key = tor_strdup(key);
1970 newline->value = tor_strdup(val);
1971 newline->next = NULL;
1972 while (*lst)
1973 lst = &((*lst)->next);
1975 (*lst) = newline;
1978 /** Helper: parse the config string and strdup into key/value
1979 * strings. Set *result to the list, or NULL if parsing the string
1980 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1981 * misformatted lines.
1983 * If <b>extended</b> is set, then treat keys beginning with / and with + as
1984 * indicating "clear" and "append" respectively. */
1986 config_get_lines(const char *string, config_line_t **result, int extended)
1988 config_line_t *list = NULL, **next;
1989 char *k, *v;
1991 next = &list;
1992 do {
1993 k = v = NULL;
1994 string = parse_config_line_from_str(string, &k, &v);
1995 if (!string) {
1996 config_free_lines(list);
1997 tor_free(k);
1998 tor_free(v);
1999 return -1;
2001 if (k && v) {
2002 unsigned command = CONFIG_LINE_NORMAL;
2003 if (extended) {
2004 if (k[0] == '+') {
2005 char *k_new = tor_strdup(k+1);
2006 tor_free(k);
2007 k = k_new;
2008 command = CONFIG_LINE_APPEND;
2009 } else if (k[0] == '/') {
2010 char *k_new = tor_strdup(k+1);
2011 tor_free(k);
2012 k = k_new;
2013 tor_free(v);
2014 v = tor_strdup("");
2015 command = CONFIG_LINE_CLEAR;
2018 /* This list can get long, so we keep a pointer to the end of it
2019 * rather than using config_line_append over and over and getting
2020 * n^2 performance. */
2021 *next = tor_malloc_zero(sizeof(config_line_t));
2022 (*next)->key = k;
2023 (*next)->value = v;
2024 (*next)->next = NULL;
2025 (*next)->command = command;
2026 next = &((*next)->next);
2027 } else {
2028 tor_free(k);
2029 tor_free(v);
2031 } while (*string);
2033 *result = list;
2034 return 0;
2038 * Free all the configuration lines on the linked list <b>front</b>.
2040 void
2041 config_free_lines(config_line_t *front)
2043 config_line_t *tmp;
2045 while (front) {
2046 tmp = front;
2047 front = tmp->next;
2049 tor_free(tmp->key);
2050 tor_free(tmp->value);
2051 tor_free(tmp);
2055 /** As config_find_option, but return a non-const pointer. */
2056 static config_var_t *
2057 config_find_option_mutable(config_format_t *fmt, const char *key)
2059 int i;
2060 size_t keylen = strlen(key);
2061 if (!keylen)
2062 return NULL; /* if they say "--" on the command line, it's not an option */
2063 /* First, check for an exact (case-insensitive) match */
2064 for (i=0; fmt->vars[i].name; ++i) {
2065 if (!strcasecmp(key, fmt->vars[i].name)) {
2066 return &fmt->vars[i];
2069 /* If none, check for an abbreviated match */
2070 for (i=0; fmt->vars[i].name; ++i) {
2071 if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
2072 log_warn(LD_CONFIG, "The abbreviation '%s' is deprecated. "
2073 "Please use '%s' instead",
2074 key, fmt->vars[i].name);
2075 return &fmt->vars[i];
2078 /* Okay, unrecognized option */
2079 return NULL;
2082 /** If <b>key</b> is a configuration option, return the corresponding const
2083 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
2084 * warn, and return the corresponding const config_var_t. Otherwise return
2085 * NULL.
2087 static const config_var_t *
2088 config_find_option(const config_format_t *fmt, const char *key)
2090 return config_find_option_mutable((config_format_t*)fmt, key);
2093 /** Return the number of option entries in <b>fmt</b>. */
2094 static int
2095 config_count_options(const config_format_t *fmt)
2097 int i;
2098 for (i=0; fmt->vars[i].name; ++i)
2100 return i;
2104 * Functions to assign config options.
2107 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
2108 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
2110 * Called from config_assign_line() and option_reset().
2112 static int
2113 config_assign_value(const config_format_t *fmt, or_options_t *options,
2114 config_line_t *c, char **msg)
2116 int i, ok;
2117 const config_var_t *var;
2118 void *lvalue;
2120 CHECK(fmt, options);
2122 var = config_find_option(fmt, c->key);
2123 tor_assert(var);
2125 lvalue = STRUCT_VAR_P(options, var->var_offset);
2127 switch (var->type) {
2129 case CONFIG_TYPE_PORT:
2130 if (!strcasecmp(c->value, "auto")) {
2131 *(int *)lvalue = CFG_AUTO_PORT;
2132 break;
2134 /* fall through */
2135 case CONFIG_TYPE_INT:
2136 case CONFIG_TYPE_UINT:
2137 i = (int)tor_parse_long(c->value, 10,
2138 var->type==CONFIG_TYPE_INT ? INT_MIN : 0,
2139 var->type==CONFIG_TYPE_PORT ? 65535 : INT_MAX,
2140 &ok, NULL);
2141 if (!ok) {
2142 tor_asprintf(msg,
2143 "Int keyword '%s %s' is malformed or out of bounds.",
2144 c->key, c->value);
2145 return -1;
2147 *(int *)lvalue = i;
2148 break;
2150 case CONFIG_TYPE_INTERVAL: {
2151 i = config_parse_interval(c->value, &ok);
2152 if (!ok) {
2153 tor_asprintf(msg,
2154 "Interval '%s %s' is malformed or out of bounds.",
2155 c->key, c->value);
2156 return -1;
2158 *(int *)lvalue = i;
2159 break;
2162 case CONFIG_TYPE_MSEC_INTERVAL: {
2163 i = config_parse_msec_interval(c->value, &ok);
2164 if (!ok) {
2165 tor_asprintf(msg,
2166 "Msec interval '%s %s' is malformed or out of bounds.",
2167 c->key, c->value);
2168 return -1;
2170 *(int *)lvalue = i;
2171 break;
2174 case CONFIG_TYPE_MEMUNIT: {
2175 uint64_t u64 = config_parse_memunit(c->value, &ok);
2176 if (!ok) {
2177 tor_asprintf(msg,
2178 "Value '%s %s' is malformed or out of bounds.",
2179 c->key, c->value);
2180 return -1;
2182 *(uint64_t *)lvalue = u64;
2183 break;
2186 case CONFIG_TYPE_BOOL:
2187 i = (int)tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
2188 if (!ok) {
2189 tor_asprintf(msg,
2190 "Boolean '%s %s' expects 0 or 1.",
2191 c->key, c->value);
2192 return -1;
2194 *(int *)lvalue = i;
2195 break;
2197 case CONFIG_TYPE_AUTOBOOL:
2198 if (!strcmp(c->value, "auto"))
2199 *(int *)lvalue = -1;
2200 else if (!strcmp(c->value, "0"))
2201 *(int *)lvalue = 0;
2202 else if (!strcmp(c->value, "1"))
2203 *(int *)lvalue = 1;
2204 else {
2205 tor_asprintf(msg, "Boolean '%s %s' expects 0, 1, or 'auto'.",
2206 c->key, c->value);
2207 return -1;
2209 break;
2211 case CONFIG_TYPE_STRING:
2212 case CONFIG_TYPE_FILENAME:
2213 tor_free(*(char **)lvalue);
2214 *(char **)lvalue = tor_strdup(c->value);
2215 break;
2217 case CONFIG_TYPE_DOUBLE:
2218 *(double *)lvalue = atof(c->value);
2219 break;
2221 case CONFIG_TYPE_ISOTIME:
2222 if (parse_iso_time(c->value, (time_t *)lvalue)) {
2223 tor_asprintf(msg,
2224 "Invalid time '%s' for keyword '%s'", c->value, c->key);
2225 return -1;
2227 break;
2229 case CONFIG_TYPE_ROUTERSET:
2230 if (*(routerset_t**)lvalue) {
2231 routerset_free(*(routerset_t**)lvalue);
2233 *(routerset_t**)lvalue = routerset_new();
2234 if (routerset_parse(*(routerset_t**)lvalue, c->value, c->key)<0) {
2235 tor_asprintf(msg, "Invalid exit list '%s' for option '%s'",
2236 c->value, c->key);
2237 return -1;
2239 break;
2241 case CONFIG_TYPE_CSV:
2242 if (*(smartlist_t**)lvalue) {
2243 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
2244 smartlist_clear(*(smartlist_t**)lvalue);
2245 } else {
2246 *(smartlist_t**)lvalue = smartlist_new();
2249 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
2250 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2251 break;
2253 case CONFIG_TYPE_LINELIST:
2254 case CONFIG_TYPE_LINELIST_S:
2256 config_line_t *lastval = *(config_line_t**)lvalue;
2257 if (lastval && lastval->fragile) {
2258 if (c->command != CONFIG_LINE_APPEND) {
2259 config_free_lines(lastval);
2260 *(config_line_t**)lvalue = NULL;
2261 } else {
2262 lastval->fragile = 0;
2266 config_line_append((config_line_t**)lvalue, c->key, c->value);
2268 break;
2269 case CONFIG_TYPE_OBSOLETE:
2270 log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
2271 break;
2272 case CONFIG_TYPE_LINELIST_V:
2273 tor_asprintf(msg,
2274 "You may not provide a value for virtual option '%s'", c->key);
2275 return -1;
2276 default:
2277 tor_assert(0);
2278 break;
2280 return 0;
2283 /** Mark every linelist in <b>options</b> "fragile", so that fresh assignments
2284 * to it will replace old ones. */
2285 static void
2286 config_mark_lists_fragile(const config_format_t *fmt, or_options_t *options)
2288 int i;
2289 tor_assert(fmt);
2290 tor_assert(options);
2292 for (i = 0; fmt->vars[i].name; ++i) {
2293 const config_var_t *var = &fmt->vars[i];
2294 config_line_t *list;
2295 if (var->type != CONFIG_TYPE_LINELIST &&
2296 var->type != CONFIG_TYPE_LINELIST_V)
2297 continue;
2299 list = *(config_line_t **)STRUCT_VAR_P(options, var->var_offset);
2300 if (list)
2301 list->fragile = 1;
2305 /** If <b>c</b> is a syntactically valid configuration line, update
2306 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
2307 * key, -2 for bad value.
2309 * If <b>clear_first</b> is set, clear the value first. Then if
2310 * <b>use_defaults</b> is set, set the value to the default.
2312 * Called from config_assign().
2314 static int
2315 config_assign_line(const config_format_t *fmt, or_options_t *options,
2316 config_line_t *c, int use_defaults,
2317 int clear_first, bitarray_t *options_seen, char **msg)
2319 const config_var_t *var;
2321 CHECK(fmt, options);
2323 var = config_find_option(fmt, c->key);
2324 if (!var) {
2325 if (fmt->extra) {
2326 void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
2327 log_info(LD_CONFIG,
2328 "Found unrecognized option '%s'; saving it.", c->key);
2329 config_line_append((config_line_t**)lvalue, c->key, c->value);
2330 return 0;
2331 } else {
2332 tor_asprintf(msg,
2333 "Unknown option '%s'. Failing.", c->key);
2334 return -1;
2338 /* Put keyword into canonical case. */
2339 if (strcmp(var->name, c->key)) {
2340 tor_free(c->key);
2341 c->key = tor_strdup(var->name);
2344 if (!strlen(c->value)) {
2345 /* reset or clear it, then return */
2346 if (!clear_first) {
2347 if ((var->type == CONFIG_TYPE_LINELIST ||
2348 var->type == CONFIG_TYPE_LINELIST_S) &&
2349 c->command != CONFIG_LINE_CLEAR) {
2350 /* We got an empty linelist from the torrc or command line.
2351 As a special case, call this an error. Warn and ignore. */
2352 log_warn(LD_CONFIG,
2353 "Linelist option '%s' has no value. Skipping.", c->key);
2354 } else { /* not already cleared */
2355 option_reset(fmt, options, var, use_defaults);
2358 return 0;
2359 } else if (c->command == CONFIG_LINE_CLEAR && !clear_first) {
2360 option_reset(fmt, options, var, use_defaults);
2363 if (options_seen && (var->type != CONFIG_TYPE_LINELIST &&
2364 var->type != CONFIG_TYPE_LINELIST_S)) {
2365 /* We're tracking which options we've seen, and this option is not
2366 * supposed to occur more than once. */
2367 int var_index = (int)(var - fmt->vars);
2368 if (bitarray_is_set(options_seen, var_index)) {
2369 log_warn(LD_CONFIG, "Option '%s' used more than once; all but the last "
2370 "value will be ignored.", var->name);
2372 bitarray_set(options_seen, var_index);
2375 if (config_assign_value(fmt, options, c, msg) < 0)
2376 return -2;
2377 return 0;
2380 /** Restore the option named <b>key</b> in options to its default value.
2381 * Called from config_assign(). */
2382 static void
2383 config_reset_line(const config_format_t *fmt, or_options_t *options,
2384 const char *key, int use_defaults)
2386 const config_var_t *var;
2388 CHECK(fmt, options);
2390 var = config_find_option(fmt, key);
2391 if (!var)
2392 return; /* give error on next pass. */
2394 option_reset(fmt, options, var, use_defaults);
2397 /** Return true iff key is a valid configuration option. */
2399 option_is_recognized(const char *key)
2401 const config_var_t *var = config_find_option(&options_format, key);
2402 return (var != NULL);
2405 /** Return the canonical name of a configuration option, or NULL
2406 * if no such option exists. */
2407 const char *
2408 option_get_canonical_name(const char *key)
2410 const config_var_t *var = config_find_option(&options_format, key);
2411 return var ? var->name : NULL;
2414 /** Return a canonical list of the options assigned for key.
2416 config_line_t *
2417 option_get_assignment(const or_options_t *options, const char *key)
2419 return get_assigned_option(&options_format, options, key, 1);
2422 /** Return true iff value needs to be quoted and escaped to be used in
2423 * a configuration file. */
2424 static int
2425 config_value_needs_escape(const char *value)
2427 if (*value == '\"')
2428 return 1;
2429 while (*value) {
2430 switch (*value)
2432 case '\r':
2433 case '\n':
2434 case '#':
2435 /* Note: quotes and backspaces need special handling when we are using
2436 * quotes, not otherwise, so they don't trigger escaping on their
2437 * own. */
2438 return 1;
2439 default:
2440 if (!TOR_ISPRINT(*value))
2441 return 1;
2443 ++value;
2445 return 0;
2448 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
2449 static config_line_t *
2450 config_lines_dup(const config_line_t *inp)
2452 config_line_t *result = NULL;
2453 config_line_t **next_out = &result;
2454 while (inp) {
2455 *next_out = tor_malloc_zero(sizeof(config_line_t));
2456 (*next_out)->key = tor_strdup(inp->key);
2457 (*next_out)->value = tor_strdup(inp->value);
2458 inp = inp->next;
2459 next_out = &((*next_out)->next);
2461 (*next_out) = NULL;
2462 return result;
2465 /** Return newly allocated line or lines corresponding to <b>key</b> in the
2466 * configuration <b>options</b>. If <b>escape_val</b> is true and a
2467 * value needs to be quoted before it's put in a config file, quote and
2468 * escape that value. Return NULL if no such key exists. */
2469 static config_line_t *
2470 get_assigned_option(const config_format_t *fmt, const void *options,
2471 const char *key, int escape_val)
2473 const config_var_t *var;
2474 const void *value;
2475 config_line_t *result;
2476 tor_assert(options && key);
2478 CHECK(fmt, options);
2480 var = config_find_option(fmt, key);
2481 if (!var) {
2482 log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
2483 return NULL;
2485 value = STRUCT_VAR_P(options, var->var_offset);
2487 result = tor_malloc_zero(sizeof(config_line_t));
2488 result->key = tor_strdup(var->name);
2489 switch (var->type)
2491 case CONFIG_TYPE_STRING:
2492 case CONFIG_TYPE_FILENAME:
2493 if (*(char**)value) {
2494 result->value = tor_strdup(*(char**)value);
2495 } else {
2496 tor_free(result->key);
2497 tor_free(result);
2498 return NULL;
2500 break;
2501 case CONFIG_TYPE_ISOTIME:
2502 if (*(time_t*)value) {
2503 result->value = tor_malloc(ISO_TIME_LEN+1);
2504 format_iso_time(result->value, *(time_t*)value);
2505 } else {
2506 tor_free(result->key);
2507 tor_free(result);
2509 escape_val = 0; /* Can't need escape. */
2510 break;
2511 case CONFIG_TYPE_PORT:
2512 if (*(int*)value == CFG_AUTO_PORT) {
2513 result->value = tor_strdup("auto");
2514 escape_val = 0;
2515 break;
2517 /* fall through */
2518 case CONFIG_TYPE_INTERVAL:
2519 case CONFIG_TYPE_MSEC_INTERVAL:
2520 case CONFIG_TYPE_UINT:
2521 case CONFIG_TYPE_INT:
2522 /* This means every or_options_t uint or bool element
2523 * needs to be an int. Not, say, a uint16_t or char. */
2524 tor_asprintf(&result->value, "%d", *(int*)value);
2525 escape_val = 0; /* Can't need escape. */
2526 break;
2527 case CONFIG_TYPE_MEMUNIT:
2528 tor_asprintf(&result->value, U64_FORMAT,
2529 U64_PRINTF_ARG(*(uint64_t*)value));
2530 escape_val = 0; /* Can't need escape. */
2531 break;
2532 case CONFIG_TYPE_DOUBLE:
2533 tor_asprintf(&result->value, "%f", *(double*)value);
2534 escape_val = 0; /* Can't need escape. */
2535 break;
2537 case CONFIG_TYPE_AUTOBOOL:
2538 if (*(int*)value == -1) {
2539 result->value = tor_strdup("auto");
2540 escape_val = 0;
2541 break;
2543 /* fall through */
2544 case CONFIG_TYPE_BOOL:
2545 result->value = tor_strdup(*(int*)value ? "1" : "0");
2546 escape_val = 0; /* Can't need escape. */
2547 break;
2548 case CONFIG_TYPE_ROUTERSET:
2549 result->value = routerset_to_string(*(routerset_t**)value);
2550 break;
2551 case CONFIG_TYPE_CSV:
2552 if (*(smartlist_t**)value)
2553 result->value =
2554 smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
2555 else
2556 result->value = tor_strdup("");
2557 break;
2558 case CONFIG_TYPE_OBSOLETE:
2559 log_fn(LOG_PROTOCOL_WARN, LD_CONFIG,
2560 "You asked me for the value of an obsolete config option '%s'.",
2561 key);
2562 tor_free(result->key);
2563 tor_free(result);
2564 return NULL;
2565 case CONFIG_TYPE_LINELIST_S:
2566 log_warn(LD_CONFIG,
2567 "Can't return context-sensitive '%s' on its own", key);
2568 tor_free(result->key);
2569 tor_free(result);
2570 return NULL;
2571 case CONFIG_TYPE_LINELIST:
2572 case CONFIG_TYPE_LINELIST_V:
2573 tor_free(result->key);
2574 tor_free(result);
2575 result = config_lines_dup(*(const config_line_t**)value);
2576 break;
2577 default:
2578 tor_free(result->key);
2579 tor_free(result);
2580 log_warn(LD_BUG,"Unknown type %d for known key '%s'",
2581 var->type, key);
2582 return NULL;
2585 if (escape_val) {
2586 config_line_t *line;
2587 for (line = result; line; line = line->next) {
2588 if (line->value && config_value_needs_escape(line->value)) {
2589 char *newval = esc_for_log(line->value);
2590 tor_free(line->value);
2591 line->value = newval;
2596 return result;
2599 /** Iterate through the linked list of requested options <b>list</b>.
2600 * For each item, convert as appropriate and assign to <b>options</b>.
2601 * If an item is unrecognized, set *msg and return -1 immediately,
2602 * else return 0 for success.
2604 * If <b>clear_first</b>, interpret config options as replacing (not
2605 * extending) their previous values. If <b>clear_first</b> is set,
2606 * then <b>use_defaults</b> to decide if you set to defaults after
2607 * clearing, or make the value 0 or NULL.
2609 * Here are the use cases:
2610 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
2611 * if linelist, replaces current if csv.
2612 * 2. An empty AllowInvalid line in your torrc. Should clear it.
2613 * 3. "RESETCONF AllowInvalid" sets it to default.
2614 * 4. "SETCONF AllowInvalid" makes it NULL.
2615 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
2617 * Use_defaults Clear_first
2618 * 0 0 "append"
2619 * 1 0 undefined, don't use
2620 * 0 1 "set to null first"
2621 * 1 1 "set to defaults first"
2622 * Return 0 on success, -1 on bad key, -2 on bad value.
2624 * As an additional special case, if a LINELIST config option has
2625 * no value and clear_first is 0, then warn and ignore it.
2629 There are three call cases for config_assign() currently.
2631 Case one: Torrc entry
2632 options_init_from_torrc() calls config_assign(0, 0)
2633 calls config_assign_line(0, 0).
2634 if value is empty, calls option_reset(0) and returns.
2635 calls config_assign_value(), appends.
2637 Case two: setconf
2638 options_trial_assign() calls config_assign(0, 1)
2639 calls config_reset_line(0)
2640 calls option_reset(0)
2641 calls option_clear().
2642 calls config_assign_line(0, 1).
2643 if value is empty, returns.
2644 calls config_assign_value(), appends.
2646 Case three: resetconf
2647 options_trial_assign() calls config_assign(1, 1)
2648 calls config_reset_line(1)
2649 calls option_reset(1)
2650 calls option_clear().
2651 calls config_assign_value(default)
2652 calls config_assign_line(1, 1).
2653 returns.
2655 static int
2656 config_assign(const config_format_t *fmt, void *options, config_line_t *list,
2657 int use_defaults, int clear_first, char **msg)
2659 config_line_t *p;
2660 bitarray_t *options_seen;
2661 const int n_options = config_count_options(fmt);
2663 CHECK(fmt, options);
2665 /* pass 1: normalize keys */
2666 for (p = list; p; p = p->next) {
2667 const char *full = expand_abbrev(fmt, p->key, 0, 1);
2668 if (strcmp(full,p->key)) {
2669 tor_free(p->key);
2670 p->key = tor_strdup(full);
2674 /* pass 2: if we're reading from a resetting source, clear all
2675 * mentioned config options, and maybe set to their defaults. */
2676 if (clear_first) {
2677 for (p = list; p; p = p->next)
2678 config_reset_line(fmt, options, p->key, use_defaults);
2681 options_seen = bitarray_init_zero(n_options);
2682 /* pass 3: assign. */
2683 while (list) {
2684 int r;
2685 if ((r=config_assign_line(fmt, options, list, use_defaults,
2686 clear_first, options_seen, msg))) {
2687 bitarray_free(options_seen);
2688 return r;
2690 list = list->next;
2692 bitarray_free(options_seen);
2694 /** Now we're done assigning a group of options to the configuration.
2695 * Subsequent group assignments should _replace_ linelists, not extend
2696 * them. */
2697 config_mark_lists_fragile(fmt, options);
2699 return 0;
2702 /** Try assigning <b>list</b> to the global options. You do this by duping
2703 * options, assigning list to the new one, then validating it. If it's
2704 * ok, then throw out the old one and stick with the new one. Else,
2705 * revert to old and return failure. Return SETOPT_OK on success, or
2706 * a setopt_err_t on failure.
2708 * If not success, point *<b>msg</b> to a newly allocated string describing
2709 * what went wrong.
2711 setopt_err_t
2712 options_trial_assign(config_line_t *list, int use_defaults,
2713 int clear_first, char **msg)
2715 int r;
2716 or_options_t *trial_options = options_dup(&options_format, get_options());
2718 if ((r=config_assign(&options_format, trial_options,
2719 list, use_defaults, clear_first, msg)) < 0) {
2720 config_free(&options_format, trial_options);
2721 return r;
2724 if (options_validate(get_options_mutable(), trial_options, 1, msg) < 0) {
2725 config_free(&options_format, trial_options);
2726 return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2729 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2730 config_free(&options_format, trial_options);
2731 return SETOPT_ERR_TRANSITION;
2734 if (set_options(trial_options, msg)<0) {
2735 config_free(&options_format, trial_options);
2736 return SETOPT_ERR_SETTING;
2739 /* we liked it. put it in place. */
2740 return SETOPT_OK;
2743 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2744 * Called from option_reset() and config_free(). */
2745 static void
2746 option_clear(const config_format_t *fmt, or_options_t *options,
2747 const config_var_t *var)
2749 void *lvalue = STRUCT_VAR_P(options, var->var_offset);
2750 (void)fmt; /* unused */
2751 switch (var->type) {
2752 case CONFIG_TYPE_STRING:
2753 case CONFIG_TYPE_FILENAME:
2754 tor_free(*(char**)lvalue);
2755 break;
2756 case CONFIG_TYPE_DOUBLE:
2757 *(double*)lvalue = 0.0;
2758 break;
2759 case CONFIG_TYPE_ISOTIME:
2760 *(time_t*)lvalue = 0;
2761 break;
2762 case CONFIG_TYPE_INTERVAL:
2763 case CONFIG_TYPE_MSEC_INTERVAL:
2764 case CONFIG_TYPE_UINT:
2765 case CONFIG_TYPE_INT:
2766 case CONFIG_TYPE_PORT:
2767 case CONFIG_TYPE_BOOL:
2768 *(int*)lvalue = 0;
2769 break;
2770 case CONFIG_TYPE_AUTOBOOL:
2771 *(int*)lvalue = -1;
2772 break;
2773 case CONFIG_TYPE_MEMUNIT:
2774 *(uint64_t*)lvalue = 0;
2775 break;
2776 case CONFIG_TYPE_ROUTERSET:
2777 if (*(routerset_t**)lvalue) {
2778 routerset_free(*(routerset_t**)lvalue);
2779 *(routerset_t**)lvalue = NULL;
2781 break;
2782 case CONFIG_TYPE_CSV:
2783 if (*(smartlist_t**)lvalue) {
2784 SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
2785 smartlist_free(*(smartlist_t **)lvalue);
2786 *(smartlist_t **)lvalue = NULL;
2788 break;
2789 case CONFIG_TYPE_LINELIST:
2790 case CONFIG_TYPE_LINELIST_S:
2791 config_free_lines(*(config_line_t **)lvalue);
2792 *(config_line_t **)lvalue = NULL;
2793 break;
2794 case CONFIG_TYPE_LINELIST_V:
2795 /* handled by linelist_s. */
2796 break;
2797 case CONFIG_TYPE_OBSOLETE:
2798 break;
2802 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2803 * <b>use_defaults</b>, set it to its default value.
2804 * Called by config_init() and option_reset_line() and option_assign_line(). */
2805 static void
2806 option_reset(const config_format_t *fmt, or_options_t *options,
2807 const config_var_t *var, int use_defaults)
2809 config_line_t *c;
2810 char *msg = NULL;
2811 CHECK(fmt, options);
2812 option_clear(fmt, options, var); /* clear it first */
2813 if (!use_defaults)
2814 return; /* all done */
2815 if (var->initvalue) {
2816 c = tor_malloc_zero(sizeof(config_line_t));
2817 c->key = tor_strdup(var->name);
2818 c->value = tor_strdup(var->initvalue);
2819 if (config_assign_value(fmt, options, c, &msg) < 0) {
2820 log_warn(LD_BUG, "Failed to assign default: %s", msg);
2821 tor_free(msg); /* if this happens it's a bug */
2823 config_free_lines(c);
2827 /** Print a usage message for tor. */
2828 static void
2829 print_usage(void)
2831 printf(
2832 "Copyright (c) 2001-2004, Roger Dingledine\n"
2833 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2834 "Copyright (c) 2007-2012, The Tor Project, Inc.\n\n"
2835 "tor -f <torrc> [args]\n"
2836 "See man page for options, or https://www.torproject.org/ for "
2837 "documentation.\n");
2840 /** Print all non-obsolete torrc options. */
2841 static void
2842 list_torrc_options(void)
2844 int i;
2845 smartlist_t *lines = smartlist_new();
2846 for (i = 0; _option_vars[i].name; ++i) {
2847 const config_var_t *var = &_option_vars[i];
2848 if (var->type == CONFIG_TYPE_OBSOLETE ||
2849 var->type == CONFIG_TYPE_LINELIST_V)
2850 continue;
2851 printf("%s\n", var->name);
2853 smartlist_free(lines);
2856 /** Last value actually set by resolve_my_address. */
2857 static uint32_t last_resolved_addr = 0;
2859 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2860 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2861 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2862 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2863 * public IP address.
2864 * XXXX ipv6
2867 resolve_my_address(int warn_severity, const or_options_t *options,
2868 uint32_t *addr_out, char **hostname_out)
2870 struct in_addr in;
2871 uint32_t addr; /* host order */
2872 char hostname[256];
2873 int explicit_ip=1;
2874 int explicit_hostname=1;
2875 int from_interface=0;
2876 char *addr_string = NULL;
2877 const char *address = options->Address;
2878 int notice_severity = warn_severity <= LOG_NOTICE ?
2879 LOG_NOTICE : warn_severity;
2881 tor_assert(addr_out);
2883 if (address && *address) {
2884 strlcpy(hostname, address, sizeof(hostname));
2885 } else { /* then we need to guess our address */
2886 explicit_ip = 0; /* it's implicit */
2887 explicit_hostname = 0; /* it's implicit */
2889 if (gethostname(hostname, sizeof(hostname)) < 0) {
2890 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2891 return -1;
2893 log_debug(LD_CONFIG,"Guessed local host name as '%s'",hostname);
2896 /* now we know hostname. resolve it and keep only the IP address */
2898 if (tor_inet_aton(hostname, &in) == 0) {
2899 /* then we have to resolve it */
2900 explicit_ip = 0;
2901 if (tor_lookup_hostname(hostname, &addr)) { /* failed to resolve */
2902 uint32_t interface_ip; /* host order */
2904 if (explicit_hostname) {
2905 log_fn(warn_severity, LD_CONFIG,
2906 "Could not resolve local Address '%s'. Failing.", hostname);
2907 return -1;
2909 log_fn(notice_severity, LD_CONFIG,
2910 "Could not resolve guessed local hostname '%s'. "
2911 "Trying something else.", hostname);
2912 if (get_interface_address(warn_severity, &interface_ip)) {
2913 log_fn(warn_severity, LD_CONFIG,
2914 "Could not get local interface IP address. Failing.");
2915 return -1;
2917 from_interface = 1;
2918 addr = interface_ip;
2919 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2920 "local interface. Using that.", fmt_addr32(addr));
2921 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2922 } else { /* resolved hostname into addr */
2923 if (!explicit_hostname &&
2924 is_internal_IP(addr, 0)) {
2925 uint32_t interface_ip;
2927 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2928 "resolves to a private IP address (%s). Trying something "
2929 "else.", hostname, fmt_addr32(addr));
2931 if (get_interface_address(warn_severity, &interface_ip)) {
2932 log_fn(warn_severity, LD_CONFIG,
2933 "Could not get local interface IP address. Too bad.");
2934 } else if (is_internal_IP(interface_ip, 0)) {
2935 log_fn(notice_severity, LD_CONFIG,
2936 "Interface IP address '%s' is a private address too. "
2937 "Ignoring.", fmt_addr32(interface_ip));
2938 } else {
2939 from_interface = 1;
2940 addr = interface_ip;
2941 log_fn(notice_severity, LD_CONFIG,
2942 "Learned IP address '%s' for local interface."
2943 " Using that.", fmt_addr32(addr));
2944 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2948 } else {
2949 addr = ntohl(in.s_addr); /* set addr so that addr_string is not
2950 * illformed */
2953 addr_string = tor_dup_ip(addr);
2954 if (is_internal_IP(addr, 0)) {
2955 /* make sure we're ok with publishing an internal IP */
2956 if (!options->DirServers && !options->AlternateDirAuthority) {
2957 /* if they are using the default dirservers, disallow internal IPs
2958 * always. */
2959 log_fn(warn_severity, LD_CONFIG,
2960 "Address '%s' resolves to private IP address '%s'. "
2961 "Tor servers that use the default DirServers must have public "
2962 "IP addresses.", hostname, addr_string);
2963 tor_free(addr_string);
2964 return -1;
2966 if (!explicit_ip) {
2967 /* even if they've set their own dirservers, require an explicit IP if
2968 * they're using an internal address. */
2969 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2970 "IP address '%s'. Please set the Address config option to be "
2971 "the IP address you want to use.", hostname, addr_string);
2972 tor_free(addr_string);
2973 return -1;
2977 log_debug(LD_CONFIG, "Resolved Address to '%s'.", fmt_addr32(addr));
2978 *addr_out = addr;
2979 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2980 /* Leave this as a notice, regardless of the requested severity,
2981 * at least until dynamic IP address support becomes bulletproof. */
2982 log_notice(LD_NET,
2983 "Your IP address seems to have changed to %s. Updating.",
2984 addr_string);
2985 ip_address_changed(0);
2987 if (last_resolved_addr != *addr_out) {
2988 const char *method;
2989 const char *h = hostname;
2990 if (explicit_ip) {
2991 method = "CONFIGURED";
2992 h = NULL;
2993 } else if (explicit_hostname) {
2994 method = "RESOLVED";
2995 } else if (from_interface) {
2996 method = "INTERFACE";
2997 h = NULL;
2998 } else {
2999 method = "GETHOSTNAME";
3001 control_event_server_status(LOG_NOTICE,
3002 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
3003 addr_string, method, h?"HOSTNAME=":"", h);
3005 last_resolved_addr = *addr_out;
3006 if (hostname_out)
3007 *hostname_out = tor_strdup(hostname);
3008 tor_free(addr_string);
3009 return 0;
3012 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
3013 * on a private network.
3016 is_local_addr(const tor_addr_t *addr)
3018 if (tor_addr_is_internal(addr, 0))
3019 return 1;
3020 /* Check whether ip is on the same /24 as we are. */
3021 if (get_options()->EnforceDistinctSubnets == 0)
3022 return 0;
3023 if (tor_addr_family(addr) == AF_INET) {
3024 /*XXXX023 IP6 what corresponds to an /24? */
3025 uint32_t ip = tor_addr_to_ipv4h(addr);
3027 /* It's possible that this next check will hit before the first time
3028 * resolve_my_address actually succeeds. (For clients, it is likely that
3029 * resolve_my_address will never be called at all). In those cases,
3030 * last_resolved_addr will be 0, and so checking to see whether ip is on
3031 * the same /24 as last_resolved_addr will be the same as checking whether
3032 * it was on net 0, which is already done by is_internal_IP.
3034 if ((last_resolved_addr & (uint32_t)0xffffff00ul)
3035 == (ip & (uint32_t)0xffffff00ul))
3036 return 1;
3038 return 0;
3041 /** Release storage held by <b>options</b>. */
3042 static void
3043 config_free(const config_format_t *fmt, void *options)
3045 int i;
3047 if (!options)
3048 return;
3050 tor_assert(fmt);
3052 for (i=0; fmt->vars[i].name; ++i)
3053 option_clear(fmt, options, &(fmt->vars[i]));
3054 if (fmt->extra) {
3055 config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
3056 config_free_lines(*linep);
3057 *linep = NULL;
3059 tor_free(options);
3062 /** Return true iff a and b contain identical keys and values in identical
3063 * order. */
3064 static int
3065 config_lines_eq(config_line_t *a, config_line_t *b)
3067 while (a && b) {
3068 if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
3069 return 0;
3070 a = a->next;
3071 b = b->next;
3073 if (a || b)
3074 return 0;
3075 return 1;
3078 /** Return the number of lines in <b>a</b> whose key is <b>key</b>. */
3079 static int
3080 config_count_key(const config_line_t *a, const char *key)
3082 int n = 0;
3083 while (a) {
3084 if (!strcasecmp(a->key, key)) {
3085 ++n;
3087 a = a->next;
3089 return n;
3092 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
3093 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
3095 static int
3096 option_is_same(const config_format_t *fmt,
3097 const or_options_t *o1, const or_options_t *o2,
3098 const char *name)
3100 config_line_t *c1, *c2;
3101 int r = 1;
3102 CHECK(fmt, o1);
3103 CHECK(fmt, o2);
3105 c1 = get_assigned_option(fmt, o1, name, 0);
3106 c2 = get_assigned_option(fmt, o2, name, 0);
3107 r = config_lines_eq(c1, c2);
3108 config_free_lines(c1);
3109 config_free_lines(c2);
3110 return r;
3113 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
3114 static or_options_t *
3115 options_dup(const config_format_t *fmt, const or_options_t *old)
3117 or_options_t *newopts;
3118 int i;
3119 config_line_t *line;
3121 newopts = config_alloc(fmt);
3122 for (i=0; fmt->vars[i].name; ++i) {
3123 if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
3124 continue;
3125 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
3126 continue;
3127 line = get_assigned_option(fmt, old, fmt->vars[i].name, 0);
3128 if (line) {
3129 char *msg = NULL;
3130 if (config_assign(fmt, newopts, line, 0, 0, &msg) < 0) {
3131 log_err(LD_BUG, "Config_get_assigned_option() generated "
3132 "something we couldn't config_assign(): %s", msg);
3133 tor_free(msg);
3134 tor_assert(0);
3137 config_free_lines(line);
3139 return newopts;
3142 /** Return a new empty or_options_t. Used for testing. */
3143 or_options_t *
3144 options_new(void)
3146 return config_alloc(&options_format);
3149 /** Set <b>options</b> to hold reasonable defaults for most options.
3150 * Each option defaults to zero. */
3151 void
3152 options_init(or_options_t *options)
3154 config_init(&options_format, options);
3157 /** Set all vars in the configuration object <b>options</b> to their default
3158 * values. */
3159 static void
3160 config_init(const config_format_t *fmt, void *options)
3162 int i;
3163 const config_var_t *var;
3164 CHECK(fmt, options);
3166 for (i=0; fmt->vars[i].name; ++i) {
3167 var = &fmt->vars[i];
3168 if (!var->initvalue)
3169 continue; /* defaults to NULL or 0 */
3170 option_reset(fmt, options, var, 1);
3174 /** Allocate and return a new string holding the written-out values of the vars
3175 * in 'options'. If 'minimal', do not write out any default-valued vars.
3176 * Else, if comment_defaults, write default values as comments.
3178 static char *
3179 config_dump(const config_format_t *fmt, const void *default_options,
3180 const void *options, int minimal,
3181 int comment_defaults)
3183 smartlist_t *elements;
3184 const or_options_t *defaults = default_options;
3185 void *defaults_tmp = NULL;
3186 config_line_t *line, *assigned;
3187 char *result;
3188 int i;
3189 char *msg = NULL;
3191 if (defaults == NULL) {
3192 defaults = defaults_tmp = config_alloc(fmt);
3193 config_init(fmt, defaults_tmp);
3196 /* XXX use a 1 here so we don't add a new log line while dumping */
3197 if (default_options == NULL) {
3198 if (fmt->validate_fn(NULL, defaults_tmp, 1, &msg) < 0) {
3199 log_err(LD_BUG, "Failed to validate default config.");
3200 tor_free(msg);
3201 tor_assert(0);
3205 elements = smartlist_new();
3206 for (i=0; fmt->vars[i].name; ++i) {
3207 int comment_option = 0;
3208 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
3209 fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
3210 continue;
3211 /* Don't save 'hidden' control variables. */
3212 if (!strcmpstart(fmt->vars[i].name, "__"))
3213 continue;
3214 if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
3215 continue;
3216 else if (comment_defaults &&
3217 option_is_same(fmt, options, defaults, fmt->vars[i].name))
3218 comment_option = 1;
3220 line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name, 1);
3222 for (; line; line = line->next) {
3223 smartlist_add_asprintf(elements, "%s%s %s\n",
3224 comment_option ? "# " : "",
3225 line->key, line->value);
3227 config_free_lines(assigned);
3230 if (fmt->extra) {
3231 line = *(config_line_t**)STRUCT_VAR_P(options, fmt->extra->var_offset);
3232 for (; line; line = line->next) {
3233 smartlist_add_asprintf(elements, "%s %s\n", line->key, line->value);
3237 result = smartlist_join_strings(elements, "", 0, NULL);
3238 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
3239 smartlist_free(elements);
3240 if (defaults_tmp)
3241 config_free(fmt, defaults_tmp);
3242 return result;
3245 /** Return a string containing a possible configuration file that would give
3246 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
3247 * include options that are the same as Tor's defaults.
3249 char *
3250 options_dump(const or_options_t *options, int minimal)
3252 return config_dump(&options_format, global_default_options,
3253 options, minimal, 0);
3256 /** Return 0 if every element of sl is a string holding a decimal
3257 * representation of a port number, or if sl is NULL.
3258 * Otherwise set *msg and return -1. */
3259 static int
3260 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
3262 int i;
3263 tor_assert(name);
3265 if (!sl)
3266 return 0;
3268 SMARTLIST_FOREACH(sl, const char *, cp,
3270 i = atoi(cp);
3271 if (i < 1 || i > 65535) {
3272 tor_asprintf(msg, "Port '%s' out of range in %s", cp, name);
3273 return -1;
3276 return 0;
3279 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
3280 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
3281 * Else return 0.
3283 static int
3284 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
3286 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
3287 /* This handles an understandable special case where somebody says "2gb"
3288 * whereas our actual maximum is 2gb-1 (INT_MAX) */
3289 --*value;
3291 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
3292 tor_asprintf(msg, "%s ("U64_FORMAT") must be at most %d",
3293 desc, U64_PRINTF_ARG(*value),
3294 ROUTER_MAX_DECLARED_BANDWIDTH);
3295 return -1;
3297 return 0;
3300 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
3301 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
3302 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
3303 * Treat "0" as "".
3304 * Return 0 on success or -1 if not a recognized authority type (in which
3305 * case the value of _PublishServerDescriptor is undefined). */
3306 static int
3307 compute_publishserverdescriptor(or_options_t *options)
3309 smartlist_t *list = options->PublishServerDescriptor;
3310 dirinfo_type_t *auth = &options->_PublishServerDescriptor;
3311 *auth = NO_DIRINFO;
3312 if (!list) /* empty list, answer is none */
3313 return 0;
3314 SMARTLIST_FOREACH_BEGIN(list, const char *, string) {
3315 if (!strcasecmp(string, "v1"))
3316 *auth |= V1_DIRINFO;
3317 else if (!strcmp(string, "1"))
3318 if (options->BridgeRelay)
3319 *auth |= BRIDGE_DIRINFO;
3320 else
3321 *auth |= V2_DIRINFO | V3_DIRINFO;
3322 else if (!strcasecmp(string, "v2"))
3323 *auth |= V2_DIRINFO;
3324 else if (!strcasecmp(string, "v3"))
3325 *auth |= V3_DIRINFO;
3326 else if (!strcasecmp(string, "bridge"))
3327 *auth |= BRIDGE_DIRINFO;
3328 else if (!strcasecmp(string, "hidserv"))
3329 log_warn(LD_CONFIG,
3330 "PublishServerDescriptor hidserv is invalid. See "
3331 "PublishHidServDescriptors.");
3332 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
3333 /* no authority */;
3334 else
3335 return -1;
3336 } SMARTLIST_FOREACH_END(string);
3337 return 0;
3340 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
3341 * services can overload the directory system. */
3342 #define MIN_REND_POST_PERIOD (10*60)
3344 /** Highest allowable value for RendPostPeriod. */
3345 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
3347 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
3348 * will generate too many circuits and potentially overload the network. */
3349 #define MIN_MAX_CIRCUIT_DIRTINESS 10
3351 /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
3352 * will generate too many circuits and potentially overload the network. */
3353 #define MIN_CIRCUIT_STREAM_TIMEOUT 10
3355 /** Lowest allowable value for HeartbeatPeriod; if this is too low, we might
3356 * expose more information than we're comfortable with. */
3357 #define MIN_HEARTBEAT_PERIOD (30*60)
3359 /** Lowest recommended value for CircuitBuildTimeout; if it is set too low
3360 * and LearnCircuitBuildTimeout is off, the failure rate for circuit
3361 * construction may be very high. In that case, if it is set below this
3362 * threshold emit a warning.
3363 * */
3364 #define RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT (10)
3366 /** Return 0 if every setting in <b>options</b> is reasonable, and a
3367 * permissible transition from <b>old_options</b>. Else return -1.
3368 * Should have no side effects, except for normalizing the contents of
3369 * <b>options</b>.
3371 * On error, tor_strdup an error explanation into *<b>msg</b>.
3373 * XXX
3374 * If <b>from_setconf</b>, we were called by the controller, and our
3375 * Log line should stay empty. If it's 0, then give us a default log
3376 * if there are no logs defined.
3378 static int
3379 options_validate(or_options_t *old_options, or_options_t *options,
3380 int from_setconf, char **msg)
3382 int i;
3383 config_line_t *cl;
3384 const char *uname = get_uname();
3385 int n_ports=0;
3386 #define REJECT(arg) \
3387 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
3388 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
3390 tor_assert(msg);
3391 *msg = NULL;
3393 if (server_mode(options) &&
3394 (!strcmpstart(uname, "Windows 95") ||
3395 !strcmpstart(uname, "Windows 98") ||
3396 !strcmpstart(uname, "Windows Me"))) {
3397 log(LOG_WARN, LD_CONFIG, "Tor is running as a server, but you are "
3398 "running %s; this probably won't work. See "
3399 "https://wiki.torproject.org/TheOnionRouter/TorFAQ#ServerOS "
3400 "for details.", uname);
3403 if (parse_ports(options, 1, msg, &n_ports) < 0)
3404 return -1;
3406 if (validate_data_directory(options)<0)
3407 REJECT("Invalid DataDirectory");
3409 if (options->Nickname == NULL) {
3410 if (server_mode(options)) {
3411 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
3413 } else {
3414 if (!is_legal_nickname(options->Nickname)) {
3415 tor_asprintf(msg,
3416 "Nickname '%s' is wrong length or contains illegal characters.",
3417 options->Nickname);
3418 return -1;
3422 if (server_mode(options) && !options->ContactInfo)
3423 log(LOG_NOTICE, LD_CONFIG, "Your ContactInfo config option is not set. "
3424 "Please consider setting it, so we can contact you if your server is "
3425 "misconfigured or something else goes wrong.");
3427 /* Special case on first boot if no Log options are given. */
3428 if (!options->Logs && !options->RunAsDaemon && !from_setconf) {
3429 if (quiet_level == 0)
3430 config_line_append(&options->Logs, "Log", "notice stdout");
3431 else if (quiet_level == 1)
3432 config_line_append(&options->Logs, "Log", "warn stdout");
3435 if (options_init_logs(options, 1)<0) /* Validate the log(s) */
3436 REJECT("Failed to validate Log options. See logs for details.");
3438 if (authdir_mode(options)) {
3439 /* confirm that our address isn't broken, so we can complain now */
3440 uint32_t tmp;
3441 if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
3442 REJECT("Failed to resolve/guess local address. See logs for details.");
3445 #ifndef _WIN32
3446 if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
3447 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
3448 #endif
3450 /* XXXX require that the only port not be DirPort? */
3451 /* XXXX require that at least one port be listened-upon. */
3452 if (n_ports == 0 && !options->RendConfigLines)
3453 log(LOG_WARN, LD_CONFIG,
3454 "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
3455 "undefined, and there aren't any hidden services configured. "
3456 "Tor will still run, but probably won't do anything.");
3458 #ifndef USE_TRANSPARENT
3459 /* XXXX024 I think we can remove this TransListenAddress */
3460 if (options->TransPort_set || options->TransListenAddress)
3461 REJECT("TransPort and TransListenAddress are disabled in this build.");
3462 #endif
3464 if (options->TokenBucketRefillInterval <= 0
3465 || options->TokenBucketRefillInterval > 1000) {
3466 REJECT("TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
3469 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3470 options->_ExcludeExitNodesUnion = routerset_new();
3471 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeExitNodes);
3472 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeNodes);
3475 if (options->NodeFamilies) {
3476 options->NodeFamilySets = smartlist_new();
3477 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3478 routerset_t *rs = routerset_new();
3479 if (routerset_parse(rs, cl->value, cl->key) == 0) {
3480 smartlist_add(options->NodeFamilySets, rs);
3481 } else {
3482 routerset_free(rs);
3487 if (options->ExcludeNodes && options->StrictNodes) {
3488 COMPLAIN("You have asked to exclude certain relays from all positions "
3489 "in your circuits. Expect hidden services and other Tor "
3490 "features to be broken in unpredictable ways.");
3493 if (options->AuthoritativeDir) {
3494 if (!options->ContactInfo && !options->TestingTorNetwork)
3495 REJECT("Authoritative directory servers must set ContactInfo");
3496 if (options->V1AuthoritativeDir && !options->RecommendedVersions)
3497 REJECT("V1 authoritative dir servers must set RecommendedVersions.");
3498 if (!options->RecommendedClientVersions)
3499 options->RecommendedClientVersions =
3500 config_lines_dup(options->RecommendedVersions);
3501 if (!options->RecommendedServerVersions)
3502 options->RecommendedServerVersions =
3503 config_lines_dup(options->RecommendedVersions);
3504 if (options->VersioningAuthoritativeDir &&
3505 (!options->RecommendedClientVersions ||
3506 !options->RecommendedServerVersions))
3507 REJECT("Versioning authoritative dir servers must set "
3508 "Recommended*Versions.");
3509 if (options->UseEntryGuards) {
3510 log_info(LD_CONFIG, "Authoritative directory servers can't set "
3511 "UseEntryGuards. Disabling.");
3512 options->UseEntryGuards = 0;
3514 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
3515 log_info(LD_CONFIG, "Authoritative directories always try to download "
3516 "extra-info documents. Setting DownloadExtraInfo.");
3517 options->DownloadExtraInfo = 1;
3519 if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
3520 options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
3521 options->V3AuthoritativeDir))
3522 REJECT("AuthoritativeDir is set, but none of "
3523 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
3524 /* If we have a v3bandwidthsfile and it's broken, complain on startup */
3525 if (options->V3BandwidthsFile && !old_options) {
3526 dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
3530 if (options->AuthoritativeDir && !options->DirPort_set)
3531 REJECT("Running as authoritative directory, but no DirPort set.");
3533 if (options->AuthoritativeDir && !options->ORPort_set)
3534 REJECT("Running as authoritative directory, but no ORPort set.");
3536 if (options->AuthoritativeDir && options->ClientOnly)
3537 REJECT("Running as authoritative directory, but ClientOnly also set.");
3539 if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
3540 REJECT("FetchDirInfoExtraEarly requires that you also set "
3541 "FetchDirInfoEarly");
3543 if (options->HSAuthoritativeDir && proxy_mode(options))
3544 REJECT("Running as authoritative v0 HS directory, but also configured "
3545 "as a client.");
3547 if (options->ConnLimit <= 0) {
3548 tor_asprintf(msg,
3549 "ConnLimit must be greater than 0, but was set to %d",
3550 options->ConnLimit);
3551 return -1;
3554 if (options->MaxClientCircuitsPending <= 0 ||
3555 options->MaxClientCircuitsPending > MAX_MAX_CLIENT_CIRCUITS_PENDING) {
3556 tor_asprintf(msg,
3557 "MaxClientCircuitsPending must be between 1 and %d, but "
3558 "was set to %d", MAX_MAX_CLIENT_CIRCUITS_PENDING,
3559 options->MaxClientCircuitsPending);
3560 return -1;
3563 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3564 return -1;
3566 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3567 return -1;
3569 if (validate_ports_csv(options->RejectPlaintextPorts,
3570 "RejectPlaintextPorts", msg) < 0)
3571 return -1;
3573 if (validate_ports_csv(options->WarnPlaintextPorts,
3574 "WarnPlaintextPorts", msg) < 0)
3575 return -1;
3577 if (options->FascistFirewall && !options->ReachableAddresses) {
3578 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3579 /* We already have firewall ports set, so migrate them to
3580 * ReachableAddresses, which will set ReachableORAddresses and
3581 * ReachableDirAddresses if they aren't set explicitly. */
3582 smartlist_t *instead = smartlist_new();
3583 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3584 new_line->key = tor_strdup("ReachableAddresses");
3585 /* If we're configured with the old format, we need to prepend some
3586 * open ports. */
3587 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3589 int p = atoi(portno);
3590 if (p<0) continue;
3591 smartlist_add_asprintf(instead, "*:%d", p);
3593 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3594 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3595 log(LOG_NOTICE, LD_CONFIG,
3596 "Converting FascistFirewall and FirewallPorts "
3597 "config options to new format: \"ReachableAddresses %s\"",
3598 new_line->value);
3599 options->ReachableAddresses = new_line;
3600 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3601 smartlist_free(instead);
3602 } else {
3603 /* We do not have FirewallPorts set, so add 80 to
3604 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3605 if (!options->ReachableDirAddresses) {
3606 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3607 new_line->key = tor_strdup("ReachableDirAddresses");
3608 new_line->value = tor_strdup("*:80");
3609 options->ReachableDirAddresses = new_line;
3610 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3611 "to new format: \"ReachableDirAddresses *:80\"");
3613 if (!options->ReachableORAddresses) {
3614 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3615 new_line->key = tor_strdup("ReachableORAddresses");
3616 new_line->value = tor_strdup("*:443");
3617 options->ReachableORAddresses = new_line;
3618 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3619 "to new format: \"ReachableORAddresses *:443\"");
3624 for (i=0; i<3; i++) {
3625 config_line_t **linep =
3626 (i==0) ? &options->ReachableAddresses :
3627 (i==1) ? &options->ReachableORAddresses :
3628 &options->ReachableDirAddresses;
3629 if (!*linep)
3630 continue;
3631 /* We need to end with a reject *:*, not an implicit accept *:* */
3632 for (;;) {
3633 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
3634 break;
3635 linep = &((*linep)->next);
3636 if (!*linep) {
3637 *linep = tor_malloc_zero(sizeof(config_line_t));
3638 (*linep)->key = tor_strdup(
3639 (i==0) ? "ReachableAddresses" :
3640 (i==1) ? "ReachableORAddresses" :
3641 "ReachableDirAddresses");
3642 (*linep)->value = tor_strdup("reject *:*");
3643 break;
3648 if ((options->ReachableAddresses ||
3649 options->ReachableORAddresses ||
3650 options->ReachableDirAddresses) &&
3651 server_mode(options))
3652 REJECT("Servers must be able to freely connect to the rest "
3653 "of the Internet, so they must not set Reachable*Addresses "
3654 "or FascistFirewall.");
3656 if (options->UseBridges &&
3657 server_mode(options))
3658 REJECT("Servers must be able to freely connect to the rest "
3659 "of the Internet, so they must not set UseBridges.");
3661 /* If both of these are set, we'll end up with funny behavior where we
3662 * demand enough entrynodes be up and running else we won't build
3663 * circuits, yet we never actually use them. */
3664 if (options->UseBridges && options->EntryNodes)
3665 REJECT("You cannot set both UseBridges and EntryNodes.");
3667 if (options->EntryNodes && !options->UseEntryGuards)
3668 log_warn(LD_CONFIG, "EntryNodes is set, but UseEntryGuards is disabled. "
3669 "EntryNodes will be ignored.");
3671 options->_AllowInvalid = 0;
3672 if (options->AllowInvalidNodes) {
3673 SMARTLIST_FOREACH_BEGIN(options->AllowInvalidNodes, const char *, cp) {
3674 if (!strcasecmp(cp, "entry"))
3675 options->_AllowInvalid |= ALLOW_INVALID_ENTRY;
3676 else if (!strcasecmp(cp, "exit"))
3677 options->_AllowInvalid |= ALLOW_INVALID_EXIT;
3678 else if (!strcasecmp(cp, "middle"))
3679 options->_AllowInvalid |= ALLOW_INVALID_MIDDLE;
3680 else if (!strcasecmp(cp, "introduction"))
3681 options->_AllowInvalid |= ALLOW_INVALID_INTRODUCTION;
3682 else if (!strcasecmp(cp, "rendezvous"))
3683 options->_AllowInvalid |= ALLOW_INVALID_RENDEZVOUS;
3684 else {
3685 tor_asprintf(msg,
3686 "Unrecognized value '%s' in AllowInvalidNodes", cp);
3687 return -1;
3689 } SMARTLIST_FOREACH_END(cp);
3692 if (!options->SafeLogging ||
3693 !strcasecmp(options->SafeLogging, "0")) {
3694 options->_SafeLogging = SAFELOG_SCRUB_NONE;
3695 } else if (!strcasecmp(options->SafeLogging, "relay")) {
3696 options->_SafeLogging = SAFELOG_SCRUB_RELAY;
3697 } else if (!strcasecmp(options->SafeLogging, "1")) {
3698 options->_SafeLogging = SAFELOG_SCRUB_ALL;
3699 } else {
3700 tor_asprintf(msg,
3701 "Unrecognized value '%s' in SafeLogging",
3702 escaped(options->SafeLogging));
3703 return -1;
3706 if (compute_publishserverdescriptor(options) < 0) {
3707 tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
3708 return -1;
3711 if ((options->BridgeRelay
3712 || options->_PublishServerDescriptor & BRIDGE_DIRINFO)
3713 && (options->_PublishServerDescriptor
3714 & (V1_DIRINFO|V2_DIRINFO|V3_DIRINFO))) {
3715 REJECT("Bridges are not supposed to publish router descriptors to the "
3716 "directory authorities. Please correct your "
3717 "PublishServerDescriptor line.");
3720 if (options->BridgeRelay && options->DirPort_set) {
3721 log_warn(LD_CONFIG, "Can't set a DirPort on a bridge relay; disabling "
3722 "DirPort");
3723 config_free_lines(options->DirPort_lines);
3724 options->DirPort_lines = NULL;
3725 options->DirPort_set = 0;
3728 if (options->MinUptimeHidServDirectoryV2 < 0) {
3729 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3730 "least 0 seconds. Changing to 0.");
3731 options->MinUptimeHidServDirectoryV2 = 0;
3734 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
3735 log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
3736 "raising to %d seconds.", MIN_REND_POST_PERIOD);
3737 options->RendPostPeriod = MIN_REND_POST_PERIOD;
3740 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3741 log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3742 MAX_DIR_PERIOD);
3743 options->RendPostPeriod = MAX_DIR_PERIOD;
3746 if (options->Tor2webMode && options->LearnCircuitBuildTimeout) {
3747 /* LearnCircuitBuildTimeout and Tor2webMode are incompatible in
3748 * two ways:
3750 * - LearnCircuitBuildTimeout results in a low CBT, which
3751 * Tor2webMode's use of one-hop rendezvous circuits lowers
3752 * much further, producing *far* too many timeouts.
3754 * - The adaptive CBT code does not update its timeout estimate
3755 * using build times for single-hop circuits.
3757 * If we fix both of these issues someday, we should test
3758 * Tor2webMode with LearnCircuitBuildTimeout on again. */
3759 log_notice(LD_CONFIG,"Tor2webMode is enabled; turning "
3760 "LearnCircuitBuildTimeout off.");
3761 options->LearnCircuitBuildTimeout = 0;
3764 if (!(options->LearnCircuitBuildTimeout) &&
3765 options->CircuitBuildTimeout < RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT) {
3766 log_warn(LD_CONFIG,
3767 "CircuitBuildTimeout is shorter (%d seconds) than recommended "
3768 "(%d seconds), and LearnCircuitBuildTimeout is disabled. "
3769 "If tor isn't working, raise this value or enable "
3770 "LearnCircuitBuildTimeout.",
3771 options->CircuitBuildTimeout,
3772 RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT );
3775 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3776 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3777 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3778 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3781 if (options->CircuitStreamTimeout &&
3782 options->CircuitStreamTimeout < MIN_CIRCUIT_STREAM_TIMEOUT) {
3783 log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
3784 "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
3785 options->CircuitStreamTimeout = MIN_CIRCUIT_STREAM_TIMEOUT;
3788 if (options->HeartbeatPeriod &&
3789 options->HeartbeatPeriod < MIN_HEARTBEAT_PERIOD) {
3790 log_warn(LD_CONFIG, "HeartbeatPeriod option is too short; "
3791 "raising to %d seconds.", MIN_HEARTBEAT_PERIOD);
3792 options->HeartbeatPeriod = MIN_HEARTBEAT_PERIOD;
3795 if (options->KeepalivePeriod < 1)
3796 REJECT("KeepalivePeriod option must be positive.");
3798 if (ensure_bandwidth_cap(&options->BandwidthRate,
3799 "BandwidthRate", msg) < 0)
3800 return -1;
3801 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3802 "BandwidthBurst", msg) < 0)
3803 return -1;
3804 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3805 "MaxAdvertisedBandwidth", msg) < 0)
3806 return -1;
3807 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3808 "RelayBandwidthRate", msg) < 0)
3809 return -1;
3810 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3811 "RelayBandwidthBurst", msg) < 0)
3812 return -1;
3813 if (ensure_bandwidth_cap(&options->PerConnBWRate,
3814 "PerConnBWRate", msg) < 0)
3815 return -1;
3816 if (ensure_bandwidth_cap(&options->PerConnBWBurst,
3817 "PerConnBWBurst", msg) < 0)
3818 return -1;
3819 if (ensure_bandwidth_cap(&options->AuthDirFastGuarantee,
3820 "AuthDirFastGuarantee", msg) < 0)
3821 return -1;
3822 if (ensure_bandwidth_cap(&options->AuthDirGuardBWGuarantee,
3823 "AuthDirGuardBWGuarantee", msg) < 0)
3824 return -1;
3826 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3827 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3828 if (options->RelayBandwidthBurst && !options->RelayBandwidthRate)
3829 options->RelayBandwidthRate = options->RelayBandwidthBurst;
3831 if (server_mode(options)) {
3832 if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3833 tor_asprintf(msg,
3834 "BandwidthRate is set to %d bytes/second. "
3835 "For servers, it must be at least %d.",
3836 (int)options->BandwidthRate,
3837 ROUTER_REQUIRED_MIN_BANDWIDTH);
3838 return -1;
3839 } else if (options->MaxAdvertisedBandwidth <
3840 ROUTER_REQUIRED_MIN_BANDWIDTH/2) {
3841 tor_asprintf(msg,
3842 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3843 "For servers, it must be at least %d.",
3844 (int)options->MaxAdvertisedBandwidth,
3845 ROUTER_REQUIRED_MIN_BANDWIDTH/2);
3846 return -1;
3848 if (options->RelayBandwidthRate &&
3849 options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3850 tor_asprintf(msg,
3851 "RelayBandwidthRate is set to %d bytes/second. "
3852 "For servers, it must be at least %d.",
3853 (int)options->RelayBandwidthRate,
3854 ROUTER_REQUIRED_MIN_BANDWIDTH);
3855 return -1;
3859 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3860 REJECT("RelayBandwidthBurst must be at least equal "
3861 "to RelayBandwidthRate.");
3863 if (options->BandwidthRate > options->BandwidthBurst)
3864 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3866 /* if they set relaybandwidth* really high but left bandwidth*
3867 * at the default, raise the defaults. */
3868 if (options->RelayBandwidthRate > options->BandwidthRate)
3869 options->BandwidthRate = options->RelayBandwidthRate;
3870 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3871 options->BandwidthBurst = options->RelayBandwidthBurst;
3873 if (accounting_parse_options(options, 1)<0)
3874 REJECT("Failed to parse accounting options. See logs for details.");
3876 if (options->AccountingMax) {
3877 if (options->RendConfigLines && server_mode(options)) {
3878 log_warn(LD_CONFIG, "Using accounting with a hidden service and an "
3879 "ORPort is risky: your hidden service(s) and your public "
3880 "address will all turn off at the same time, which may alert "
3881 "observers that they are being run by the same party.");
3882 } else if (config_count_key(options->RendConfigLines,
3883 "HiddenServiceDir") > 1) {
3884 log_warn(LD_CONFIG, "Using accounting with multiple hidden services is "
3885 "risky: they will all turn off at the same time, which may "
3886 "alert observers that they are being run by the same party.");
3890 if (options->HTTPProxy) { /* parse it now */
3891 if (tor_addr_port_lookup(options->HTTPProxy,
3892 &options->HTTPProxyAddr, &options->HTTPProxyPort) < 0)
3893 REJECT("HTTPProxy failed to parse or resolve. Please fix.");
3894 if (options->HTTPProxyPort == 0) { /* give it a default */
3895 options->HTTPProxyPort = 80;
3899 if (options->HTTPProxyAuthenticator) {
3900 if (strlen(options->HTTPProxyAuthenticator) >= 512)
3901 REJECT("HTTPProxyAuthenticator is too long (>= 512 chars).");
3904 if (options->HTTPSProxy) { /* parse it now */
3905 if (tor_addr_port_lookup(options->HTTPSProxy,
3906 &options->HTTPSProxyAddr, &options->HTTPSProxyPort) <0)
3907 REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
3908 if (options->HTTPSProxyPort == 0) { /* give it a default */
3909 options->HTTPSProxyPort = 443;
3913 if (options->HTTPSProxyAuthenticator) {
3914 if (strlen(options->HTTPSProxyAuthenticator) >= 512)
3915 REJECT("HTTPSProxyAuthenticator is too long (>= 512 chars).");
3918 if (options->Socks4Proxy) { /* parse it now */
3919 if (tor_addr_port_lookup(options->Socks4Proxy,
3920 &options->Socks4ProxyAddr,
3921 &options->Socks4ProxyPort) <0)
3922 REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
3923 if (options->Socks4ProxyPort == 0) { /* give it a default */
3924 options->Socks4ProxyPort = 1080;
3928 if (options->Socks5Proxy) { /* parse it now */
3929 if (tor_addr_port_lookup(options->Socks5Proxy,
3930 &options->Socks5ProxyAddr,
3931 &options->Socks5ProxyPort) <0)
3932 REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
3933 if (options->Socks5ProxyPort == 0) { /* give it a default */
3934 options->Socks5ProxyPort = 1080;
3938 /* Check if more than one proxy type has been enabled. */
3939 if (!!options->Socks4Proxy + !!options->Socks5Proxy +
3940 !!options->HTTPSProxy + !!options->ClientTransportPlugin > 1)
3941 REJECT("You have configured more than one proxy type. "
3942 "(Socks4Proxy|Socks5Proxy|HTTPSProxy|ClientTransportPlugin)");
3944 /* Check if the proxies will give surprising behavior. */
3945 if (options->HTTPProxy && !(options->Socks4Proxy ||
3946 options->Socks5Proxy ||
3947 options->HTTPSProxy)) {
3948 log_warn(LD_CONFIG, "HTTPProxy configured, but no SOCKS proxy or "
3949 "HTTPS proxy configured. Watch out: this configuration will "
3950 "proxy unencrypted directory connections only.");
3953 if (options->Socks5ProxyUsername) {
3954 size_t len;
3956 len = strlen(options->Socks5ProxyUsername);
3957 if (len < 1 || len > 255)
3958 REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
3960 if (!options->Socks5ProxyPassword)
3961 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3963 len = strlen(options->Socks5ProxyPassword);
3964 if (len < 1 || len > 255)
3965 REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
3966 } else if (options->Socks5ProxyPassword)
3967 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3969 if (options->HashedControlPassword) {
3970 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3971 if (!sl) {
3972 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3973 } else {
3974 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3975 smartlist_free(sl);
3979 if (options->HashedControlSessionPassword) {
3980 smartlist_t *sl = decode_hashed_passwords(
3981 options->HashedControlSessionPassword);
3982 if (!sl) {
3983 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3984 } else {
3985 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3986 smartlist_free(sl);
3990 if (options->OwningControllerProcess) {
3991 const char *validate_pspec_msg = NULL;
3992 if (tor_validate_process_specifier(options->OwningControllerProcess,
3993 &validate_pspec_msg)) {
3994 tor_asprintf(msg, "Bad OwningControllerProcess: %s",
3995 validate_pspec_msg);
3996 return -1;
4000 if (options->ControlPort_set && !options->HashedControlPassword &&
4001 !options->HashedControlSessionPassword &&
4002 !options->CookieAuthentication) {
4003 log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
4004 "has been configured. This means that any program on your "
4005 "computer can reconfigure your Tor. That's bad! You should "
4006 "upgrade your Tor controller as soon as possible.");
4009 if (options->CookieAuthFileGroupReadable && !options->CookieAuthFile) {
4010 log_warn(LD_CONFIG, "CookieAuthFileGroupReadable is set, but will have "
4011 "no effect: you must specify an explicit CookieAuthFile to "
4012 "have it group-readable.");
4015 if (options->UseEntryGuards && ! options->NumEntryGuards)
4016 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
4018 if (options->MyFamily && options->BridgeRelay) {
4019 log_warn(LD_CONFIG, "Listing a family for a bridge relay is not "
4020 "supported: it can reveal bridge fingerprints to censors. "
4021 "You should also make sure you aren't listing this bridge's "
4022 "fingerprint in any other MyFamily.");
4024 if (check_nickname_list(options->MyFamily, "MyFamily", msg))
4025 return -1;
4026 for (cl = options->NodeFamilies; cl; cl = cl->next) {
4027 routerset_t *rs = routerset_new();
4028 if (routerset_parse(rs, cl->value, cl->key)) {
4029 routerset_free(rs);
4030 return -1;
4032 routerset_free(rs);
4035 if (validate_addr_policies(options, msg) < 0)
4036 return -1;
4038 if (validate_dir_authorities(options, old_options) < 0)
4039 REJECT("Directory authority line did not parse. See logs for details.");
4041 if (options->UseBridges && !options->Bridges)
4042 REJECT("If you set UseBridges, you must specify at least one bridge.");
4043 if (options->UseBridges && !options->TunnelDirConns)
4044 REJECT("If you set UseBridges, you must set TunnelDirConns.");
4046 for (cl = options->Bridges; cl; cl = cl->next) {
4047 if (parse_bridge_line(cl->value, 1)<0)
4048 REJECT("Bridge line did not parse. See logs for details.");
4051 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
4052 if (parse_client_transport_line(cl->value, 1)<0)
4053 REJECT("Transport line did not parse. See logs for details.");
4056 for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
4057 if (parse_server_transport_line(cl->value, 1)<0)
4058 REJECT("Server transport line did not parse. See logs for details.");
4061 if (options->ServerTransportPlugin && !server_mode(options)) {
4062 log_notice(LD_GENERAL, "Tor is not configured as a relay but you specified"
4063 " a ServerTransportPlugin line (%s). The ServerTransportPlugin "
4064 "line will be ignored.",
4065 esc_for_log(options->ServerTransportPlugin->value));
4068 if (options->ConstrainedSockets) {
4069 /* If the user wants to constrain socket buffer use, make sure the desired
4070 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
4071 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
4072 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
4073 options->ConstrainedSockSize % 1024) {
4074 tor_asprintf(msg,
4075 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
4076 "in 1024 byte increments.",
4077 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
4078 return -1;
4080 if (options->DirPort_set) {
4081 /* Providing cached directory entries while system TCP buffers are scarce
4082 * will exacerbate the socket errors. Suggest that this be disabled. */
4083 COMPLAIN("You have requested constrained socket buffers while also "
4084 "serving directory entries via DirPort. It is strongly "
4085 "suggested that you disable serving directory requests when "
4086 "system TCP buffer resources are scarce.");
4090 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
4091 options->V3AuthVotingInterval/2) {
4092 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
4093 "V3AuthVotingInterval");
4095 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
4096 REJECT("V3AuthVoteDelay is way too low.");
4097 if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
4098 REJECT("V3AuthDistDelay is way too low.");
4100 if (options->V3AuthNIntervalsValid < 2)
4101 REJECT("V3AuthNIntervalsValid must be at least 2.");
4103 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
4104 REJECT("V3AuthVotingInterval is insanely low.");
4105 } else if (options->V3AuthVotingInterval > 24*60*60) {
4106 REJECT("V3AuthVotingInterval is insanely high.");
4107 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
4108 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
4111 if (rend_config_services(options, 1) < 0)
4112 REJECT("Failed to configure rendezvous options. See logs for details.");
4114 /* Parse client-side authorization for hidden services. */
4115 if (rend_parse_service_authorization(options, 1) < 0)
4116 REJECT("Failed to configure client authorization for hidden services. "
4117 "See logs for details.");
4119 if (parse_virtual_addr_network(options->VirtualAddrNetwork, 1, NULL)<0)
4120 return -1;
4122 if (options->PreferTunneledDirConns && !options->TunnelDirConns)
4123 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
4125 if ((options->Socks4Proxy || options->Socks5Proxy) &&
4126 !options->HTTPProxy && !options->PreferTunneledDirConns)
4127 REJECT("When Socks4Proxy or Socks5Proxy is configured, "
4128 "PreferTunneledDirConns and TunnelDirConns must both be "
4129 "set to 1, or HTTPProxy must be configured.");
4131 if (options->AutomapHostsSuffixes) {
4132 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
4134 size_t len = strlen(suf);
4135 if (len && suf[len-1] == '.')
4136 suf[len-1] = '\0';
4140 if (options->TestingTorNetwork &&
4141 !(options->DirServers ||
4142 (options->AlternateDirAuthority &&
4143 options->AlternateBridgeAuthority))) {
4144 REJECT("TestingTorNetwork may only be configured in combination with "
4145 "a non-default set of DirServer or both of AlternateDirAuthority "
4146 "and AlternateBridgeAuthority configured.");
4149 if (options->AllowSingleHopExits && !options->DirServers) {
4150 COMPLAIN("You have set AllowSingleHopExits; now your relay will allow "
4151 "others to make one-hop exits. However, since by default most "
4152 "clients avoid relays that set this option, most clients will "
4153 "ignore you.");
4156 /*XXXX checking for defaults manually like this is a bit fragile.*/
4158 /* Keep changes to hard-coded values synchronous to man page and default
4159 * values table. */
4160 if (options->TestingV3AuthInitialVotingInterval != 30*60 &&
4161 !options->TestingTorNetwork && !options->_UsingTestNetworkDefaults) {
4162 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
4163 "Tor networks!");
4164 } else if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
4165 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
4166 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
4167 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
4168 "30 minutes.");
4171 if (options->TestingV3AuthInitialVoteDelay != 5*60 &&
4172 !options->TestingTorNetwork && !options->_UsingTestNetworkDefaults) {
4174 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
4175 "Tor networks!");
4176 } else if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
4177 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
4180 if (options->TestingV3AuthInitialDistDelay != 5*60 &&
4181 !options->TestingTorNetwork && !options->_UsingTestNetworkDefaults) {
4182 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
4183 "Tor networks!");
4184 } else if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
4185 REJECT("TestingV3AuthInitialDistDelay is way too low.");
4188 if (options->TestingV3AuthInitialVoteDelay +
4189 options->TestingV3AuthInitialDistDelay >=
4190 options->TestingV3AuthInitialVotingInterval/2) {
4191 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
4192 "must be less than half TestingV3AuthInitialVotingInterval");
4195 if (options->TestingAuthDirTimeToLearnReachability != 30*60 &&
4196 !options->TestingTorNetwork && !options->_UsingTestNetworkDefaults) {
4197 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
4198 "testing Tor networks!");
4199 } else if (options->TestingAuthDirTimeToLearnReachability < 0) {
4200 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
4201 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
4202 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
4205 if (options->TestingEstimatedDescriptorPropagationTime != 10*60 &&
4206 !options->TestingTorNetwork && !options->_UsingTestNetworkDefaults) {
4207 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
4208 "testing Tor networks!");
4209 } else if (options->TestingEstimatedDescriptorPropagationTime < 0) {
4210 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
4211 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
4212 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
4215 if (options->TestingTorNetwork) {
4216 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
4217 "almost unusable in the public Tor network, and is "
4218 "therefore only advised if you are building a "
4219 "testing Tor network!");
4222 if (options->AccelName && !options->HardwareAccel)
4223 options->HardwareAccel = 1;
4224 if (options->AccelDir && !options->AccelName)
4225 REJECT("Can't use hardware crypto accelerator dir without engine name.");
4227 if (options->PublishServerDescriptor)
4228 SMARTLIST_FOREACH(options->PublishServerDescriptor, const char *, pubdes, {
4229 if (!strcmp(pubdes, "1") || !strcmp(pubdes, "0"))
4230 if (smartlist_len(options->PublishServerDescriptor) > 1) {
4231 COMPLAIN("You have passed a list of multiple arguments to the "
4232 "PublishServerDescriptor option that includes 0 or 1. "
4233 "0 or 1 should only be used as the sole argument. "
4234 "This configuration will be rejected in a future release.");
4235 break;
4239 if (options->BridgeRelay == 1 && ! options->ORPort_set)
4240 REJECT("BridgeRelay is 1, ORPort is not set. This is an invalid "
4241 "combination.");
4243 return 0;
4244 #undef REJECT
4245 #undef COMPLAIN
4248 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
4249 * equal strings. */
4250 static int
4251 opt_streq(const char *s1, const char *s2)
4253 return 0 == strcmp_opt(s1, s2);
4256 /** Check if any of the previous options have changed but aren't allowed to. */
4257 static int
4258 options_transition_allowed(const or_options_t *old,
4259 const or_options_t *new_val,
4260 char **msg)
4262 if (!old)
4263 return 0;
4265 if (!opt_streq(old->PidFile, new_val->PidFile)) {
4266 *msg = tor_strdup("PidFile is not allowed to change.");
4267 return -1;
4270 if (old->RunAsDaemon != new_val->RunAsDaemon) {
4271 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
4272 "is not allowed.");
4273 return -1;
4276 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
4277 tor_asprintf(msg,
4278 "While Tor is running, changing DataDirectory "
4279 "(\"%s\"->\"%s\") is not allowed.",
4280 old->DataDirectory, new_val->DataDirectory);
4281 return -1;
4284 if (!opt_streq(old->User, new_val->User)) {
4285 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
4286 return -1;
4289 if ((old->HardwareAccel != new_val->HardwareAccel)
4290 || !opt_streq(old->AccelName, new_val->AccelName)
4291 || !opt_streq(old->AccelDir, new_val->AccelDir)) {
4292 *msg = tor_strdup("While Tor is running, changing OpenSSL hardware "
4293 "acceleration engine is not allowed.");
4294 return -1;
4297 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
4298 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
4299 "is not allowed.");
4300 return -1;
4303 if (old->DisableAllSwap != new_val->DisableAllSwap) {
4304 *msg = tor_strdup("While Tor is running, changing DisableAllSwap "
4305 "is not allowed.");
4306 return -1;
4309 if (old->TokenBucketRefillInterval != new_val->TokenBucketRefillInterval) {
4310 *msg = tor_strdup("While Tor is running, changing TokenBucketRefill"
4311 "Interval is not allowed");
4312 return -1;
4315 if (old->DisableIOCP != new_val->DisableIOCP) {
4316 *msg = tor_strdup("While Tor is running, changing DisableIOCP "
4317 "is not allowed.");
4318 return -1;
4321 if (old->DisableDebuggerAttachment &&
4322 !new_val->DisableDebuggerAttachment) {
4323 *msg = tor_strdup("While Tor is running, disabling "
4324 "DisableDebuggerAttachment is not allowed.");
4325 return -1;
4328 return 0;
4331 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
4332 * will require us to rotate the CPU and DNS workers; else return 0. */
4333 static int
4334 options_transition_affects_workers(const or_options_t *old_options,
4335 const or_options_t *new_options)
4337 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
4338 old_options->NumCPUs != new_options->NumCPUs ||
4339 !config_lines_eq(old_options->ORPort_lines, new_options->ORPort_lines) ||
4340 old_options->ServerDNSSearchDomains !=
4341 new_options->ServerDNSSearchDomains ||
4342 old_options->_SafeLogging != new_options->_SafeLogging ||
4343 old_options->ClientOnly != new_options->ClientOnly ||
4344 public_server_mode(old_options) != public_server_mode(new_options) ||
4345 !config_lines_eq(old_options->Logs, new_options->Logs) ||
4346 old_options->LogMessageDomains != new_options->LogMessageDomains)
4347 return 1;
4349 /* Check whether log options match. */
4351 /* Nothing that changed matters. */
4352 return 0;
4355 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
4356 * will require us to generate a new descriptor; else return 0. */
4357 static int
4358 options_transition_affects_descriptor(const or_options_t *old_options,
4359 const or_options_t *new_options)
4361 /* XXX We can be smarter here. If your DirPort isn't being
4362 * published and you just turned it off, no need to republish. Etc. */
4363 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
4364 !opt_streq(old_options->Nickname,new_options->Nickname) ||
4365 !opt_streq(old_options->Address,new_options->Address) ||
4366 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
4367 old_options->ExitPolicyRejectPrivate !=
4368 new_options->ExitPolicyRejectPrivate ||
4369 !config_lines_eq(old_options->ORPort_lines,
4370 new_options->ORPort_lines) ||
4371 !config_lines_eq(old_options->DirPort_lines,
4372 new_options->DirPort_lines) ||
4373 old_options->ClientOnly != new_options->ClientOnly ||
4374 old_options->DisableNetwork != new_options->DisableNetwork ||
4375 old_options->_PublishServerDescriptor !=
4376 new_options->_PublishServerDescriptor ||
4377 get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
4378 get_effective_bwburst(old_options) !=
4379 get_effective_bwburst(new_options) ||
4380 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
4381 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
4382 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
4383 old_options->AccountingMax != new_options->AccountingMax ||
4384 public_server_mode(old_options) != public_server_mode(new_options))
4385 return 1;
4387 return 0;
4390 #ifdef _WIN32
4391 /** Return the directory on windows where we expect to find our application
4392 * data. */
4393 static char *
4394 get_windows_conf_root(void)
4396 static int is_set = 0;
4397 static char path[MAX_PATH*2+1];
4398 TCHAR tpath[MAX_PATH] = {0};
4400 LPITEMIDLIST idl;
4401 IMalloc *m;
4402 HRESULT result;
4404 if (is_set)
4405 return path;
4407 /* Find X:\documents and settings\username\application data\ .
4408 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
4410 #ifdef ENABLE_LOCAL_APPDATA
4411 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
4412 #else
4413 #define APPDATA_PATH CSIDL_APPDATA
4414 #endif
4415 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
4416 getcwd(path,MAX_PATH);
4417 is_set = 1;
4418 log_warn(LD_CONFIG,
4419 "I couldn't find your application data folder: are you "
4420 "running an ancient version of Windows 95? Defaulting to \"%s\"",
4421 path);
4422 return path;
4424 /* Convert the path from an "ID List" (whatever that is!) to a path. */
4425 result = SHGetPathFromIDList(idl, tpath);
4426 #ifdef UNICODE
4427 wcstombs(path,tpath,sizeof(path));
4428 path[sizeof(path)-1] = '\0';
4429 #else
4430 strlcpy(path,tpath,sizeof(path));
4431 #endif
4433 /* Now we need to free the memory that the path-idl was stored in. In
4434 * typical Windows fashion, we can't just call 'free()' on it. */
4435 SHGetMalloc(&m);
4436 if (m) {
4437 m->lpVtbl->Free(m, idl);
4438 m->lpVtbl->Release(m);
4440 if (!SUCCEEDED(result)) {
4441 return NULL;
4443 strlcat(path,"\\tor",MAX_PATH);
4444 is_set = 1;
4445 return path;
4447 #endif
4449 /** Return the default location for our torrc file (if <b>defaults_file</b> is
4450 * false), or for the torrc-defaults file (if <b>defaults_file</b> is true). */
4451 static const char *
4452 get_default_conf_file(int defaults_file)
4454 #ifdef _WIN32
4455 if (defaults_file) {
4456 static char defaults_path[MAX_PATH+1];
4457 tor_snprintf(defaults_path, MAX_PATH, "%s\\torrc-defaults",
4458 get_windows_conf_root());
4459 return defaults_path;
4460 } else {
4461 static char path[MAX_PATH+1];
4462 tor_snprintf(path, MAX_PATH, "%s\\torrc",
4463 get_windows_conf_root());
4464 return path;
4466 #else
4467 return defaults_file ? CONFDIR "/torrc-defaults" : CONFDIR "/torrc";
4468 #endif
4471 /** Verify whether lst is a string containing valid-looking comma-separated
4472 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
4474 static int
4475 check_nickname_list(const char *lst, const char *name, char **msg)
4477 int r = 0;
4478 smartlist_t *sl;
4480 if (!lst)
4481 return 0;
4482 sl = smartlist_new();
4484 smartlist_split_string(sl, lst, ",",
4485 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
4487 SMARTLIST_FOREACH(sl, const char *, s,
4489 if (!is_legal_nickname_or_hexdigest(s)) {
4490 tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
4491 r = -1;
4492 break;
4495 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
4496 smartlist_free(sl);
4497 return r;
4500 /** Learn config file name from command line arguments, or use the default.
4502 * If <b>defaults_file</b> is true, we're looking for torrc-defaults;
4503 * otherwise, we're looking for the regular torrc_file.
4505 * Set *<b>using_default_fname</b> to true if we're using the default
4506 * configuration file name; or false if we've set it from the command line.
4508 * Set *<b>ignore_missing_torrc</b> to true if we should ignore the resulting
4509 * filename if it doesn't exist.
4511 static char *
4512 find_torrc_filename(int argc, char **argv,
4513 int defaults_file,
4514 int *using_default_fname, int *ignore_missing_torrc)
4516 char *fname=NULL;
4517 int i;
4518 const char *fname_opt = defaults_file ? "--defaults-torrc" : "-f";
4519 const char *ignore_opt = defaults_file ? NULL : "--ignore-missing-torrc";
4521 if (defaults_file)
4522 *ignore_missing_torrc = 1;
4524 for (i = 1; i < argc; ++i) {
4525 if (i < argc-1 && !strcmp(argv[i],fname_opt)) {
4526 if (fname) {
4527 log(LOG_WARN, LD_CONFIG, "Duplicate %s options on command line.",
4528 fname_opt);
4529 tor_free(fname);
4531 fname = expand_filename(argv[i+1]);
4534 char *absfname;
4535 absfname = make_path_absolute(fname);
4536 tor_free(fname);
4537 fname = absfname;
4540 *using_default_fname = 0;
4541 ++i;
4542 } else if (ignore_opt && !strcmp(argv[i],ignore_opt)) {
4543 *ignore_missing_torrc = 1;
4547 if (*using_default_fname) {
4548 /* didn't find one, try CONFDIR */
4549 const char *dflt = get_default_conf_file(defaults_file);
4550 if (dflt && file_status(dflt) == FN_FILE) {
4551 fname = tor_strdup(dflt);
4552 } else {
4553 #ifndef _WIN32
4554 char *fn = NULL;
4555 if (!defaults_file)
4556 fn = expand_filename("~/.torrc");
4557 if (fn && file_status(fn) == FN_FILE) {
4558 fname = fn;
4559 } else {
4560 tor_free(fn);
4561 fname = tor_strdup(dflt);
4563 #else
4564 fname = tor_strdup(dflt);
4565 #endif
4568 return fname;
4571 /** Load a configuration file from disk, setting torrc_fname or
4572 * torrc_defaults_fname if successful.
4574 * If <b>defaults_file</b> is true, load torrc-defaults; otherwise load torrc.
4576 * Return the contents of the file on success, and NULL on failure.
4578 static char *
4579 load_torrc_from_disk(int argc, char **argv, int defaults_file)
4581 char *fname=NULL;
4582 char *cf = NULL;
4583 int using_default_torrc = 1;
4584 int ignore_missing_torrc = 0;
4585 char **fname_var = defaults_file ? &torrc_defaults_fname : &torrc_fname;
4587 fname = find_torrc_filename(argc, argv, defaults_file,
4588 &using_default_torrc, &ignore_missing_torrc);
4589 tor_assert(fname);
4590 log(LOG_DEBUG, LD_CONFIG, "Opening config file \"%s\"", fname);
4592 tor_free(*fname_var);
4593 *fname_var = fname;
4595 /* Open config file */
4596 if (file_status(fname) != FN_FILE ||
4597 !(cf = read_file_to_str(fname,0,NULL))) {
4598 if (using_default_torrc == 1 || ignore_missing_torrc) {
4599 if (!defaults_file)
4600 log(LOG_NOTICE, LD_CONFIG, "Configuration file \"%s\" not present, "
4601 "using reasonable defaults.", fname);
4602 tor_free(fname); /* sets fname to NULL */
4603 *fname_var = NULL;
4604 cf = tor_strdup("");
4605 } else {
4606 log(LOG_WARN, LD_CONFIG,
4607 "Unable to open configuration file \"%s\".", fname);
4608 goto err;
4610 } else {
4611 log(LOG_NOTICE, LD_CONFIG, "Read configuration file \"%s\".", fname);
4614 return cf;
4615 err:
4616 tor_free(fname);
4617 *fname_var = NULL;
4618 return NULL;
4621 /** Read a configuration file into <b>options</b>, finding the configuration
4622 * file location based on the command line. After loading the file
4623 * call options_init_from_string() to load the config.
4624 * Return 0 if success, -1 if failure. */
4626 options_init_from_torrc(int argc, char **argv)
4628 char *cf=NULL, *cf_defaults=NULL;
4629 int i, command;
4630 int retval = -1;
4631 static char **backup_argv;
4632 static int backup_argc;
4633 char *command_arg = NULL;
4634 char *errmsg=NULL;
4636 if (argv) { /* first time we're called. save command line args */
4637 backup_argv = argv;
4638 backup_argc = argc;
4639 } else { /* we're reloading. need to clean up old options first. */
4640 argv = backup_argv;
4641 argc = backup_argc;
4643 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
4644 print_usage();
4645 exit(0);
4647 if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
4648 /* For documenting validating whether we've documented everything. */
4649 list_torrc_options();
4650 exit(0);
4653 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
4654 printf("Tor version %s.\n",get_version());
4655 exit(0);
4657 if (argc > 1 && (!strcmp(argv[1],"--digests"))) {
4658 printf("Tor version %s.\n",get_version());
4659 printf("%s", libor_get_digests());
4660 printf("%s", tor_get_digests());
4661 exit(0);
4664 /* Go through command-line variables */
4665 if (!global_cmdline_options) {
4666 /* Or we could redo the list every time we pass this place.
4667 * It does not really matter */
4668 if (config_get_commandlines(argc, argv, &global_cmdline_options) < 0) {
4669 goto err;
4673 command = CMD_RUN_TOR;
4674 for (i = 1; i < argc; ++i) {
4675 if (!strcmp(argv[i],"--list-fingerprint")) {
4676 command = CMD_LIST_FINGERPRINT;
4677 } else if (!strcmp(argv[i],"--hash-password")) {
4678 command = CMD_HASH_PASSWORD;
4679 command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
4680 ++i;
4681 } else if (!strcmp(argv[i],"--verify-config")) {
4682 command = CMD_VERIFY_CONFIG;
4686 if (command == CMD_HASH_PASSWORD) {
4687 cf = tor_strdup("");
4688 } else {
4689 cf_defaults = load_torrc_from_disk(argc, argv, 1);
4690 cf = load_torrc_from_disk(argc, argv, 0);
4691 if (!cf)
4692 goto err;
4695 retval = options_init_from_string(cf_defaults, cf, command, command_arg,
4696 &errmsg);
4698 err:
4700 tor_free(cf);
4701 tor_free(cf_defaults);
4702 if (errmsg) {
4703 log(LOG_WARN,LD_CONFIG,"%s", errmsg);
4704 tor_free(errmsg);
4706 return retval < 0 ? -1 : 0;
4709 /** Load the options from the configuration in <b>cf</b>, validate
4710 * them for consistency and take actions based on them.
4712 * Return 0 if success, negative on error:
4713 * * -1 for general errors.
4714 * * -2 for failure to parse/validate,
4715 * * -3 for transition not allowed
4716 * * -4 for error while setting the new options
4718 setopt_err_t
4719 options_init_from_string(const char *cf_defaults, const char *cf,
4720 int command, const char *command_arg,
4721 char **msg)
4723 or_options_t *oldoptions, *newoptions, *newdefaultoptions=NULL;
4724 config_line_t *cl;
4725 int retval, i;
4726 setopt_err_t err = SETOPT_ERR_MISC;
4727 tor_assert(msg);
4729 oldoptions = global_options; /* get_options unfortunately asserts if
4730 this is the first time we run*/
4732 newoptions = tor_malloc_zero(sizeof(or_options_t));
4733 newoptions->_magic = OR_OPTIONS_MAGIC;
4734 options_init(newoptions);
4735 newoptions->command = command;
4736 newoptions->command_arg = command_arg;
4738 for (i = 0; i < 2; ++i) {
4739 const char *body = i==0 ? cf_defaults : cf;
4740 if (!body)
4741 continue;
4742 /* get config lines, assign them */
4743 retval = config_get_lines(body, &cl, 1);
4744 if (retval < 0) {
4745 err = SETOPT_ERR_PARSE;
4746 goto err;
4748 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4749 config_free_lines(cl);
4750 if (retval < 0) {
4751 err = SETOPT_ERR_PARSE;
4752 goto err;
4754 if (i==0)
4755 newdefaultoptions = options_dup(&options_format, newoptions);
4758 /* Go through command-line variables too */
4759 retval = config_assign(&options_format, newoptions,
4760 global_cmdline_options, 0, 0, msg);
4761 if (retval < 0) {
4762 err = SETOPT_ERR_PARSE;
4763 goto err;
4766 /* If this is a testing network configuration, change defaults
4767 * for a list of dependent config options, re-initialize newoptions
4768 * with the new defaults, and assign all options to it second time. */
4769 if (newoptions->TestingTorNetwork) {
4770 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4771 * this? We could, for example, make the parsing algorithm do two passes
4772 * over the configuration. If it finds any "suite" options like
4773 * TestingTorNetwork, it could change the defaults before its second pass.
4774 * Not urgent so long as this seems to work, but at any sign of trouble,
4775 * let's clean it up. -NM */
4777 /* Change defaults. */
4778 int i;
4779 for (i = 0; testing_tor_network_defaults[i].name; ++i) {
4780 const config_var_t *new_var = &testing_tor_network_defaults[i];
4781 config_var_t *old_var =
4782 config_find_option_mutable(&options_format, new_var->name);
4783 tor_assert(new_var);
4784 tor_assert(old_var);
4785 old_var->initvalue = new_var->initvalue;
4788 /* Clear newoptions and re-initialize them with new defaults. */
4789 config_free(&options_format, newoptions);
4790 config_free(&options_format, newdefaultoptions);
4791 newdefaultoptions = NULL;
4792 newoptions = tor_malloc_zero(sizeof(or_options_t));
4793 newoptions->_magic = OR_OPTIONS_MAGIC;
4794 options_init(newoptions);
4795 newoptions->command = command;
4796 newoptions->command_arg = command_arg;
4798 /* Assign all options a second time. */
4799 for (i = 0; i < 2; ++i) {
4800 const char *body = i==0 ? cf_defaults : cf;
4801 if (!body)
4802 continue;
4803 /* get config lines, assign them */
4804 retval = config_get_lines(body, &cl, 1);
4805 if (retval < 0) {
4806 err = SETOPT_ERR_PARSE;
4807 goto err;
4809 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4810 config_free_lines(cl);
4811 if (retval < 0) {
4812 err = SETOPT_ERR_PARSE;
4813 goto err;
4815 if (i==0)
4816 newdefaultoptions = options_dup(&options_format, newoptions);
4818 /* Assign command-line variables a second time too */
4819 retval = config_assign(&options_format, newoptions,
4820 global_cmdline_options, 0, 0, msg);
4821 if (retval < 0) {
4822 err = SETOPT_ERR_PARSE;
4823 goto err;
4827 /* Validate newoptions */
4828 if (options_validate(oldoptions, newoptions, 0, msg) < 0) {
4829 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
4830 goto err;
4833 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
4834 err = SETOPT_ERR_TRANSITION;
4835 goto err;
4838 if (set_options(newoptions, msg)) {
4839 err = SETOPT_ERR_SETTING;
4840 goto err; /* frees and replaces old options */
4842 config_free(&options_format, global_default_options);
4843 global_default_options = newdefaultoptions;
4845 return SETOPT_OK;
4847 err:
4848 config_free(&options_format, newoptions);
4849 config_free(&options_format, newdefaultoptions);
4850 if (*msg) {
4851 char *old_msg = *msg;
4852 tor_asprintf(msg, "Failed to parse/validate config: %s", old_msg);
4853 tor_free(old_msg);
4855 return err;
4858 /** Return the location for our configuration file.
4860 const char *
4861 get_torrc_fname(int defaults_fname)
4863 const char *fname = defaults_fname ? torrc_defaults_fname : torrc_fname;
4865 if (fname)
4866 return fname;
4867 else
4868 return get_default_conf_file(defaults_fname);
4871 /** Adjust the address map based on the MapAddress elements in the
4872 * configuration <b>options</b>
4874 void
4875 config_register_addressmaps(const or_options_t *options)
4877 smartlist_t *elts;
4878 config_line_t *opt;
4879 const char *from, *to, *msg;
4881 addressmap_clear_configured();
4882 elts = smartlist_new();
4883 for (opt = options->AddressMap; opt; opt = opt->next) {
4884 smartlist_split_string(elts, opt->value, NULL,
4885 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4886 if (smartlist_len(elts) < 2) {
4887 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
4888 opt->value);
4889 goto cleanup;
4892 from = smartlist_get(elts,0);
4893 to = smartlist_get(elts,1);
4895 if (to[0] == '.' || from[0] == '.') {
4896 log_warn(LD_CONFIG,"MapAddress '%s' is ambiguous - address starts with a"
4897 "'.'. Ignoring.",opt->value);
4898 goto cleanup;
4901 if (addressmap_register_auto(from, to, 0, ADDRMAPSRC_TORRC, &msg) < 0) {
4902 log_warn(LD_CONFIG,"MapAddress '%s' failed: %s. Ignoring.", opt->value,
4903 msg);
4904 goto cleanup;
4907 if (smartlist_len(elts) > 2)
4908 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
4910 cleanup:
4911 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4912 smartlist_clear(elts);
4914 smartlist_free(elts);
4917 /** As addressmap_register(), but detect the wildcarded status of "from" and
4918 * "to", and do not steal a reference to <b>to</b>. */
4919 /* XXXX024 move to connection_edge.c */
4921 addressmap_register_auto(const char *from, const char *to,
4922 time_t expires,
4923 addressmap_entry_source_t addrmap_source,
4924 const char **msg)
4926 int from_wildcard = 0, to_wildcard = 0;
4928 *msg = "whoops, forgot the error message";
4929 if (1) {
4930 if (!strcmp(to, "*") || !strcmp(from, "*")) {
4931 *msg = "can't remap from or to *";
4932 return -1;
4934 /* Detect asterisks in expressions of type: '*.example.com' */
4935 if (!strncmp(from,"*.",2)) {
4936 from += 2;
4937 from_wildcard = 1;
4939 if (!strncmp(to,"*.",2)) {
4940 to += 2;
4941 to_wildcard = 1;
4944 if (to_wildcard && !from_wildcard) {
4945 *msg = "can only use wildcard (i.e. '*.') if 'from' address "
4946 "uses wildcard also";
4947 return -1;
4950 if (address_is_invalid_destination(to, 1)) {
4951 *msg = "destination is invalid";
4952 return -1;
4955 addressmap_register(from, tor_strdup(to), expires, addrmap_source,
4956 from_wildcard, to_wildcard);
4958 return 0;
4962 * Initialize the logs based on the configuration file.
4964 static int
4965 options_init_logs(or_options_t *options, int validate_only)
4967 config_line_t *opt;
4968 int ok;
4969 smartlist_t *elts;
4970 int daemon =
4971 #ifdef _WIN32
4973 #else
4974 options->RunAsDaemon;
4975 #endif
4977 if (options->LogTimeGranularity <= 0) {
4978 log_warn(LD_CONFIG, "Log time granularity '%d' has to be positive.",
4979 options->LogTimeGranularity);
4980 return -1;
4981 } else if (1000 % options->LogTimeGranularity != 0 &&
4982 options->LogTimeGranularity % 1000 != 0) {
4983 int granularity = options->LogTimeGranularity;
4984 if (granularity < 40) {
4985 do granularity++;
4986 while (1000 % granularity != 0);
4987 } else if (granularity < 1000) {
4988 granularity = 1000 / granularity;
4989 while (1000 % granularity != 0)
4990 granularity--;
4991 granularity = 1000 / granularity;
4992 } else {
4993 granularity = 1000 * ((granularity / 1000) + 1);
4995 log_warn(LD_CONFIG, "Log time granularity '%d' has to be either a "
4996 "divisor or a multiple of 1 second. Changing to "
4997 "'%d'.",
4998 options->LogTimeGranularity, granularity);
4999 if (!validate_only)
5000 set_log_time_granularity(granularity);
5001 } else {
5002 if (!validate_only)
5003 set_log_time_granularity(options->LogTimeGranularity);
5006 ok = 1;
5007 elts = smartlist_new();
5009 for (opt = options->Logs; opt; opt = opt->next) {
5010 log_severity_list_t *severity;
5011 const char *cfg = opt->value;
5012 severity = tor_malloc_zero(sizeof(log_severity_list_t));
5013 if (parse_log_severity_config(&cfg, severity) < 0) {
5014 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
5015 opt->value);
5016 ok = 0; goto cleanup;
5019 smartlist_split_string(elts, cfg, NULL,
5020 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
5022 if (smartlist_len(elts) == 0)
5023 smartlist_add(elts, tor_strdup("stdout"));
5025 if (smartlist_len(elts) == 1 &&
5026 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
5027 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
5028 int err = smartlist_len(elts) &&
5029 !strcasecmp(smartlist_get(elts,0), "stderr");
5030 if (!validate_only) {
5031 if (daemon) {
5032 log_warn(LD_CONFIG,
5033 "Can't log to %s with RunAsDaemon set; skipping stdout",
5034 err?"stderr":"stdout");
5035 } else {
5036 add_stream_log(severity, err?"<stderr>":"<stdout>",
5037 fileno(err?stderr:stdout));
5040 goto cleanup;
5042 if (smartlist_len(elts) == 1 &&
5043 !strcasecmp(smartlist_get(elts,0), "syslog")) {
5044 #ifdef HAVE_SYSLOG_H
5045 if (!validate_only) {
5046 add_syslog_log(severity);
5048 #else
5049 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
5050 #endif
5051 goto cleanup;
5054 if (smartlist_len(elts) == 2 &&
5055 !strcasecmp(smartlist_get(elts,0), "file")) {
5056 if (!validate_only) {
5057 char *fname = expand_filename(smartlist_get(elts, 1));
5058 if (add_file_log(severity, fname) < 0) {
5059 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
5060 opt->value, strerror(errno));
5061 ok = 0;
5063 tor_free(fname);
5065 goto cleanup;
5068 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
5069 opt->value);
5070 ok = 0; goto cleanup;
5072 cleanup:
5073 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
5074 smartlist_clear(elts);
5075 tor_free(severity);
5077 smartlist_free(elts);
5079 if (ok && !validate_only)
5080 logs_set_domain_logging(options->LogMessageDomains);
5082 return ok?0:-1;
5085 /** Read the contents of a Bridge line from <b>line</b>. Return 0
5086 * if the line is well-formed, and -1 if it isn't. If
5087 * <b>validate_only</b> is 0, and the line is well-formed, then add
5088 * the bridge described in the line to our internal bridge list. */
5089 static int
5090 parse_bridge_line(const char *line, int validate_only)
5092 smartlist_t *items = NULL;
5093 int r;
5094 char *addrport=NULL, *fingerprint=NULL;
5095 char *transport_name=NULL;
5096 char *field1=NULL;
5097 tor_addr_t addr;
5098 uint16_t port = 0;
5099 char digest[DIGEST_LEN];
5101 items = smartlist_new();
5102 smartlist_split_string(items, line, NULL,
5103 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5104 if (smartlist_len(items) < 1) {
5105 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
5106 goto err;
5109 /* field1 is either a transport name or addrport */
5110 field1 = smartlist_get(items, 0);
5111 smartlist_del_keeporder(items, 0);
5113 if (!(strstr(field1, ".") || strstr(field1, ":"))) {
5114 /* new-style bridge line */
5115 transport_name = field1;
5116 if (smartlist_len(items) < 1) {
5117 log_warn(LD_CONFIG, "Too few items to Bridge line.");
5118 goto err;
5120 addrport = smartlist_get(items, 0);
5121 smartlist_del_keeporder(items, 0);
5122 } else {
5123 addrport = field1;
5126 if (tor_addr_port_lookup(addrport, &addr, &port)<0) {
5127 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
5128 goto err;
5130 if (!port) {
5131 log_info(LD_CONFIG,
5132 "Bridge address '%s' has no port; using default port 443.",
5133 addrport);
5134 port = 443;
5137 if (smartlist_len(items)) {
5138 fingerprint = smartlist_join_strings(items, "", 0, NULL);
5139 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
5140 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
5141 goto err;
5143 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
5144 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
5145 goto err;
5149 if (!validate_only) {
5150 log_debug(LD_DIR, "Bridge at %s:%d (transport: %s) (%s)",
5151 fmt_addr(&addr), (int)port,
5152 transport_name ? transport_name : "no transport",
5153 fingerprint ? fingerprint : "no key listed");
5154 bridge_add_from_config(&addr, port,
5155 fingerprint ? digest : NULL, transport_name);
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 tor_free(addrport);
5168 tor_free(transport_name);
5169 tor_free(fingerprint);
5170 return r;
5173 /** Read the contents of a ClientTransportPlugin line from
5174 * <b>line</b>. Return 0 if the line is well-formed, and -1 if it
5175 * isn't.
5177 * If <b>validate_only</b> is 0, and the line is well-formed:
5178 * - If it's an external proxy line, add the transport described in the line to
5179 * our internal transport list.
5180 * - If it's a managed proxy line, launch the managed proxy. */
5181 static int
5182 parse_client_transport_line(const char *line, int validate_only)
5184 smartlist_t *items = NULL;
5185 int r;
5186 char *field2=NULL;
5188 const char *transports=NULL;
5189 smartlist_t *transport_list=NULL;
5190 char *addrport=NULL;
5191 tor_addr_t addr;
5192 uint16_t port = 0;
5193 int socks_ver=PROXY_NONE;
5195 /* managed proxy options */
5196 int is_managed=0;
5197 char **proxy_argv=NULL;
5198 char **tmp=NULL;
5199 int proxy_argc,i;
5201 int line_length;
5203 items = smartlist_new();
5204 smartlist_split_string(items, line, NULL,
5205 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5207 line_length = smartlist_len(items);
5208 if (line_length < 3) {
5209 log_warn(LD_CONFIG, "Too few arguments on ClientTransportPlugin line.");
5210 goto err;
5213 /* Get the first line element, split it to commas into
5214 transport_list (in case it's multiple transports) and validate
5215 the transport names. */
5216 transports = smartlist_get(items, 0);
5217 transport_list = smartlist_new();
5218 smartlist_split_string(transport_list, transports, ",",
5219 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
5220 SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
5221 if (!string_is_C_identifier(transport_name)) {
5222 log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
5223 transport_name);
5224 goto err;
5226 } SMARTLIST_FOREACH_END(transport_name);
5228 /* field2 is either a SOCKS version or "exec" */
5229 field2 = smartlist_get(items, 1);
5231 if (!strcmp(field2,"socks4")) {
5232 socks_ver = PROXY_SOCKS4;
5233 } else if (!strcmp(field2,"socks5")) {
5234 socks_ver = PROXY_SOCKS5;
5235 } else if (!strcmp(field2,"exec")) {
5236 is_managed=1;
5237 } else {
5238 log_warn(LD_CONFIG, "Strange ClientTransportPlugin field '%s'.",
5239 field2);
5240 goto err;
5243 if (is_managed) { /* managed */
5244 if (!validate_only) { /* if we are not just validating, use the
5245 rest of the line as the argv of the proxy
5246 to be launched */
5247 proxy_argc = line_length-2;
5248 tor_assert(proxy_argc > 0);
5249 proxy_argv = tor_malloc_zero(sizeof(char*)*(proxy_argc+1));
5250 tmp = proxy_argv;
5251 for (i=0;i<proxy_argc;i++) { /* store arguments */
5252 *tmp++ = smartlist_get(items, 2);
5253 smartlist_del_keeporder(items, 2);
5255 *tmp = NULL; /*terminated with NULL, just like execve() likes it*/
5257 /* kickstart the thing */
5258 pt_kickstart_client_proxy(transport_list, proxy_argv);
5260 } else { /* external */
5261 if (smartlist_len(transport_list) != 1) {
5262 log_warn(LD_CONFIG, "You can't have an external proxy with "
5263 "more than one transports.");
5264 goto err;
5267 addrport = smartlist_get(items, 2);
5269 if (tor_addr_port_lookup(addrport, &addr, &port)<0) {
5270 log_warn(LD_CONFIG, "Error parsing transport "
5271 "address '%s'", addrport);
5272 goto err;
5274 if (!port) {
5275 log_warn(LD_CONFIG,
5276 "Transport address '%s' has no port.", addrport);
5277 goto err;
5280 if (!validate_only) {
5281 transport_add_from_config(&addr, port, smartlist_get(transport_list, 0),
5282 socks_ver);
5284 log_info(LD_DIR, "Transport '%s' found at %s:%d",
5285 transports, fmt_addr(&addr), (int)port);
5289 r = 0;
5290 goto done;
5292 err:
5293 r = -1;
5295 done:
5296 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5297 smartlist_free(items);
5298 if (transport_list) {
5299 SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
5300 smartlist_free(transport_list);
5303 return r;
5306 /** Read the contents of a ServerTransportPlugin line from
5307 * <b>line</b>. Return 0 if the line is well-formed, and -1 if it
5308 * isn't.
5309 * If <b>validate_only</b> is 0, the line is well-formed, and it's a
5310 * managed proxy line, launch the managed proxy. */
5311 static int
5312 parse_server_transport_line(const char *line, int validate_only)
5314 smartlist_t *items = NULL;
5315 int r;
5316 const char *transports=NULL;
5317 smartlist_t *transport_list=NULL;
5318 char *type=NULL;
5319 char *addrport=NULL;
5320 tor_addr_t addr;
5321 uint16_t port = 0;
5323 /* managed proxy options */
5324 int is_managed=0;
5325 char **proxy_argv=NULL;
5326 char **tmp=NULL;
5327 int proxy_argc,i;
5329 int line_length;
5331 items = smartlist_new();
5332 smartlist_split_string(items, line, NULL,
5333 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5335 line_length = smartlist_len(items);
5336 if (line_length < 3) {
5337 log_warn(LD_CONFIG, "Too few arguments on ServerTransportPlugin line.");
5338 goto err;
5341 /* Get the first line element, split it to commas into
5342 transport_list (in case it's multiple transports) and validate
5343 the transport names. */
5344 transports = smartlist_get(items, 0);
5345 transport_list = smartlist_new();
5346 smartlist_split_string(transport_list, transports, ",",
5347 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
5348 SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
5349 if (!string_is_C_identifier(transport_name)) {
5350 log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
5351 transport_name);
5352 goto err;
5354 } SMARTLIST_FOREACH_END(transport_name);
5356 type = smartlist_get(items, 1);
5358 if (!strcmp(type, "exec")) {
5359 is_managed=1;
5360 } else if (!strcmp(type, "proxy")) {
5361 is_managed=0;
5362 } else {
5363 log_warn(LD_CONFIG, "Strange ServerTransportPlugin type '%s'", type);
5364 goto err;
5367 if (is_managed) { /* managed */
5368 if (!validate_only) {
5369 proxy_argc = line_length-2;
5370 tor_assert(proxy_argc > 0);
5371 proxy_argv = tor_malloc_zero(sizeof(char*)*(proxy_argc+1));
5372 tmp = proxy_argv;
5374 for (i=0;i<proxy_argc;i++) { /* store arguments */
5375 *tmp++ = smartlist_get(items, 2);
5376 smartlist_del_keeporder(items, 2);
5378 *tmp = NULL; /*terminated with NULL, just like execve() likes it*/
5380 /* kickstart the thing */
5381 pt_kickstart_server_proxy(transport_list, proxy_argv);
5383 } else { /* external */
5384 if (smartlist_len(transport_list) != 1) {
5385 log_warn(LD_CONFIG, "You can't have an external proxy with "
5386 "more than one transports.");
5387 goto err;
5390 addrport = smartlist_get(items, 2);
5392 if (tor_addr_port_lookup(addrport, &addr, &port)<0) {
5393 log_warn(LD_CONFIG, "Error parsing transport "
5394 "address '%s'", addrport);
5395 goto err;
5397 if (!port) {
5398 log_warn(LD_CONFIG,
5399 "Transport address '%s' has no port.", addrport);
5400 goto err;
5403 if (!validate_only) {
5404 log_info(LD_DIR, "Server transport '%s' at %s:%d.",
5405 transports, fmt_addr(&addr), (int)port);
5409 r = 0;
5410 goto done;
5412 err:
5413 r = -1;
5415 done:
5416 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5417 smartlist_free(items);
5418 if (transport_list) {
5419 SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
5420 smartlist_free(transport_list);
5423 return r;
5426 /** Read the contents of a DirServer line from <b>line</b>. If
5427 * <b>validate_only</b> is 0, and the line is well-formed, and it
5428 * shares any bits with <b>required_type</b> or <b>required_type</b>
5429 * is 0, then add the dirserver described in the line (minus whatever
5430 * bits it's missing) as a valid authority. Return 0 on success,
5431 * or -1 if the line isn't well-formed or if we can't add it. */
5432 static int
5433 parse_dir_server_line(const char *line, dirinfo_type_t required_type,
5434 int validate_only)
5436 smartlist_t *items = NULL;
5437 int r;
5438 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
5439 uint16_t dir_port = 0, or_port = 0;
5440 char digest[DIGEST_LEN];
5441 char v3_digest[DIGEST_LEN];
5442 dirinfo_type_t type = V2_DIRINFO;
5443 int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
5445 items = smartlist_new();
5446 smartlist_split_string(items, line, NULL,
5447 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5448 if (smartlist_len(items) < 1) {
5449 log_warn(LD_CONFIG, "No arguments on DirServer line.");
5450 goto err;
5453 if (is_legal_nickname(smartlist_get(items, 0))) {
5454 nickname = smartlist_get(items, 0);
5455 smartlist_del_keeporder(items, 0);
5458 while (smartlist_len(items)) {
5459 char *flag = smartlist_get(items, 0);
5460 if (TOR_ISDIGIT(flag[0]))
5461 break;
5462 if (!strcasecmp(flag, "v1")) {
5463 type |= (V1_DIRINFO | HIDSERV_DIRINFO);
5464 } else if (!strcasecmp(flag, "hs")) {
5465 type |= HIDSERV_DIRINFO;
5466 } else if (!strcasecmp(flag, "no-hs")) {
5467 is_not_hidserv_authority = 1;
5468 } else if (!strcasecmp(flag, "bridge")) {
5469 type |= BRIDGE_DIRINFO;
5470 } else if (!strcasecmp(flag, "no-v2")) {
5471 is_not_v2_authority = 1;
5472 } else if (!strcasecmpstart(flag, "orport=")) {
5473 int ok;
5474 char *portstring = flag + strlen("orport=");
5475 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
5476 if (!ok)
5477 log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
5478 portstring);
5479 } else if (!strcasecmpstart(flag, "v3ident=")) {
5480 char *idstr = flag + strlen("v3ident=");
5481 if (strlen(idstr) != HEX_DIGEST_LEN ||
5482 base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
5483 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirServer line",
5484 flag);
5485 } else {
5486 type |= V3_DIRINFO|EXTRAINFO_DIRINFO|MICRODESC_DIRINFO;
5488 } else {
5489 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
5490 flag);
5492 tor_free(flag);
5493 smartlist_del_keeporder(items, 0);
5495 if (is_not_hidserv_authority)
5496 type &= ~HIDSERV_DIRINFO;
5497 if (is_not_v2_authority)
5498 type &= ~V2_DIRINFO;
5500 if (smartlist_len(items) < 2) {
5501 log_warn(LD_CONFIG, "Too few arguments to DirServer line.");
5502 goto err;
5504 addrport = smartlist_get(items, 0);
5505 smartlist_del_keeporder(items, 0);
5506 if (addr_port_lookup(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
5507 log_warn(LD_CONFIG, "Error parsing DirServer address '%s'", addrport);
5508 goto err;
5510 if (!dir_port) {
5511 log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
5512 goto err;
5515 fingerprint = smartlist_join_strings(items, "", 0, NULL);
5516 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
5517 log_warn(LD_CONFIG, "Key digest for DirServer is wrong length %d.",
5518 (int)strlen(fingerprint));
5519 goto err;
5521 if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
5522 /* a known bad fingerprint. refuse to use it. We can remove this
5523 * clause once Tor 0.1.2.17 is obsolete. */
5524 log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
5525 "torrc file (%s), or reinstall Tor and use the default torrc.",
5526 get_torrc_fname(0));
5527 goto err;
5529 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
5530 log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
5531 goto err;
5534 if (!validate_only && (!required_type || required_type & type)) {
5535 if (required_type)
5536 type &= required_type; /* pare down what we think of them as an
5537 * authority for. */
5538 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
5539 address, (int)dir_port, (char*)smartlist_get(items,0));
5540 if (!add_trusted_dir_server(nickname, address, dir_port, or_port,
5541 digest, v3_digest, type))
5542 goto err;
5545 r = 0;
5546 goto done;
5548 err:
5549 r = -1;
5551 done:
5552 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5553 smartlist_free(items);
5554 tor_free(addrport);
5555 tor_free(address);
5556 tor_free(nickname);
5557 tor_free(fingerprint);
5558 return r;
5561 /** Free all storage held in <b>port</b> */
5562 static void
5563 port_cfg_free(port_cfg_t *port)
5565 tor_free(port);
5568 /** Warn for every port in <b>ports</b> that is on a publicly routable
5569 * address. */
5570 static void
5571 warn_nonlocal_client_ports(const smartlist_t *ports, const char *portname)
5573 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
5574 if (port->is_unix_addr) {
5575 /* Unix sockets aren't accessible over a network. */
5576 } else if (!tor_addr_is_internal(&port->addr, 1)) {
5577 log_warn(LD_CONFIG, "You specified a public address for %sPort. "
5578 "Other people on the Internet might find your computer and "
5579 "use it as an open proxy. Please don't allow this unless you "
5580 "have a good reason.", portname);
5581 } else if (!tor_addr_is_loopback(&port->addr)) {
5582 log_notice(LD_CONFIG, "You configured a non-loopback address for "
5583 "%sPort. This allows everybody on your local network to use "
5584 "your machine as a proxy. Make sure this is what you wanted.",
5585 portname);
5587 } SMARTLIST_FOREACH_END(port);
5590 /** Given a list of port_cfg_t in <b>ports</b>, warn any controller port there
5591 * is listening on any non-loopback address. If <b>forbid</b> is true,
5592 * then emit a stronger warning and remove the port from the list.
5594 static void
5595 warn_nonlocal_controller_ports(smartlist_t *ports, unsigned forbid)
5597 int warned = 0;
5598 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
5599 if (port->type != CONN_TYPE_CONTROL_LISTENER)
5600 continue;
5601 if (port->is_unix_addr)
5602 continue;
5603 if (!tor_addr_is_loopback(&port->addr)) {
5604 if (forbid) {
5605 if (!warned)
5606 log_warn(LD_CONFIG,
5607 "You have a ControlPort set to accept "
5608 "unauthenticated connections from a non-local address. "
5609 "This means that programs not running on your computer "
5610 "can reconfigure your Tor, without even having to guess a "
5611 "password. That's so bad that I'm closing your ControlPort "
5612 "for you. If you need to control your Tor remotely, try "
5613 "enabling authentication and using a tool like stunnel or "
5614 "ssh to encrypt remote access.");
5615 warned = 1;
5616 port_cfg_free(port);
5617 SMARTLIST_DEL_CURRENT(ports, port);
5618 } else {
5619 log_warn(LD_CONFIG, "You have a ControlPort set to accept "
5620 "connections from a non-local address. This means that "
5621 "programs not running on your computer can reconfigure your "
5622 "Tor. That's pretty bad, since the controller "
5623 "protocol isn't encrypted! Maybe you should just listen on "
5624 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
5625 "remote connections to your control port.");
5626 return; /* No point in checking the rest */
5629 } SMARTLIST_FOREACH_END(port);
5632 #define CL_PORT_NO_OPTIONS (1u<<0)
5633 #define CL_PORT_WARN_NONLOCAL (1u<<1)
5634 #define CL_PORT_ALLOW_EXTRA_LISTENADDR (1u<<2)
5635 #define CL_PORT_SERVER_OPTIONS (1u<<3)
5636 #define CL_PORT_FORBID_NONLOCAL (1u<<4)
5639 * Parse port configuration for a single port type.
5641 * Read entries of the "FooPort" type from the list <b>ports</b>, and
5642 * entries of the "FooListenAddress" type from the list
5643 * <b>listenaddrs</b>. Two syntaxes are supported: a legacy syntax
5644 * where FooPort is at most a single entry containing a port number and
5645 * where FooListenAddress has any number of address:port combinations;
5646 * and a new syntax where there are no FooListenAddress entries and
5647 * where FooPort can have any number of entries of the format
5648 * "[Address:][Port] IsolationOptions".
5650 * In log messages, describe the port type as <b>portname</b>.
5652 * If no address is specified, default to <b>defaultaddr</b>. If no
5653 * FooPort is given, default to defaultport (if 0, there is no default).
5655 * If CL_PORT_NO_OPTIONS is set in <b>flags</b>, do not allow stream
5656 * isolation options in the FooPort entries.
5658 * If CL_PORT_WARN_NONLOCAL is set in <b>flags</b>, warn if any of the
5659 * ports are not on a local address. If CL_PORT_FORBID_NONLOCAL is set,
5660 * this is a contrl port with no password set: don't even allow it.
5662 * Unless CL_PORT_ALLOW_EXTRA_LISTENADDR is set in <b>flags</b>, warn
5663 * if FooListenAddress is set but FooPort is 0.
5665 * If CL_PORT_SERVER_OPTIONS is set in <b>flags</b>, do not allow stream
5666 * isolation options in the FooPort entries; instead allow the
5667 * server-port option set.
5669 * On success, if <b>out</b> is given, add a new port_cfg_t entry to
5670 * <b>out</b> for every port that the client should listen on. Return 0
5671 * on success, -1 on failure.
5673 static int
5674 parse_port_config(smartlist_t *out,
5675 const config_line_t *ports,
5676 const config_line_t *listenaddrs,
5677 const char *portname,
5678 int listener_type,
5679 const char *defaultaddr,
5680 int defaultport,
5681 unsigned flags)
5683 smartlist_t *elts;
5684 int retval = -1;
5685 const unsigned is_control = (listener_type == CONN_TYPE_CONTROL_LISTENER);
5686 const unsigned allow_no_options = flags & CL_PORT_NO_OPTIONS;
5687 const unsigned use_server_options = flags & CL_PORT_SERVER_OPTIONS;
5688 const unsigned warn_nonlocal = flags & CL_PORT_WARN_NONLOCAL;
5689 const unsigned forbid_nonlocal = flags & CL_PORT_FORBID_NONLOCAL;
5690 const unsigned allow_spurious_listenaddr =
5691 flags & CL_PORT_ALLOW_EXTRA_LISTENADDR;
5692 int got_zero_port=0, got_nonzero_port=0;
5694 /* FooListenAddress is deprecated; let's make it work like it used to work,
5695 * though. */
5696 if (listenaddrs) {
5697 int mainport = defaultport;
5699 if (ports && ports->next) {
5700 log_warn(LD_CONFIG, "%sListenAddress can't be used when there are "
5701 "multiple %sPort lines", portname, portname);
5702 return -1;
5703 } else if (ports) {
5704 if (!strcmp(ports->value, "auto")) {
5705 mainport = CFG_AUTO_PORT;
5706 } else {
5707 int ok;
5708 mainport = (int)tor_parse_long(ports->value, 10, 0, 65535, &ok, NULL);
5709 if (!ok) {
5710 log_warn(LD_CONFIG, "%sListenAddress can only be used with a single "
5711 "%sPort with value \"auto\" or 1-65535 and no options set.",
5712 portname, portname);
5713 return -1;
5718 if (mainport == 0) {
5719 if (allow_spurious_listenaddr)
5720 return 1; /*DOCDOC*/
5721 log_warn(LD_CONFIG, "%sPort must be defined if %sListenAddress is used",
5722 portname, portname);
5723 return -1;
5726 if (use_server_options && out) {
5727 /* Add a no_listen port. */
5728 port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t));
5729 cfg->type = listener_type;
5730 cfg->port = mainport;
5731 tor_addr_make_unspec(&cfg->addr); /* Server ports default to 0.0.0.0 */
5732 cfg->no_listen = 1;
5733 cfg->ipv4_only = 1;
5734 smartlist_add(out, cfg);
5737 for (; listenaddrs; listenaddrs = listenaddrs->next) {
5738 tor_addr_t addr;
5739 uint16_t port = 0;
5740 if (tor_addr_port_lookup(listenaddrs->value, &addr, &port) < 0) {
5741 log_warn(LD_CONFIG, "Unable to parse %sListenAddress '%s'",
5742 portname, listenaddrs->value);
5743 return -1;
5745 if (out) {
5746 port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t));
5747 cfg->type = listener_type;
5748 cfg->port = port ? port : mainport;
5749 tor_addr_copy(&cfg->addr, &addr);
5750 cfg->session_group = SESSION_GROUP_UNSET;
5751 cfg->isolation_flags = ISO_DEFAULT;
5752 cfg->no_advertise = 1;
5753 smartlist_add(out, cfg);
5757 if (warn_nonlocal && out) {
5758 if (is_control)
5759 warn_nonlocal_controller_ports(out, forbid_nonlocal);
5760 else
5761 warn_nonlocal_client_ports(out, portname);
5763 return 0;
5764 } /* end if (listenaddrs) */
5766 /* No ListenAddress lines. If there's no FooPort, then maybe make a default
5767 * one. */
5768 if (! ports) {
5769 if (defaultport && out) {
5770 port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t));
5771 cfg->type = listener_type;
5772 cfg->port = defaultport;
5773 tor_addr_parse(&cfg->addr, defaultaddr);
5774 cfg->session_group = SESSION_GROUP_UNSET;
5775 cfg->isolation_flags = ISO_DEFAULT;
5776 smartlist_add(out, cfg);
5778 return 0;
5781 /* At last we can actually parse the FooPort lines. The syntax is:
5782 * [Addr:](Port|auto) [Options].*/
5783 elts = smartlist_new();
5785 for (; ports; ports = ports->next) {
5786 tor_addr_t addr;
5787 int port;
5788 int sessiongroup = SESSION_GROUP_UNSET;
5789 unsigned isolation = ISO_DEFAULT;
5791 char *addrport;
5792 uint16_t ptmp=0;
5793 int ok;
5794 int no_listen = 0, no_advertise = 0, all_addrs = 0,
5795 ipv4_only = 0, ipv6_only = 0;
5797 smartlist_split_string(elts, ports->value, NULL,
5798 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
5799 if (smartlist_len(elts) == 0) {
5800 log_warn(LD_CONFIG, "Invalid %sPort line with no value", portname);
5801 goto err;
5804 if (allow_no_options && smartlist_len(elts) > 1) {
5805 log_warn(LD_CONFIG, "Too many options on %sPort line", portname);
5806 goto err;
5809 /* Now parse the addr/port value */
5810 addrport = smartlist_get(elts, 0);
5811 if (!strcmp(addrport, "auto")) {
5812 port = CFG_AUTO_PORT;
5813 tor_addr_parse(&addr, defaultaddr);
5814 } else if (!strcasecmpend(addrport, ":auto")) {
5815 char *addrtmp = tor_strndup(addrport, strlen(addrport)-5);
5816 port = CFG_AUTO_PORT;
5817 if (tor_addr_port_lookup(addrtmp, &addr, &ptmp)<0 || ptmp) {
5818 log_warn(LD_CONFIG, "Invalid address '%s' for %sPort",
5819 escaped(addrport), portname);
5820 tor_free(addrtmp);
5821 goto err;
5823 } else {
5824 /* Try parsing integer port before address, because, who knows?
5825 "9050" might be a valid address. */
5826 port = (int) tor_parse_long(addrport, 10, 0, 65535, &ok, NULL);
5827 if (ok) {
5828 tor_addr_parse(&addr, defaultaddr);
5829 } else if (tor_addr_port_lookup(addrport, &addr, &ptmp) == 0) {
5830 if (ptmp == 0) {
5831 log_warn(LD_CONFIG, "%sPort line has address but no port", portname);
5832 goto err;
5834 port = ptmp;
5835 } else {
5836 log_warn(LD_CONFIG, "Couldn't parse address '%s' for %sPort",
5837 escaped(addrport), portname);
5838 goto err;
5842 /* Now parse the rest of the options, if any. */
5843 if (use_server_options) {
5844 /* This is a server port; parse advertising options */
5845 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
5846 if (elt_sl_idx == 0)
5847 continue; /* Skip addr:port */
5849 if (!strcasecmp(elt, "NoAdvertise")) {
5850 no_advertise = 1;
5851 } else if (!strcasecmp(elt, "NoListen")) {
5852 no_listen = 1;
5853 #if 0
5854 /* not implemented yet. */
5855 } else if (!strcasecmp(elt, "AllAddrs")) {
5857 all_addrs = 1;
5858 #endif
5859 } else if (!strcasecmp(elt, "IPv4Only")) {
5860 ipv4_only = 1;
5861 } else if (!strcasecmp(elt, "IPv6Only")) {
5862 ipv6_only = 1;
5863 } else {
5864 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
5865 portname, escaped(elt));
5867 } SMARTLIST_FOREACH_END(elt);
5869 if (no_advertise && no_listen) {
5870 log_warn(LD_CONFIG, "Tried to set both NoListen and NoAdvertise "
5871 "on %sPort line '%s'",
5872 portname, escaped(ports->value));
5873 goto err;
5875 if (ipv4_only && ipv6_only) {
5876 log_warn(LD_CONFIG, "Tried to set both IPv4Only and IPv6Only "
5877 "on %sPort line '%s'",
5878 portname, escaped(ports->value));
5879 goto err;
5881 if (ipv4_only && tor_addr_family(&addr) == AF_INET6) {
5882 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv6",
5883 portname);
5884 goto err;
5886 if (ipv6_only && tor_addr_family(&addr) == AF_INET) {
5887 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv4",
5888 portname);
5889 goto err;
5891 } else {
5892 /* This is a client port; parse isolation options */
5893 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
5894 int no = 0, isoflag = 0;
5895 const char *elt_orig = elt;
5896 if (elt_sl_idx == 0)
5897 continue; /* Skip addr:port */
5898 if (!strcasecmpstart(elt, "SessionGroup=")) {
5899 int group = (int)tor_parse_long(elt+strlen("SessionGroup="),
5900 10, 0, INT_MAX, &ok, NULL);
5901 if (!ok) {
5902 log_warn(LD_CONFIG, "Invalid %sPort option '%s'",
5903 portname, escaped(elt));
5904 goto err;
5906 if (sessiongroup >= 0) {
5907 log_warn(LD_CONFIG, "Multiple SessionGroup options on %sPort",
5908 portname);
5909 goto err;
5911 sessiongroup = group;
5912 continue;
5915 if (!strcasecmpstart(elt, "No")) {
5916 no = 1;
5917 elt += 2;
5919 if (!strcasecmpend(elt, "s"))
5920 elt[strlen(elt)-1] = '\0'; /* kill plurals. */
5922 if (!strcasecmp(elt, "IsolateDestPort")) {
5923 isoflag = ISO_DESTPORT;
5924 } else if (!strcasecmp(elt, "IsolateDestAddr")) {
5925 isoflag = ISO_DESTADDR;
5926 } else if (!strcasecmp(elt, "IsolateSOCKSAuth")) {
5927 isoflag = ISO_SOCKSAUTH;
5928 } else if (!strcasecmp(elt, "IsolateClientProtocol")) {
5929 isoflag = ISO_CLIENTPROTO;
5930 } else if (!strcasecmp(elt, "IsolateClientAddr")) {
5931 isoflag = ISO_CLIENTADDR;
5932 } else {
5933 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
5934 portname, escaped(elt_orig));
5937 if (no) {
5938 isolation &= ~isoflag;
5939 } else {
5940 isolation |= isoflag;
5942 } SMARTLIST_FOREACH_END(elt);
5945 if (port)
5946 got_nonzero_port = 1;
5947 else
5948 got_zero_port = 1;
5950 if (out && port) {
5951 port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t));
5952 tor_addr_copy(&cfg->addr, &addr);
5953 cfg->port = port;
5954 cfg->type = listener_type;
5955 cfg->isolation_flags = isolation;
5956 cfg->session_group = sessiongroup;
5957 cfg->no_advertise = no_advertise;
5958 cfg->no_listen = no_listen;
5959 cfg->all_addrs = all_addrs;
5960 cfg->ipv4_only = ipv4_only;
5961 cfg->ipv6_only = ipv6_only;
5963 smartlist_add(out, cfg);
5965 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
5966 smartlist_clear(elts);
5969 if (warn_nonlocal && out) {
5970 if (is_control)
5971 warn_nonlocal_controller_ports(out, forbid_nonlocal);
5972 else
5973 warn_nonlocal_client_ports(out, portname);
5976 if (got_zero_port && got_nonzero_port) {
5977 log_warn(LD_CONFIG, "You specified a nonzero %sPort along with '%sPort 0' "
5978 "in the same configuration. Did you mean to disable %sPort or "
5979 "not?", portname, portname, portname);
5980 goto err;
5983 retval = 0;
5984 err:
5985 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
5986 smartlist_free(elts);
5987 return retval;
5990 /** Parse a list of config_line_t for an AF_UNIX unix socket listener option
5991 * from <b>cfg</b> and add them to <b>out</b>. No fancy options are
5992 * supported: the line contains nothing but the path to the AF_UNIX socket. */
5993 static int
5994 parse_unix_socket_config(smartlist_t *out, const config_line_t *cfg,
5995 int listener_type)
5998 if (!out)
5999 return 0;
6001 for ( ; cfg; cfg = cfg->next) {
6002 size_t len = strlen(cfg->value);
6003 port_cfg_t *port = tor_malloc_zero(sizeof(port_cfg_t) + len + 1);
6004 port->is_unix_addr = 1;
6005 memcpy(port->unix_addr, cfg->value, len+1);
6006 port->type = listener_type;
6007 smartlist_add(out, port);
6010 return 0;
6013 /** Return the number of ports which are actually going to listen with type
6014 * <b>listenertype</b>. Do not count no_listen ports. Do not count unix
6015 * sockets. */
6016 static int
6017 count_real_listeners(const smartlist_t *ports, int listenertype)
6019 int n = 0;
6020 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
6021 if (port->no_listen || port->is_unix_addr)
6022 continue;
6023 if (port->type != listenertype)
6024 continue;
6025 ++n;
6026 } SMARTLIST_FOREACH_END(port);
6027 return n;
6030 /** Parse all client port types (Socks, DNS, Trans, NATD) from
6031 * <b>options</b>. On success, set *<b>n_ports_out</b> to the number
6032 * of ports that are listed, update the *Port_set values in
6033 * <b>options</b>, and return 0. On failure, set *<b>msg</b> to a
6034 * description of the problem and return -1.
6036 * If <b>validate_only</b> is false, set configured_client_ports to the
6037 * new list of ports parsed from <b>options</b>.
6039 static int
6040 parse_ports(or_options_t *options, int validate_only,
6041 char **msg, int *n_ports_out)
6043 smartlist_t *ports;
6044 int retval = -1;
6046 ports = smartlist_new();
6048 *n_ports_out = 0;
6050 if (parse_port_config(ports,
6051 options->SocksPort_lines, options->SocksListenAddress,
6052 "Socks", CONN_TYPE_AP_LISTENER,
6053 "127.0.0.1", 9050,
6054 CL_PORT_WARN_NONLOCAL|CL_PORT_ALLOW_EXTRA_LISTENADDR) < 0) {
6055 *msg = tor_strdup("Invalid SocksPort/SocksListenAddress configuration");
6056 goto err;
6058 if (parse_port_config(ports,
6059 options->DNSPort_lines, options->DNSListenAddress,
6060 "DNS", CONN_TYPE_AP_DNS_LISTENER,
6061 "127.0.0.1", 0,
6062 CL_PORT_WARN_NONLOCAL) < 0) {
6063 *msg = tor_strdup("Invalid DNSPort/DNSListenAddress configuration");
6064 goto err;
6066 if (parse_port_config(ports,
6067 options->TransPort_lines, options->TransListenAddress,
6068 "Trans", CONN_TYPE_AP_TRANS_LISTENER,
6069 "127.0.0.1", 0,
6070 CL_PORT_WARN_NONLOCAL) < 0) {
6071 *msg = tor_strdup("Invalid TransPort/TransListenAddress configuration");
6072 goto err;
6074 if (parse_port_config(ports,
6075 options->NATDPort_lines, options->NATDListenAddress,
6076 "NATD", CONN_TYPE_AP_NATD_LISTENER,
6077 "127.0.0.1", 0,
6078 CL_PORT_WARN_NONLOCAL) < 0) {
6079 *msg = tor_strdup("Invalid NatdPort/NatdListenAddress configuration");
6080 goto err;
6083 unsigned control_port_flags = CL_PORT_NO_OPTIONS | CL_PORT_WARN_NONLOCAL;
6084 const int any_passwords = (options->HashedControlPassword ||
6085 options->HashedControlSessionPassword ||
6086 options->CookieAuthentication);
6087 if (! any_passwords)
6088 control_port_flags |= CL_PORT_FORBID_NONLOCAL;
6090 if (parse_port_config(ports,
6091 options->ControlPort_lines,
6092 options->ControlListenAddress,
6093 "Control", CONN_TYPE_CONTROL_LISTENER,
6094 "127.0.0.1", 0,
6095 control_port_flags) < 0) {
6096 *msg = tor_strdup("Invalid ControlPort/ControlListenAddress "
6097 "configuration");
6098 goto err;
6100 if (parse_unix_socket_config(ports,
6101 options->ControlSocket,
6102 CONN_TYPE_CONTROL_LISTENER) < 0) {
6103 *msg = tor_strdup("Invalid ControlSocket configuration");
6104 goto err;
6107 if (! options->ClientOnly) {
6108 if (parse_port_config(ports,
6109 options->ORPort_lines, options->ORListenAddress,
6110 "OR", CONN_TYPE_OR_LISTENER,
6111 "0.0.0.0", 0,
6112 CL_PORT_SERVER_OPTIONS) < 0) {
6113 *msg = tor_strdup("Invalid ORPort/ORListenAddress configuration");
6114 goto err;
6116 if (parse_port_config(ports,
6117 options->DirPort_lines, options->DirListenAddress,
6118 "Dir", CONN_TYPE_DIR_LISTENER,
6119 "0.0.0.0", 0,
6120 CL_PORT_SERVER_OPTIONS) < 0) {
6121 *msg = tor_strdup("Invalid DirPort/DirListenAddress configuration");
6122 goto err;
6126 if (check_server_ports(ports, options) < 0) {
6127 *msg = tor_strdup("Misconfigured server ports");
6128 goto err;
6131 *n_ports_out = smartlist_len(ports);
6133 retval = 0;
6135 /* Update the *Port_set options. The !! here is to force a boolean out of
6136 an integer. */
6137 options->ORPort_set =
6138 !! count_real_listeners(ports, CONN_TYPE_OR_LISTENER);
6139 options->SocksPort_set =
6140 !! count_real_listeners(ports, CONN_TYPE_AP_LISTENER);
6141 options->TransPort_set =
6142 !! count_real_listeners(ports, CONN_TYPE_AP_TRANS_LISTENER);
6143 options->NATDPort_set =
6144 !! count_real_listeners(ports, CONN_TYPE_AP_NATD_LISTENER);
6145 options->ControlPort_set =
6146 !! count_real_listeners(ports, CONN_TYPE_CONTROL_LISTENER);
6147 options->DirPort_set =
6148 !! count_real_listeners(ports, CONN_TYPE_DIR_LISTENER);
6149 options->DNSPort_set =
6150 !! count_real_listeners(ports, CONN_TYPE_AP_DNS_LISTENER);
6152 if (!validate_only) {
6153 if (configured_ports) {
6154 SMARTLIST_FOREACH(configured_ports,
6155 port_cfg_t *, p, port_cfg_free(p));
6156 smartlist_free(configured_ports);
6158 configured_ports = ports;
6159 ports = NULL; /* prevent free below. */
6162 err:
6163 if (ports) {
6164 SMARTLIST_FOREACH(ports, port_cfg_t *, p, port_cfg_free(p));
6165 smartlist_free(ports);
6167 return retval;
6170 /** Given a list of <b>port_cfg_t</b> in <b>ports</b>, check them for internal
6171 * consistency and warn as appropriate. */
6172 static int
6173 check_server_ports(const smartlist_t *ports,
6174 const or_options_t *options)
6176 int n_orport_advertised = 0;
6177 int n_orport_advertised_ipv4 = 0;
6178 int n_orport_listeners = 0;
6179 int n_dirport_advertised = 0;
6180 int n_dirport_listeners = 0;
6181 int n_low_port = 0;
6182 int r = 0;
6184 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
6185 if (port->type == CONN_TYPE_DIR_LISTENER) {
6186 if (! port->no_advertise)
6187 ++n_dirport_advertised;
6188 if (! port->no_listen)
6189 ++n_dirport_listeners;
6190 } else if (port->type == CONN_TYPE_OR_LISTENER) {
6191 if (! port->no_advertise) {
6192 ++n_orport_advertised;
6193 if (tor_addr_family(&port->addr) == AF_INET ||
6194 (tor_addr_family(&port->addr) == AF_UNSPEC && !port->ipv6_only))
6195 ++n_orport_advertised_ipv4;
6197 if (! port->no_listen)
6198 ++n_orport_listeners;
6199 } else {
6200 continue;
6202 #ifndef _WIN32
6203 if (!port->no_advertise && port->port < 1024)
6204 ++n_low_port;
6205 #endif
6206 } SMARTLIST_FOREACH_END(port);
6208 if (n_orport_advertised && !n_orport_listeners) {
6209 log_warn(LD_CONFIG, "We are advertising an ORPort, but not actually "
6210 "listening on one.");
6211 r = -1;
6213 if (n_dirport_advertised && !n_dirport_listeners) {
6214 log_warn(LD_CONFIG, "We are advertising a DirPort, but not actually "
6215 "listening on one.");
6216 r = -1;
6218 if (n_dirport_advertised > 1) {
6219 log_warn(LD_CONFIG, "Can't advertise more than one DirPort.");
6220 r = -1;
6222 if (n_orport_advertised && !n_orport_advertised_ipv4 &&
6223 !options->BridgeRelay) {
6224 log_warn(LD_CONFIG, "Configured non-bridge only to listen on an IPv6 "
6225 "address.");
6226 r = -1;
6229 if (n_low_port && options->AccountingMax) {
6230 log(LOG_WARN, LD_CONFIG,
6231 "You have set AccountingMax to use hibernation. You have also "
6232 "chosen a low DirPort or OrPort. This combination can make Tor stop "
6233 "working when it tries to re-attach the port after a period of "
6234 "hibernation. Please choose a different port or turn off "
6235 "hibernation unless you know this combination will work on your "
6236 "platform.");
6239 return r;
6242 /** Return a list of port_cfg_t for client ports parsed from the
6243 * options. */
6244 const smartlist_t *
6245 get_configured_ports(void)
6247 if (!configured_ports)
6248 configured_ports = smartlist_new();
6249 return configured_ports;
6252 /** Return an address:port string representation of the address
6253 * where the first <b>listener_type</b> listener waits for
6254 * connections. Return NULL if we couldn't find a listener. The
6255 * string is allocated on the heap and it's the responsibility of the
6256 * caller to free it after use.
6258 * This function is meant to be used by the pluggable transport proxy
6259 * spawning code, please make sure that it fits your purposes before
6260 * using it. */
6261 char *
6262 get_first_listener_addrport_string(int listener_type)
6264 static const char *ipv4_localhost = "127.0.0.1";
6265 static const char *ipv6_localhost = "[::1]";
6266 const char *address;
6267 uint16_t port;
6268 char *string = NULL;
6270 if (!configured_ports)
6271 return NULL;
6273 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
6274 if (cfg->no_listen)
6275 continue;
6277 if (cfg->type == listener_type &&
6278 tor_addr_family(&cfg->addr) != AF_UNSPEC) {
6280 /* We found the first listener of the type we are interested in! */
6282 /* If a listener is listening on INADDR_ANY, assume that it's
6283 also listening on 127.0.0.1, and point the transport proxy
6284 there: */
6285 if (tor_addr_is_null(&cfg->addr))
6286 address = tor_addr_is_v4(&cfg->addr) ? ipv4_localhost : ipv6_localhost;
6287 else
6288 address = fmt_and_decorate_addr(&cfg->addr);
6290 /* If a listener is configured with port 'auto', we are forced
6291 to iterate all listener connections and find out in which
6292 port it ended up listening: */
6293 if (cfg->port == CFG_AUTO_PORT) {
6294 port = router_get_active_listener_port_by_type(listener_type);
6295 if (!port)
6296 return NULL;
6297 } else {
6298 port = cfg->port;
6301 tor_asprintf(&string, "%s:%u", address, port);
6303 return string;
6306 } SMARTLIST_FOREACH_END(cfg);
6308 return NULL;
6311 /** Return the first advertised port of type <b>listener_type</b> in
6312 <b>address_family</b>. */
6314 get_first_advertised_port_by_type_af(int listener_type, int address_family)
6316 if (!configured_ports)
6317 return 0;
6318 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
6319 if (cfg->type == listener_type &&
6320 !cfg->no_advertise &&
6321 (tor_addr_family(&cfg->addr) == address_family ||
6322 tor_addr_family(&cfg->addr) == AF_UNSPEC)) {
6323 if (tor_addr_family(&cfg->addr) != AF_UNSPEC ||
6324 (address_family == AF_INET && !cfg->ipv6_only) ||
6325 (address_family == AF_INET6 && !cfg->ipv4_only)) {
6326 return cfg->port;
6329 } SMARTLIST_FOREACH_END(cfg);
6330 return 0;
6333 /** Adjust the value of options->DataDirectory, or fill it in if it's
6334 * absent. Return 0 on success, -1 on failure. */
6335 static int
6336 normalize_data_directory(or_options_t *options)
6338 #ifdef _WIN32
6339 char *p;
6340 if (options->DataDirectory)
6341 return 0; /* all set */
6342 p = tor_malloc(MAX_PATH);
6343 strlcpy(p,get_windows_conf_root(),MAX_PATH);
6344 options->DataDirectory = p;
6345 return 0;
6346 #else
6347 const char *d = options->DataDirectory;
6348 if (!d)
6349 d = "~/.tor";
6351 if (strncmp(d,"~/",2) == 0) {
6352 char *fn = expand_filename(d);
6353 if (!fn) {
6354 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
6355 return -1;
6357 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
6358 /* If our homedir is /, we probably don't want to use it. */
6359 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
6360 * want. */
6361 log_warn(LD_CONFIG,
6362 "Default DataDirectory is \"~/.tor\". This expands to "
6363 "\"%s\", which is probably not what you want. Using "
6364 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
6365 tor_free(fn);
6366 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
6368 tor_free(options->DataDirectory);
6369 options->DataDirectory = fn;
6371 return 0;
6372 #endif
6375 /** Check and normalize the value of options->DataDirectory; return 0 if it
6376 * is sane, -1 otherwise. */
6377 static int
6378 validate_data_directory(or_options_t *options)
6380 if (normalize_data_directory(options) < 0)
6381 return -1;
6382 tor_assert(options->DataDirectory);
6383 if (strlen(options->DataDirectory) > (512-128)) {
6384 log_warn(LD_CONFIG, "DataDirectory is too long.");
6385 return -1;
6387 return 0;
6390 /** This string must remain the same forevermore. It is how we
6391 * recognize that the torrc file doesn't need to be backed up. */
6392 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
6393 "if you edit it, comments will not be preserved"
6394 /** This string can change; it tries to give the reader an idea
6395 * that editing this file by hand is not a good plan. */
6396 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
6397 "to torrc.orig.1 or similar, and Tor will ignore it"
6399 /** Save a configuration file for the configuration in <b>options</b>
6400 * into the file <b>fname</b>. If the file already exists, and
6401 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
6402 * replace it. Return 0 on success, -1 on failure. */
6403 static int
6404 write_configuration_file(const char *fname, const or_options_t *options)
6406 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
6407 int rename_old = 0, r;
6409 tor_assert(fname);
6411 switch (file_status(fname)) {
6412 case FN_FILE:
6413 old_val = read_file_to_str(fname, 0, NULL);
6414 if (!old_val || strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
6415 rename_old = 1;
6417 tor_free(old_val);
6418 break;
6419 case FN_NOENT:
6420 break;
6421 case FN_ERROR:
6422 case FN_DIR:
6423 default:
6424 log_warn(LD_CONFIG,
6425 "Config file \"%s\" is not a file? Failing.", fname);
6426 return -1;
6429 if (!(new_conf = options_dump(options, 1))) {
6430 log_warn(LD_BUG, "Couldn't get configuration string");
6431 goto err;
6434 tor_asprintf(&new_val, "%s\n%s\n\n%s",
6435 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
6437 if (rename_old) {
6438 int i = 1;
6439 char *fn_tmp = NULL;
6440 while (1) {
6441 tor_asprintf(&fn_tmp, "%s.orig.%d", fname, i);
6442 if (file_status(fn_tmp) == FN_NOENT)
6443 break;
6444 tor_free(fn_tmp);
6445 ++i;
6447 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
6448 if (rename(fname, fn_tmp) < 0) {
6449 log_warn(LD_FS,
6450 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
6451 fname, fn_tmp, strerror(errno));
6452 tor_free(fn_tmp);
6453 goto err;
6455 tor_free(fn_tmp);
6458 if (write_str_to_file(fname, new_val, 0) < 0)
6459 goto err;
6461 r = 0;
6462 goto done;
6463 err:
6464 r = -1;
6465 done:
6466 tor_free(new_val);
6467 tor_free(new_conf);
6468 return r;
6472 * Save the current configuration file value to disk. Return 0 on
6473 * success, -1 on failure.
6476 options_save_current(void)
6478 /* This fails if we can't write to our configuration file.
6480 * If we try falling back to datadirectory or something, we have a better
6481 * chance of saving the configuration, but a better chance of doing
6482 * something the user never expected. */
6483 return write_configuration_file(get_torrc_fname(0), get_options());
6486 /** Mapping from a unit name to a multiplier for converting that unit into a
6487 * base unit. Used by config_parse_unit. */
6488 struct unit_table_t {
6489 const char *unit; /**< The name of the unit */
6490 uint64_t multiplier; /**< How many of the base unit appear in this unit */
6493 /** Table to map the names of memory units to the number of bytes they
6494 * contain. */
6495 static struct unit_table_t memory_units[] = {
6496 { "", 1 },
6497 { "b", 1<< 0 },
6498 { "byte", 1<< 0 },
6499 { "bytes", 1<< 0 },
6500 { "kb", 1<<10 },
6501 { "kbyte", 1<<10 },
6502 { "kbytes", 1<<10 },
6503 { "kilobyte", 1<<10 },
6504 { "kilobytes", 1<<10 },
6505 { "m", 1<<20 },
6506 { "mb", 1<<20 },
6507 { "mbyte", 1<<20 },
6508 { "mbytes", 1<<20 },
6509 { "megabyte", 1<<20 },
6510 { "megabytes", 1<<20 },
6511 { "gb", 1<<30 },
6512 { "gbyte", 1<<30 },
6513 { "gbytes", 1<<30 },
6514 { "gigabyte", 1<<30 },
6515 { "gigabytes", 1<<30 },
6516 { "tb", U64_LITERAL(1)<<40 },
6517 { "terabyte", U64_LITERAL(1)<<40 },
6518 { "terabytes", U64_LITERAL(1)<<40 },
6519 { NULL, 0 },
6522 /** Table to map the names of time units to the number of seconds they
6523 * contain. */
6524 static struct unit_table_t time_units[] = {
6525 { "", 1 },
6526 { "second", 1 },
6527 { "seconds", 1 },
6528 { "minute", 60 },
6529 { "minutes", 60 },
6530 { "hour", 60*60 },
6531 { "hours", 60*60 },
6532 { "day", 24*60*60 },
6533 { "days", 24*60*60 },
6534 { "week", 7*24*60*60 },
6535 { "weeks", 7*24*60*60 },
6536 { NULL, 0 },
6539 /** Table to map the names of time units to the number of milliseconds
6540 * they contain. */
6541 static struct unit_table_t time_msec_units[] = {
6542 { "", 1 },
6543 { "msec", 1 },
6544 { "millisecond", 1 },
6545 { "milliseconds", 1 },
6546 { "second", 1000 },
6547 { "seconds", 1000 },
6548 { "minute", 60*1000 },
6549 { "minutes", 60*1000 },
6550 { "hour", 60*60*1000 },
6551 { "hours", 60*60*1000 },
6552 { "day", 24*60*60*1000 },
6553 { "days", 24*60*60*1000 },
6554 { "week", 7*24*60*60*1000 },
6555 { "weeks", 7*24*60*60*1000 },
6556 { NULL, 0 },
6559 /** Parse a string <b>val</b> containing a number, zero or more
6560 * spaces, and an optional unit string. If the unit appears in the
6561 * table <b>u</b>, then multiply the number by the unit multiplier.
6562 * On success, set *<b>ok</b> to 1 and return this product.
6563 * Otherwise, set *<b>ok</b> to 0.
6565 static uint64_t
6566 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
6568 uint64_t v = 0;
6569 double d = 0;
6570 int use_float = 0;
6571 char *cp;
6573 tor_assert(ok);
6575 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
6576 if (!*ok || (cp && *cp == '.')) {
6577 d = tor_parse_double(val, 0, UINT64_MAX, ok, &cp);
6578 if (!*ok)
6579 goto done;
6580 use_float = 1;
6583 if (!cp) {
6584 *ok = 1;
6585 v = use_float ? DBL_TO_U64(d) : v;
6586 goto done;
6589 cp = (char*) eat_whitespace(cp);
6591 for ( ;u->unit;++u) {
6592 if (!strcasecmp(u->unit, cp)) {
6593 if (use_float)
6594 v = u->multiplier * d;
6595 else
6596 v *= u->multiplier;
6597 *ok = 1;
6598 goto done;
6601 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
6602 *ok = 0;
6603 done:
6605 if (*ok)
6606 return v;
6607 else
6608 return 0;
6611 /** Parse a string in the format "number unit", where unit is a unit of
6612 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
6613 * and return the number of bytes specified. Otherwise, set
6614 * *<b>ok</b> to false and return 0. */
6615 static uint64_t
6616 config_parse_memunit(const char *s, int *ok)
6618 uint64_t u = config_parse_units(s, memory_units, ok);
6619 return u;
6622 /** Parse a string in the format "number unit", where unit is a unit of
6623 * time in milliseconds. On success, set *<b>ok</b> to true and return
6624 * the number of milliseconds in the provided interval. Otherwise, set
6625 * *<b>ok</b> to 0 and return -1. */
6626 static int
6627 config_parse_msec_interval(const char *s, int *ok)
6629 uint64_t r;
6630 r = config_parse_units(s, time_msec_units, ok);
6631 if (!ok)
6632 return -1;
6633 if (r > INT_MAX) {
6634 log_warn(LD_CONFIG, "Msec interval '%s' is too long", s);
6635 *ok = 0;
6636 return -1;
6638 return (int)r;
6641 /** Parse a string in the format "number unit", where unit is a unit of time.
6642 * On success, set *<b>ok</b> to true and return the number of seconds in
6643 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
6645 static int
6646 config_parse_interval(const char *s, int *ok)
6648 uint64_t r;
6649 r = config_parse_units(s, time_units, ok);
6650 if (!ok)
6651 return -1;
6652 if (r > INT_MAX) {
6653 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
6654 *ok = 0;
6655 return -1;
6657 return (int)r;
6660 /** Return the number of cpus configured in <b>options</b>. If we are
6661 * told to auto-detect the number of cpus, return the auto-detected number. */
6663 get_num_cpus(const or_options_t *options)
6665 if (options->NumCPUs == 0) {
6666 int n = compute_num_cpus();
6667 return (n >= 1) ? n : 1;
6668 } else {
6669 return options->NumCPUs;
6674 * Initialize the libevent library.
6676 static void
6677 init_libevent(const or_options_t *options)
6679 const char *badness=NULL;
6680 tor_libevent_cfg cfg;
6682 tor_assert(options);
6684 configure_libevent_logging();
6685 /* If the kernel complains that some method (say, epoll) doesn't
6686 * exist, we don't care about it, since libevent will cope.
6688 suppress_libevent_log_msg("Function not implemented");
6690 tor_check_libevent_header_compatibility();
6692 memset(&cfg, 0, sizeof(cfg));
6693 cfg.disable_iocp = options->DisableIOCP;
6694 cfg.num_cpus = get_num_cpus(options);
6695 cfg.msec_per_tick = options->TokenBucketRefillInterval;
6697 tor_libevent_initialize(&cfg);
6699 suppress_libevent_log_msg(NULL);
6701 tor_check_libevent_version(tor_libevent_get_method(),
6702 server_mode(get_options()),
6703 &badness);
6704 if (badness) {
6705 const char *v = tor_libevent_get_version_str();
6706 const char *m = tor_libevent_get_method();
6707 control_event_general_status(LOG_WARN,
6708 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
6709 v, m, badness);
6713 /** Return the persistent state struct for this Tor. */
6714 or_state_t *
6715 get_or_state(void)
6717 tor_assert(global_state);
6718 return global_state;
6721 /** Return a newly allocated string holding a filename relative to the data
6722 * directory. If <b>sub1</b> is present, it is the first path component after
6723 * the data directory. If <b>sub2</b> is also present, it is the second path
6724 * component after the data directory. If <b>suffix</b> is present, it
6725 * is appended to the filename.
6727 * Examples:
6728 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
6729 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
6730 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
6731 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
6733 * Note: Consider using the get_datadir_fname* macros in or.h.
6735 char *
6736 options_get_datadir_fname2_suffix(const or_options_t *options,
6737 const char *sub1, const char *sub2,
6738 const char *suffix)
6740 char *fname = NULL;
6741 size_t len;
6742 tor_assert(options);
6743 tor_assert(options->DataDirectory);
6744 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
6745 len = strlen(options->DataDirectory);
6746 if (sub1) {
6747 len += strlen(sub1)+1;
6748 if (sub2)
6749 len += strlen(sub2)+1;
6751 if (suffix)
6752 len += strlen(suffix);
6753 len++;
6754 fname = tor_malloc(len);
6755 if (sub1) {
6756 if (sub2) {
6757 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
6758 options->DataDirectory, sub1, sub2);
6759 } else {
6760 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
6761 options->DataDirectory, sub1);
6763 } else {
6764 strlcpy(fname, options->DataDirectory, len);
6766 if (suffix)
6767 strlcat(fname, suffix, len);
6768 return fname;
6771 /** Return true if <b>line</b> is a valid state TransportProxy line.
6772 * Return false otherwise. */
6773 static int
6774 state_transport_line_is_valid(const char *line)
6776 smartlist_t *items = NULL;
6777 char *addrport=NULL;
6778 tor_addr_t addr;
6779 uint16_t port = 0;
6780 int r;
6782 items = smartlist_new();
6783 smartlist_split_string(items, line, NULL,
6784 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6786 if (smartlist_len(items) != 2) {
6787 log_warn(LD_CONFIG, "state: Not enough arguments in TransportProxy line.");
6788 goto err;
6791 addrport = smartlist_get(items, 1);
6792 if (tor_addr_port_lookup(addrport, &addr, &port) < 0) {
6793 log_warn(LD_CONFIG, "state: Could not parse addrport.");
6794 goto err;
6797 if (!port) {
6798 log_warn(LD_CONFIG, "state: Transport line did not contain port.");
6799 goto err;
6802 r = 1;
6803 goto done;
6805 err:
6806 r = 0;
6808 done:
6809 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
6810 smartlist_free(items);
6811 return r;
6814 /** Return 0 if all TransportProxy lines in <b>state</b> are well
6815 * formed. Otherwise, return -1. */
6816 static int
6817 validate_transports_in_state(or_state_t *state)
6819 int broken = 0;
6820 config_line_t *line;
6822 for (line = state->TransportProxies ; line ; line = line->next) {
6823 tor_assert(!strcmp(line->key, "TransportProxy"));
6824 if (!state_transport_line_is_valid(line->value))
6825 broken = 1;
6828 if (broken)
6829 log_warn(LD_CONFIG, "state: State file seems to be broken.");
6831 return 0;
6834 /** Return 0 if every setting in <b>state</b> is reasonable, and a
6835 * permissible transition from <b>old_state</b>. Else warn and return -1.
6836 * Should have no side effects, except for normalizing the contents of
6837 * <b>state</b>.
6839 /* XXX from_setconf is here because of bug 238 */
6840 static int
6841 or_state_validate(or_state_t *old_state, or_state_t *state,
6842 int from_setconf, char **msg)
6844 /* We don't use these; only options do. Still, we need to match that
6845 * signature. */
6846 (void) from_setconf;
6847 (void) old_state;
6849 if (entry_guards_parse_state(state, 0, msg)<0)
6850 return -1;
6852 if (validate_transports_in_state(state)<0)
6853 return -1;
6855 return 0;
6858 /** Replace the current persistent state with <b>new_state</b> */
6859 static int
6860 or_state_set(or_state_t *new_state)
6862 char *err = NULL;
6863 int ret = 0;
6864 tor_assert(new_state);
6865 config_free(&state_format, global_state);
6866 global_state = new_state;
6867 if (entry_guards_parse_state(global_state, 1, &err)<0) {
6868 log_warn(LD_GENERAL,"%s",err);
6869 tor_free(err);
6870 ret = -1;
6872 if (rep_hist_load_state(global_state, &err)<0) {
6873 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
6874 tor_free(err);
6875 ret = -1;
6877 if (circuit_build_times_parse_state(&circ_times, global_state) < 0) {
6878 ret = -1;
6880 return ret;
6884 * Save a broken state file to a backup location.
6886 static void
6887 or_state_save_broken(char *fname)
6889 int i;
6890 file_status_t status;
6891 char *fname2 = NULL;
6892 for (i = 0; i < 100; ++i) {
6893 tor_asprintf(&fname2, "%s.%d", fname, i);
6894 status = file_status(fname2);
6895 if (status == FN_NOENT)
6896 break;
6897 tor_free(fname2);
6899 if (i == 100) {
6900 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
6901 "state files to move aside. Discarding the old state file.",
6902 fname);
6903 unlink(fname);
6904 } else {
6905 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
6906 "to \"%s\". This could be a bug in Tor; please tell "
6907 "the developers.", fname, fname2);
6908 if (rename(fname, fname2) < 0) {
6909 log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
6910 "OS gave an error of %s", strerror(errno));
6913 tor_free(fname2);
6916 /** Reload the persistent state from disk, generating a new state as needed.
6917 * Return 0 on success, less than 0 on failure.
6919 static int
6920 or_state_load(void)
6922 or_state_t *new_state = NULL;
6923 char *contents = NULL, *fname;
6924 char *errmsg = NULL;
6925 int r = -1, badstate = 0;
6927 fname = get_datadir_fname("state");
6928 switch (file_status(fname)) {
6929 case FN_FILE:
6930 if (!(contents = read_file_to_str(fname, 0, NULL))) {
6931 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
6932 goto done;
6934 break;
6935 case FN_NOENT:
6936 break;
6937 case FN_ERROR:
6938 case FN_DIR:
6939 default:
6940 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
6941 goto done;
6943 new_state = tor_malloc_zero(sizeof(or_state_t));
6944 new_state->_magic = OR_STATE_MAGIC;
6945 config_init(&state_format, new_state);
6946 if (contents) {
6947 config_line_t *lines=NULL;
6948 int assign_retval;
6949 if (config_get_lines(contents, &lines, 0)<0)
6950 goto done;
6951 assign_retval = config_assign(&state_format, new_state,
6952 lines, 0, 0, &errmsg);
6953 config_free_lines(lines);
6954 if (assign_retval<0)
6955 badstate = 1;
6956 if (errmsg) {
6957 log_warn(LD_GENERAL, "%s", errmsg);
6958 tor_free(errmsg);
6962 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
6963 badstate = 1;
6965 if (errmsg) {
6966 log_warn(LD_GENERAL, "%s", errmsg);
6967 tor_free(errmsg);
6970 if (badstate && !contents) {
6971 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
6972 " This is a bug in Tor.");
6973 goto done;
6974 } else if (badstate && contents) {
6975 or_state_save_broken(fname);
6977 tor_free(contents);
6978 config_free(&state_format, new_state);
6980 new_state = tor_malloc_zero(sizeof(or_state_t));
6981 new_state->_magic = OR_STATE_MAGIC;
6982 config_init(&state_format, new_state);
6983 } else if (contents) {
6984 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
6985 } else {
6986 log_info(LD_GENERAL, "Initialized state");
6988 if (or_state_set(new_state) == -1) {
6989 or_state_save_broken(fname);
6991 new_state = NULL;
6992 if (!contents) {
6993 global_state->next_write = 0;
6994 or_state_save(time(NULL));
6996 r = 0;
6998 done:
6999 tor_free(fname);
7000 tor_free(contents);
7001 if (new_state)
7002 config_free(&state_format, new_state);
7004 return r;
7007 /** Did the last time we tried to write the state file fail? If so, we
7008 * should consider disabling such features as preemptive circuit generation
7009 * to compute circuit-build-time. */
7010 static int last_state_file_write_failed = 0;
7012 /** Return whether the state file failed to write last time we tried. */
7014 did_last_state_file_write_fail(void)
7016 return last_state_file_write_failed;
7019 /** If writing the state to disk fails, try again after this many seconds. */
7020 #define STATE_WRITE_RETRY_INTERVAL 3600
7022 /** If we're a relay, how often should we checkpoint our state file even
7023 * if nothing else dirties it? This will checkpoint ongoing stats like
7024 * bandwidth used, per-country user stats, etc. */
7025 #define STATE_RELAY_CHECKPOINT_INTERVAL (12*60*60)
7027 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
7029 or_state_save(time_t now)
7031 char *state, *contents;
7032 char tbuf[ISO_TIME_LEN+1];
7033 char *fname;
7035 tor_assert(global_state);
7037 if (global_state->next_write > now)
7038 return 0;
7040 /* Call everything else that might dirty the state even more, in order
7041 * to avoid redundant writes. */
7042 entry_guards_update_state(global_state);
7043 rep_hist_update_state(global_state);
7044 circuit_build_times_update_state(&circ_times, global_state);
7045 if (accounting_is_enabled(get_options()))
7046 accounting_run_housekeeping(now);
7048 global_state->LastWritten = now;
7050 tor_free(global_state->TorVersion);
7051 tor_asprintf(&global_state->TorVersion, "Tor %s", get_version());
7053 state = config_dump(&state_format, NULL, global_state, 1, 0);
7054 format_local_iso_time(tbuf, now);
7055 tor_asprintf(&contents,
7056 "# Tor state file last generated on %s local time\n"
7057 "# Other times below are in GMT\n"
7058 "# You *do not* need to edit this file.\n\n%s",
7059 tbuf, state);
7060 tor_free(state);
7061 fname = get_datadir_fname("state");
7062 if (write_str_to_file(fname, contents, 0)<0) {
7063 log_warn(LD_FS, "Unable to write state to file \"%s\"; "
7064 "will try again later", fname);
7065 last_state_file_write_failed = 1;
7066 tor_free(fname);
7067 tor_free(contents);
7068 /* Try again after STATE_WRITE_RETRY_INTERVAL (or sooner, if the state
7069 * changes sooner). */
7070 global_state->next_write = now + STATE_WRITE_RETRY_INTERVAL;
7071 return -1;
7074 last_state_file_write_failed = 0;
7075 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
7076 tor_free(fname);
7077 tor_free(contents);
7079 if (server_mode(get_options()))
7080 global_state->next_write = now + STATE_RELAY_CHECKPOINT_INTERVAL;
7081 else
7082 global_state->next_write = TIME_MAX;
7084 return 0;
7087 /** Return the config line for transport <b>transport</b> in the current state.
7088 * Return NULL if there is no config line for <b>transport</b>. */
7089 static config_line_t *
7090 get_transport_in_state_by_name(const char *transport)
7092 or_state_t *or_state = get_or_state();
7093 config_line_t *line;
7094 config_line_t *ret = NULL;
7095 smartlist_t *items = NULL;
7097 for (line = or_state->TransportProxies ; line ; line = line->next) {
7098 tor_assert(!strcmp(line->key, "TransportProxy"));
7100 items = smartlist_new();
7101 smartlist_split_string(items, line->value, NULL,
7102 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
7103 if (smartlist_len(items) != 2) /* broken state */
7104 goto done;
7106 if (!strcmp(smartlist_get(items, 0), transport)) {
7107 ret = line;
7108 goto done;
7111 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
7112 smartlist_free(items);
7113 items = NULL;
7116 done:
7117 if (items) {
7118 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
7119 smartlist_free(items);
7121 return ret;
7124 /** Return string containing the address:port part of the
7125 * TransportProxy <b>line</b> for transport <b>transport</b>.
7126 * If the line is corrupted, return NULL. */
7127 static const char *
7128 get_transport_bindaddr(const char *line, const char *transport)
7130 char *line_tmp = NULL;
7132 if (strlen(line) < strlen(transport) + 2) {
7133 goto broken_state;
7134 } else {
7135 /* line should start with the name of the transport and a space.
7136 (for example, "obfs2 127.0.0.1:47245") */
7137 tor_asprintf(&line_tmp, "%s ", transport);
7138 if (strcmpstart(line, line_tmp))
7139 goto broken_state;
7141 tor_free(line_tmp);
7142 return (line+strlen(transport)+1);
7145 broken_state:
7146 tor_free(line_tmp);
7147 return NULL;
7150 /** Return a string containing the address:port that a proxy transport
7151 * should bind on. The string is stored on the heap and must be freed
7152 * by the caller of this function. */
7153 char *
7154 get_stored_bindaddr_for_server_transport(const char *transport)
7156 char *default_addrport = NULL;
7157 const char *stored_bindaddr = NULL;
7159 config_line_t *line = get_transport_in_state_by_name(transport);
7160 if (!line) /* Found no references in state for this transport. */
7161 goto no_bindaddr_found;
7163 stored_bindaddr = get_transport_bindaddr(line->value, transport);
7164 if (stored_bindaddr) /* found stored bindaddr in state file. */
7165 return tor_strdup(stored_bindaddr);
7167 no_bindaddr_found:
7168 /** If we didn't find references for this pluggable transport in the
7169 state file, we should instruct the pluggable transport proxy to
7170 listen on INADDR_ANY on a random ephemeral port. */
7171 tor_asprintf(&default_addrport, "%s:%s", fmt_addr32(INADDR_ANY), "0");
7172 return default_addrport;
7175 /** Save <b>transport</b> listening on <b>addr</b>:<b>port</b> to
7176 state */
7177 void
7178 save_transport_to_state(const char *transport,
7179 const tor_addr_t *addr, uint16_t port)
7181 or_state_t *state = get_or_state();
7183 char *transport_addrport=NULL;
7185 /** find where to write on the state */
7186 config_line_t **next, *line;
7188 /* see if this transport is already stored in state */
7189 config_line_t *transport_line =
7190 get_transport_in_state_by_name(transport);
7192 if (transport_line) { /* if transport already exists in state... */
7193 const char *prev_bindaddr = /* get its addrport... */
7194 get_transport_bindaddr(transport_line->value, transport);
7195 tor_asprintf(&transport_addrport, "%s:%d", fmt_addr(addr), (int)port);
7197 /* if transport in state has the same address as this one, life is good */
7198 if (!strcmp(prev_bindaddr, transport_addrport)) {
7199 log_info(LD_CONFIG, "Transport seems to have spawned on its usual "
7200 "address:port.");
7201 goto done;
7202 } else { /* if addrport in state is different than the one we got */
7203 log_info(LD_CONFIG, "Transport seems to have spawned on different "
7204 "address:port. Let's update the state file with the new "
7205 "address:port");
7206 tor_free(transport_line->value); /* free the old line */
7207 tor_asprintf(&transport_line->value, "%s %s:%d", transport,
7208 fmt_addr(addr),
7209 (int) port); /* replace old addrport line with new line */
7211 } else { /* never seen this one before; save it in state for next time */
7212 log_info(LD_CONFIG, "It's the first time we see this transport. "
7213 "Let's save its address:port");
7214 next = &state->TransportProxies;
7215 /* find the last TransportProxy line in the state and point 'next'
7216 right after it */
7217 line = state->TransportProxies;
7218 while (line) {
7219 next = &(line->next);
7220 line = line->next;
7223 /* allocate space for the new line and fill it in */
7224 *next = line = tor_malloc_zero(sizeof(config_line_t));
7225 line->key = tor_strdup("TransportProxy");
7226 tor_asprintf(&line->value, "%s %s:%d", transport,
7227 fmt_addr(addr), (int) port);
7229 next = &(line->next);
7232 if (!get_options()->AvoidDiskWrites)
7233 or_state_mark_dirty(state, 0);
7235 done:
7236 tor_free(transport_addrport);
7239 /** Given a file name check to see whether the file exists but has not been
7240 * modified for a very long time. If so, remove it. */
7241 void
7242 remove_file_if_very_old(const char *fname, time_t now)
7244 #define VERY_OLD_FILE_AGE (28*24*60*60)
7245 struct stat st;
7247 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
7248 char buf[ISO_TIME_LEN+1];
7249 format_local_iso_time(buf, st.st_mtime);
7250 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
7251 "Removing it.", fname, buf);
7252 unlink(fname);
7256 /** Helper to implement GETINFO functions about configuration variables (not
7257 * their values). Given a "config/names" question, set *<b>answer</b> to a
7258 * new string describing the supported configuration variables and their
7259 * types. */
7261 getinfo_helper_config(control_connection_t *conn,
7262 const char *question, char **answer,
7263 const char **errmsg)
7265 (void) conn;
7266 (void) errmsg;
7267 if (!strcmp(question, "config/names")) {
7268 smartlist_t *sl = smartlist_new();
7269 int i;
7270 for (i = 0; _option_vars[i].name; ++i) {
7271 const config_var_t *var = &_option_vars[i];
7272 const char *type;
7273 switch (var->type) {
7274 case CONFIG_TYPE_STRING: type = "String"; break;
7275 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
7276 case CONFIG_TYPE_UINT: type = "Integer"; break;
7277 case CONFIG_TYPE_INT: type = "SignedInteger"; break;
7278 case CONFIG_TYPE_PORT: type = "Port"; break;
7279 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
7280 case CONFIG_TYPE_MSEC_INTERVAL: type = "TimeMsecInterval"; break;
7281 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
7282 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
7283 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
7284 case CONFIG_TYPE_AUTOBOOL: type = "Boolean+Auto"; break;
7285 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
7286 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
7287 case CONFIG_TYPE_CSV: type = "CommaList"; break;
7288 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
7289 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
7290 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
7291 default:
7292 case CONFIG_TYPE_OBSOLETE:
7293 type = NULL; break;
7295 if (!type)
7296 continue;
7297 smartlist_add_asprintf(sl, "%s %s\n",var->name,type);
7299 *answer = smartlist_join_strings(sl, "", 0, NULL);
7300 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
7301 smartlist_free(sl);
7303 return 0;