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-2011, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
9 * \brief Code to parse and interpret configuration files.
12 #define CONFIG_PRIVATE
15 #include "circuitbuild.h"
16 #include "circuitlist.h"
18 #include "connection.h"
19 #include "connection_edge.h"
20 #include "connection_or.h"
22 #include "cpuworker.h"
27 #include "hibernate.h"
29 #include "networkstatus.h"
32 #include "rendclient.h"
33 #include "rendservice.h"
36 #include "routerlist.h"
41 /** Enumeration of types which option values can take */
42 typedef enum config_type_t
{
43 CONFIG_TYPE_STRING
= 0, /**< An arbitrary string. */
44 CONFIG_TYPE_FILENAME
, /**< A filename: some prefixes get expanded. */
45 CONFIG_TYPE_UINT
, /**< A non-negative integer less than MAX_INT */
46 CONFIG_TYPE_INTERVAL
, /**< A number of seconds, with optional units*/
47 CONFIG_TYPE_MEMUNIT
, /**< A number of bytes, with optional units*/
48 CONFIG_TYPE_DOUBLE
, /**< A floating-point value */
49 CONFIG_TYPE_BOOL
, /**< A boolean value, expressed as 0 or 1. */
50 CONFIG_TYPE_ISOTIME
, /**< An ISO-formatted time relative to GMT. */
51 CONFIG_TYPE_CSV
, /**< A list of strings, separated by commas and
52 * optional whitespace. */
53 CONFIG_TYPE_LINELIST
, /**< Uninterpreted config lines */
54 CONFIG_TYPE_LINELIST_S
, /**< Uninterpreted, context-sensitive config lines,
55 * mixed with other keywords. */
56 CONFIG_TYPE_LINELIST_V
, /**< Catch-all "virtual" option to summarize
57 * context-sensitive config lines when fetching.
59 CONFIG_TYPE_ROUTERSET
, /**< A list of router names, addrs, and fps,
60 * parsed into a routerset_t. */
61 CONFIG_TYPE_OBSOLETE
, /**< Obsolete (ignored) option. */
64 /** An abbreviation for a configuration option allowed on the command line. */
65 typedef struct config_abbrev_t
{
66 const char *abbreviated
;
72 /* Handy macro for declaring "In the config file or on the command line,
73 * you can abbreviate <b>tok</b>s as <b>tok</b>". */
74 #define PLURAL(tok) { #tok, #tok "s", 0, 0 }
76 /** A list of abbreviations and aliases to map command-line options, obsolete
77 * option names, or alternative option names, to their current values. */
78 static config_abbrev_t _option_abbrevs
[] = {
83 PLURAL(LongLivedPort
),
84 PLURAL(HiddenServiceNode
),
85 PLURAL(HiddenServiceExcludeNode
),
88 PLURAL(RendExcludeNode
),
89 PLURAL(StrictEntryNode
),
90 PLURAL(StrictExitNode
),
93 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
94 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
95 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
96 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
97 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
98 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
99 { "MaxConn", "ConnLimit", 0, 1},
100 { "ORBindAddress", "ORListenAddress", 0, 0},
101 { "DirBindAddress", "DirListenAddress", 0, 0},
102 { "SocksBindAddress", "SocksListenAddress", 0, 0},
103 { "UseHelperNodes", "UseEntryGuards", 0, 0},
104 { "NumHelperNodes", "NumEntryGuards", 0, 0},
105 { "UseEntryNodes", "UseEntryGuards", 0, 0},
106 { "NumEntryNodes", "NumEntryGuards", 0, 0},
107 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
108 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
109 { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0},
110 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
111 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
112 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
113 { "StrictEntryNodes", "StrictNodes", 0, 1},
114 { "StrictExitNodes", "StrictNodes", 0, 1},
118 /** A list of state-file "abbreviations," for compatibility. */
119 static config_abbrev_t _state_abbrevs
[] = {
120 { "AccountingBytesReadInterval", "AccountingBytesReadInInterval", 0, 0 },
121 { "HelperNode", "EntryGuard", 0, 0 },
122 { "HelperNodeDownSince", "EntryGuardDownSince", 0, 0 },
123 { "HelperNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
124 { "EntryNode", "EntryGuard", 0, 0 },
125 { "EntryNodeDownSince", "EntryGuardDownSince", 0, 0 },
126 { "EntryNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
131 /** A variable allowed in the configuration file or on the command line. */
132 typedef struct config_var_t
{
133 const char *name
; /**< The full keyword (case insensitive). */
134 config_type_t type
; /**< How to interpret the type and turn it into a
136 off_t var_offset
; /**< Offset of the corresponding member of or_options_t. */
137 const char *initvalue
; /**< String (or null) describing initial value. */
140 /** An entry for config_vars: "The option <b>name</b> has type
141 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
142 * or_options_t.<b>member</b>"
144 #define VAR(name,conftype,member,initvalue) \
145 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
147 /** As VAR, but the option name and member name are the same. */
148 #define V(member,conftype,initvalue) \
149 VAR(#member, conftype, member, initvalue)
150 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
151 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
153 /** Array of configuration options. Until we disallow nonstandard
154 * abbreviations, order is significant, since the first matching option will
157 static config_var_t _option_vars
[] = {
158 OBSOLETE("AccountingMaxKB"),
159 V(AccountingMax
, MEMUNIT
, "0 bytes"),
160 V(AccountingStart
, STRING
, NULL
),
161 V(Address
, STRING
, NULL
),
162 V(AllowDotExit
, BOOL
, "0"),
163 V(AllowInvalidNodes
, CSV
, "middle,rendezvous"),
164 V(AllowNonRFC953Hostnames
, BOOL
, "0"),
165 V(AllowSingleHopCircuits
, BOOL
, "0"),
166 V(AllowSingleHopExits
, BOOL
, "0"),
167 V(AlternateBridgeAuthority
, LINELIST
, NULL
),
168 V(AlternateDirAuthority
, LINELIST
, NULL
),
169 V(AlternateHSAuthority
, LINELIST
, NULL
),
170 V(AssumeReachable
, BOOL
, "0"),
171 V(AuthDirBadDir
, LINELIST
, NULL
),
172 V(AuthDirBadExit
, LINELIST
, NULL
),
173 V(AuthDirInvalid
, LINELIST
, NULL
),
174 V(AuthDirReject
, LINELIST
, NULL
),
175 V(AuthDirRejectUnlisted
, BOOL
, "0"),
176 V(AuthDirListBadDirs
, BOOL
, "0"),
177 V(AuthDirListBadExits
, BOOL
, "0"),
178 V(AuthDirMaxServersPerAddr
, UINT
, "2"),
179 V(AuthDirMaxServersPerAuthAddr
,UINT
, "5"),
180 VAR("AuthoritativeDirectory", BOOL
, AuthoritativeDir
, "0"),
181 V(AutomapHostsOnResolve
, BOOL
, "0"),
182 V(AutomapHostsSuffixes
, CSV
, ".onion,.exit"),
183 V(AvoidDiskWrites
, BOOL
, "0"),
184 V(BandwidthBurst
, MEMUNIT
, "10 MB"),
185 V(BandwidthRate
, MEMUNIT
, "5 MB"),
186 V(BridgeAuthoritativeDir
, BOOL
, "0"),
187 VAR("Bridge", LINELIST
, Bridges
, NULL
),
188 V(BridgePassword
, STRING
, NULL
),
189 V(BridgeRecordUsageByCountry
, BOOL
, "1"),
190 V(BridgeRelay
, BOOL
, "0"),
191 V(CellStatistics
, BOOL
, "0"),
192 V(LearnCircuitBuildTimeout
, BOOL
, "1"),
193 V(CircuitBuildTimeout
, INTERVAL
, "0"),
194 V(CircuitIdleTimeout
, INTERVAL
, "1 hour"),
195 V(CircuitStreamTimeout
, INTERVAL
, "0"),
196 V(CircuitPriorityHalflife
, DOUBLE
, "-100.0"), /*negative:'Use default'*/
197 V(ClientDNSRejectInternalAddresses
, BOOL
,"1"),
198 V(ClientRejectInternalAddresses
, BOOL
, "1"),
199 V(ClientOnly
, BOOL
, "0"),
200 V(ConsensusParams
, STRING
, NULL
),
201 V(ConnLimit
, UINT
, "1000"),
202 V(ConstrainedSockets
, BOOL
, "0"),
203 V(ConstrainedSockSize
, MEMUNIT
, "8192"),
204 V(ContactInfo
, STRING
, NULL
),
205 V(ControlListenAddress
, LINELIST
, NULL
),
206 V(ControlPort
, UINT
, "0"),
207 V(ControlSocket
, LINELIST
, NULL
),
208 V(CookieAuthentication
, BOOL
, "0"),
209 V(CookieAuthFileGroupReadable
, BOOL
, "0"),
210 V(CookieAuthFile
, STRING
, NULL
),
211 V(DataDirectory
, FILENAME
, NULL
),
212 OBSOLETE("DebugLogFile"),
213 V(DirAllowPrivateAddresses
, BOOL
, NULL
),
214 V(TestingAuthDirTimeToLearnReachability
, INTERVAL
, "30 minutes"),
215 V(DirListenAddress
, LINELIST
, NULL
),
216 OBSOLETE("DirFetchPeriod"),
217 V(DirPolicy
, LINELIST
, NULL
),
218 V(DirPort
, UINT
, "0"),
219 V(DirPortFrontPage
, FILENAME
, NULL
),
220 OBSOLETE("DirPostPeriod"),
221 OBSOLETE("DirRecordUsageByCountry"),
222 OBSOLETE("DirRecordUsageGranularity"),
223 OBSOLETE("DirRecordUsageRetainIPs"),
224 OBSOLETE("DirRecordUsageSaveInterval"),
225 V(DirReqStatistics
, BOOL
, "0"),
226 VAR("DirServer", LINELIST
, DirServers
, NULL
),
227 V(DisableAllSwap
, BOOL
, "0"),
228 V(DNSPort
, UINT
, "0"),
229 V(DNSListenAddress
, LINELIST
, NULL
),
230 V(DownloadExtraInfo
, BOOL
, "0"),
231 V(EnforceDistinctSubnets
, BOOL
, "1"),
232 V(EntryNodes
, ROUTERSET
, NULL
),
233 V(EntryStatistics
, BOOL
, "0"),
234 V(TestingEstimatedDescriptorPropagationTime
, INTERVAL
, "10 minutes"),
235 V(ExcludeNodes
, ROUTERSET
, NULL
),
236 V(ExcludeExitNodes
, ROUTERSET
, NULL
),
237 V(ExcludeSingleHopRelays
, BOOL
, "1"),
238 V(ExitNodes
, ROUTERSET
, NULL
),
239 V(ExitPolicy
, LINELIST
, NULL
),
240 V(ExitPolicyRejectPrivate
, BOOL
, "1"),
241 V(ExitPortStatistics
, BOOL
, "0"),
242 V(ExtraInfoStatistics
, BOOL
, "0"),
245 V(FallbackNetworkstatusFile
, FILENAME
, "fallback-consensus"),
247 V(FallbackNetworkstatusFile
, FILENAME
,
248 SHARE_DATADIR PATH_SEPARATOR
"tor" PATH_SEPARATOR
"fallback-consensus"),
250 V(FascistFirewall
, BOOL
, "0"),
251 V(FirewallPorts
, CSV
, ""),
252 V(FastFirstHopPK
, BOOL
, "1"),
253 V(FetchDirInfoEarly
, BOOL
, "0"),
254 V(FetchDirInfoExtraEarly
, BOOL
, "0"),
255 V(FetchServerDescriptors
, BOOL
, "1"),
256 V(FetchHidServDescriptors
, BOOL
, "1"),
257 V(FetchUselessDescriptors
, BOOL
, "0"),
259 V(GeoIPFile
, FILENAME
, "<default>"),
261 V(GeoIPFile
, FILENAME
,
262 SHARE_DATADIR PATH_SEPARATOR
"tor" PATH_SEPARATOR
"geoip"),
265 V(HardwareAccel
, BOOL
, "0"),
266 V(AccelName
, STRING
, NULL
),
267 V(AccelDir
, FILENAME
, NULL
),
268 V(HashedControlPassword
, LINELIST
, NULL
),
269 V(HidServDirectoryV2
, BOOL
, "1"),
270 VAR("HiddenServiceDir", LINELIST_S
, RendConfigLines
, NULL
),
271 OBSOLETE("HiddenServiceExcludeNodes"),
272 OBSOLETE("HiddenServiceNodes"),
273 VAR("HiddenServiceOptions",LINELIST_V
, RendConfigLines
, NULL
),
274 VAR("HiddenServicePort", LINELIST_S
, RendConfigLines
, NULL
),
275 VAR("HiddenServiceVersion",LINELIST_S
, RendConfigLines
, NULL
),
276 VAR("HiddenServiceAuthorizeClient",LINELIST_S
,RendConfigLines
, NULL
),
277 V(HidServAuth
, LINELIST
, NULL
),
278 V(HSAuthoritativeDir
, BOOL
, "0"),
279 OBSOLETE("HSAuthorityRecordStats"),
280 V(HTTPProxy
, STRING
, NULL
),
281 V(HTTPProxyAuthenticator
, STRING
, NULL
),
282 V(HTTPSProxy
, STRING
, NULL
),
283 V(HTTPSProxyAuthenticator
, STRING
, NULL
),
284 V(Socks4Proxy
, STRING
, NULL
),
285 V(Socks5Proxy
, STRING
, NULL
),
286 V(Socks5ProxyUsername
, STRING
, NULL
),
287 V(Socks5ProxyPassword
, STRING
, NULL
),
288 OBSOLETE("IgnoreVersion"),
289 V(KeepalivePeriod
, INTERVAL
, "5 minutes"),
290 VAR("Log", LINELIST
, Logs
, NULL
),
291 V(LogMessageDomains
, BOOL
, "0"),
292 OBSOLETE("LinkPadding"),
293 OBSOLETE("LogLevel"),
295 V(LongLivedPorts
, CSV
,
296 "21,22,706,1863,5050,5190,5222,5223,6667,6697,8300"),
297 VAR("MapAddress", LINELIST
, AddressMap
, NULL
),
298 V(MaxAdvertisedBandwidth
, MEMUNIT
, "1 GB"),
299 V(MaxCircuitDirtiness
, INTERVAL
, "10 minutes"),
300 V(MaxOnionsPending
, UINT
, "100"),
301 OBSOLETE("MonthlyAccountingStart"),
302 V(MyFamily
, STRING
, NULL
),
303 V(NewCircuitPeriod
, INTERVAL
, "30 seconds"),
304 VAR("NamingAuthoritativeDirectory",BOOL
, NamingAuthoritativeDir
, "0"),
305 V(NATDListenAddress
, LINELIST
, NULL
),
306 V(NATDPort
, UINT
, "0"),
307 V(Nickname
, STRING
, NULL
),
308 V(WarnUnsafeSocks
, BOOL
, "1"),
309 OBSOLETE("NoPublish"),
310 VAR("NodeFamily", LINELIST
, NodeFamilies
, NULL
),
311 V(NumCPUs
, UINT
, "1"),
312 V(NumEntryGuards
, UINT
, "3"),
313 V(ORListenAddress
, LINELIST
, NULL
),
314 V(ORPort
, UINT
, "0"),
315 V(OutboundBindAddress
, STRING
, NULL
),
316 OBSOLETE("PathlenCoinWeight"),
317 V(PerConnBWBurst
, MEMUNIT
, "0"),
318 V(PerConnBWRate
, MEMUNIT
, "0"),
319 V(PidFile
, STRING
, NULL
),
320 V(TestingTorNetwork
, BOOL
, "0"),
321 V(PreferTunneledDirConns
, BOOL
, "1"),
322 V(ProtocolWarnings
, BOOL
, "0"),
323 V(PublishServerDescriptor
, CSV
, "1"),
324 V(PublishHidServDescriptors
, BOOL
, "1"),
325 V(ReachableAddresses
, LINELIST
, NULL
),
326 V(ReachableDirAddresses
, LINELIST
, NULL
),
327 V(ReachableORAddresses
, LINELIST
, NULL
),
328 V(RecommendedVersions
, LINELIST
, NULL
),
329 V(RecommendedClientVersions
, LINELIST
, NULL
),
330 V(RecommendedServerVersions
, LINELIST
, NULL
),
331 OBSOLETE("RedirectExit"),
332 V(RefuseUnknownExits
, STRING
, "auto"),
333 V(RejectPlaintextPorts
, CSV
, ""),
334 V(RelayBandwidthBurst
, MEMUNIT
, "0"),
335 V(RelayBandwidthRate
, MEMUNIT
, "0"),
336 OBSOLETE("RendExcludeNodes"),
337 OBSOLETE("RendNodes"),
338 V(RendPostPeriod
, INTERVAL
, "1 hour"),
339 V(RephistTrackTime
, INTERVAL
, "24 hours"),
340 OBSOLETE("RouterFile"),
341 V(RunAsDaemon
, BOOL
, "0"),
342 // V(RunTesting, BOOL, "0"),
343 OBSOLETE("RunTesting"), // currently unused
344 V(SafeLogging
, STRING
, "1"),
345 V(SafeSocks
, BOOL
, "0"),
346 V(ServerDNSAllowBrokenConfig
, BOOL
, "1"),
347 V(ServerDNSAllowNonRFC953Hostnames
, BOOL
,"0"),
348 V(ServerDNSDetectHijacking
, BOOL
, "1"),
349 V(ServerDNSRandomizeCase
, BOOL
, "1"),
350 V(ServerDNSResolvConfFile
, STRING
, NULL
),
351 V(ServerDNSSearchDomains
, BOOL
, "0"),
352 V(ServerDNSTestAddresses
, CSV
,
353 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
354 V(ShutdownWaitLength
, INTERVAL
, "30 seconds"),
355 V(SocksListenAddress
, LINELIST
, NULL
),
356 V(SocksPolicy
, LINELIST
, NULL
),
357 V(SocksPort
, UINT
, "9050"),
358 V(SocksTimeout
, INTERVAL
, "2 minutes"),
359 OBSOLETE("StatusFetchPeriod"),
360 V(StrictNodes
, BOOL
, "0"),
362 V(TestSocks
, BOOL
, "0"),
364 V(TrackHostExits
, CSV
, NULL
),
365 V(TrackHostExitsExpire
, INTERVAL
, "30 minutes"),
366 OBSOLETE("TrafficShaping"),
367 V(TransListenAddress
, LINELIST
, NULL
),
368 V(TransPort
, UINT
, "0"),
369 V(TunnelDirConns
, BOOL
, "1"),
370 V(UpdateBridgesFromAuthority
, BOOL
, "0"),
371 V(UseBridges
, BOOL
, "0"),
372 V(UseEntryGuards
, BOOL
, "1"),
373 V(User
, STRING
, NULL
),
374 VAR("V1AuthoritativeDirectory",BOOL
, V1AuthoritativeDir
, "0"),
375 VAR("V2AuthoritativeDirectory",BOOL
, V2AuthoritativeDir
, "0"),
376 VAR("V3AuthoritativeDirectory",BOOL
, V3AuthoritativeDir
, "0"),
377 V(TestingV3AuthInitialVotingInterval
, INTERVAL
, "30 minutes"),
378 V(TestingV3AuthInitialVoteDelay
, INTERVAL
, "5 minutes"),
379 V(TestingV3AuthInitialDistDelay
, INTERVAL
, "5 minutes"),
380 V(V3AuthVotingInterval
, INTERVAL
, "1 hour"),
381 V(V3AuthVoteDelay
, INTERVAL
, "5 minutes"),
382 V(V3AuthDistDelay
, INTERVAL
, "5 minutes"),
383 V(V3AuthNIntervalsValid
, UINT
, "3"),
384 V(V3AuthUseLegacyKey
, BOOL
, "0"),
385 V(V3BandwidthsFile
, FILENAME
, NULL
),
386 VAR("VersioningAuthoritativeDirectory",BOOL
,VersioningAuthoritativeDir
, "0"),
387 V(VirtualAddrNetwork
, STRING
, "127.192.0.0/10"),
388 V(WarnPlaintextPorts
, CSV
, "23,109,110,143"),
389 VAR("__ReloadTorrcOnSIGHUP", BOOL
, ReloadTorrcOnSIGHUP
, "1"),
390 VAR("__AllDirActionsPrivate", BOOL
, AllDirActionsPrivate
, "0"),
391 VAR("__DisablePredictedCircuits",BOOL
,DisablePredictedCircuits
, "0"),
392 VAR("__LeaveStreamsUnattached",BOOL
, LeaveStreamsUnattached
, "0"),
393 VAR("__HashedControlSessionPassword", LINELIST
, HashedControlSessionPassword
,
395 V(MinUptimeHidServDirectoryV2
, INTERVAL
, "24 hours"),
397 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
400 /** Override default values with these if the user sets the TestingTorNetwork
402 static config_var_t testing_tor_network_defaults
[] = {
403 V(ServerDNSAllowBrokenConfig
, BOOL
, "1"),
404 V(DirAllowPrivateAddresses
, BOOL
, "1"),
405 V(EnforceDistinctSubnets
, BOOL
, "0"),
406 V(AssumeReachable
, BOOL
, "1"),
407 V(AuthDirMaxServersPerAddr
, UINT
, "0"),
408 V(AuthDirMaxServersPerAuthAddr
,UINT
, "0"),
409 V(ClientDNSRejectInternalAddresses
, BOOL
,"0"),
410 V(ClientRejectInternalAddresses
, BOOL
, "0"),
411 V(ExitPolicyRejectPrivate
, BOOL
, "0"),
412 V(V3AuthVotingInterval
, INTERVAL
, "5 minutes"),
413 V(V3AuthVoteDelay
, INTERVAL
, "20 seconds"),
414 V(V3AuthDistDelay
, INTERVAL
, "20 seconds"),
415 V(TestingV3AuthInitialVotingInterval
, INTERVAL
, "5 minutes"),
416 V(TestingV3AuthInitialVoteDelay
, INTERVAL
, "20 seconds"),
417 V(TestingV3AuthInitialDistDelay
, INTERVAL
, "20 seconds"),
418 V(TestingAuthDirTimeToLearnReachability
, INTERVAL
, "0 minutes"),
419 V(TestingEstimatedDescriptorPropagationTime
, INTERVAL
, "0 minutes"),
420 V(MinUptimeHidServDirectoryV2
, INTERVAL
, "0 minutes"),
421 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
425 #define VAR(name,conftype,member,initvalue) \
426 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
429 /** Array of "state" variables saved to the ~/.tor/state file. */
430 static config_var_t _state_vars
[] = {
431 V(AccountingBytesReadInInterval
, MEMUNIT
, NULL
),
432 V(AccountingBytesWrittenInInterval
, MEMUNIT
, NULL
),
433 V(AccountingExpectedUsage
, MEMUNIT
, NULL
),
434 V(AccountingIntervalStart
, ISOTIME
, NULL
),
435 V(AccountingSecondsActive
, INTERVAL
, NULL
),
436 V(AccountingSecondsToReachSoftLimit
,INTERVAL
, NULL
),
437 V(AccountingSoftLimitHitAt
, ISOTIME
, NULL
),
438 V(AccountingBytesAtSoftLimit
, MEMUNIT
, NULL
),
440 VAR("EntryGuard", LINELIST_S
, EntryGuards
, NULL
),
441 VAR("EntryGuardDownSince", LINELIST_S
, EntryGuards
, NULL
),
442 VAR("EntryGuardUnlistedSince", LINELIST_S
, EntryGuards
, NULL
),
443 VAR("EntryGuardAddedBy", LINELIST_S
, EntryGuards
, NULL
),
444 V(EntryGuards
, LINELIST_V
, NULL
),
446 V(BWHistoryReadEnds
, ISOTIME
, NULL
),
447 V(BWHistoryReadInterval
, UINT
, "900"),
448 V(BWHistoryReadValues
, CSV
, ""),
449 V(BWHistoryWriteEnds
, ISOTIME
, NULL
),
450 V(BWHistoryWriteInterval
, UINT
, "900"),
451 V(BWHistoryWriteValues
, CSV
, ""),
452 V(BWHistoryDirReadEnds
, ISOTIME
, NULL
),
453 V(BWHistoryDirReadInterval
, UINT
, "900"),
454 V(BWHistoryDirReadValues
, CSV
, ""),
455 V(BWHistoryDirWriteEnds
, ISOTIME
, NULL
),
456 V(BWHistoryDirWriteInterval
, UINT
, "900"),
457 V(BWHistoryDirWriteValues
, CSV
, ""),
459 V(TorVersion
, STRING
, NULL
),
461 V(LastRotatedOnionKey
, ISOTIME
, NULL
),
462 V(LastWritten
, ISOTIME
, NULL
),
464 V(TotalBuildTimes
, UINT
, NULL
),
465 V(CircuitBuildAbandonedCount
, UINT
, "0"),
466 VAR("CircuitBuildTimeBin", LINELIST_S
, BuildtimeHistogram
, NULL
),
467 VAR("BuildtimeHistogram", LINELIST_V
, BuildtimeHistogram
, NULL
),
469 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
476 /** Represents an English description of a configuration variable; used when
477 * generating configuration file comments. */
478 typedef struct config_var_description_t
{
480 const char *description
;
481 } config_var_description_t
;
483 /** Type of a callback to validate whether a given configuration is
484 * well-formed and consistent. See options_trial_assign() for documentation
486 typedef int (*validate_fn_t
)(void*,void*,int,char**);
488 /** Information on the keys, value types, key-to-struct-member mappings,
489 * variable descriptions, validation functions, and abbreviations for a
490 * configuration or storage format. */
492 size_t size
; /**< Size of the struct that everything gets parsed into. */
493 uint32_t magic
; /**< Required 'magic value' to make sure we have a struct
494 * of the right type. */
495 off_t magic_offset
; /**< Offset of the magic value within the struct. */
496 config_abbrev_t
*abbrevs
; /**< List of abbreviations that we expand when
497 * parsing this format. */
498 config_var_t
*vars
; /**< List of variables we recognize, their default
499 * values, and where we stick them in the structure. */
500 validate_fn_t validate_fn
; /**< Function to validate config. */
501 /** If present, extra is a LINELIST variable for unrecognized
502 * lines. Otherwise, unrecognized lines are an error. */
506 /** Macro: assert that <b>cfg</b> has the right magic field for format
508 #define CHECK(fmt, cfg) STMT_BEGIN \
509 tor_assert(fmt && cfg); \
510 tor_assert((fmt)->magic == \
511 *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
515 static char *get_windows_conf_root(void);
517 static void config_line_append(config_line_t
**lst
,
518 const char *key
, const char *val
);
519 static void option_clear(config_format_t
*fmt
, or_options_t
*options
,
521 static void option_reset(config_format_t
*fmt
, or_options_t
*options
,
522 config_var_t
*var
, int use_defaults
);
523 static void config_free(config_format_t
*fmt
, void *options
);
524 static int config_lines_eq(config_line_t
*a
, config_line_t
*b
);
525 static int option_is_same(config_format_t
*fmt
,
526 or_options_t
*o1
, or_options_t
*o2
,
528 static or_options_t
*options_dup(config_format_t
*fmt
, or_options_t
*old
);
529 static int options_validate(or_options_t
*old_options
, or_options_t
*options
,
530 int from_setconf
, char **msg
);
531 static int options_act_reversible(or_options_t
*old_options
, char **msg
);
532 static int options_act(or_options_t
*old_options
);
533 static int options_transition_allowed(or_options_t
*old
, or_options_t
*new,
535 static int options_transition_affects_workers(or_options_t
*old_options
,
536 or_options_t
*new_options
);
537 static int options_transition_affects_descriptor(or_options_t
*old_options
,
538 or_options_t
*new_options
);
539 static int check_nickname_list(const char *lst
, const char *name
, char **msg
);
540 static void config_register_addressmaps(or_options_t
*options
);
542 static int parse_bridge_line(const char *line
, int validate_only
);
543 static int parse_dir_server_line(const char *line
,
544 authority_type_t required_type
,
546 static int validate_data_directory(or_options_t
*options
);
547 static int write_configuration_file(const char *fname
, or_options_t
*options
);
548 static config_line_t
*get_assigned_option(config_format_t
*fmt
,
549 void *options
, const char *key
,
551 static void config_init(config_format_t
*fmt
, void *options
);
552 static int or_state_validate(or_state_t
*old_options
, or_state_t
*options
,
553 int from_setconf
, char **msg
);
554 static int or_state_load(void);
555 static int options_init_logs(or_options_t
*options
, int validate_only
);
557 static int is_listening_on_low_port(uint16_t port_option
,
558 const config_line_t
*listen_options
);
560 static uint64_t config_parse_memunit(const char *s
, int *ok
);
561 static int config_parse_interval(const char *s
, int *ok
);
562 static void init_libevent(void);
563 static int opt_streq(const char *s1
, const char *s2
);
565 /** Magic value for or_options_t. */
566 #define OR_OPTIONS_MAGIC 9090909
568 /** Configuration format for or_options_t. */
569 static config_format_t options_format
= {
570 sizeof(or_options_t
),
572 STRUCT_OFFSET(or_options_t
, _magic
),
575 (validate_fn_t
)options_validate
,
579 /** Magic value for or_state_t. */
580 #define OR_STATE_MAGIC 0x57A73f57
582 /** "Extra" variable in the state that receives lines we can't parse. This
583 * lets us preserve options from versions of Tor newer than us. */
584 static config_var_t state_extra_var
= {
585 "__extra", CONFIG_TYPE_LINELIST
, STRUCT_OFFSET(or_state_t
, ExtraLines
), NULL
588 /** Configuration format for or_state_t. */
589 static config_format_t state_format
= {
592 STRUCT_OFFSET(or_state_t
, _magic
),
595 (validate_fn_t
)or_state_validate
,
600 * Functions to read and write the global options pointer.
603 /** Command-line and config-file options. */
604 static or_options_t
*global_options
= NULL
;
605 /** Name of most recently read torrc file. */
606 static char *torrc_fname
= NULL
;
607 /** Persistent serialized state. */
608 static or_state_t
*global_state
= NULL
;
609 /** Configuration Options set by command line. */
610 static config_line_t
*global_cmdline_options
= NULL
;
611 /** Contents of most recently read DirPortFrontPage file. */
612 static char *global_dirfrontpagecontents
= NULL
;
614 /** Return the contents of our frontpage string, or NULL if not configured. */
616 get_dirportfrontpage(void)
618 return global_dirfrontpagecontents
;
621 /** Allocate an empty configuration object of a given format type. */
623 config_alloc(config_format_t
*fmt
)
625 void *opts
= tor_malloc_zero(fmt
->size
);
626 *(uint32_t*)STRUCT_VAR_P(opts
, fmt
->magic_offset
) = fmt
->magic
;
631 /** Return the currently configured options. */
635 tor_assert(global_options
);
636 return global_options
;
639 /** Change the current global options to contain <b>new_val</b> instead of
640 * their current value; take action based on the new value; free the old value
641 * as necessary. Returns 0 on success, -1 on failure.
644 set_options(or_options_t
*new_val
, char **msg
)
646 or_options_t
*old_options
= global_options
;
647 global_options
= new_val
;
648 /* Note that we pass the *old* options below, for comparison. It
649 * pulls the new options directly out of global_options. */
650 if (options_act_reversible(old_options
, msg
)<0) {
652 global_options
= old_options
;
655 if (options_act(old_options
) < 0) { /* acting on the options failed. die. */
657 "Acting on config options left us in a broken state. Dying.");
661 config_free(&options_format
, old_options
);
666 extern const char tor_git_revision
[]; /* from tor_main.c */
668 /** The version of this Tor process, as parsed. */
669 static char *_version
= NULL
;
671 /** Return the current Tor version. */
675 if (_version
== NULL
) {
676 if (strlen(tor_git_revision
)) {
677 size_t len
= strlen(VERSION
)+strlen(tor_git_revision
)+16;
678 _version
= tor_malloc(len
);
679 tor_snprintf(_version
, len
, "%s (git-%s)", VERSION
, tor_git_revision
);
681 _version
= tor_strdup(VERSION
);
687 /** Release additional memory allocated in options
690 or_options_free(or_options_t
*options
)
695 routerset_free(options
->_ExcludeExitNodesUnion
);
696 config_free(&options_format
, options
);
699 /** Release all memory and resources held by global configuration structures.
702 config_free_all(void)
704 or_options_free(global_options
);
705 global_options
= NULL
;
707 config_free(&state_format
, global_state
);
710 config_free_lines(global_cmdline_options
);
711 global_cmdline_options
= NULL
;
713 tor_free(torrc_fname
);
715 tor_free(global_dirfrontpagecontents
);
718 /** Make <b>address</b> -- a piece of information related to our operation as
719 * a client -- safe to log according to the settings in options->SafeLogging,
722 * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
725 safe_str_client(const char *address
)
728 if (get_options()->_SafeLogging
== SAFELOG_SCRUB_ALL
)
734 /** Make <b>address</b> -- a piece of information of unspecified sensitivity
735 * -- safe to log according to the settings in options->SafeLogging, and
738 * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
742 safe_str(const char *address
)
745 if (get_options()->_SafeLogging
!= SAFELOG_SCRUB_NONE
)
751 /** Equivalent to escaped(safe_str_client(address)). See reentrancy note on
752 * escaped(): don't use this outside the main thread, or twice in the same
755 escaped_safe_str_client(const char *address
)
757 if (get_options()->_SafeLogging
== SAFELOG_SCRUB_ALL
)
760 return escaped(address
);
763 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
764 * escaped(): don't use this outside the main thread, or twice in the same
767 escaped_safe_str(const char *address
)
769 if (get_options()->_SafeLogging
!= SAFELOG_SCRUB_NONE
)
772 return escaped(address
);
775 /** Add the default directory authorities directly into the trusted dir list,
776 * but only add them insofar as they share bits with <b>type</b>. */
778 add_default_trusted_dir_authorities(authority_type_t type
)
781 const char *dirservers
[] = {
782 "moria1 orport=9101 no-v2 "
783 "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
784 "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
785 "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
786 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
787 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
788 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
789 "Tonga orport=443 bridge no-v2 82.94.251.203:80 "
790 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
791 "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
792 "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
793 "gabelmoo orport=443 no-v2 "
794 "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
795 "212.112.245.170:80 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
796 "dannenberg orport=443 no-v2 "
797 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
798 "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
799 "urras orport=80 no-v2 v3ident=80550987E1D626E3EBA5E5E75A458DE0626D088C "
800 "208.83.223.34:443 0AD3 FA88 4D18 F89E EA2D 89C0 1937 9E0E 7FD9 4417",
801 "maatuska orport=80 no-v2 "
802 "v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
803 "213.115.239.118:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
806 for (i
=0; dirservers
[i
]; i
++) {
807 if (parse_dir_server_line(dirservers
[i
], type
, 0)<0) {
808 log_err(LD_BUG
, "Couldn't parse internal dirserver line %s",
814 /** Look at all the config options for using alternate directory
815 * authorities, and make sure none of them are broken. Also, warn the
816 * user if we changed any dangerous ones.
819 validate_dir_authorities(or_options_t
*options
, or_options_t
*old_options
)
823 if (options
->DirServers
&&
824 (options
->AlternateDirAuthority
|| options
->AlternateBridgeAuthority
||
825 options
->AlternateHSAuthority
)) {
827 "You cannot set both DirServers and Alternate*Authority.");
831 /* do we want to complain to the user about being partitionable? */
832 if ((options
->DirServers
&&
834 !config_lines_eq(options
->DirServers
, old_options
->DirServers
))) ||
835 (options
->AlternateDirAuthority
&&
837 !config_lines_eq(options
->AlternateDirAuthority
,
838 old_options
->AlternateDirAuthority
)))) {
840 "You have used DirServer or AlternateDirAuthority to "
841 "specify alternate directory authorities in "
842 "your configuration. This is potentially dangerous: it can "
843 "make you look different from all other Tor users, and hurt "
844 "your anonymity. Even if you've specified the same "
845 "authorities as Tor uses by default, the defaults could "
846 "change in the future. Be sure you know what you're doing.");
849 /* Now go through the four ways you can configure an alternate
850 * set of directory authorities, and make sure none are broken. */
851 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
)
852 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
854 for (cl
= options
->AlternateBridgeAuthority
; cl
; cl
= cl
->next
)
855 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
857 for (cl
= options
->AlternateDirAuthority
; cl
; cl
= cl
->next
)
858 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
860 for (cl
= options
->AlternateHSAuthority
; cl
; cl
= cl
->next
)
861 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
866 /** Look at all the config options and assign new dir authorities
870 consider_adding_dir_authorities(or_options_t
*options
,
871 or_options_t
*old_options
)
875 !smartlist_len(router_get_trusted_dir_servers()) || !old_options
||
876 !config_lines_eq(options
->DirServers
, old_options
->DirServers
) ||
877 !config_lines_eq(options
->AlternateBridgeAuthority
,
878 old_options
->AlternateBridgeAuthority
) ||
879 !config_lines_eq(options
->AlternateDirAuthority
,
880 old_options
->AlternateDirAuthority
) ||
881 !config_lines_eq(options
->AlternateHSAuthority
,
882 old_options
->AlternateHSAuthority
);
885 return 0; /* all done */
887 /* Start from a clean slate. */
888 clear_trusted_dir_servers();
890 if (!options
->DirServers
) {
891 /* then we may want some of the defaults */
892 authority_type_t type
= NO_AUTHORITY
;
893 if (!options
->AlternateBridgeAuthority
)
894 type
|= BRIDGE_AUTHORITY
;
895 if (!options
->AlternateDirAuthority
)
896 type
|= V1_AUTHORITY
| V2_AUTHORITY
| V3_AUTHORITY
;
897 if (!options
->AlternateHSAuthority
)
898 type
|= HIDSERV_AUTHORITY
;
899 add_default_trusted_dir_authorities(type
);
902 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
)
903 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
905 for (cl
= options
->AlternateBridgeAuthority
; cl
; cl
= cl
->next
)
906 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
908 for (cl
= options
->AlternateDirAuthority
; cl
; cl
= cl
->next
)
909 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
911 for (cl
= options
->AlternateHSAuthority
; cl
; cl
= cl
->next
)
912 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
917 /** Fetch the active option list, and take actions based on it. All of the
918 * things we do should survive being done repeatedly. If present,
919 * <b>old_options</b> contains the previous value of the options.
921 * Return 0 if all goes well, return -1 if things went badly.
924 options_act_reversible(or_options_t
*old_options
, char **msg
)
926 smartlist_t
*new_listeners
= smartlist_create();
927 smartlist_t
*replaced_listeners
= smartlist_create();
928 static int libevent_initialized
= 0;
929 or_options_t
*options
= get_options();
930 int running_tor
= options
->command
== CMD_RUN_TOR
;
931 int set_conn_limit
= 0;
935 /* Daemonize _first_, since we only want to open most of this stuff in
936 * the subprocess. Libevent bases can't be reliably inherited across
938 if (running_tor
&& options
->RunAsDaemon
) {
939 /* No need to roll back, since you can't change the value. */
943 #ifndef HAVE_SYS_UN_H
944 if (options
->ControlSocket
) {
945 *msg
= tor_strdup("Unix domain sockets (ControlSocket) not supported"
946 " on this OS/with this build.");
952 /* We need to set the connection limit before we can open the listeners. */
953 if (set_max_file_descriptors((unsigned)options
->ConnLimit
,
954 &options
->_ConnLimit
) < 0) {
955 *msg
= tor_strdup("Problem with ConnLimit value. See logs for details.");
960 /* Set up libevent. (We need to do this before we can register the
961 * listeners as listeners.) */
962 if (running_tor
&& !libevent_initialized
) {
964 libevent_initialized
= 1;
967 /* Launch the listeners. (We do this before we setuid, so we can bind to
968 * ports under 1024.) We don't want to rebind if we're hibernating. */
969 if (!we_are_hibernating()) {
970 if (retry_all_listeners(replaced_listeners
, new_listeners
) < 0) {
971 *msg
= tor_strdup("Failed to bind one of the listener ports.");
977 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
978 /* Open /dev/pf before dropping privileges. */
979 if (options
->TransPort
) {
980 if (get_pf_socket() < 0) {
981 *msg
= tor_strdup("Unable to open /dev/pf for transparent proxy.");
987 /* Attempt to lock all current and future memory with mlockall() only once */
988 if (options
->DisableAllSwap
) {
989 if (tor_mlockall() == -1) {
990 *msg
= tor_strdup("DisableAllSwap failure. Do you have proper "
996 /* Setuid/setgid as appropriate */
998 if (switch_id(options
->User
) != 0) {
999 /* No need to roll back, since you can't change the value. */
1000 *msg
= tor_strdup("Problem with User value. See logs for details.");
1005 /* Ensure data directory is private; create if possible. */
1006 if (check_private_dir(options
->DataDirectory
,
1007 running_tor
? CPD_CREATE
: CPD_CHECK
)<0) {
1009 "Couldn't access/create private data directory \"%s\"",
1010 options
->DataDirectory
);
1012 /* No need to roll back, since you can't change the value. */
1015 if (directory_caches_v2_dir_info(options
)) {
1016 size_t len
= strlen(options
->DataDirectory
)+32;
1017 char *fn
= tor_malloc(len
);
1018 tor_snprintf(fn
, len
, "%s"PATH_SEPARATOR
"cached-status",
1019 options
->DataDirectory
);
1020 if (check_private_dir(fn
, running_tor
? CPD_CREATE
: CPD_CHECK
) < 0) {
1022 "Couldn't access/create private data directory \"%s\"", fn
);
1029 /* Bail out at this point if we're not going to be a client or server:
1030 * we don't run Tor itself. */
1034 mark_logs_temp(); /* Close current logs once new logs are open. */
1036 if (options_init_logs(options
, 0)<0) { /* Configure the log(s) */
1037 *msg
= tor_strdup("Failed to init Log options. See logs for details.");
1044 log_severity_list_t
*severity
=
1045 tor_malloc_zero(sizeof(log_severity_list_t
));
1047 add_callback_log(severity
, control_event_logmsg
);
1048 control_adjust_event_log_severity();
1051 SMARTLIST_FOREACH(replaced_listeners
, connection_t
*, conn
,
1053 log_notice(LD_NET
, "Closing old %s on %s:%d",
1054 conn_type_to_string(conn
->type
), conn
->address
, conn
->port
);
1055 connection_close_immediate(conn
);
1056 connection_mark_for_close(conn
);
1065 rollback_log_changes();
1066 control_adjust_event_log_severity();
1069 if (set_conn_limit
&& old_options
)
1070 set_max_file_descriptors((unsigned)old_options
->ConnLimit
,
1071 &options
->_ConnLimit
);
1073 SMARTLIST_FOREACH(new_listeners
, connection_t
*, conn
,
1075 log_notice(LD_NET
, "Closing partially-constructed listener %s on %s:%d",
1076 conn_type_to_string(conn
->type
), conn
->address
, conn
->port
);
1077 connection_close_immediate(conn
);
1078 connection_mark_for_close(conn
);
1082 smartlist_free(new_listeners
);
1083 smartlist_free(replaced_listeners
);
1087 /** If we need to have a GEOIP ip-to-country map to run with our configured
1088 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1090 options_need_geoip_info(or_options_t
*options
, const char **reason_out
)
1093 options
->BridgeRelay
&& options
->BridgeRecordUsageByCountry
;
1094 int routerset_usage
=
1095 routerset_needs_geoip(options
->EntryNodes
) ||
1096 routerset_needs_geoip(options
->ExitNodes
) ||
1097 routerset_needs_geoip(options
->ExcludeExitNodes
) ||
1098 routerset_needs_geoip(options
->ExcludeNodes
);
1100 if (routerset_usage
&& reason_out
) {
1101 *reason_out
= "We've been configured to use (or avoid) nodes in certain "
1102 "countries, and we need GEOIP information to figure out which ones they "
1104 } else if (bridge_usage
&& reason_out
) {
1105 *reason_out
= "We've been configured to see which countries can access "
1106 "us as a bridge, and we need GEOIP information to tell which countries "
1109 return bridge_usage
|| routerset_usage
;
1112 /** Return the bandwidthrate that we are going to report to the authorities
1113 * based on the config options. */
1115 get_effective_bwrate(or_options_t
*options
)
1117 uint64_t bw
= options
->BandwidthRate
;
1118 if (bw
> options
->MaxAdvertisedBandwidth
)
1119 bw
= options
->MaxAdvertisedBandwidth
;
1120 if (options
->RelayBandwidthRate
> 0 && bw
> options
->RelayBandwidthRate
)
1121 bw
= options
->RelayBandwidthRate
;
1122 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1123 return (uint32_t)bw
;
1126 /** Return the bandwidthburst that we are going to report to the authorities
1127 * based on the config options. */
1129 get_effective_bwburst(or_options_t
*options
)
1131 uint64_t bw
= options
->BandwidthBurst
;
1132 if (options
->RelayBandwidthBurst
> 0 && bw
> options
->RelayBandwidthBurst
)
1133 bw
= options
->RelayBandwidthBurst
;
1134 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1135 return (uint32_t)bw
;
1138 /** Fetch the active option list, and take actions based on it. All of the
1139 * things we do should survive being done repeatedly. If present,
1140 * <b>old_options</b> contains the previous value of the options.
1142 * Return 0 if all goes well, return -1 if it's time to die.
1144 * Note: We haven't moved all the "act on new configuration" logic
1145 * here yet. Some is still in do_hup() and other places.
1148 options_act(or_options_t
*old_options
)
1151 or_options_t
*options
= get_options();
1152 int running_tor
= options
->command
== CMD_RUN_TOR
;
1155 if (running_tor
&& !have_lockfile()) {
1156 if (try_locking(options
, 1) < 0)
1160 if (consider_adding_dir_authorities(options
, old_options
) < 0)
1163 if (options
->Bridges
) {
1164 clear_bridge_list();
1165 for (cl
= options
->Bridges
; cl
; cl
= cl
->next
) {
1166 if (parse_bridge_line(cl
->value
, 0)<0) {
1168 "Previously validated Bridge line could not be added!");
1174 if (running_tor
&& rend_config_services(options
, 0)<0) {
1176 "Previously validated hidden services line could not be added!");
1180 if (running_tor
&& rend_parse_service_authorization(options
, 0) < 0) {
1181 log_warn(LD_BUG
, "Previously validated client authorization for "
1182 "hidden services could not be added!");
1187 if (! global_state
&& running_tor
) {
1188 if (or_state_load())
1190 rep_hist_load_mtbf_data(time(NULL
));
1193 /* Bail out at this point if we're not going to be a client or server:
1194 * we want to not fork, and to log stuff to stderr. */
1198 /* Finish backgrounding the process */
1199 if (options
->RunAsDaemon
) {
1200 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1201 finish_daemon(options
->DataDirectory
);
1204 /* Write our PID to the PID file. If we do not have write permissions we
1205 * will log a warning */
1206 if (options
->PidFile
)
1207 write_pidfile(options
->PidFile
);
1209 /* Register addressmap directives */
1210 config_register_addressmaps(options
);
1211 parse_virtual_addr_network(options
->VirtualAddrNetwork
, 0, &msg
);
1213 /* Update address policies. */
1214 if (policies_parse_from_options(options
) < 0) {
1215 /* This should be impossible, but let's be sure. */
1216 log_warn(LD_BUG
,"Error parsing already-validated policy options.");
1220 if (init_cookie_authentication(options
->CookieAuthentication
) < 0) {
1221 log_warn(LD_CONFIG
,"Error creating cookie authentication file.");
1225 /* reload keys as needed for rendezvous services. */
1226 if (rend_service_load_keys()<0) {
1227 log_warn(LD_GENERAL
,"Error loading rendezvous service keys");
1231 /* Set up accounting */
1232 if (accounting_parse_options(options
, 0)<0) {
1233 log_warn(LD_CONFIG
,"Error in accounting options");
1236 if (accounting_is_enabled(options
))
1237 configure_accounting(time(NULL
));
1239 /* parse RefuseUnknownExits tristate */
1240 if (!strcmp(options
->RefuseUnknownExits
, "0"))
1241 options
->RefuseUnknownExits_
= 0;
1242 else if (!strcmp(options
->RefuseUnknownExits
, "1"))
1243 options
->RefuseUnknownExits_
= 1;
1244 else if (!strcmp(options
->RefuseUnknownExits
, "auto"))
1245 options
->RefuseUnknownExits_
= -1;
1247 /* Should have caught this in options_validate */
1251 /* Change the cell EWMA settings */
1252 cell_ewma_set_scale_factor(options
, networkstatus_get_latest_consensus());
1254 /* Check for transitions that need action. */
1256 if ((options
->UseEntryGuards
&& !old_options
->UseEntryGuards
) ||
1257 (options
->ExcludeNodes
&&
1258 !routerset_equal(old_options
->ExcludeNodes
,options
->ExcludeNodes
)) ||
1259 (options
->ExcludeExitNodes
&&
1260 !routerset_equal(old_options
->ExcludeExitNodes
,
1261 options
->ExcludeExitNodes
)) ||
1262 (options
->EntryNodes
&&
1263 !routerset_equal(old_options
->EntryNodes
, options
->EntryNodes
)) ||
1264 (options
->ExitNodes
&&
1265 !routerset_equal(old_options
->ExitNodes
, options
->ExitNodes
)) ||
1266 options
->StrictNodes
!= old_options
->StrictNodes
) {
1268 "Changed to using entry guards, or changed preferred or "
1269 "excluded node lists. Abandoning previous circuits.");
1270 circuit_mark_all_unused_circs();
1271 circuit_expire_all_dirty_circs();
1274 /* How long should we delay counting bridge stats after becoming a bridge?
1275 * We use this so we don't count people who used our bridge thinking it is
1276 * a relay. If you change this, don't forget to change the log message
1277 * below. It's 4 hours (the time it takes to stop being used by clients)
1278 * plus some extra time for clock skew. */
1279 #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
1281 if (! bool_eq(options
->BridgeRelay
, old_options
->BridgeRelay
)) {
1283 if (options
->BridgeRelay
) {
1284 time_t int_start
= time(NULL
);
1285 if (old_options
->ORPort
== options
->ORPort
) {
1286 int_start
+= RELAY_BRIDGE_STATS_DELAY
;
1289 geoip_bridge_stats_init(int_start
);
1290 log_info(LD_CONFIG
, "We are acting as a bridge now. Starting new "
1291 "GeoIP stats interval%s.", was_relay
? " in 6 "
1292 "hours from now" : "");
1294 geoip_bridge_stats_term();
1295 log_info(LD_GENERAL
, "We are no longer acting as a bridge. "
1296 "Forgetting GeoIP stats.");
1300 if (options_transition_affects_workers(old_options
, options
)) {
1301 log_info(LD_GENERAL
,
1302 "Worker-related options changed. Rotating workers.");
1304 if (init_keys() < 0) {
1305 log_warn(LD_BUG
,"Error initializing keys; exiting");
1308 if (server_mode(options
) && !server_mode(old_options
)) {
1309 ip_address_changed(0);
1310 if (can_complete_circuit
|| !any_predicted_circuits(time(NULL
)))
1311 inform_testing_reachability();
1313 cpuworkers_rotate();
1321 if (options
->V3AuthoritativeDir
&& !old_options
->V3AuthoritativeDir
)
1324 if (options
->PerConnBWRate
!= old_options
->PerConnBWRate
||
1325 options
->PerConnBWBurst
!= old_options
->PerConnBWBurst
)
1326 connection_or_update_token_buckets(get_connection_array(), options
);
1329 /* Maybe load geoip file */
1330 if (options
->GeoIPFile
&&
1331 ((!old_options
|| !opt_streq(old_options
->GeoIPFile
, options
->GeoIPFile
))
1332 || !geoip_is_loaded())) {
1333 /* XXXX Don't use this "<default>" junk; make our filename options
1334 * understand prefixes somehow. -NM */
1335 /* XXXX021 Reload GeoIPFile on SIGHUP. -NM */
1336 char *actual_fname
= tor_strdup(options
->GeoIPFile
);
1338 if (!strcmp(actual_fname
, "<default>")) {
1339 const char *conf_root
= get_windows_conf_root();
1340 size_t len
= strlen(conf_root
)+16;
1341 tor_free(actual_fname
);
1342 actual_fname
= tor_malloc(len
+1);
1343 tor_snprintf(actual_fname
, len
, "%s\\geoip", conf_root
);
1346 geoip_load_file(actual_fname
, options
);
1347 tor_free(actual_fname
);
1350 if (options
->DirReqStatistics
&& !geoip_is_loaded()) {
1351 /* Check if GeoIP database could be loaded. */
1352 log_warn(LD_CONFIG
, "Configured to measure directory request "
1353 "statistics, but no GeoIP database found!");
1357 if (options
->EntryStatistics
) {
1358 if (should_record_bridge_info(options
)) {
1359 /* Don't allow measuring statistics on entry guards when configured
1361 log_warn(LD_CONFIG
, "Bridges cannot be configured to measure "
1362 "additional GeoIP statistics as entry guards.");
1364 } else if (!geoip_is_loaded()) {
1365 /* Check if GeoIP database could be loaded. */
1366 log_warn(LD_CONFIG
, "Configured to measure entry node statistics, "
1367 "but no GeoIP database found!");
1372 if (options
->CellStatistics
|| options
->DirReqStatistics
||
1373 options
->EntryStatistics
|| options
->ExitPortStatistics
) {
1374 time_t now
= time(NULL
);
1375 if ((!old_options
|| !old_options
->CellStatistics
) &&
1376 options
->CellStatistics
)
1377 rep_hist_buffer_stats_init(now
);
1378 if ((!old_options
|| !old_options
->DirReqStatistics
) &&
1379 options
->DirReqStatistics
)
1380 geoip_dirreq_stats_init(now
);
1381 if ((!old_options
|| !old_options
->EntryStatistics
) &&
1382 options
->EntryStatistics
)
1383 geoip_entry_stats_init(now
);
1384 if ((!old_options
|| !old_options
->ExitPortStatistics
) &&
1385 options
->ExitPortStatistics
)
1386 rep_hist_exit_stats_init(now
);
1388 log_notice(LD_CONFIG
, "Configured to measure statistics. Look for "
1389 "the *-stats files that will first be written to the "
1390 "data directory in 24 hours from now.");
1393 if (old_options
&& old_options
->CellStatistics
&&
1394 !options
->CellStatistics
)
1395 rep_hist_buffer_stats_term();
1396 if (old_options
&& old_options
->DirReqStatistics
&&
1397 !options
->DirReqStatistics
)
1398 geoip_dirreq_stats_term();
1399 if (old_options
&& old_options
->EntryStatistics
&&
1400 !options
->EntryStatistics
)
1401 geoip_entry_stats_term();
1402 if (old_options
&& old_options
->ExitPortStatistics
&&
1403 !options
->ExitPortStatistics
)
1404 rep_hist_exit_stats_term();
1406 /* Check if we need to parse and add the EntryNodes config option. */
1407 if (options
->EntryNodes
&&
1409 (!routerset_equal(old_options
->EntryNodes
,options
->EntryNodes
))))
1410 entry_nodes_should_be_added();
1412 /* Since our options changed, we might need to regenerate and upload our
1413 * server descriptor.
1416 options_transition_affects_descriptor(old_options
, options
))
1417 mark_my_descriptor_dirty();
1419 /* We may need to reschedule some directory stuff if our status changed. */
1421 if (authdir_mode_v3(options
) && !authdir_mode_v3(old_options
))
1422 dirvote_recalculate_timing(options
, time(NULL
));
1423 if (!bool_eq(directory_fetches_dir_info_early(options
),
1424 directory_fetches_dir_info_early(old_options
)) ||
1425 !bool_eq(directory_fetches_dir_info_later(options
),
1426 directory_fetches_dir_info_later(old_options
))) {
1427 /* Make sure update_router_have_min_dir_info gets called. */
1428 router_dir_info_changed();
1429 /* We might need to download a new consensus status later or sooner than
1430 * we had expected. */
1431 update_consensus_networkstatus_fetch_time(time(NULL
));
1435 /* Load the webpage we're going to serve every time someone asks for '/' on
1437 tor_free(global_dirfrontpagecontents
);
1438 if (options
->DirPortFrontPage
) {
1439 global_dirfrontpagecontents
=
1440 read_file_to_str(options
->DirPortFrontPage
, 0, NULL
);
1441 if (!global_dirfrontpagecontents
) {
1443 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1444 options
->DirPortFrontPage
);
1452 * Functions to parse config options
1455 /** If <b>option</b> is an official abbreviation for a longer option,
1456 * return the longer option. Otherwise return <b>option</b>.
1457 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1458 * apply abbreviations that work for the config file and the command line.
1459 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1461 expand_abbrev(config_format_t
*fmt
, const char *option
, int command_line
,
1467 for (i
=0; fmt
->abbrevs
[i
].abbreviated
; ++i
) {
1468 /* Abbreviations are case insensitive. */
1469 if (!strcasecmp(option
,fmt
->abbrevs
[i
].abbreviated
) &&
1470 (command_line
|| !fmt
->abbrevs
[i
].commandline_only
)) {
1471 if (warn_obsolete
&& fmt
->abbrevs
[i
].warn
) {
1473 "The configuration option '%s' is deprecated; "
1474 "use '%s' instead.",
1475 fmt
->abbrevs
[i
].abbreviated
,
1476 fmt
->abbrevs
[i
].full
);
1478 /* Keep going through the list in case we want to rewrite it more.
1479 * (We could imagine recursing here, but I don't want to get the
1480 * user into an infinite loop if we craft our list wrong.) */
1481 option
= fmt
->abbrevs
[i
].full
;
1487 /** Helper: Read a list of configuration options from the command line.
1488 * If successful, put them in *<b>result</b> and return 0, and return
1489 * -1 and leave *<b>result</b> alone. */
1491 config_get_commandlines(int argc
, char **argv
, config_line_t
**result
)
1493 config_line_t
*front
= NULL
;
1494 config_line_t
**new = &front
;
1499 if (!strcmp(argv
[i
],"-f") ||
1500 !strcmp(argv
[i
],"--hash-password")) {
1501 i
+= 2; /* command-line option with argument. ignore them. */
1503 } else if (!strcmp(argv
[i
],"--list-fingerprint") ||
1504 !strcmp(argv
[i
],"--verify-config") ||
1505 !strcmp(argv
[i
],"--ignore-missing-torrc") ||
1506 !strcmp(argv
[i
],"--quiet") ||
1507 !strcmp(argv
[i
],"--hush")) {
1508 i
+= 1; /* command-line option. ignore it. */
1510 } else if (!strcmp(argv
[i
],"--nt-service") ||
1511 !strcmp(argv
[i
],"-nt-service")) {
1517 log_warn(LD_CONFIG
,"Command-line option '%s' with no value. Failing.",
1519 config_free_lines(front
);
1523 *new = tor_malloc_zero(sizeof(config_line_t
));
1526 /* Each keyword may be prefixed with one or two dashes. */
1532 (*new)->key
= tor_strdup(expand_abbrev(&options_format
, s
, 1, 1));
1533 (*new)->value
= tor_strdup(argv
[i
+1]);
1534 (*new)->next
= NULL
;
1535 log(LOG_DEBUG
, LD_CONFIG
, "command line: parsed keyword '%s', value '%s'",
1536 (*new)->key
, (*new)->value
);
1538 new = &((*new)->next
);
1545 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1546 * append it to *<b>lst</b>. */
1548 config_line_append(config_line_t
**lst
,
1552 config_line_t
*newline
;
1554 newline
= tor_malloc(sizeof(config_line_t
));
1555 newline
->key
= tor_strdup(key
);
1556 newline
->value
= tor_strdup(val
);
1557 newline
->next
= NULL
;
1559 lst
= &((*lst
)->next
);
1564 /** Helper: parse the config string and strdup into key/value
1565 * strings. Set *result to the list, or NULL if parsing the string
1566 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1567 * misformatted lines. */
1569 config_get_lines(const char *string
, config_line_t
**result
)
1571 config_line_t
*list
= NULL
, **next
;
1577 string
= parse_config_line_from_str(string
, &k
, &v
);
1579 config_free_lines(list
);
1585 /* This list can get long, so we keep a pointer to the end of it
1586 * rather than using config_line_append over and over and getting
1587 * n^2 performance. */
1588 *next
= tor_malloc(sizeof(config_line_t
));
1591 (*next
)->next
= NULL
;
1592 next
= &((*next
)->next
);
1604 * Free all the configuration lines on the linked list <b>front</b>.
1607 config_free_lines(config_line_t
*front
)
1616 tor_free(tmp
->value
);
1621 /** If <b>key</b> is a configuration option, return the corresponding
1622 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1623 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1625 static config_var_t
*
1626 config_find_option(config_format_t
*fmt
, const char *key
)
1629 size_t keylen
= strlen(key
);
1631 return NULL
; /* if they say "--" on the command line, it's not an option */
1632 /* First, check for an exact (case-insensitive) match */
1633 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
1634 if (!strcasecmp(key
, fmt
->vars
[i
].name
)) {
1635 return &fmt
->vars
[i
];
1638 /* If none, check for an abbreviated match */
1639 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
1640 if (!strncasecmp(key
, fmt
->vars
[i
].name
, keylen
)) {
1641 log_warn(LD_CONFIG
, "The abbreviation '%s' is deprecated. "
1642 "Please use '%s' instead",
1643 key
, fmt
->vars
[i
].name
);
1644 return &fmt
->vars
[i
];
1647 /* Okay, unrecognized option */
1651 /** Return the number of option entries in <b>fmt</b>. */
1653 config_count_options(config_format_t
*fmt
)
1656 for (i
=0; fmt
->vars
[i
].name
; ++i
)
1662 * Functions to assign config options.
1665 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1666 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1668 * Called from config_assign_line() and option_reset().
1671 config_assign_value(config_format_t
*fmt
, or_options_t
*options
,
1672 config_line_t
*c
, char **msg
)
1678 CHECK(fmt
, options
);
1680 var
= config_find_option(fmt
, c
->key
);
1683 lvalue
= STRUCT_VAR_P(options
, var
->var_offset
);
1685 switch (var
->type
) {
1687 case CONFIG_TYPE_UINT
:
1688 i
= (int)tor_parse_long(c
->value
, 10, 0, INT_MAX
, &ok
, NULL
);
1691 "Int keyword '%s %s' is malformed or out of bounds.",
1698 case CONFIG_TYPE_INTERVAL
: {
1699 i
= config_parse_interval(c
->value
, &ok
);
1702 "Interval '%s %s' is malformed or out of bounds.",
1710 case CONFIG_TYPE_MEMUNIT
: {
1711 uint64_t u64
= config_parse_memunit(c
->value
, &ok
);
1714 "Value '%s %s' is malformed or out of bounds.",
1718 *(uint64_t *)lvalue
= u64
;
1722 case CONFIG_TYPE_BOOL
:
1723 i
= (int)tor_parse_long(c
->value
, 10, 0, 1, &ok
, NULL
);
1726 "Boolean '%s %s' expects 0 or 1.",
1733 case CONFIG_TYPE_STRING
:
1734 case CONFIG_TYPE_FILENAME
:
1735 tor_free(*(char **)lvalue
);
1736 *(char **)lvalue
= tor_strdup(c
->value
);
1739 case CONFIG_TYPE_DOUBLE
:
1740 *(double *)lvalue
= atof(c
->value
);
1743 case CONFIG_TYPE_ISOTIME
:
1744 if (parse_iso_time(c
->value
, (time_t *)lvalue
)) {
1746 "Invalid time '%s' for keyword '%s'", c
->value
, c
->key
);
1751 case CONFIG_TYPE_ROUTERSET
:
1752 if (*(routerset_t
**)lvalue
) {
1753 routerset_free(*(routerset_t
**)lvalue
);
1755 *(routerset_t
**)lvalue
= routerset_new();
1756 if (routerset_parse(*(routerset_t
**)lvalue
, c
->value
, c
->key
)<0) {
1757 tor_asprintf(msg
, "Invalid exit list '%s' for option '%s'",
1763 case CONFIG_TYPE_CSV
:
1764 if (*(smartlist_t
**)lvalue
) {
1765 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
1766 smartlist_clear(*(smartlist_t
**)lvalue
);
1768 *(smartlist_t
**)lvalue
= smartlist_create();
1771 smartlist_split_string(*(smartlist_t
**)lvalue
, c
->value
, ",",
1772 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1775 case CONFIG_TYPE_LINELIST
:
1776 case CONFIG_TYPE_LINELIST_S
:
1777 config_line_append((config_line_t
**)lvalue
, c
->key
, c
->value
);
1779 case CONFIG_TYPE_OBSOLETE
:
1780 log_warn(LD_CONFIG
, "Skipping obsolete configuration option '%s'", c
->key
);
1782 case CONFIG_TYPE_LINELIST_V
:
1784 "You may not provide a value for virtual option '%s'", c
->key
);
1793 /** If <b>c</b> is a syntactically valid configuration line, update
1794 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1795 * key, -2 for bad value.
1797 * If <b>clear_first</b> is set, clear the value first. Then if
1798 * <b>use_defaults</b> is set, set the value to the default.
1800 * Called from config_assign().
1803 config_assign_line(config_format_t
*fmt
, or_options_t
*options
,
1804 config_line_t
*c
, int use_defaults
,
1805 int clear_first
, bitarray_t
*options_seen
, char **msg
)
1809 CHECK(fmt
, options
);
1811 var
= config_find_option(fmt
, c
->key
);
1814 void *lvalue
= STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
1816 "Found unrecognized option '%s'; saving it.", c
->key
);
1817 config_line_append((config_line_t
**)lvalue
, c
->key
, c
->value
);
1821 "Unknown option '%s'. Failing.", c
->key
);
1826 /* Put keyword into canonical case. */
1827 if (strcmp(var
->name
, c
->key
)) {
1829 c
->key
= tor_strdup(var
->name
);
1832 if (!strlen(c
->value
)) {
1833 /* reset or clear it, then return */
1835 if (var
->type
== CONFIG_TYPE_LINELIST
||
1836 var
->type
== CONFIG_TYPE_LINELIST_S
) {
1837 /* We got an empty linelist from the torrc or command line.
1838 As a special case, call this an error. Warn and ignore. */
1840 "Linelist option '%s' has no value. Skipping.", c
->key
);
1841 } else { /* not already cleared */
1842 option_reset(fmt
, options
, var
, use_defaults
);
1848 if (options_seen
&& (var
->type
!= CONFIG_TYPE_LINELIST
&&
1849 var
->type
!= CONFIG_TYPE_LINELIST_S
)) {
1850 /* We're tracking which options we've seen, and this option is not
1851 * supposed to occur more than once. */
1852 int var_index
= (int)(var
- fmt
->vars
);
1853 if (bitarray_is_set(options_seen
, var_index
)) {
1854 log_warn(LD_CONFIG
, "Option '%s' used more than once; all but the last "
1855 "value will be ignored.", var
->name
);
1857 bitarray_set(options_seen
, var_index
);
1860 if (config_assign_value(fmt
, options
, c
, msg
) < 0)
1865 /** Restore the option named <b>key</b> in options to its default value.
1866 * Called from config_assign(). */
1868 config_reset_line(config_format_t
*fmt
, or_options_t
*options
,
1869 const char *key
, int use_defaults
)
1873 CHECK(fmt
, options
);
1875 var
= config_find_option(fmt
, key
);
1877 return; /* give error on next pass. */
1879 option_reset(fmt
, options
, var
, use_defaults
);
1882 /** Return true iff key is a valid configuration option. */
1884 option_is_recognized(const char *key
)
1886 config_var_t
*var
= config_find_option(&options_format
, key
);
1887 return (var
!= NULL
);
1890 /** Return the canonical name of a configuration option, or NULL
1891 * if no such option exists. */
1893 option_get_canonical_name(const char *key
)
1895 config_var_t
*var
= config_find_option(&options_format
, key
);
1896 return var
? var
->name
: NULL
;
1899 /** Return a canonical list of the options assigned for key.
1902 option_get_assignment(or_options_t
*options
, const char *key
)
1904 return get_assigned_option(&options_format
, options
, key
, 1);
1907 /** Return true iff value needs to be quoted and escaped to be used in
1908 * a configuration file. */
1910 config_value_needs_escape(const char *value
)
1920 /* Note: quotes and backspaces need special handling when we are using
1921 * quotes, not otherwise, so they don't trigger escaping on their
1925 if (!TOR_ISPRINT(*value
))
1933 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1934 static config_line_t
*
1935 config_lines_dup(const config_line_t
*inp
)
1937 config_line_t
*result
= NULL
;
1938 config_line_t
**next_out
= &result
;
1940 *next_out
= tor_malloc(sizeof(config_line_t
));
1941 (*next_out
)->key
= tor_strdup(inp
->key
);
1942 (*next_out
)->value
= tor_strdup(inp
->value
);
1944 next_out
= &((*next_out
)->next
);
1950 /** Return newly allocated line or lines corresponding to <b>key</b> in the
1951 * configuration <b>options</b>. If <b>escape_val</b> is true and a
1952 * value needs to be quoted before it's put in a config file, quote and
1953 * escape that value. Return NULL if no such key exists. */
1954 static config_line_t
*
1955 get_assigned_option(config_format_t
*fmt
, void *options
,
1956 const char *key
, int escape_val
)
1960 config_line_t
*result
;
1961 tor_assert(options
&& key
);
1963 CHECK(fmt
, options
);
1965 var
= config_find_option(fmt
, key
);
1967 log_warn(LD_CONFIG
, "Unknown option '%s'. Failing.", key
);
1970 value
= STRUCT_VAR_P(options
, var
->var_offset
);
1972 result
= tor_malloc_zero(sizeof(config_line_t
));
1973 result
->key
= tor_strdup(var
->name
);
1976 case CONFIG_TYPE_STRING
:
1977 case CONFIG_TYPE_FILENAME
:
1978 if (*(char**)value
) {
1979 result
->value
= tor_strdup(*(char**)value
);
1981 tor_free(result
->key
);
1986 case CONFIG_TYPE_ISOTIME
:
1987 if (*(time_t*)value
) {
1988 result
->value
= tor_malloc(ISO_TIME_LEN
+1);
1989 format_iso_time(result
->value
, *(time_t*)value
);
1991 tor_free(result
->key
);
1994 escape_val
= 0; /* Can't need escape. */
1996 case CONFIG_TYPE_INTERVAL
:
1997 case CONFIG_TYPE_UINT
:
1998 /* This means every or_options_t uint or bool element
1999 * needs to be an int. Not, say, a uint16_t or char. */
2000 tor_asprintf(&result
->value
, "%d", *(int*)value
);
2001 escape_val
= 0; /* Can't need escape. */
2003 case CONFIG_TYPE_MEMUNIT
:
2004 tor_asprintf(&result
->value
, U64_FORMAT
,
2005 U64_PRINTF_ARG(*(uint64_t*)value
));
2006 escape_val
= 0; /* Can't need escape. */
2008 case CONFIG_TYPE_DOUBLE
:
2009 tor_asprintf(&result
->value
, "%f", *(double*)value
);
2010 escape_val
= 0; /* Can't need escape. */
2012 case CONFIG_TYPE_BOOL
:
2013 result
->value
= tor_strdup(*(int*)value
? "1" : "0");
2014 escape_val
= 0; /* Can't need escape. */
2016 case CONFIG_TYPE_ROUTERSET
:
2017 result
->value
= routerset_to_string(*(routerset_t
**)value
);
2019 case CONFIG_TYPE_CSV
:
2020 if (*(smartlist_t
**)value
)
2022 smartlist_join_strings(*(smartlist_t
**)value
, ",", 0, NULL
);
2024 result
->value
= tor_strdup("");
2026 case CONFIG_TYPE_OBSOLETE
:
2027 log_fn(LOG_PROTOCOL_WARN
, LD_CONFIG
,
2028 "You asked me for the value of an obsolete config option '%s'.",
2030 tor_free(result
->key
);
2033 case CONFIG_TYPE_LINELIST_S
:
2035 "Can't return context-sensitive '%s' on its own", key
);
2036 tor_free(result
->key
);
2039 case CONFIG_TYPE_LINELIST
:
2040 case CONFIG_TYPE_LINELIST_V
:
2041 tor_free(result
->key
);
2043 result
= config_lines_dup(*(const config_line_t
**)value
);
2046 tor_free(result
->key
);
2048 log_warn(LD_BUG
,"Unknown type %d for known key '%s'",
2054 config_line_t
*line
;
2055 for (line
= result
; line
; line
= line
->next
) {
2056 if (line
->value
&& config_value_needs_escape(line
->value
)) {
2057 char *newval
= esc_for_log(line
->value
);
2058 tor_free(line
->value
);
2059 line
->value
= newval
;
2067 /** Iterate through the linked list of requested options <b>list</b>.
2068 * For each item, convert as appropriate and assign to <b>options</b>.
2069 * If an item is unrecognized, set *msg and return -1 immediately,
2070 * else return 0 for success.
2072 * If <b>clear_first</b>, interpret config options as replacing (not
2073 * extending) their previous values. If <b>clear_first</b> is set,
2074 * then <b>use_defaults</b> to decide if you set to defaults after
2075 * clearing, or make the value 0 or NULL.
2077 * Here are the use cases:
2078 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
2079 * if linelist, replaces current if csv.
2080 * 2. An empty AllowInvalid line in your torrc. Should clear it.
2081 * 3. "RESETCONF AllowInvalid" sets it to default.
2082 * 4. "SETCONF AllowInvalid" makes it NULL.
2083 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
2085 * Use_defaults Clear_first
2087 * 1 0 undefined, don't use
2088 * 0 1 "set to null first"
2089 * 1 1 "set to defaults first"
2090 * Return 0 on success, -1 on bad key, -2 on bad value.
2092 * As an additional special case, if a LINELIST config option has
2093 * no value and clear_first is 0, then warn and ignore it.
2097 There are three call cases for config_assign() currently.
2099 Case one: Torrc entry
2100 options_init_from_torrc() calls config_assign(0, 0)
2101 calls config_assign_line(0, 0).
2102 if value is empty, calls option_reset(0) and returns.
2103 calls config_assign_value(), appends.
2106 options_trial_assign() calls config_assign(0, 1)
2107 calls config_reset_line(0)
2108 calls option_reset(0)
2109 calls option_clear().
2110 calls config_assign_line(0, 1).
2111 if value is empty, returns.
2112 calls config_assign_value(), appends.
2114 Case three: resetconf
2115 options_trial_assign() calls config_assign(1, 1)
2116 calls config_reset_line(1)
2117 calls option_reset(1)
2118 calls option_clear().
2119 calls config_assign_value(default)
2120 calls config_assign_line(1, 1).
2124 config_assign(config_format_t
*fmt
, void *options
, config_line_t
*list
,
2125 int use_defaults
, int clear_first
, char **msg
)
2128 bitarray_t
*options_seen
;
2129 const int n_options
= config_count_options(fmt
);
2131 CHECK(fmt
, options
);
2133 /* pass 1: normalize keys */
2134 for (p
= list
; p
; p
= p
->next
) {
2135 const char *full
= expand_abbrev(fmt
, p
->key
, 0, 1);
2136 if (strcmp(full
,p
->key
)) {
2138 p
->key
= tor_strdup(full
);
2142 /* pass 2: if we're reading from a resetting source, clear all
2143 * mentioned config options, and maybe set to their defaults. */
2145 for (p
= list
; p
; p
= p
->next
)
2146 config_reset_line(fmt
, options
, p
->key
, use_defaults
);
2149 options_seen
= bitarray_init_zero(n_options
);
2150 /* pass 3: assign. */
2153 if ((r
=config_assign_line(fmt
, options
, list
, use_defaults
,
2154 clear_first
, options_seen
, msg
))) {
2155 bitarray_free(options_seen
);
2160 bitarray_free(options_seen
);
2164 /** Try assigning <b>list</b> to the global options. You do this by duping
2165 * options, assigning list to the new one, then validating it. If it's
2166 * ok, then throw out the old one and stick with the new one. Else,
2167 * revert to old and return failure. Return SETOPT_OK on success, or
2168 * a setopt_err_t on failure.
2170 * If not success, point *<b>msg</b> to a newly allocated string describing
2174 options_trial_assign(config_line_t
*list
, int use_defaults
,
2175 int clear_first
, char **msg
)
2178 or_options_t
*trial_options
= options_dup(&options_format
, get_options());
2180 if ((r
=config_assign(&options_format
, trial_options
,
2181 list
, use_defaults
, clear_first
, msg
)) < 0) {
2182 config_free(&options_format
, trial_options
);
2186 if (options_validate(get_options(), trial_options
, 1, msg
) < 0) {
2187 config_free(&options_format
, trial_options
);
2188 return SETOPT_ERR_PARSE
; /*XXX make this a separate return value. */
2191 if (options_transition_allowed(get_options(), trial_options
, msg
) < 0) {
2192 config_free(&options_format
, trial_options
);
2193 return SETOPT_ERR_TRANSITION
;
2196 if (set_options(trial_options
, msg
)<0) {
2197 config_free(&options_format
, trial_options
);
2198 return SETOPT_ERR_SETTING
;
2201 /* we liked it. put it in place. */
2205 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2206 * Called from option_reset() and config_free(). */
2208 option_clear(config_format_t
*fmt
, or_options_t
*options
, config_var_t
*var
)
2210 void *lvalue
= STRUCT_VAR_P(options
, var
->var_offset
);
2211 (void)fmt
; /* unused */
2212 switch (var
->type
) {
2213 case CONFIG_TYPE_STRING
:
2214 case CONFIG_TYPE_FILENAME
:
2215 tor_free(*(char**)lvalue
);
2217 case CONFIG_TYPE_DOUBLE
:
2218 *(double*)lvalue
= 0.0;
2220 case CONFIG_TYPE_ISOTIME
:
2221 *(time_t*)lvalue
= 0;
2223 case CONFIG_TYPE_INTERVAL
:
2224 case CONFIG_TYPE_UINT
:
2225 case CONFIG_TYPE_BOOL
:
2228 case CONFIG_TYPE_MEMUNIT
:
2229 *(uint64_t*)lvalue
= 0;
2231 case CONFIG_TYPE_ROUTERSET
:
2232 if (*(routerset_t
**)lvalue
) {
2233 routerset_free(*(routerset_t
**)lvalue
);
2234 *(routerset_t
**)lvalue
= NULL
;
2237 case CONFIG_TYPE_CSV
:
2238 if (*(smartlist_t
**)lvalue
) {
2239 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
2240 smartlist_free(*(smartlist_t
**)lvalue
);
2241 *(smartlist_t
**)lvalue
= NULL
;
2244 case CONFIG_TYPE_LINELIST
:
2245 case CONFIG_TYPE_LINELIST_S
:
2246 config_free_lines(*(config_line_t
**)lvalue
);
2247 *(config_line_t
**)lvalue
= NULL
;
2249 case CONFIG_TYPE_LINELIST_V
:
2250 /* handled by linelist_s. */
2252 case CONFIG_TYPE_OBSOLETE
:
2257 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2258 * <b>use_defaults</b>, set it to its default value.
2259 * Called by config_init() and option_reset_line() and option_assign_line(). */
2261 option_reset(config_format_t
*fmt
, or_options_t
*options
,
2262 config_var_t
*var
, int use_defaults
)
2266 CHECK(fmt
, options
);
2267 option_clear(fmt
, options
, var
); /* clear it first */
2269 return; /* all done */
2270 if (var
->initvalue
) {
2271 c
= tor_malloc_zero(sizeof(config_line_t
));
2272 c
->key
= tor_strdup(var
->name
);
2273 c
->value
= tor_strdup(var
->initvalue
);
2274 if (config_assign_value(fmt
, options
, c
, &msg
) < 0) {
2275 log_warn(LD_BUG
, "Failed to assign default: %s", msg
);
2276 tor_free(msg
); /* if this happens it's a bug */
2278 config_free_lines(c
);
2282 /** Print a usage message for tor. */
2287 "Copyright (c) 2001-2004, Roger Dingledine\n"
2288 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2289 "Copyright (c) 2007-2011, The Tor Project, Inc.\n\n"
2290 "tor -f <torrc> [args]\n"
2291 "See man page for options, or https://www.torproject.org/ for "
2292 "documentation.\n");
2295 /** Print all non-obsolete torrc options. */
2297 list_torrc_options(void)
2300 smartlist_t
*lines
= smartlist_create();
2301 for (i
= 0; _option_vars
[i
].name
; ++i
) {
2302 config_var_t
*var
= &_option_vars
[i
];
2303 if (var
->type
== CONFIG_TYPE_OBSOLETE
||
2304 var
->type
== CONFIG_TYPE_LINELIST_V
)
2306 printf("%s\n", var
->name
);
2308 smartlist_free(lines
);
2311 /** Last value actually set by resolve_my_address. */
2312 static uint32_t last_resolved_addr
= 0;
2314 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2315 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2316 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2317 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2318 * public IP address.
2321 resolve_my_address(int warn_severity
, or_options_t
*options
,
2322 uint32_t *addr_out
, char **hostname_out
)
2325 uint32_t addr
; /* host order */
2328 int explicit_hostname
=1;
2329 int from_interface
=0;
2330 char tmpbuf
[INET_NTOA_BUF_LEN
];
2331 const char *address
= options
->Address
;
2332 int notice_severity
= warn_severity
<= LOG_NOTICE
?
2333 LOG_NOTICE
: warn_severity
;
2335 tor_assert(addr_out
);
2337 if (address
&& *address
) {
2338 strlcpy(hostname
, address
, sizeof(hostname
));
2339 } else { /* then we need to guess our address */
2340 explicit_ip
= 0; /* it's implicit */
2341 explicit_hostname
= 0; /* it's implicit */
2343 if (gethostname(hostname
, sizeof(hostname
)) < 0) {
2344 log_fn(warn_severity
, LD_NET
,"Error obtaining local hostname");
2347 log_debug(LD_CONFIG
,"Guessed local host name as '%s'",hostname
);
2350 /* now we know hostname. resolve it and keep only the IP address */
2352 if (tor_inet_aton(hostname
, &in
) == 0) {
2353 /* then we have to resolve it */
2355 if (tor_lookup_hostname(hostname
, &addr
)) { /* failed to resolve */
2356 uint32_t interface_ip
; /* host order */
2358 if (explicit_hostname
) {
2359 log_fn(warn_severity
, LD_CONFIG
,
2360 "Could not resolve local Address '%s'. Failing.", hostname
);
2363 log_fn(notice_severity
, LD_CONFIG
,
2364 "Could not resolve guessed local hostname '%s'. "
2365 "Trying something else.", hostname
);
2366 if (get_interface_address(warn_severity
, &interface_ip
)) {
2367 log_fn(warn_severity
, LD_CONFIG
,
2368 "Could not get local interface IP address. Failing.");
2372 in
.s_addr
= htonl(interface_ip
);
2373 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2374 log_fn(notice_severity
, LD_CONFIG
, "Learned IP address '%s' for "
2375 "local interface. Using that.", tmpbuf
);
2376 strlcpy(hostname
, "<guessed from interfaces>", sizeof(hostname
));
2377 } else { /* resolved hostname into addr */
2378 in
.s_addr
= htonl(addr
);
2380 if (!explicit_hostname
&&
2381 is_internal_IP(ntohl(in
.s_addr
), 0)) {
2382 uint32_t interface_ip
;
2384 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2385 log_fn(notice_severity
, LD_CONFIG
, "Guessed local hostname '%s' "
2386 "resolves to a private IP address (%s). Trying something "
2387 "else.", hostname
, tmpbuf
);
2389 if (get_interface_address(warn_severity
, &interface_ip
)) {
2390 log_fn(warn_severity
, LD_CONFIG
,
2391 "Could not get local interface IP address. Too bad.");
2392 } else if (is_internal_IP(interface_ip
, 0)) {
2394 in2
.s_addr
= htonl(interface_ip
);
2395 tor_inet_ntoa(&in2
,tmpbuf
,sizeof(tmpbuf
));
2396 log_fn(notice_severity
, LD_CONFIG
,
2397 "Interface IP address '%s' is a private address too. "
2398 "Ignoring.", tmpbuf
);
2401 in
.s_addr
= htonl(interface_ip
);
2402 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2403 log_fn(notice_severity
, LD_CONFIG
,
2404 "Learned IP address '%s' for local interface."
2405 " Using that.", tmpbuf
);
2406 strlcpy(hostname
, "<guessed from interfaces>", sizeof(hostname
));
2412 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2413 if (is_internal_IP(ntohl(in
.s_addr
), 0)) {
2414 /* make sure we're ok with publishing an internal IP */
2415 if (!options
->DirServers
&& !options
->AlternateDirAuthority
) {
2416 /* if they are using the default dirservers, disallow internal IPs
2418 log_fn(warn_severity
, LD_CONFIG
,
2419 "Address '%s' resolves to private IP address '%s'. "
2420 "Tor servers that use the default DirServers must have public "
2421 "IP addresses.", hostname
, tmpbuf
);
2425 /* even if they've set their own dirservers, require an explicit IP if
2426 * they're using an internal address. */
2427 log_fn(warn_severity
, LD_CONFIG
, "Address '%s' resolves to private "
2428 "IP address '%s'. Please set the Address config option to be "
2429 "the IP address you want to use.", hostname
, tmpbuf
);
2434 log_debug(LD_CONFIG
, "Resolved Address to '%s'.", tmpbuf
);
2435 *addr_out
= ntohl(in
.s_addr
);
2436 if (last_resolved_addr
&& last_resolved_addr
!= *addr_out
) {
2437 /* Leave this as a notice, regardless of the requested severity,
2438 * at least until dynamic IP address support becomes bulletproof. */
2440 "Your IP address seems to have changed to %s. Updating.",
2442 ip_address_changed(0);
2444 if (last_resolved_addr
!= *addr_out
) {
2446 const char *h
= hostname
;
2448 method
= "CONFIGURED";
2450 } else if (explicit_hostname
) {
2451 method
= "RESOLVED";
2452 } else if (from_interface
) {
2453 method
= "INTERFACE";
2456 method
= "GETHOSTNAME";
2458 control_event_server_status(LOG_NOTICE
,
2459 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2460 tmpbuf
, method
, h
?"HOSTNAME=":"", h
);
2462 last_resolved_addr
= *addr_out
;
2464 *hostname_out
= tor_strdup(hostname
);
2468 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2469 * on a private network.
2472 is_local_addr(const tor_addr_t
*addr
)
2474 if (tor_addr_is_internal(addr
, 0))
2476 /* Check whether ip is on the same /24 as we are. */
2477 if (get_options()->EnforceDistinctSubnets
== 0)
2479 if (tor_addr_family(addr
) == AF_INET
) {
2480 /*XXXX022 IP6 what corresponds to an /24? */
2481 uint32_t ip
= tor_addr_to_ipv4h(addr
);
2483 /* It's possible that this next check will hit before the first time
2484 * resolve_my_address actually succeeds. (For clients, it is likely that
2485 * resolve_my_address will never be called at all). In those cases,
2486 * last_resolved_addr will be 0, and so checking to see whether ip is on
2487 * the same /24 as last_resolved_addr will be the same as checking whether
2488 * it was on net 0, which is already done by is_internal_IP.
2490 if ((last_resolved_addr
& (uint32_t)0xffffff00ul
)
2491 == (ip
& (uint32_t)0xffffff00ul
))
2497 /** Called when we don't have a nickname set. Try to guess a good nickname
2498 * based on the hostname, and return it in a newly allocated string. If we
2499 * can't, return NULL and let the caller warn if it wants to. */
2501 get_default_nickname(void)
2503 static const char * const bad_default_nicknames
[] = {
2507 char localhostname
[256];
2508 char *cp
, *out
, *outp
;
2511 if (gethostname(localhostname
, sizeof(localhostname
)) < 0)
2514 /* Put it in lowercase; stop at the first dot. */
2515 if ((cp
= strchr(localhostname
, '.')))
2517 tor_strlower(localhostname
);
2519 /* Strip invalid characters. */
2521 out
= outp
= tor_malloc(strlen(localhostname
) + 1);
2523 if (strchr(LEGAL_NICKNAME_CHARACTERS
, *cp
))
2530 /* Enforce length. */
2531 if (strlen(out
) > MAX_NICKNAME_LEN
)
2532 out
[MAX_NICKNAME_LEN
]='\0';
2534 /* Check for dumb names. */
2535 for (i
= 0; bad_default_nicknames
[i
]; ++i
) {
2536 if (!strcmp(out
, bad_default_nicknames
[i
])) {
2545 /** Release storage held by <b>options</b>. */
2547 config_free(config_format_t
*fmt
, void *options
)
2556 for (i
=0; fmt
->vars
[i
].name
; ++i
)
2557 option_clear(fmt
, options
, &(fmt
->vars
[i
]));
2559 config_line_t
**linep
= STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
2560 config_free_lines(*linep
);
2566 /** Return true iff a and b contain identical keys and values in identical
2569 config_lines_eq(config_line_t
*a
, config_line_t
*b
)
2572 if (strcasecmp(a
->key
, b
->key
) || strcmp(a
->value
, b
->value
))
2582 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2583 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2586 option_is_same(config_format_t
*fmt
,
2587 or_options_t
*o1
, or_options_t
*o2
, const char *name
)
2589 config_line_t
*c1
, *c2
;
2594 c1
= get_assigned_option(fmt
, o1
, name
, 0);
2595 c2
= get_assigned_option(fmt
, o2
, name
, 0);
2596 r
= config_lines_eq(c1
, c2
);
2597 config_free_lines(c1
);
2598 config_free_lines(c2
);
2602 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2603 static or_options_t
*
2604 options_dup(config_format_t
*fmt
, or_options_t
*old
)
2606 or_options_t
*newopts
;
2608 config_line_t
*line
;
2610 newopts
= config_alloc(fmt
);
2611 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2612 if (fmt
->vars
[i
].type
== CONFIG_TYPE_LINELIST_S
)
2614 if (fmt
->vars
[i
].type
== CONFIG_TYPE_OBSOLETE
)
2616 line
= get_assigned_option(fmt
, old
, fmt
->vars
[i
].name
, 0);
2619 if (config_assign(fmt
, newopts
, line
, 0, 0, &msg
) < 0) {
2620 log_err(LD_BUG
, "Config_get_assigned_option() generated "
2621 "something we couldn't config_assign(): %s", msg
);
2626 config_free_lines(line
);
2631 /** Return a new empty or_options_t. Used for testing. */
2635 return config_alloc(&options_format
);
2638 /** Set <b>options</b> to hold reasonable defaults for most options.
2639 * Each option defaults to zero. */
2641 options_init(or_options_t
*options
)
2643 config_init(&options_format
, options
);
2646 /* Check if the port number given in <b>port_option</b> in combination with
2647 * the specified port in <b>listen_options</b> will result in Tor actually
2648 * opening a low port (meaning a port lower than 1024). Return 1 if
2649 * it is, or 0 if it isn't or the concept of a low port isn't applicable for
2650 * the platform we're on. */
2652 is_listening_on_low_port(uint16_t port_option
,
2653 const config_line_t
*listen_options
)
2657 (void) listen_options
;
2658 return 0; /* No port is too low for windows. */
2660 const config_line_t
*l
;
2662 if (port_option
== 0)
2663 return 0; /* We're not listening */
2664 if (listen_options
== NULL
)
2665 return (port_option
< 1024);
2667 for (l
= listen_options
; l
; l
= l
->next
) {
2668 parse_addr_port(LOG_WARN
, l
->value
, NULL
, NULL
, &p
);
2677 /** Set all vars in the configuration object <b>options</b> to their default
2680 config_init(config_format_t
*fmt
, void *options
)
2684 CHECK(fmt
, options
);
2686 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2687 var
= &fmt
->vars
[i
];
2688 if (!var
->initvalue
)
2689 continue; /* defaults to NULL or 0 */
2690 option_reset(fmt
, options
, var
, 1);
2694 /** Allocate and return a new string holding the written-out values of the vars
2695 * in 'options'. If 'minimal', do not write out any default-valued vars.
2696 * Else, if comment_defaults, write default values as comments.
2699 config_dump(config_format_t
*fmt
, void *options
, int minimal
,
2700 int comment_defaults
)
2702 smartlist_t
*elements
;
2703 or_options_t
*defaults
;
2704 config_line_t
*line
, *assigned
;
2709 defaults
= config_alloc(fmt
);
2710 config_init(fmt
, defaults
);
2712 /* XXX use a 1 here so we don't add a new log line while dumping */
2713 if (fmt
->validate_fn(NULL
,defaults
, 1, &msg
) < 0) {
2714 log_err(LD_BUG
, "Failed to validate default config.");
2719 elements
= smartlist_create();
2720 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2721 int comment_option
= 0;
2722 if (fmt
->vars
[i
].type
== CONFIG_TYPE_OBSOLETE
||
2723 fmt
->vars
[i
].type
== CONFIG_TYPE_LINELIST_S
)
2725 /* Don't save 'hidden' control variables. */
2726 if (!strcmpstart(fmt
->vars
[i
].name
, "__"))
2728 if (minimal
&& option_is_same(fmt
, options
, defaults
, fmt
->vars
[i
].name
))
2730 else if (comment_defaults
&&
2731 option_is_same(fmt
, options
, defaults
, fmt
->vars
[i
].name
))
2734 line
= assigned
= get_assigned_option(fmt
, options
, fmt
->vars
[i
].name
, 1);
2736 for (; line
; line
= line
->next
) {
2738 tor_asprintf(&tmp
, "%s%s %s\n",
2739 comment_option
? "# " : "",
2740 line
->key
, line
->value
);
2741 smartlist_add(elements
, tmp
);
2743 config_free_lines(assigned
);
2747 line
= *(config_line_t
**)STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
2748 for (; line
; line
= line
->next
) {
2750 tor_asprintf(&tmp
, "%s %s\n", line
->key
, line
->value
);
2751 smartlist_add(elements
, tmp
);
2755 result
= smartlist_join_strings(elements
, "", 0, NULL
);
2756 SMARTLIST_FOREACH(elements
, char *, cp
, tor_free(cp
));
2757 smartlist_free(elements
);
2758 config_free(fmt
, defaults
);
2762 /** Return a string containing a possible configuration file that would give
2763 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2764 * include options that are the same as Tor's defaults.
2767 options_dump(or_options_t
*options
, int minimal
)
2769 return config_dump(&options_format
, options
, minimal
, 0);
2772 /** Return 0 if every element of sl is a string holding a decimal
2773 * representation of a port number, or if sl is NULL.
2774 * Otherwise set *msg and return -1. */
2776 validate_ports_csv(smartlist_t
*sl
, const char *name
, char **msg
)
2784 SMARTLIST_FOREACH(sl
, const char *, cp
,
2787 if (i
< 1 || i
> 65535) {
2788 tor_asprintf(msg
, "Port '%s' out of range in %s", cp
, name
);
2795 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2796 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2800 ensure_bandwidth_cap(uint64_t *value
, const char *desc
, char **msg
)
2802 if (*value
> ROUTER_MAX_DECLARED_BANDWIDTH
) {
2803 /* This handles an understandable special case where somebody says "2gb"
2804 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2807 if (*value
> ROUTER_MAX_DECLARED_BANDWIDTH
) {
2808 tor_asprintf(msg
, "%s ("U64_FORMAT
") must be at most %d",
2809 desc
, U64_PRINTF_ARG(*value
),
2810 ROUTER_MAX_DECLARED_BANDWIDTH
);
2816 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2817 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2818 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2820 * Return 0 on success or -1 if not a recognized authority type (in which
2821 * case the value of _PublishServerDescriptor is undefined). */
2823 compute_publishserverdescriptor(or_options_t
*options
)
2825 smartlist_t
*list
= options
->PublishServerDescriptor
;
2826 authority_type_t
*auth
= &options
->_PublishServerDescriptor
;
2827 *auth
= NO_AUTHORITY
;
2828 if (!list
) /* empty list, answer is none */
2830 SMARTLIST_FOREACH(list
, const char *, string
, {
2831 if (!strcasecmp(string
, "v1"))
2832 *auth
|= V1_AUTHORITY
;
2833 else if (!strcmp(string
, "1"))
2834 if (options
->BridgeRelay
)
2835 *auth
|= BRIDGE_AUTHORITY
;
2837 *auth
|= V2_AUTHORITY
| V3_AUTHORITY
;
2838 else if (!strcasecmp(string
, "v2"))
2839 *auth
|= V2_AUTHORITY
;
2840 else if (!strcasecmp(string
, "v3"))
2841 *auth
|= V3_AUTHORITY
;
2842 else if (!strcasecmp(string
, "bridge"))
2843 *auth
|= BRIDGE_AUTHORITY
;
2844 else if (!strcasecmp(string
, "hidserv"))
2846 "PublishServerDescriptor hidserv is invalid. See "
2847 "PublishHidServDescriptors.");
2848 else if (!strcasecmp(string
, "") || !strcmp(string
, "0"))
2856 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2857 * services can overload the directory system. */
2858 #define MIN_REND_POST_PERIOD (10*60)
2860 /** Highest allowable value for RendPostPeriod. */
2861 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2863 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2864 * will generate too many circuits and potentially overload the network. */
2865 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2867 /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
2868 * will generate too many circuits and potentially overload the network. */
2869 #define MIN_CIRCUIT_STREAM_TIMEOUT 10
2871 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2872 * permissible transition from <b>old_options</b>. Else return -1.
2873 * Should have no side effects, except for normalizing the contents of
2876 * On error, tor_strdup an error explanation into *<b>msg</b>.
2879 * If <b>from_setconf</b>, we were called by the controller, and our
2880 * Log line should stay empty. If it's 0, then give us a default log
2881 * if there are no logs defined.
2884 options_validate(or_options_t
*old_options
, or_options_t
*options
,
2885 int from_setconf
, char **msg
)
2889 const char *uname
= get_uname();
2890 #define REJECT(arg) \
2891 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2892 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2897 if (options
->ORPort
< 0 || options
->ORPort
> 65535)
2898 REJECT("ORPort option out of bounds.");
2900 if (server_mode(options
) &&
2901 (!strcmpstart(uname
, "Windows 95") ||
2902 !strcmpstart(uname
, "Windows 98") ||
2903 !strcmpstart(uname
, "Windows Me"))) {
2904 log(LOG_WARN
, LD_CONFIG
, "Tor is running as a server, but you are "
2905 "running %s; this probably won't work. See "
2906 "https://wiki.torproject.org/TheOnionRouter/TorFAQ#ServerOS "
2907 "for details.", uname
);
2910 if (options
->ORPort
== 0 && options
->ORListenAddress
!= NULL
)
2911 REJECT("ORPort must be defined if ORListenAddress is defined.");
2913 if (options
->DirPort
== 0 && options
->DirListenAddress
!= NULL
)
2914 REJECT("DirPort must be defined if DirListenAddress is defined.");
2916 if (options
->DNSPort
== 0 && options
->DNSListenAddress
!= NULL
)
2917 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
2919 if (options
->ControlPort
== 0 && options
->ControlListenAddress
!= NULL
)
2920 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
2922 if (options
->TransPort
== 0 && options
->TransListenAddress
!= NULL
)
2923 REJECT("TransPort must be defined if TransListenAddress is defined.");
2925 if (options
->NATDPort
== 0 && options
->NATDListenAddress
!= NULL
)
2926 REJECT("NATDPort must be defined if NATDListenAddress is defined.");
2928 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
2929 * configuration does this. */
2931 for (i
= 0; i
< 3; ++i
) {
2932 int is_socks
= i
==0;
2933 int is_trans
= i
==1;
2934 config_line_t
*line
, *opt
, *old
;
2937 opt
= options
->SocksListenAddress
;
2938 old
= old_options
? old_options
->SocksListenAddress
: NULL
;
2940 } else if (is_trans
) {
2941 opt
= options
->TransListenAddress
;
2942 old
= old_options
? old_options
->TransListenAddress
: NULL
;
2943 tp
= "transparent proxy";
2945 opt
= options
->NATDListenAddress
;
2946 old
= old_options
? old_options
->NATDListenAddress
: NULL
;
2950 for (line
= opt
; line
; line
= line
->next
) {
2951 char *address
= NULL
;
2954 if (parse_addr_port(LOG_WARN
, line
->value
, &address
, &addr
, &port
)<0)
2955 continue; /* We'll warn about this later. */
2956 if (!is_internal_IP(addr
, 1) &&
2957 (!old_options
|| !config_lines_eq(old
, opt
))) {
2959 "You specified a public address '%s' for a %s. Other "
2960 "people on the Internet might find your computer and use it as "
2961 "an open %s. Please don't allow this unless you have "
2962 "a good reason.", address
, tp
, tp
);
2968 if (validate_data_directory(options
)<0)
2969 REJECT("Invalid DataDirectory");
2971 if (options
->Nickname
== NULL
) {
2972 if (server_mode(options
)) {
2973 if (!(options
->Nickname
= get_default_nickname())) {
2974 log_notice(LD_CONFIG
, "Couldn't pick a nickname based on "
2975 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME
);
2976 options
->Nickname
= tor_strdup(UNNAMED_ROUTER_NICKNAME
);
2978 log_notice(LD_CONFIG
, "Choosing default nickname '%s'",
2983 if (!is_legal_nickname(options
->Nickname
)) {
2985 "Nickname '%s' is wrong length or contains illegal characters.",
2991 if (server_mode(options
) && !options
->ContactInfo
)
2992 log(LOG_NOTICE
, LD_CONFIG
, "Your ContactInfo config option is not set. "
2993 "Please consider setting it, so we can contact you if your server is "
2994 "misconfigured or something else goes wrong.");
2996 /* Special case on first boot if no Log options are given. */
2997 if (!options
->Logs
&& !options
->RunAsDaemon
&& !from_setconf
)
2998 config_line_append(&options
->Logs
, "Log", "notice stdout");
3000 if (options_init_logs(options
, 1)<0) /* Validate the log(s) */
3001 REJECT("Failed to validate Log options. See logs for details.");
3003 if (authdir_mode(options
)) {
3004 /* confirm that our address isn't broken, so we can complain now */
3006 if (resolve_my_address(LOG_WARN
, options
, &tmp
, NULL
) < 0)
3007 REJECT("Failed to resolve/guess local address. See logs for details.");
3010 if (strcmp(options
->RefuseUnknownExits
, "0") &&
3011 strcmp(options
->RefuseUnknownExits
, "1") &&
3012 strcmp(options
->RefuseUnknownExits
, "auto")) {
3013 REJECT("RefuseUnknownExits must be 0, 1, or auto");
3017 if (options
->RunAsDaemon
&& torrc_fname
&& path_is_relative(torrc_fname
))
3018 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
3021 if (options
->SocksPort
< 0 || options
->SocksPort
> 65535)
3022 REJECT("SocksPort option out of bounds.");
3024 if (options
->DNSPort
< 0 || options
->DNSPort
> 65535)
3025 REJECT("DNSPort option out of bounds.");
3027 if (options
->TransPort
< 0 || options
->TransPort
> 65535)
3028 REJECT("TransPort option out of bounds.");
3030 if (options
->NATDPort
< 0 || options
->NATDPort
> 65535)
3031 REJECT("NATDPort option out of bounds.");
3033 if (options
->SocksPort
== 0 && options
->TransPort
== 0 &&
3034 options
->NATDPort
== 0 && options
->ORPort
== 0 &&
3035 options
->DNSPort
== 0 && !options
->RendConfigLines
)
3036 log(LOG_WARN
, LD_CONFIG
,
3037 "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
3038 "undefined, and there aren't any hidden services configured. "
3039 "Tor will still run, but probably won't do anything.");
3041 if (options
->ControlPort
< 0 || options
->ControlPort
> 65535)
3042 REJECT("ControlPort option out of bounds.");
3044 if (options
->DirPort
< 0 || options
->DirPort
> 65535)
3045 REJECT("DirPort option out of bounds.");
3047 #ifndef USE_TRANSPARENT
3048 if (options
->TransPort
|| options
->TransListenAddress
)
3049 REJECT("TransPort and TransListenAddress are disabled in this build.");
3052 if (options
->AccountingMax
&&
3053 (is_listening_on_low_port(options
->ORPort
, options
->ORListenAddress
) ||
3054 is_listening_on_low_port(options
->DirPort
, options
->DirListenAddress
)))
3056 log(LOG_WARN
, LD_CONFIG
,
3057 "You have set AccountingMax to use hibernation. You have also "
3058 "chosen a low DirPort or OrPort. This combination can make Tor stop "
3059 "working when it tries to re-attach the port after a period of "
3060 "hibernation. Please choose a different port or turn off "
3061 "hibernation unless you know this combination will work on your "
3065 if (options
->ExcludeExitNodes
|| options
->ExcludeNodes
) {
3066 options
->_ExcludeExitNodesUnion
= routerset_new();
3067 routerset_union(options
->_ExcludeExitNodesUnion
,options
->ExcludeExitNodes
);
3068 routerset_union(options
->_ExcludeExitNodesUnion
,options
->ExcludeNodes
);
3071 if (options
->ExcludeNodes
&& options
->StrictNodes
) {
3072 COMPLAIN("You have asked to exclude certain relays from all positions "
3073 "in your circuits. Expect hidden services and other Tor "
3074 "features to be broken in unpredictable ways.");
3077 if (options
->EntryNodes
&& !routerset_is_list(options
->EntryNodes
)) {
3078 /* XXXX fix this; see entry_guards_prepend_from_config(). */
3079 REJECT("IPs or countries are not yet supported in EntryNodes.");
3082 if (options
->AuthoritativeDir
) {
3083 if (!options
->ContactInfo
&& !options
->TestingTorNetwork
)
3084 REJECT("Authoritative directory servers must set ContactInfo");
3085 if (options
->V1AuthoritativeDir
&& !options
->RecommendedVersions
)
3086 REJECT("V1 authoritative dir servers must set RecommendedVersions.");
3087 if (!options
->RecommendedClientVersions
)
3088 options
->RecommendedClientVersions
=
3089 config_lines_dup(options
->RecommendedVersions
);
3090 if (!options
->RecommendedServerVersions
)
3091 options
->RecommendedServerVersions
=
3092 config_lines_dup(options
->RecommendedVersions
);
3093 if (options
->VersioningAuthoritativeDir
&&
3094 (!options
->RecommendedClientVersions
||
3095 !options
->RecommendedServerVersions
))
3096 REJECT("Versioning authoritative dir servers must set "
3097 "Recommended*Versions.");
3098 if (options
->UseEntryGuards
) {
3099 log_info(LD_CONFIG
, "Authoritative directory servers can't set "
3100 "UseEntryGuards. Disabling.");
3101 options
->UseEntryGuards
= 0;
3103 if (!options
->DownloadExtraInfo
&& authdir_mode_any_main(options
)) {
3104 log_info(LD_CONFIG
, "Authoritative directories always try to download "
3105 "extra-info documents. Setting DownloadExtraInfo.");
3106 options
->DownloadExtraInfo
= 1;
3108 if (!(options
->BridgeAuthoritativeDir
|| options
->HSAuthoritativeDir
||
3109 options
->V1AuthoritativeDir
|| options
->V2AuthoritativeDir
||
3110 options
->V3AuthoritativeDir
))
3111 REJECT("AuthoritativeDir is set, but none of "
3112 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
3113 /* If we have a v3bandwidthsfile and it's broken, complain on startup */
3114 if (options
->V3BandwidthsFile
&& !old_options
) {
3115 dirserv_read_measured_bandwidths(options
->V3BandwidthsFile
, NULL
);
3119 if (options
->AuthoritativeDir
&& !options
->DirPort
)
3120 REJECT("Running as authoritative directory, but no DirPort set.");
3122 if (options
->AuthoritativeDir
&& !options
->ORPort
)
3123 REJECT("Running as authoritative directory, but no ORPort set.");
3125 if (options
->AuthoritativeDir
&& options
->ClientOnly
)
3126 REJECT("Running as authoritative directory, but ClientOnly also set.");
3128 if (options
->FetchDirInfoExtraEarly
&& !options
->FetchDirInfoEarly
)
3129 REJECT("FetchDirInfoExtraEarly requires that you also set "
3130 "FetchDirInfoEarly");
3132 if (options
->ConnLimit
<= 0) {
3134 "ConnLimit must be greater than 0, but was set to %d",
3135 options
->ConnLimit
);
3139 if (validate_ports_csv(options
->FirewallPorts
, "FirewallPorts", msg
) < 0)
3142 if (validate_ports_csv(options
->LongLivedPorts
, "LongLivedPorts", msg
) < 0)
3145 if (validate_ports_csv(options
->RejectPlaintextPorts
,
3146 "RejectPlaintextPorts", msg
) < 0)
3149 if (validate_ports_csv(options
->WarnPlaintextPorts
,
3150 "WarnPlaintextPorts", msg
) < 0)
3153 if (options
->FascistFirewall
&& !options
->ReachableAddresses
) {
3154 if (options
->FirewallPorts
&& smartlist_len(options
->FirewallPorts
)) {
3155 /* We already have firewall ports set, so migrate them to
3156 * ReachableAddresses, which will set ReachableORAddresses and
3157 * ReachableDirAddresses if they aren't set explicitly. */
3158 smartlist_t
*instead
= smartlist_create();
3159 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
3160 new_line
->key
= tor_strdup("ReachableAddresses");
3161 /* If we're configured with the old format, we need to prepend some
3163 SMARTLIST_FOREACH(options
->FirewallPorts
, const char *, portno
,
3165 int p
= atoi(portno
);
3169 tor_snprintf(s
, 16, "*:%d", p
);
3170 smartlist_add(instead
, s
);
3172 new_line
->value
= smartlist_join_strings(instead
,",",0,NULL
);
3173 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3174 log(LOG_NOTICE
, LD_CONFIG
,
3175 "Converting FascistFirewall and FirewallPorts "
3176 "config options to new format: \"ReachableAddresses %s\"",
3178 options
->ReachableAddresses
= new_line
;
3179 SMARTLIST_FOREACH(instead
, char *, cp
, tor_free(cp
));
3180 smartlist_free(instead
);
3182 /* We do not have FirewallPorts set, so add 80 to
3183 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3184 if (!options
->ReachableDirAddresses
) {
3185 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
3186 new_line
->key
= tor_strdup("ReachableDirAddresses");
3187 new_line
->value
= tor_strdup("*:80");
3188 options
->ReachableDirAddresses
= new_line
;
3189 log(LOG_NOTICE
, LD_CONFIG
, "Converting FascistFirewall config option "
3190 "to new format: \"ReachableDirAddresses *:80\"");
3192 if (!options
->ReachableORAddresses
) {
3193 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
3194 new_line
->key
= tor_strdup("ReachableORAddresses");
3195 new_line
->value
= tor_strdup("*:443");
3196 options
->ReachableORAddresses
= new_line
;
3197 log(LOG_NOTICE
, LD_CONFIG
, "Converting FascistFirewall config option "
3198 "to new format: \"ReachableORAddresses *:443\"");
3203 for (i
=0; i
<3; i
++) {
3204 config_line_t
**linep
=
3205 (i
==0) ? &options
->ReachableAddresses
:
3206 (i
==1) ? &options
->ReachableORAddresses
:
3207 &options
->ReachableDirAddresses
;
3210 /* We need to end with a reject *:*, not an implicit accept *:* */
3212 if (!strcmp((*linep
)->value
, "reject *:*")) /* already there */
3214 linep
= &((*linep
)->next
);
3216 *linep
= tor_malloc_zero(sizeof(config_line_t
));
3217 (*linep
)->key
= tor_strdup(
3218 (i
==0) ? "ReachableAddresses" :
3219 (i
==1) ? "ReachableORAddresses" :
3220 "ReachableDirAddresses");
3221 (*linep
)->value
= tor_strdup("reject *:*");
3227 if ((options
->ReachableAddresses
||
3228 options
->ReachableORAddresses
||
3229 options
->ReachableDirAddresses
) &&
3230 server_mode(options
))
3231 REJECT("Servers must be able to freely connect to the rest "
3232 "of the Internet, so they must not set Reachable*Addresses "
3233 "or FascistFirewall.");
3235 if (options
->UseBridges
&&
3236 server_mode(options
))
3237 REJECT("Servers must be able to freely connect to the rest "
3238 "of the Internet, so they must not set UseBridges.");
3240 options
->_AllowInvalid
= 0;
3241 if (options
->AllowInvalidNodes
) {
3242 SMARTLIST_FOREACH(options
->AllowInvalidNodes
, const char *, cp
, {
3243 if (!strcasecmp(cp
, "entry"))
3244 options
->_AllowInvalid
|= ALLOW_INVALID_ENTRY
;
3245 else if (!strcasecmp(cp
, "exit"))
3246 options
->_AllowInvalid
|= ALLOW_INVALID_EXIT
;
3247 else if (!strcasecmp(cp
, "middle"))
3248 options
->_AllowInvalid
|= ALLOW_INVALID_MIDDLE
;
3249 else if (!strcasecmp(cp
, "introduction"))
3250 options
->_AllowInvalid
|= ALLOW_INVALID_INTRODUCTION
;
3251 else if (!strcasecmp(cp
, "rendezvous"))
3252 options
->_AllowInvalid
|= ALLOW_INVALID_RENDEZVOUS
;
3255 "Unrecognized value '%s' in AllowInvalidNodes", cp
);
3261 if (!options
->SafeLogging
||
3262 !strcasecmp(options
->SafeLogging
, "0")) {
3263 options
->_SafeLogging
= SAFELOG_SCRUB_NONE
;
3264 } else if (!strcasecmp(options
->SafeLogging
, "relay")) {
3265 options
->_SafeLogging
= SAFELOG_SCRUB_RELAY
;
3266 } else if (!strcasecmp(options
->SafeLogging
, "1")) {
3267 options
->_SafeLogging
= SAFELOG_SCRUB_ALL
;
3270 "Unrecognized value '%s' in SafeLogging",
3271 escaped(options
->SafeLogging
));
3275 if (compute_publishserverdescriptor(options
) < 0) {
3276 tor_asprintf(msg
, "Unrecognized value in PublishServerDescriptor");
3280 if ((options
->BridgeRelay
3281 || options
->_PublishServerDescriptor
& BRIDGE_AUTHORITY
)
3282 && (options
->_PublishServerDescriptor
3283 & (V1_AUTHORITY
|V2_AUTHORITY
|V3_AUTHORITY
))) {
3284 REJECT("Bridges are not supposed to publish router descriptors to the "
3285 "directory authorities. Please correct your "
3286 "PublishServerDescriptor line.");
3289 if (options
->BridgeRelay
&& options
->DirPort
) {
3290 log_warn(LD_CONFIG
, "Can't set a DirPort on a bridge relay; disabling "
3292 options
->DirPort
= 0;
3295 if (options
->MinUptimeHidServDirectoryV2
< 0) {
3296 log_warn(LD_CONFIG
, "MinUptimeHidServDirectoryV2 option must be at "
3297 "least 0 seconds. Changing to 0.");
3298 options
->MinUptimeHidServDirectoryV2
= 0;
3301 if (options
->RendPostPeriod
< MIN_REND_POST_PERIOD
) {
3302 log_warn(LD_CONFIG
, "RendPostPeriod option is too short; "
3303 "raising to %d seconds.", MIN_REND_POST_PERIOD
);
3304 options
->RendPostPeriod
= MIN_REND_POST_PERIOD
;
3307 if (options
->RendPostPeriod
> MAX_DIR_PERIOD
) {
3308 log_warn(LD_CONFIG
, "RendPostPeriod is too large; clipping to %ds.",
3310 options
->RendPostPeriod
= MAX_DIR_PERIOD
;
3313 if (options
->MaxCircuitDirtiness
< MIN_MAX_CIRCUIT_DIRTINESS
) {
3314 log_warn(LD_CONFIG
, "MaxCircuitDirtiness option is too short; "
3315 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS
);
3316 options
->MaxCircuitDirtiness
= MIN_MAX_CIRCUIT_DIRTINESS
;
3319 if (options
->CircuitStreamTimeout
&&
3320 options
->CircuitStreamTimeout
< MIN_CIRCUIT_STREAM_TIMEOUT
) {
3321 log_warn(LD_CONFIG
, "CircuitStreamTimeout option is too short; "
3322 "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT
);
3323 options
->CircuitStreamTimeout
= MIN_CIRCUIT_STREAM_TIMEOUT
;
3326 if (options
->KeepalivePeriod
< 1)
3327 REJECT("KeepalivePeriod option must be positive.");
3329 if (ensure_bandwidth_cap(&options
->BandwidthRate
,
3330 "BandwidthRate", msg
) < 0)
3332 if (ensure_bandwidth_cap(&options
->BandwidthBurst
,
3333 "BandwidthBurst", msg
) < 0)
3335 if (ensure_bandwidth_cap(&options
->MaxAdvertisedBandwidth
,
3336 "MaxAdvertisedBandwidth", msg
) < 0)
3338 if (ensure_bandwidth_cap(&options
->RelayBandwidthRate
,
3339 "RelayBandwidthRate", msg
) < 0)
3341 if (ensure_bandwidth_cap(&options
->RelayBandwidthBurst
,
3342 "RelayBandwidthBurst", msg
) < 0)
3344 if (ensure_bandwidth_cap(&options
->PerConnBWRate
,
3345 "PerConnBWRate", msg
) < 0)
3347 if (ensure_bandwidth_cap(&options
->PerConnBWBurst
,
3348 "PerConnBWBurst", msg
) < 0)
3351 if (options
->RelayBandwidthRate
&& !options
->RelayBandwidthBurst
)
3352 options
->RelayBandwidthBurst
= options
->RelayBandwidthRate
;
3353 if (options
->RelayBandwidthBurst
&& !options
->RelayBandwidthRate
)
3354 options
->RelayBandwidthRate
= options
->RelayBandwidthBurst
;
3356 if (server_mode(options
)) {
3357 if (options
->BandwidthRate
< ROUTER_REQUIRED_MIN_BANDWIDTH
) {
3359 "BandwidthRate is set to %d bytes/second. "
3360 "For servers, it must be at least %d.",
3361 (int)options
->BandwidthRate
,
3362 ROUTER_REQUIRED_MIN_BANDWIDTH
);
3364 } else if (options
->MaxAdvertisedBandwidth
<
3365 ROUTER_REQUIRED_MIN_BANDWIDTH
/2) {
3367 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3368 "For servers, it must be at least %d.",
3369 (int)options
->MaxAdvertisedBandwidth
,
3370 ROUTER_REQUIRED_MIN_BANDWIDTH
/2);
3373 if (options
->RelayBandwidthRate
&&
3374 options
->RelayBandwidthRate
< ROUTER_REQUIRED_MIN_BANDWIDTH
) {
3376 "RelayBandwidthRate is set to %d bytes/second. "
3377 "For servers, it must be at least %d.",
3378 (int)options
->RelayBandwidthRate
,
3379 ROUTER_REQUIRED_MIN_BANDWIDTH
);
3384 if (options
->RelayBandwidthRate
> options
->RelayBandwidthBurst
)
3385 REJECT("RelayBandwidthBurst must be at least equal "
3386 "to RelayBandwidthRate.");
3388 if (options
->BandwidthRate
> options
->BandwidthBurst
)
3389 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3391 /* if they set relaybandwidth* really high but left bandwidth*
3392 * at the default, raise the defaults. */
3393 if (options
->RelayBandwidthRate
> options
->BandwidthRate
)
3394 options
->BandwidthRate
= options
->RelayBandwidthRate
;
3395 if (options
->RelayBandwidthBurst
> options
->BandwidthBurst
)
3396 options
->BandwidthBurst
= options
->RelayBandwidthBurst
;
3398 if (accounting_parse_options(options
, 1)<0)
3399 REJECT("Failed to parse accounting options. See logs for details.");
3401 if (options
->HTTPProxy
) { /* parse it now */
3402 if (tor_addr_port_parse(options
->HTTPProxy
,
3403 &options
->HTTPProxyAddr
, &options
->HTTPProxyPort
) < 0)
3404 REJECT("HTTPProxy failed to parse or resolve. Please fix.");
3405 if (options
->HTTPProxyPort
== 0) { /* give it a default */
3406 options
->HTTPProxyPort
= 80;
3410 if (options
->HTTPProxyAuthenticator
) {
3411 if (strlen(options
->HTTPProxyAuthenticator
) >= 48)
3412 REJECT("HTTPProxyAuthenticator is too long (>= 48 chars).");
3415 if (options
->HTTPSProxy
) { /* parse it now */
3416 if (tor_addr_port_parse(options
->HTTPSProxy
,
3417 &options
->HTTPSProxyAddr
, &options
->HTTPSProxyPort
) <0)
3418 REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
3419 if (options
->HTTPSProxyPort
== 0) { /* give it a default */
3420 options
->HTTPSProxyPort
= 443;
3424 if (options
->HTTPSProxyAuthenticator
) {
3425 if (strlen(options
->HTTPSProxyAuthenticator
) >= 48)
3426 REJECT("HTTPSProxyAuthenticator is too long (>= 48 chars).");
3429 if (options
->Socks4Proxy
) { /* parse it now */
3430 if (tor_addr_port_parse(options
->Socks4Proxy
,
3431 &options
->Socks4ProxyAddr
,
3432 &options
->Socks4ProxyPort
) <0)
3433 REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
3434 if (options
->Socks4ProxyPort
== 0) { /* give it a default */
3435 options
->Socks4ProxyPort
= 1080;
3439 if (options
->Socks5Proxy
) { /* parse it now */
3440 if (tor_addr_port_parse(options
->Socks5Proxy
,
3441 &options
->Socks5ProxyAddr
,
3442 &options
->Socks5ProxyPort
) <0)
3443 REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
3444 if (options
->Socks5ProxyPort
== 0) { /* give it a default */
3445 options
->Socks5ProxyPort
= 1080;
3449 if (options
->Socks4Proxy
&& options
->Socks5Proxy
)
3450 REJECT("You cannot specify both Socks4Proxy and SOCKS5Proxy");
3452 if (options
->Socks5ProxyUsername
) {
3455 len
= strlen(options
->Socks5ProxyUsername
);
3456 if (len
< 1 || len
> 255)
3457 REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
3459 if (!options
->Socks5ProxyPassword
)
3460 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3462 len
= strlen(options
->Socks5ProxyPassword
);
3463 if (len
< 1 || len
> 255)
3464 REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
3465 } else if (options
->Socks5ProxyPassword
)
3466 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3468 if (options
->HashedControlPassword
) {
3469 smartlist_t
*sl
= decode_hashed_passwords(options
->HashedControlPassword
);
3471 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3473 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
3478 if (options
->HashedControlSessionPassword
) {
3479 smartlist_t
*sl
= decode_hashed_passwords(
3480 options
->HashedControlSessionPassword
);
3482 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3484 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
3489 if (options
->ControlListenAddress
) {
3490 int all_are_local
= 1;
3492 for (ln
= options
->ControlListenAddress
; ln
; ln
= ln
->next
) {
3493 if (strcmpstart(ln
->value
, "127."))
3496 if (!all_are_local
) {
3497 if (!options
->HashedControlPassword
&&
3498 !options
->HashedControlSessionPassword
&&
3499 !options
->CookieAuthentication
) {
3501 "You have a ControlListenAddress set to accept "
3502 "unauthenticated connections from a non-local address. "
3503 "This means that programs not running on your computer "
3504 "can reconfigure your Tor, without even having to guess a "
3505 "password. That's so bad that I'm closing your ControlPort "
3506 "for you. If you need to control your Tor remotely, try "
3507 "enabling authentication and using a tool like stunnel or "
3508 "ssh to encrypt remote access.");
3509 options
->ControlPort
= 0;
3511 log_warn(LD_CONFIG
, "You have a ControlListenAddress set to accept "
3512 "connections from a non-local address. This means that "
3513 "programs not running on your computer can reconfigure your "
3514 "Tor. That's pretty bad, since the controller "
3515 "protocol isn't encrypted! Maybe you should just listen on "
3516 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
3517 "remote connections to your control port.");
3522 if (options
->ControlPort
&& !options
->HashedControlPassword
&&
3523 !options
->HashedControlSessionPassword
&&
3524 !options
->CookieAuthentication
) {
3525 log_warn(LD_CONFIG
, "ControlPort is open, but no authentication method "
3526 "has been configured. This means that any program on your "
3527 "computer can reconfigure your Tor. That's bad! You should "
3528 "upgrade your Tor controller as soon as possible.");
3531 if (options
->CookieAuthFileGroupReadable
&& !options
->CookieAuthFile
) {
3532 log_warn(LD_CONFIG
, "You set the CookieAuthFileGroupReadable but did "
3533 "not configure a the path for the cookie file via "
3534 "CookieAuthFile. This means your cookie will not be group "
3538 if (options
->UseEntryGuards
&& ! options
->NumEntryGuards
)
3539 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3541 if (check_nickname_list(options
->MyFamily
, "MyFamily", msg
))
3543 for (cl
= options
->NodeFamilies
; cl
; cl
= cl
->next
) {
3544 if (check_nickname_list(cl
->value
, "NodeFamily", msg
))
3548 if (validate_addr_policies(options
, msg
) < 0)
3551 if (validate_dir_authorities(options
, old_options
) < 0)
3552 REJECT("Directory authority line did not parse. See logs for details.");
3554 if (options
->UseBridges
&& !options
->Bridges
)
3555 REJECT("If you set UseBridges, you must specify at least one bridge.");
3556 if (options
->UseBridges
&& !options
->TunnelDirConns
)
3557 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3558 if (options
->Bridges
) {
3559 for (cl
= options
->Bridges
; cl
; cl
= cl
->next
) {
3560 if (parse_bridge_line(cl
->value
, 1)<0)
3561 REJECT("Bridge line did not parse. See logs for details.");
3565 if (options
->ConstrainedSockets
) {
3566 /* If the user wants to constrain socket buffer use, make sure the desired
3567 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3568 if (options
->ConstrainedSockSize
< MIN_CONSTRAINED_TCP_BUFFER
||
3569 options
->ConstrainedSockSize
> MAX_CONSTRAINED_TCP_BUFFER
||
3570 options
->ConstrainedSockSize
% 1024) {
3572 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3573 "in 1024 byte increments.",
3574 MIN_CONSTRAINED_TCP_BUFFER
, MAX_CONSTRAINED_TCP_BUFFER
);
3577 if (options
->DirPort
) {
3578 /* Providing cached directory entries while system TCP buffers are scarce
3579 * will exacerbate the socket errors. Suggest that this be disabled. */
3580 COMPLAIN("You have requested constrained socket buffers while also "
3581 "serving directory entries via DirPort. It is strongly "
3582 "suggested that you disable serving directory requests when "
3583 "system TCP buffer resources are scarce.");
3587 if (options
->V3AuthVoteDelay
+ options
->V3AuthDistDelay
>=
3588 options
->V3AuthVotingInterval
/2) {
3589 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3590 "V3AuthVotingInterval");
3592 if (options
->V3AuthVoteDelay
< MIN_VOTE_SECONDS
)
3593 REJECT("V3AuthVoteDelay is way too low.");
3594 if (options
->V3AuthDistDelay
< MIN_DIST_SECONDS
)
3595 REJECT("V3AuthDistDelay is way too low.");
3597 if (options
->V3AuthNIntervalsValid
< 2)
3598 REJECT("V3AuthNIntervalsValid must be at least 2.");
3600 if (options
->V3AuthVotingInterval
< MIN_VOTE_INTERVAL
) {
3601 REJECT("V3AuthVotingInterval is insanely low.");
3602 } else if (options
->V3AuthVotingInterval
> 24*60*60) {
3603 REJECT("V3AuthVotingInterval is insanely high.");
3604 } else if (((24*60*60) % options
->V3AuthVotingInterval
) != 0) {
3605 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3608 if (rend_config_services(options
, 1) < 0)
3609 REJECT("Failed to configure rendezvous options. See logs for details.");
3611 /* Parse client-side authorization for hidden services. */
3612 if (rend_parse_service_authorization(options
, 1) < 0)
3613 REJECT("Failed to configure client authorization for hidden services. "
3614 "See logs for details.");
3616 if (parse_virtual_addr_network(options
->VirtualAddrNetwork
, 1, NULL
)<0)
3619 if (options
->PreferTunneledDirConns
&& !options
->TunnelDirConns
)
3620 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3622 if ((options
->Socks4Proxy
|| options
->Socks5Proxy
) &&
3623 !options
->HTTPProxy
&& !options
->PreferTunneledDirConns
)
3624 REJECT("When Socks4Proxy or Socks5Proxy is configured, "
3625 "PreferTunneledDirConns and TunnelDirConns must both be "
3626 "set to 1, or HTTPProxy must be configured.");
3628 if (options
->AutomapHostsSuffixes
) {
3629 SMARTLIST_FOREACH(options
->AutomapHostsSuffixes
, char *, suf
,
3631 size_t len
= strlen(suf
);
3632 if (len
&& suf
[len
-1] == '.')
3637 if (options
->TestingTorNetwork
&& !options
->DirServers
) {
3638 REJECT("TestingTorNetwork may only be configured in combination with "
3639 "a non-default set of DirServers.");
3642 if (options
->AllowSingleHopExits
&& !options
->DirServers
) {
3643 COMPLAIN("You have set AllowSingleHopExits; now your relay will allow "
3644 "others to make one-hop exits. However, since by default most "
3645 "clients avoid relays that set this option, most clients will "
3649 /*XXXX022 checking for defaults manually like this is a bit fragile.*/
3651 /* Keep changes to hard-coded values synchronous to man page and default
3653 if (options
->TestingV3AuthInitialVotingInterval
!= 30*60 &&
3654 !options
->TestingTorNetwork
) {
3655 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
3657 } else if (options
->TestingV3AuthInitialVotingInterval
< MIN_VOTE_INTERVAL
) {
3658 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3659 } else if (((30*60) % options
->TestingV3AuthInitialVotingInterval
) != 0) {
3660 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3664 if (options
->TestingV3AuthInitialVoteDelay
!= 5*60 &&
3665 !options
->TestingTorNetwork
) {
3666 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
3668 } else if (options
->TestingV3AuthInitialVoteDelay
< MIN_VOTE_SECONDS
) {
3669 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3672 if (options
->TestingV3AuthInitialDistDelay
!= 5*60 &&
3673 !options
->TestingTorNetwork
) {
3674 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
3676 } else if (options
->TestingV3AuthInitialDistDelay
< MIN_DIST_SECONDS
) {
3677 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3680 if (options
->TestingV3AuthInitialVoteDelay
+
3681 options
->TestingV3AuthInitialDistDelay
>=
3682 options
->TestingV3AuthInitialVotingInterval
/2) {
3683 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3684 "must be less than half TestingV3AuthInitialVotingInterval");
3687 if (options
->TestingAuthDirTimeToLearnReachability
!= 30*60 &&
3688 !options
->TestingTorNetwork
) {
3689 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
3690 "testing Tor networks!");
3691 } else if (options
->TestingAuthDirTimeToLearnReachability
< 0) {
3692 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3693 } else if (options
->TestingAuthDirTimeToLearnReachability
> 2*60*60) {
3694 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3697 if (options
->TestingEstimatedDescriptorPropagationTime
!= 10*60 &&
3698 !options
->TestingTorNetwork
) {
3699 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
3700 "testing Tor networks!");
3701 } else if (options
->TestingEstimatedDescriptorPropagationTime
< 0) {
3702 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3703 } else if (options
->TestingEstimatedDescriptorPropagationTime
> 60*60) {
3704 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3707 if (options
->TestingTorNetwork
) {
3708 log_warn(LD_CONFIG
, "TestingTorNetwork is set. This will make your node "
3709 "almost unusable in the public Tor network, and is "
3710 "therefore only advised if you are building a "
3711 "testing Tor network!");
3714 if (options
->AccelName
&& !options
->HardwareAccel
)
3715 options
->HardwareAccel
= 1;
3716 if (options
->AccelDir
&& !options
->AccelName
)
3717 REJECT("Can't use hardware crypto accelerator dir without engine name.");
3719 if (options
->PublishServerDescriptor
)
3720 SMARTLIST_FOREACH(options
->PublishServerDescriptor
, const char *, pubdes
, {
3721 if (!strcmp(pubdes
, "1") || !strcmp(pubdes
, "0"))
3722 if (smartlist_len(options
->PublishServerDescriptor
) > 1) {
3723 COMPLAIN("You have passed a list of multiple arguments to the "
3724 "PublishServerDescriptor option that includes 0 or 1. "
3725 "0 or 1 should only be used as the sole argument. "
3726 "This configuration will be rejected in a future release.");
3731 if (options
->BridgeRelay
== 1 && options
->ORPort
== 0)
3732 REJECT("BridgeRelay is 1, ORPort is 0. This is an invalid combination.");
3739 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3742 opt_streq(const char *s1
, const char *s2
)
3746 else if (s1
&& s2
&& !strcmp(s1
,s2
))
3752 /** Check if any of the previous options have changed but aren't allowed to. */
3754 options_transition_allowed(or_options_t
*old
, or_options_t
*new_val
,
3760 if (!opt_streq(old
->PidFile
, new_val
->PidFile
)) {
3761 *msg
= tor_strdup("PidFile is not allowed to change.");
3765 if (old
->RunAsDaemon
!= new_val
->RunAsDaemon
) {
3766 *msg
= tor_strdup("While Tor is running, changing RunAsDaemon "
3771 if (strcmp(old
->DataDirectory
,new_val
->DataDirectory
)!=0) {
3773 "While Tor is running, changing DataDirectory "
3774 "(\"%s\"->\"%s\") is not allowed.",
3775 old
->DataDirectory
, new_val
->DataDirectory
);
3779 if (!opt_streq(old
->User
, new_val
->User
)) {
3780 *msg
= tor_strdup("While Tor is running, changing User is not allowed.");
3784 if ((old
->HardwareAccel
!= new_val
->HardwareAccel
)
3785 || !opt_streq(old
->AccelName
, new_val
->AccelName
)
3786 || !opt_streq(old
->AccelDir
, new_val
->AccelDir
)) {
3787 *msg
= tor_strdup("While Tor is running, changing OpenSSL hardware "
3788 "acceleration engine is not allowed.");
3792 if (old
->TestingTorNetwork
!= new_val
->TestingTorNetwork
) {
3793 *msg
= tor_strdup("While Tor is running, changing TestingTorNetwork "
3798 if (old
->DisableAllSwap
!= new_val
->DisableAllSwap
) {
3799 *msg
= tor_strdup("While Tor is running, changing DisableAllSwap "
3807 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3808 * will require us to rotate the CPU and DNS workers; else return 0. */
3810 options_transition_affects_workers(or_options_t
*old_options
,
3811 or_options_t
*new_options
)
3813 if (!opt_streq(old_options
->DataDirectory
, new_options
->DataDirectory
) ||
3814 old_options
->NumCPUs
!= new_options
->NumCPUs
||
3815 old_options
->ORPort
!= new_options
->ORPort
||
3816 old_options
->ServerDNSSearchDomains
!=
3817 new_options
->ServerDNSSearchDomains
||
3818 old_options
->SafeLogging
!= new_options
->SafeLogging
||
3819 old_options
->ClientOnly
!= new_options
->ClientOnly
||
3820 public_server_mode(old_options
) != public_server_mode(new_options
) ||
3821 !config_lines_eq(old_options
->Logs
, new_options
->Logs
) ||
3822 old_options
->LogMessageDomains
!= new_options
->LogMessageDomains
)
3825 /* Check whether log options match. */
3827 /* Nothing that changed matters. */
3831 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3832 * will require us to generate a new descriptor; else return 0. */
3834 options_transition_affects_descriptor(or_options_t
*old_options
,
3835 or_options_t
*new_options
)
3837 /* XXX We can be smarter here. If your DirPort isn't being
3838 * published and you just turned it off, no need to republish. Etc. */
3839 if (!opt_streq(old_options
->DataDirectory
, new_options
->DataDirectory
) ||
3840 !opt_streq(old_options
->Nickname
,new_options
->Nickname
) ||
3841 !opt_streq(old_options
->Address
,new_options
->Address
) ||
3842 !config_lines_eq(old_options
->ExitPolicy
,new_options
->ExitPolicy
) ||
3843 old_options
->ExitPolicyRejectPrivate
!=
3844 new_options
->ExitPolicyRejectPrivate
||
3845 old_options
->ORPort
!= new_options
->ORPort
||
3846 old_options
->DirPort
!= new_options
->DirPort
||
3847 old_options
->ClientOnly
!= new_options
->ClientOnly
||
3848 old_options
->_PublishServerDescriptor
!=
3849 new_options
->_PublishServerDescriptor
||
3850 get_effective_bwrate(old_options
) != get_effective_bwrate(new_options
) ||
3851 get_effective_bwburst(old_options
) !=
3852 get_effective_bwburst(new_options
) ||
3853 !opt_streq(old_options
->ContactInfo
, new_options
->ContactInfo
) ||
3854 !opt_streq(old_options
->MyFamily
, new_options
->MyFamily
) ||
3855 !opt_streq(old_options
->AccountingStart
, new_options
->AccountingStart
) ||
3856 old_options
->AccountingMax
!= new_options
->AccountingMax
)
3863 /** Return the directory on windows where we expect to find our application
3866 get_windows_conf_root(void)
3868 static int is_set
= 0;
3869 static char path
[MAX_PATH
+1];
3870 TCHAR tpath
[MAX_PATH
] = {0};
3879 /* Find X:\documents and settings\username\application data\ .
3880 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3882 #ifdef ENABLE_LOCAL_APPDATA
3883 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
3885 #define APPDATA_PATH CSIDL_APPDATA
3887 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL
, APPDATA_PATH
, &idl
))) {
3888 getcwd(path
,MAX_PATH
);
3891 "I couldn't find your application data folder: are you "
3892 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3896 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3897 result
= SHGetPathFromIDList(idl
, tpath
);
3899 wcstombs(path
,tpath
,MAX_PATH
);
3901 strlcpy(path
,tpath
,sizeof(path
));
3904 /* Now we need to free the memory that the path-idl was stored in. In
3905 * typical Windows fashion, we can't just call 'free()' on it. */
3908 m
->lpVtbl
->Free(m
, idl
);
3909 m
->lpVtbl
->Release(m
);
3911 if (!SUCCEEDED(result
)) {
3914 strlcat(path
,"\\tor",MAX_PATH
);
3920 /** Return the default location for our torrc file. */
3922 get_default_conf_file(void)
3925 static char path
[MAX_PATH
+1];
3926 strlcpy(path
, get_windows_conf_root(), MAX_PATH
);
3927 strlcat(path
,"\\torrc",MAX_PATH
);
3930 return (CONFDIR
"/torrc");
3934 /** Verify whether lst is a string containing valid-looking comma-separated
3935 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3938 check_nickname_list(const char *lst
, const char *name
, char **msg
)
3945 sl
= smartlist_create();
3947 smartlist_split_string(sl
, lst
, ",",
3948 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
|SPLIT_STRIP_SPACE
, 0);
3950 SMARTLIST_FOREACH(sl
, const char *, s
,
3952 if (!is_legal_nickname_or_hexdigest(s
)) {
3953 tor_asprintf(msg
, "Invalid nickname '%s' in %s line", s
, name
);
3958 SMARTLIST_FOREACH(sl
, char *, s
, tor_free(s
));
3963 /** Learn config file name from command line arguments, or use the default */
3965 find_torrc_filename(int argc
, char **argv
,
3966 int *using_default_torrc
, int *ignore_missing_torrc
)
3971 for (i
= 1; i
< argc
; ++i
) {
3972 if (i
< argc
-1 && !strcmp(argv
[i
],"-f")) {
3974 log(LOG_WARN
, LD_CONFIG
, "Duplicate -f options on command line.");
3977 fname
= expand_filename(argv
[i
+1]);
3978 *using_default_torrc
= 0;
3980 } else if (!strcmp(argv
[i
],"--ignore-missing-torrc")) {
3981 *ignore_missing_torrc
= 1;
3985 if (*using_default_torrc
) {
3986 /* didn't find one, try CONFDIR */
3987 const char *dflt
= get_default_conf_file();
3988 if (dflt
&& file_status(dflt
) == FN_FILE
) {
3989 fname
= tor_strdup(dflt
);
3993 fn
= expand_filename("~/.torrc");
3994 if (fn
&& file_status(fn
) == FN_FILE
) {
3998 fname
= tor_strdup(dflt
);
4001 fname
= tor_strdup(dflt
);
4008 /** Load torrc from disk, setting torrc_fname if successful */
4010 load_torrc_from_disk(int argc
, char **argv
)
4014 int using_default_torrc
= 1;
4015 int ignore_missing_torrc
= 0;
4017 fname
= find_torrc_filename(argc
, argv
,
4018 &using_default_torrc
, &ignore_missing_torrc
);
4020 log(LOG_DEBUG
, LD_CONFIG
, "Opening config file \"%s\"", fname
);
4022 tor_free(torrc_fname
);
4023 torrc_fname
= fname
;
4025 /* Open config file */
4026 if (file_status(fname
) != FN_FILE
||
4027 !(cf
= read_file_to_str(fname
,0,NULL
))) {
4028 if (using_default_torrc
== 1 || ignore_missing_torrc
) {
4029 log(LOG_NOTICE
, LD_CONFIG
, "Configuration file \"%s\" not present, "
4030 "using reasonable defaults.", fname
);
4031 tor_free(fname
); /* sets fname to NULL */
4033 cf
= tor_strdup("");
4035 log(LOG_WARN
, LD_CONFIG
,
4036 "Unable to open configuration file \"%s\".", fname
);
4048 /** Read a configuration file into <b>options</b>, finding the configuration
4049 * file location based on the command line. After loading the file
4050 * call options_init_from_string() to load the config.
4051 * Return 0 if success, -1 if failure. */
4053 options_init_from_torrc(int argc
, char **argv
)
4056 int i
, retval
, command
;
4057 static char **backup_argv
;
4058 static int backup_argc
;
4059 char *command_arg
= NULL
;
4062 if (argv
) { /* first time we're called. save command line args */
4065 } else { /* we're reloading. need to clean up old options first. */
4069 if (argc
> 1 && (!strcmp(argv
[1], "-h") || !strcmp(argv
[1],"--help"))) {
4073 if (argc
> 1 && !strcmp(argv
[1], "--list-torrc-options")) {
4074 /* For documenting validating whether we've documented everything. */
4075 list_torrc_options();
4079 if (argc
> 1 && (!strcmp(argv
[1],"--version"))) {
4080 printf("Tor version %s.\n",get_version());
4083 if (argc
> 1 && (!strcmp(argv
[1],"--digests"))) {
4084 printf("Tor version %s.\n",get_version());
4085 printf("%s", libor_get_digests());
4086 printf("%s", tor_get_digests());
4090 /* Go through command-line variables */
4091 if (!global_cmdline_options
) {
4092 /* Or we could redo the list every time we pass this place.
4093 * It does not really matter */
4094 if (config_get_commandlines(argc
, argv
, &global_cmdline_options
) < 0) {
4099 command
= CMD_RUN_TOR
;
4100 for (i
= 1; i
< argc
; ++i
) {
4101 if (!strcmp(argv
[i
],"--list-fingerprint")) {
4102 command
= CMD_LIST_FINGERPRINT
;
4103 } else if (!strcmp(argv
[i
],"--hash-password")) {
4104 command
= CMD_HASH_PASSWORD
;
4105 command_arg
= tor_strdup( (i
< argc
-1) ? argv
[i
+1] : "");
4107 } else if (!strcmp(argv
[i
],"--verify-config")) {
4108 command
= CMD_VERIFY_CONFIG
;
4112 if (command
== CMD_HASH_PASSWORD
) {
4113 cf
= tor_strdup("");
4115 cf
= load_torrc_from_disk(argc
, argv
);
4120 retval
= options_init_from_string(cf
, command
, command_arg
, &errmsg
);
4129 log(LOG_WARN
,LD_CONFIG
,"%s", errmsg
);
4135 /** Load the options from the configuration in <b>cf</b>, validate
4136 * them for consistency and take actions based on them.
4138 * Return 0 if success, negative on error:
4139 * * -1 for general errors.
4140 * * -2 for failure to parse/validate,
4141 * * -3 for transition not allowed
4142 * * -4 for error while setting the new options
4145 options_init_from_string(const char *cf
,
4146 int command
, const char *command_arg
,
4149 or_options_t
*oldoptions
, *newoptions
;
4152 setopt_err_t err
= SETOPT_ERR_MISC
;
4155 oldoptions
= global_options
; /* get_options unfortunately asserts if
4156 this is the first time we run*/
4158 newoptions
= tor_malloc_zero(sizeof(or_options_t
));
4159 newoptions
->_magic
= OR_OPTIONS_MAGIC
;
4160 options_init(newoptions
);
4161 newoptions
->command
= command
;
4162 newoptions
->command_arg
= command_arg
;
4164 /* get config lines, assign them */
4165 retval
= config_get_lines(cf
, &cl
);
4167 err
= SETOPT_ERR_PARSE
;
4170 retval
= config_assign(&options_format
, newoptions
, cl
, 0, 0, msg
);
4171 config_free_lines(cl
);
4173 err
= SETOPT_ERR_PARSE
;
4177 /* Go through command-line variables too */
4178 retval
= config_assign(&options_format
, newoptions
,
4179 global_cmdline_options
, 0, 0, msg
);
4181 err
= SETOPT_ERR_PARSE
;
4185 /* If this is a testing network configuration, change defaults
4186 * for a list of dependent config options, re-initialize newoptions
4187 * with the new defaults, and assign all options to it second time. */
4188 if (newoptions
->TestingTorNetwork
) {
4189 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4190 * this? We could, for example, make the parsing algorithm do two passes
4191 * over the configuration. If it finds any "suite" options like
4192 * TestingTorNetwork, it could change the defaults before its second pass.
4193 * Not urgent so long as this seems to work, but at any sign of trouble,
4194 * let's clean it up. -NM */
4196 /* Change defaults. */
4198 for (i
= 0; testing_tor_network_defaults
[i
].name
; ++i
) {
4199 config_var_t
*new_var
= &testing_tor_network_defaults
[i
];
4200 config_var_t
*old_var
=
4201 config_find_option(&options_format
, new_var
->name
);
4202 tor_assert(new_var
);
4203 tor_assert(old_var
);
4204 old_var
->initvalue
= new_var
->initvalue
;
4207 /* Clear newoptions and re-initialize them with new defaults. */
4208 config_free(&options_format
, newoptions
);
4209 newoptions
= tor_malloc_zero(sizeof(or_options_t
));
4210 newoptions
->_magic
= OR_OPTIONS_MAGIC
;
4211 options_init(newoptions
);
4212 newoptions
->command
= command
;
4213 newoptions
->command_arg
= command_arg
;
4215 /* Assign all options a second time. */
4216 retval
= config_get_lines(cf
, &cl
);
4218 err
= SETOPT_ERR_PARSE
;
4221 retval
= config_assign(&options_format
, newoptions
, cl
, 0, 0, msg
);
4222 config_free_lines(cl
);
4224 err
= SETOPT_ERR_PARSE
;
4227 retval
= config_assign(&options_format
, newoptions
,
4228 global_cmdline_options
, 0, 0, msg
);
4230 err
= SETOPT_ERR_PARSE
;
4235 /* Validate newoptions */
4236 if (options_validate(oldoptions
, newoptions
, 0, msg
) < 0) {
4237 err
= SETOPT_ERR_PARSE
; /*XXX make this a separate return value.*/
4241 if (options_transition_allowed(oldoptions
, newoptions
, msg
) < 0) {
4242 err
= SETOPT_ERR_TRANSITION
;
4246 if (set_options(newoptions
, msg
)) {
4247 err
= SETOPT_ERR_SETTING
;
4248 goto err
; /* frees and replaces old options */
4254 config_free(&options_format
, newoptions
);
4256 char *old_msg
= *msg
;
4257 tor_asprintf(msg
, "Failed to parse/validate config: %s", old_msg
);
4263 /** Return the location for our configuration file.
4266 get_torrc_fname(void)
4271 return get_default_conf_file();
4274 /** Adjust the address map based on the MapAddress elements in the
4275 * configuration <b>options</b>
4278 config_register_addressmaps(or_options_t
*options
)
4284 addressmap_clear_configured();
4285 elts
= smartlist_create();
4286 for (opt
= options
->AddressMap
; opt
; opt
= opt
->next
) {
4287 smartlist_split_string(elts
, opt
->value
, NULL
,
4288 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
4289 if (smartlist_len(elts
) >= 2) {
4290 from
= smartlist_get(elts
,0);
4291 to
= smartlist_get(elts
,1);
4292 if (address_is_invalid_destination(to
, 1)) {
4294 "Skipping invalid argument '%s' to MapAddress", to
);
4296 addressmap_register(from
, tor_strdup(to
), 0, ADDRMAPSRC_TORRC
);
4297 if (smartlist_len(elts
)>2) {
4298 log_warn(LD_CONFIG
,"Ignoring extra arguments to MapAddress.");
4302 log_warn(LD_CONFIG
,"MapAddress '%s' has too few arguments. Ignoring.",
4305 SMARTLIST_FOREACH(elts
, char*, cp
, tor_free(cp
));
4306 smartlist_clear(elts
);
4308 smartlist_free(elts
);
4312 * Initialize the logs based on the configuration file.
4315 options_init_logs(or_options_t
*options
, int validate_only
)
4324 options
->RunAsDaemon
;
4328 elts
= smartlist_create();
4330 for (opt
= options
->Logs
; opt
; opt
= opt
->next
) {
4331 log_severity_list_t
*severity
;
4332 const char *cfg
= opt
->value
;
4333 severity
= tor_malloc_zero(sizeof(log_severity_list_t
));
4334 if (parse_log_severity_config(&cfg
, severity
) < 0) {
4335 log_warn(LD_CONFIG
, "Couldn't parse log levels in Log option 'Log %s'",
4337 ok
= 0; goto cleanup
;
4340 smartlist_split_string(elts
, cfg
, NULL
,
4341 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
4343 if (smartlist_len(elts
) == 0)
4344 smartlist_add(elts
, tor_strdup("stdout"));
4346 if (smartlist_len(elts
) == 1 &&
4347 (!strcasecmp(smartlist_get(elts
,0), "stdout") ||
4348 !strcasecmp(smartlist_get(elts
,0), "stderr"))) {
4349 int err
= smartlist_len(elts
) &&
4350 !strcasecmp(smartlist_get(elts
,0), "stderr");
4351 if (!validate_only
) {
4354 "Can't log to %s with RunAsDaemon set; skipping stdout",
4355 err
?"stderr":"stdout");
4357 add_stream_log(severity
, err
?"<stderr>":"<stdout>",
4358 fileno(err
?stderr
:stdout
));
4363 if (smartlist_len(elts
) == 1 &&
4364 !strcasecmp(smartlist_get(elts
,0), "syslog")) {
4365 #ifdef HAVE_SYSLOG_H
4366 if (!validate_only
) {
4367 add_syslog_log(severity
);
4370 log_warn(LD_CONFIG
, "Syslog is not supported on this system. Sorry.");
4375 if (smartlist_len(elts
) == 2 &&
4376 !strcasecmp(smartlist_get(elts
,0), "file")) {
4377 if (!validate_only
) {
4378 if (add_file_log(severity
, smartlist_get(elts
, 1)) < 0) {
4379 log_warn(LD_CONFIG
, "Couldn't open file for 'Log %s': %s",
4380 opt
->value
, strerror(errno
));
4387 log_warn(LD_CONFIG
, "Bad syntax on file Log option 'Log %s'",
4389 ok
= 0; goto cleanup
;
4392 SMARTLIST_FOREACH(elts
, char*, cp
, tor_free(cp
));
4393 smartlist_clear(elts
);
4396 smartlist_free(elts
);
4398 if (ok
&& !validate_only
)
4399 logs_set_domain_logging(options
->LogMessageDomains
);
4404 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4405 * if the line is well-formed, and -1 if it isn't. If
4406 * <b>validate_only</b> is 0, and the line is well-formed, then add
4407 * the bridge described in the line to our internal bridge list. */
4409 parse_bridge_line(const char *line
, int validate_only
)
4411 smartlist_t
*items
= NULL
;
4413 char *addrport
=NULL
, *fingerprint
=NULL
;
4416 char digest
[DIGEST_LEN
];
4418 items
= smartlist_create();
4419 smartlist_split_string(items
, line
, NULL
,
4420 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, -1);
4421 if (smartlist_len(items
) < 1) {
4422 log_warn(LD_CONFIG
, "Too few arguments to Bridge line.");
4425 addrport
= smartlist_get(items
, 0);
4426 smartlist_del_keeporder(items
, 0);
4427 if (tor_addr_port_parse(addrport
, &addr
, &port
)<0) {
4428 log_warn(LD_CONFIG
, "Error parsing Bridge address '%s'", addrport
);
4433 "Bridge address '%s' has no port; using default port 443.",
4438 if (smartlist_len(items
)) {
4439 fingerprint
= smartlist_join_strings(items
, "", 0, NULL
);
4440 if (strlen(fingerprint
) != HEX_DIGEST_LEN
) {
4441 log_warn(LD_CONFIG
, "Key digest for Bridge is wrong length.");
4444 if (base16_decode(digest
, DIGEST_LEN
, fingerprint
, HEX_DIGEST_LEN
)<0) {
4445 log_warn(LD_CONFIG
, "Unable to decode Bridge key digest.");
4450 if (!validate_only
) {
4451 log_debug(LD_DIR
, "Bridge at %s:%d (%s)", fmt_addr(&addr
),
4453 fingerprint
? fingerprint
: "no key listed");
4454 bridge_add_from_config(&addr
, port
, fingerprint
? digest
: NULL
);
4464 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
4465 smartlist_free(items
);
4467 tor_free(fingerprint
);
4471 /** Read the contents of a DirServer line from <b>line</b>. If
4472 * <b>validate_only</b> is 0, and the line is well-formed, and it
4473 * shares any bits with <b>required_type</b> or <b>required_type</b>
4474 * is 0, then add the dirserver described in the line (minus whatever
4475 * bits it's missing) as a valid authority. Return 0 on success,
4476 * or -1 if the line isn't well-formed or if we can't add it. */
4478 parse_dir_server_line(const char *line
, authority_type_t required_type
,
4481 smartlist_t
*items
= NULL
;
4483 char *addrport
=NULL
, *address
=NULL
, *nickname
=NULL
, *fingerprint
=NULL
;
4484 uint16_t dir_port
= 0, or_port
= 0;
4485 char digest
[DIGEST_LEN
];
4486 char v3_digest
[DIGEST_LEN
];
4487 authority_type_t type
= V2_AUTHORITY
;
4488 int is_not_hidserv_authority
= 0, is_not_v2_authority
= 0;
4490 items
= smartlist_create();
4491 smartlist_split_string(items
, line
, NULL
,
4492 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, -1);
4493 if (smartlist_len(items
) < 1) {
4494 log_warn(LD_CONFIG
, "No arguments on DirServer line.");
4498 if (is_legal_nickname(smartlist_get(items
, 0))) {
4499 nickname
= smartlist_get(items
, 0);
4500 smartlist_del_keeporder(items
, 0);
4503 while (smartlist_len(items
)) {
4504 char *flag
= smartlist_get(items
, 0);
4505 if (TOR_ISDIGIT(flag
[0]))
4507 if (!strcasecmp(flag
, "v1")) {
4508 type
|= (V1_AUTHORITY
| HIDSERV_AUTHORITY
);
4509 } else if (!strcasecmp(flag
, "hs")) {
4510 type
|= HIDSERV_AUTHORITY
;
4511 } else if (!strcasecmp(flag
, "no-hs")) {
4512 is_not_hidserv_authority
= 1;
4513 } else if (!strcasecmp(flag
, "bridge")) {
4514 type
|= BRIDGE_AUTHORITY
;
4515 } else if (!strcasecmp(flag
, "no-v2")) {
4516 is_not_v2_authority
= 1;
4517 } else if (!strcasecmpstart(flag
, "orport=")) {
4519 char *portstring
= flag
+ strlen("orport=");
4520 or_port
= (uint16_t) tor_parse_long(portstring
, 10, 1, 65535, &ok
, NULL
);
4522 log_warn(LD_CONFIG
, "Invalid orport '%s' on DirServer line.",
4524 } else if (!strcasecmpstart(flag
, "v3ident=")) {
4525 char *idstr
= flag
+ strlen("v3ident=");
4526 if (strlen(idstr
) != HEX_DIGEST_LEN
||
4527 base16_decode(v3_digest
, DIGEST_LEN
, idstr
, HEX_DIGEST_LEN
)<0) {
4528 log_warn(LD_CONFIG
, "Bad v3 identity digest '%s' on DirServer line",
4531 type
|= V3_AUTHORITY
;
4534 log_warn(LD_CONFIG
, "Unrecognized flag '%s' on DirServer line",
4538 smartlist_del_keeporder(items
, 0);
4540 if (is_not_hidserv_authority
)
4541 type
&= ~HIDSERV_AUTHORITY
;
4542 if (is_not_v2_authority
)
4543 type
&= ~V2_AUTHORITY
;
4545 if (smartlist_len(items
) < 2) {
4546 log_warn(LD_CONFIG
, "Too few arguments to DirServer line.");
4549 addrport
= smartlist_get(items
, 0);
4550 smartlist_del_keeporder(items
, 0);
4551 if (parse_addr_port(LOG_WARN
, addrport
, &address
, NULL
, &dir_port
)<0) {
4552 log_warn(LD_CONFIG
, "Error parsing DirServer address '%s'", addrport
);
4556 log_warn(LD_CONFIG
, "Missing port in DirServer address '%s'",addrport
);
4560 fingerprint
= smartlist_join_strings(items
, "", 0, NULL
);
4561 if (strlen(fingerprint
) != HEX_DIGEST_LEN
) {
4562 log_warn(LD_CONFIG
, "Key digest for DirServer is wrong length %d.",
4563 (int)strlen(fingerprint
));
4566 if (!strcmp(fingerprint
, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4567 /* a known bad fingerprint. refuse to use it. We can remove this
4568 * clause once Tor 0.1.2.17 is obsolete. */
4569 log_warn(LD_CONFIG
, "Dangerous dirserver line. To correct, erase your "
4570 "torrc file (%s), or reinstall Tor and use the default torrc.",
4574 if (base16_decode(digest
, DIGEST_LEN
, fingerprint
, HEX_DIGEST_LEN
)<0) {
4575 log_warn(LD_CONFIG
, "Unable to decode DirServer key digest.");
4579 if (!validate_only
&& (!required_type
|| required_type
& type
)) {
4581 type
&= required_type
; /* pare down what we think of them as an
4583 log_debug(LD_DIR
, "Trusted %d dirserver at %s:%d (%s)", (int)type
,
4584 address
, (int)dir_port
, (char*)smartlist_get(items
,0));
4585 if (!add_trusted_dir_server(nickname
, address
, dir_port
, or_port
,
4586 digest
, v3_digest
, type
))
4597 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
4598 smartlist_free(items
);
4602 tor_free(fingerprint
);
4606 /** Adjust the value of options->DataDirectory, or fill it in if it's
4607 * absent. Return 0 on success, -1 on failure. */
4609 normalize_data_directory(or_options_t
*options
)
4613 if (options
->DataDirectory
)
4614 return 0; /* all set */
4615 p
= tor_malloc(MAX_PATH
);
4616 strlcpy(p
,get_windows_conf_root(),MAX_PATH
);
4617 options
->DataDirectory
= p
;
4620 const char *d
= options
->DataDirectory
;
4624 if (strncmp(d
,"~/",2) == 0) {
4625 char *fn
= expand_filename(d
);
4627 log_warn(LD_CONFIG
,"Failed to expand filename \"%s\".", d
);
4630 if (!options
->DataDirectory
&& !strcmp(fn
,"/.tor")) {
4631 /* If our homedir is /, we probably don't want to use it. */
4632 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4635 "Default DataDirectory is \"~/.tor\". This expands to "
4636 "\"%s\", which is probably not what you want. Using "
4637 "\"%s"PATH_SEPARATOR
"tor\" instead
", fn, LOCALSTATEDIR);
4639 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor
");
4641 tor_free(options->DataDirectory);
4642 options->DataDirectory = fn;
4648 /** Check and normalize the value of options->DataDirectory; return 0 if it
4649 * is sane, -1 otherwise. */
4651 validate_data_directory(or_options_t *options)
4653 if (normalize_data_directory(options) < 0)
4655 tor_assert(options->DataDirectory);
4656 if (strlen(options->DataDirectory) > (512-128)) {
4657 log_warn(LD_CONFIG, "DataDirectory is too
long.");
4663 /** This string must remain the same forevermore. It is how we
4664 * recognize that the torrc file doesn't need to be backed up. */
4665 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4666 "if you edit it, comments will not be preserved"
4667 /** This string can change; it tries to give the reader an idea
4668 * that editing this file by hand is not a good plan. */
4669 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4670 "to torrc.orig.1 or similar, and Tor will ignore it"
4672 /** Save a configuration file for the configuration in <b>options</b>
4673 * into the file <b>fname</b>. If the file already exists, and
4674 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4675 * replace it. Return 0 on success, -1 on failure. */
4677 write_configuration_file(const char *fname, or_options_t *options)
4679 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4680 int rename_old = 0, r;
4684 switch (file_status(fname)) {
4686 old_val = read_file_to_str(fname, 0, NULL);
4687 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4698 "Config file \"%s\" is not a file? Failing.", fname);
4702 if (!(new_conf = options_dump(options, 1))) {
4703 log_warn(LD_BUG, "Couldn't get configuration string");
4707 tor_asprintf(&new_val, "%s\n%s\n\n%s",
4708 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4712 size_t fn_tmp_len = strlen(fname)+32;
4714 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4715 fn_tmp = tor_malloc(fn_tmp_len);
4717 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4718 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4722 if (file_status(fn_tmp) == FN_NOENT)
4726 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4727 if (rename(fname, fn_tmp) < 0) {
4729 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4730 fname, fn_tmp, strerror(errno));
4737 if (write_str_to_file(fname, new_val, 0) < 0)
4751 * Save the current configuration file value to disk. Return 0 on
4752 * success, -1 on failure.
4755 options_save_current(void)
4757 /* This fails if we can't write to our configuration file.
4759 * If we try falling back to datadirectory or something, we have a better
4760 * chance of saving the configuration, but a better chance of doing
4761 * something the user never expected. */
4762 return write_configuration_file(get_torrc_fname(), get_options());
4765 /** Mapping from a unit name to a multiplier for converting that unit into a
4767 struct unit_table_t {
4769 uint64_t multiplier;
4772 /** Table to map the names of memory units to the number of bytes they
4774 static struct unit_table_t memory_units[] = {
4781 { "kbytes", 1<<10 },
4782 { "kilobyte", 1<<10 },
4783 { "kilobytes", 1<<10 },
4787 { "mbytes", 1<<20 },
4788 { "megabyte", 1<<20 },
4789 { "megabytes", 1<<20 },
4792 { "gbytes", 1<<30 },
4793 { "gigabyte", 1<<30 },
4794 { "gigabytes", 1<<30 },
4795 { "tb", U64_LITERAL(1)<<40 },
4796 { "terabyte", U64_LITERAL(1)<<40 },
4797 { "terabytes", U64_LITERAL(1)<<40 },
4801 /** Table to map the names of time units to the number of seconds they
4803 static struct unit_table_t time_units[] = {
4811 { "day", 24*60*60 },
4812 { "days", 24*60*60 },
4813 { "week", 7*24*60*60 },
4814 { "weeks", 7*24*60*60 },
4818 /** Parse a string <b>val</b> containing a number, zero or more
4819 * spaces, and an optional unit string. If the unit appears in the
4820 * table <b>u</b>, then multiply the number by the unit multiplier.
4821 * On success, set *<b>ok</b> to 1 and return this product.
4822 * Otherwise, set *<b>ok</b> to 0.
4825 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4834 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4835 if (!*ok || (cp && *cp == '.')) {
4836 d = tor_parse_double(val, 0, UINT64_MAX, ok, &cp);
4844 v = use_float ? DBL_TO_U64(d) : v;
4848 cp = (char*) eat_whitespace(cp);
4850 for ( ;u->unit;++u) {
4851 if (!strcasecmp(u->unit, cp)) {
4853 v = u->multiplier * d;
4860 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4870 /** Parse a string in the format "number unit", where unit is a unit of
4871 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4872 * and return the number of bytes specified. Otherwise, set
4873 * *<b>ok</b> to false and return 0. */
4875 config_parse_memunit(const char *s, int *ok)
4877 uint64_t u = config_parse_units(s, memory_units, ok);
4881 /** Parse a string in the format "number unit", where unit is a unit of time.
4882 * On success, set *<b>ok</b> to true and return the number of seconds in
4883 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4886 config_parse_interval(const char *s, int *ok)
4889 r = config_parse_units(s, time_units, ok);
4893 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4901 * Initialize the libevent library.
4906 const char *badness=NULL;
4908 configure_libevent_logging();
4909 /* If the kernel complains that some method (say, epoll) doesn't
4910 * exist, we don't care about it, since libevent will cope.
4912 suppress_libevent_log_msg("Function not implemented");
4914 tor_check_libevent_header_compatibility();
4916 tor_libevent_initialize();
4918 suppress_libevent_log_msg(NULL);
4920 tor_check_libevent_version(tor_libevent_get_method(),
4921 get_options()->ORPort != 0,
4924 const char *v = tor_libevent_get_version_str();
4925 const char *m = tor_libevent_get_method();
4926 control_event_general_status(LOG_WARN,
4927 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
4932 /** Return the persistent state struct for this Tor. */
4936 tor_assert(global_state);
4937 return global_state;
4940 /** Return a newly allocated string holding a filename relative to the data
4941 * directory. If <b>sub1</b> is present, it is the first path component after
4942 * the data directory. If <b>sub2</b> is also present, it is the second path
4943 * component after the data directory. If <b>suffix</b> is present, it
4944 * is appended to the filename.
4947 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
4948 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
4949 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
4950 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
4952 * Note: Consider using the get_datadir_fname* macros in or.h.
4955 options_get_datadir_fname2_suffix(or_options_t *options,
4956 const char *sub1, const char *sub2,
4961 tor_assert(options);
4962 tor_assert(options->DataDirectory);
4963 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
4964 len = strlen(options->DataDirectory);
4966 len += strlen(sub1)+1;
4968 len += strlen(sub2)+1;
4971 len += strlen(suffix);
4973 fname = tor_malloc(len);
4976 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
4977 options->DataDirectory, sub1, sub2);
4979 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
4980 options->DataDirectory, sub1);
4983 strlcpy(fname, options->DataDirectory, len);
4986 strlcat(fname, suffix, len);
4990 /** Return 0 if every setting in <b>state</b> is reasonable, and a
4991 * permissible transition from <b>old_state</b>. Else warn and return -1.
4992 * Should have no side effects, except for normalizing the contents of
4995 /* XXX from_setconf is here because of bug 238 */
4997 or_state_validate(or_state_t *old_state, or_state_t *state,
4998 int from_setconf, char **msg)
5000 /* We don't use these; only options do. Still, we need to match that
5002 (void) from_setconf;
5005 if (entry_guards_parse_state(state, 0, msg)<0)
5011 /** Replace the current persistent state with <b>new_state</b> */
5013 or_state_set(or_state_t *new_state)
5017 tor_assert(new_state);
5018 config_free(&state_format, global_state);
5019 global_state = new_state;
5020 if (entry_guards_parse_state(global_state, 1, &err)<0) {
5021 log_warn(LD_GENERAL,"%s",err);
5025 if (rep_hist_load_state(global_state, &err)<0) {
5026 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
5030 if (circuit_build_times_parse_state(&circ_times, global_state) < 0) {
5037 * Save a broken state file to a backup location.
5040 or_state_save_broken(char *fname)
5043 file_status_t status;
5044 size_t len = strlen(fname)+16;
5045 char *fname2 = tor_malloc(len);
5046 for (i = 0; i < 100; ++i) {
5047 tor_snprintf(fname2, len, "%s.%d", fname, i);
5048 status = file_status(fname2);
5049 if (status == FN_NOENT)
5053 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
5054 "state files to move aside. Discarding the old state file.",
5058 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
5059 "to \"%s\". This could be a bug in Tor; please tell "
5060 "the developers.", fname, fname2);
5061 if (rename(fname, fname2) < 0) {
5062 log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
5063 "OS gave an error of %s", strerror(errno));
5069 /** Reload the persistent state from disk, generating a new state as needed.
5070 * Return 0 on success, less than 0 on failure.
5075 or_state_t *new_state = NULL;
5076 char *contents = NULL, *fname;
5077 char *errmsg = NULL;
5078 int r = -1, badstate = 0;
5080 fname = get_datadir_fname("state");
5081 switch (file_status(fname)) {
5083 if (!(contents = read_file_to_str(fname, 0, NULL))) {
5084 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
5093 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
5096 new_state = tor_malloc_zero(sizeof(or_state_t));
5097 new_state->_magic = OR_STATE_MAGIC;
5098 config_init(&state_format, new_state);
5100 config_line_t *lines=NULL;
5102 if (config_get_lines(contents, &lines)<0)
5104 assign_retval = config_assign(&state_format, new_state,
5105 lines, 0, 0, &errmsg);
5106 config_free_lines(lines);
5107 if (assign_retval<0)
5110 log_warn(LD_GENERAL, "%s", errmsg);
5115 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
5119 log_warn(LD_GENERAL, "%s", errmsg);
5123 if (badstate && !contents) {
5124 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
5125 " This is a bug in Tor.");
5127 } else if (badstate && contents) {
5128 or_state_save_broken(fname);
5131 config_free(&state_format, new_state);
5133 new_state = tor_malloc_zero(sizeof(or_state_t));
5134 new_state->_magic = OR_STATE_MAGIC;
5135 config_init(&state_format, new_state);
5136 } else if (contents) {
5137 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
5139 log_info(LD_GENERAL, "Initialized state");
5141 if (or_state_set(new_state) == -1) {
5142 or_state_save_broken(fname);
5146 global_state->next_write = 0;
5147 or_state_save(time(NULL));
5155 config_free(&state_format, new_state);
5160 /** If writing the state to disk fails, try again after this many seconds. */
5161 #define STATE_WRITE_RETRY_INTERVAL 3600
5163 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
5165 or_state_save(time_t now)
5167 char *state, *contents;
5168 char tbuf[ISO_TIME_LEN+1];
5171 tor_assert(global_state);
5173 if (global_state->next_write > now)
5176 /* Call everything else that might dirty the state even more, in order
5177 * to avoid redundant writes. */
5178 entry_guards_update_state(global_state);
5179 rep_hist_update_state(global_state);
5180 circuit_build_times_update_state(&circ_times, global_state);
5181 if (accounting_is_enabled(get_options()))
5182 accounting_run_housekeeping(now);
5184 tor_free(global_state->TorVersion);
5185 tor_asprintf(&global_state->TorVersion, "Tor %s", get_version());
5187 state = config_dump(&state_format, global_state, 1, 0);
5188 format_local_iso_time(tbuf, time(NULL));
5189 tor_asprintf(&contents,
5190 "# Tor state file last generated on %s local time\n"
5191 "# Other times below are in GMT\n"
5192 "# You *do not* need to edit this file.\n\n%s",
5195 fname = get_datadir_fname("state");
5196 if (write_str_to_file(fname, contents, 0)<0) {
5197 log_warn(LD_FS, "Unable to write state to file \"%s\"; "
5198 "will try again later", fname);
5199 global_state->LastWritten = -1;
5202 /* Try again after STATE_WRITE_RETRY_INTERVAL (or sooner, if the state
5203 * changes sooner). */
5204 global_state->next_write = now + STATE_WRITE_RETRY_INTERVAL;
5208 global_state->LastWritten = time(NULL);
5209 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
5213 global_state->next_write = TIME_MAX;
5217 /** Given a file name check to see whether the file exists but has not been
5218 * modified for a very long time. If so, remove it. */
5220 remove_file_if_very_old(const char *fname, time_t now)
5222 #define VERY_OLD_FILE_AGE (28*24*60*60)
5225 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
5226 char buf[ISO_TIME_LEN+1];
5227 format_local_iso_time(buf, st.st_mtime);
5228 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
5229 "Removing it.", fname, buf);
5234 /** Helper to implement GETINFO functions about configuration variables (not
5235 * their values). Given a "config/names" question, set *<b>answer</b> to a
5236 * new string describing the supported configuration variables and their
5239 getinfo_helper_config(control_connection_t *conn,
5240 const char *question, char **answer,
5241 const char **errmsg)
5245 if (!strcmp(question, "config/names")) {
5246 smartlist_t *sl = smartlist_create();
5248 for (i = 0; _option_vars[i].name; ++i) {
5249 config_var_t *var = &_option_vars[i];
5252 switch (var->type) {
5253 case CONFIG_TYPE_STRING: type = "String"; break;
5254 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
5255 case CONFIG_TYPE_UINT: type = "Integer"; break;
5256 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
5257 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
5258 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
5259 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
5260 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
5261 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
5262 case CONFIG_TYPE_CSV: type = "CommaList"; break;
5263 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
5264 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
5265 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
5267 case CONFIG_TYPE_OBSOLETE:
5272 tor_asprintf(&line, "%s %s\n",var->name,type);
5273 smartlist_add(sl, line);
5275 *answer = smartlist_join_strings(sl, "", 0, NULL);
5276 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));