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"
43 /** Enumeration of types which option values can take */
44 typedef enum config_type_t
{
45 CONFIG_TYPE_STRING
= 0, /**< An arbitrary string. */
46 CONFIG_TYPE_FILENAME
, /**< A filename: some prefixes get expanded. */
47 CONFIG_TYPE_UINT
, /**< A non-negative integer less than MAX_INT */
48 CONFIG_TYPE_PORT
, /**< A port from 1...65535, 0 for "not set", or
50 CONFIG_TYPE_INTERVAL
, /**< A number of seconds, with optional units*/
51 CONFIG_TYPE_MEMUNIT
, /**< A number of bytes, with optional units*/
52 CONFIG_TYPE_DOUBLE
, /**< A floating-point value */
53 CONFIG_TYPE_BOOL
, /**< A boolean value, expressed as 0 or 1. */
54 CONFIG_TYPE_ISOTIME
, /**< An ISO-formatted time relative to GMT. */
55 CONFIG_TYPE_CSV
, /**< A list of strings, separated by commas and
56 * optional whitespace. */
57 CONFIG_TYPE_LINELIST
, /**< Uninterpreted config lines */
58 CONFIG_TYPE_LINELIST_S
, /**< Uninterpreted, context-sensitive config lines,
59 * mixed with other keywords. */
60 CONFIG_TYPE_LINELIST_V
, /**< Catch-all "virtual" option to summarize
61 * context-sensitive config lines when fetching.
63 CONFIG_TYPE_ROUTERSET
, /**< A list of router names, addrs, and fps,
64 * parsed into a routerset_t. */
65 CONFIG_TYPE_OBSOLETE
, /**< Obsolete (ignored) option. */
68 /** An abbreviation for a configuration option allowed on the command line. */
69 typedef struct config_abbrev_t
{
70 const char *abbreviated
;
76 /* Handy macro for declaring "In the config file or on the command line,
77 * you can abbreviate <b>tok</b>s as <b>tok</b>". */
78 #define PLURAL(tok) { #tok, #tok "s", 0, 0 }
80 /** A list of abbreviations and aliases to map command-line options, obsolete
81 * option names, or alternative option names, to their current values. */
82 static config_abbrev_t _option_abbrevs
[] = {
87 PLURAL(LongLivedPort
),
88 PLURAL(HiddenServiceNode
),
89 PLURAL(HiddenServiceExcludeNode
),
92 PLURAL(RendExcludeNode
),
93 PLURAL(StrictEntryNode
),
94 PLURAL(StrictExitNode
),
97 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
98 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
99 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
100 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
101 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
102 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
103 { "MaxConn", "ConnLimit", 0, 1},
104 { "ORBindAddress", "ORListenAddress", 0, 0},
105 { "DirBindAddress", "DirListenAddress", 0, 0},
106 { "SocksBindAddress", "SocksListenAddress", 0, 0},
107 { "UseHelperNodes", "UseEntryGuards", 0, 0},
108 { "NumHelperNodes", "NumEntryGuards", 0, 0},
109 { "UseEntryNodes", "UseEntryGuards", 0, 0},
110 { "NumEntryNodes", "NumEntryGuards", 0, 0},
111 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
112 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
113 { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0},
114 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
115 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
116 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
117 { "StrictEntryNodes", "StrictNodes", 0, 1},
118 { "StrictExitNodes", "StrictNodes", 0, 1},
122 /** A list of state-file "abbreviations," for compatibility. */
123 static config_abbrev_t _state_abbrevs
[] = {
124 { "AccountingBytesReadInterval", "AccountingBytesReadInInterval", 0, 0 },
125 { "HelperNode", "EntryGuard", 0, 0 },
126 { "HelperNodeDownSince", "EntryGuardDownSince", 0, 0 },
127 { "HelperNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
128 { "EntryNode", "EntryGuard", 0, 0 },
129 { "EntryNodeDownSince", "EntryGuardDownSince", 0, 0 },
130 { "EntryNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
135 /** A variable allowed in the configuration file or on the command line. */
136 typedef struct config_var_t
{
137 const char *name
; /**< The full keyword (case insensitive). */
138 config_type_t type
; /**< How to interpret the type and turn it into a
140 off_t var_offset
; /**< Offset of the corresponding member of or_options_t. */
141 const char *initvalue
; /**< String (or null) describing initial value. */
144 /** An entry for config_vars: "The option <b>name</b> has type
145 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
146 * or_options_t.<b>member</b>"
148 #define VAR(name,conftype,member,initvalue) \
149 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
151 /** As VAR, but the option name and member name are the same. */
152 #define V(member,conftype,initvalue) \
153 VAR(#member, conftype, member, initvalue)
154 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
155 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
157 /** Array of configuration options. Until we disallow nonstandard
158 * abbreviations, order is significant, since the first matching option will
161 static config_var_t _option_vars
[] = {
162 OBSOLETE("AccountingMaxKB"),
163 V(AccountingMax
, MEMUNIT
, "0 bytes"),
164 V(AccountingStart
, STRING
, NULL
),
165 V(Address
, STRING
, NULL
),
166 V(AllowDotExit
, BOOL
, "0"),
167 V(AllowInvalidNodes
, CSV
, "middle,rendezvous"),
168 V(AllowNonRFC953Hostnames
, BOOL
, "0"),
169 V(AllowSingleHopCircuits
, BOOL
, "0"),
170 V(AllowSingleHopExits
, BOOL
, "0"),
171 V(AlternateBridgeAuthority
, LINELIST
, NULL
),
172 V(AlternateDirAuthority
, LINELIST
, NULL
),
173 V(AlternateHSAuthority
, LINELIST
, NULL
),
174 V(AssumeReachable
, BOOL
, "0"),
175 V(AuthDirBadDir
, LINELIST
, NULL
),
176 V(AuthDirBadExit
, LINELIST
, NULL
),
177 V(AuthDirInvalid
, LINELIST
, NULL
),
178 V(AuthDirReject
, LINELIST
, NULL
),
179 V(AuthDirRejectUnlisted
, BOOL
, "0"),
180 V(AuthDirListBadDirs
, BOOL
, "0"),
181 V(AuthDirListBadExits
, BOOL
, "0"),
182 V(AuthDirMaxServersPerAddr
, UINT
, "2"),
183 V(AuthDirMaxServersPerAuthAddr
,UINT
, "5"),
184 VAR("AuthoritativeDirectory", BOOL
, AuthoritativeDir
, "0"),
185 V(AutomapHostsOnResolve
, BOOL
, "0"),
186 V(AutomapHostsSuffixes
, CSV
, ".onion,.exit"),
187 V(AvoidDiskWrites
, BOOL
, "0"),
188 V(BandwidthBurst
, MEMUNIT
, "10 MB"),
189 V(BandwidthRate
, MEMUNIT
, "5 MB"),
190 V(BridgeAuthoritativeDir
, BOOL
, "0"),
191 VAR("Bridge", LINELIST
, Bridges
, NULL
),
192 V(BridgePassword
, STRING
, NULL
),
193 V(BridgeRecordUsageByCountry
, BOOL
, "1"),
194 V(BridgeRelay
, BOOL
, "0"),
195 V(CellStatistics
, BOOL
, "0"),
196 V(LearnCircuitBuildTimeout
, BOOL
, "1"),
197 V(CircuitBuildTimeout
, INTERVAL
, "0"),
198 V(CircuitIdleTimeout
, INTERVAL
, "1 hour"),
199 V(CircuitStreamTimeout
, INTERVAL
, "0"),
200 V(CircuitPriorityHalflife
, DOUBLE
, "-100.0"), /*negative:'Use default'*/
201 V(ClientDNSRejectInternalAddresses
, BOOL
,"1"),
202 V(ClientRejectInternalAddresses
, BOOL
, "1"),
203 V(ClientOnly
, BOOL
, "0"),
204 V(ConsensusParams
, STRING
, NULL
),
205 V(ConnLimit
, UINT
, "1000"),
206 V(ConstrainedSockets
, BOOL
, "0"),
207 V(ConstrainedSockSize
, MEMUNIT
, "8192"),
208 V(ContactInfo
, STRING
, NULL
),
209 V(ControlListenAddress
, LINELIST
, NULL
),
210 V(ControlPort
, PORT
, "0"),
211 V(ControlPortFileGroupReadable
,BOOL
, "0"),
212 V(ControlPortWriteToFile
, FILENAME
, NULL
),
213 V(ControlSocket
, LINELIST
, NULL
),
214 V(ControlSocketsGroupWritable
, BOOL
, "0"),
215 V(CookieAuthentication
, BOOL
, "0"),
216 V(CookieAuthFileGroupReadable
, BOOL
, "0"),
217 V(CookieAuthFile
, STRING
, NULL
),
218 V(DataDirectory
, FILENAME
, NULL
),
219 OBSOLETE("DebugLogFile"),
220 V(DirAllowPrivateAddresses
, BOOL
, NULL
),
221 V(TestingAuthDirTimeToLearnReachability
, INTERVAL
, "30 minutes"),
222 V(DirListenAddress
, LINELIST
, NULL
),
223 OBSOLETE("DirFetchPeriod"),
224 V(DirPolicy
, LINELIST
, NULL
),
225 V(DirPort
, PORT
, "0"),
226 V(DirPortFrontPage
, FILENAME
, NULL
),
227 OBSOLETE("DirPostPeriod"),
228 OBSOLETE("DirRecordUsageByCountry"),
229 OBSOLETE("DirRecordUsageGranularity"),
230 OBSOLETE("DirRecordUsageRetainIPs"),
231 OBSOLETE("DirRecordUsageSaveInterval"),
232 V(DirReqStatistics
, BOOL
, "0"),
233 VAR("DirServer", LINELIST
, DirServers
, NULL
),
234 V(DisableAllSwap
, BOOL
, "0"),
235 V(DNSPort
, PORT
, "0"),
236 V(DNSListenAddress
, LINELIST
, NULL
),
237 V(DownloadExtraInfo
, BOOL
, "0"),
238 V(EnforceDistinctSubnets
, BOOL
, "1"),
239 V(EntryNodes
, ROUTERSET
, NULL
),
240 V(EntryStatistics
, BOOL
, "0"),
241 V(TestingEstimatedDescriptorPropagationTime
, INTERVAL
, "10 minutes"),
242 V(ExcludeNodes
, ROUTERSET
, NULL
),
243 V(ExcludeExitNodes
, ROUTERSET
, NULL
),
244 V(ExcludeSingleHopRelays
, BOOL
, "1"),
245 V(ExitNodes
, ROUTERSET
, NULL
),
246 V(ExitPolicy
, LINELIST
, NULL
),
247 V(ExitPolicyRejectPrivate
, BOOL
, "1"),
248 V(ExitPortStatistics
, BOOL
, "0"),
249 V(ExtraInfoStatistics
, BOOL
, "0"),
252 V(FallbackNetworkstatusFile
, FILENAME
, "fallback-consensus"),
254 V(FallbackNetworkstatusFile
, FILENAME
,
255 SHARE_DATADIR PATH_SEPARATOR
"tor" PATH_SEPARATOR
"fallback-consensus"),
257 V(FascistFirewall
, BOOL
, "0"),
258 V(FirewallPorts
, CSV
, ""),
259 V(FastFirstHopPK
, BOOL
, "1"),
260 V(FetchDirInfoEarly
, BOOL
, "0"),
261 V(FetchDirInfoExtraEarly
, BOOL
, "0"),
262 V(FetchServerDescriptors
, BOOL
, "1"),
263 V(FetchHidServDescriptors
, BOOL
, "1"),
264 V(FetchUselessDescriptors
, BOOL
, "0"),
265 V(FetchV2Networkstatus
, BOOL
, "0"),
267 V(GeoIPFile
, FILENAME
, "<default>"),
269 V(GeoIPFile
, FILENAME
,
270 SHARE_DATADIR PATH_SEPARATOR
"tor" PATH_SEPARATOR
"geoip"),
273 V(HardwareAccel
, BOOL
, "0"),
274 V(AccelName
, STRING
, NULL
),
275 V(AccelDir
, FILENAME
, NULL
),
276 V(HashedControlPassword
, LINELIST
, NULL
),
277 V(HidServDirectoryV2
, BOOL
, "1"),
278 VAR("HiddenServiceDir", LINELIST_S
, RendConfigLines
, NULL
),
279 OBSOLETE("HiddenServiceExcludeNodes"),
280 OBSOLETE("HiddenServiceNodes"),
281 VAR("HiddenServiceOptions",LINELIST_V
, RendConfigLines
, NULL
),
282 VAR("HiddenServicePort", LINELIST_S
, RendConfigLines
, NULL
),
283 VAR("HiddenServiceVersion",LINELIST_S
, RendConfigLines
, NULL
),
284 VAR("HiddenServiceAuthorizeClient",LINELIST_S
,RendConfigLines
, NULL
),
285 V(HidServAuth
, LINELIST
, NULL
),
286 V(HSAuthoritativeDir
, BOOL
, "0"),
287 OBSOLETE("HSAuthorityRecordStats"),
288 V(HTTPProxy
, STRING
, NULL
),
289 V(HTTPProxyAuthenticator
, STRING
, NULL
),
290 V(HTTPSProxy
, STRING
, NULL
),
291 V(HTTPSProxyAuthenticator
, STRING
, NULL
),
292 V(Socks4Proxy
, STRING
, NULL
),
293 V(Socks5Proxy
, STRING
, NULL
),
294 V(Socks5ProxyUsername
, STRING
, NULL
),
295 V(Socks5ProxyPassword
, STRING
, NULL
),
296 OBSOLETE("IgnoreVersion"),
297 V(KeepalivePeriod
, INTERVAL
, "5 minutes"),
298 VAR("Log", LINELIST
, Logs
, NULL
),
299 V(LogMessageDomains
, BOOL
, "0"),
300 OBSOLETE("LinkPadding"),
301 OBSOLETE("LogLevel"),
303 V(LongLivedPorts
, CSV
,
304 "21,22,706,1863,5050,5190,5222,5223,6667,6697,8300"),
305 VAR("MapAddress", LINELIST
, AddressMap
, NULL
),
306 V(MaxAdvertisedBandwidth
, MEMUNIT
, "1 GB"),
307 V(MaxCircuitDirtiness
, INTERVAL
, "10 minutes"),
308 V(MaxOnionsPending
, UINT
, "100"),
309 OBSOLETE("MonthlyAccountingStart"),
310 V(MyFamily
, STRING
, NULL
),
311 V(NewCircuitPeriod
, INTERVAL
, "30 seconds"),
312 VAR("NamingAuthoritativeDirectory",BOOL
, NamingAuthoritativeDir
, "0"),
313 V(NATDListenAddress
, LINELIST
, NULL
),
314 V(NATDPort
, PORT
, "0"),
315 V(Nickname
, STRING
, NULL
),
316 V(WarnUnsafeSocks
, BOOL
, "1"),
317 OBSOLETE("NoPublish"),
318 VAR("NodeFamily", LINELIST
, NodeFamilies
, NULL
),
319 V(NumCPUs
, UINT
, "1"),
320 V(NumEntryGuards
, UINT
, "3"),
321 V(ORListenAddress
, LINELIST
, NULL
),
322 V(ORPort
, PORT
, "0"),
323 V(OutboundBindAddress
, STRING
, NULL
),
324 OBSOLETE("PathlenCoinWeight"),
325 V(PerConnBWBurst
, MEMUNIT
, "0"),
326 V(PerConnBWRate
, MEMUNIT
, "0"),
327 V(PidFile
, STRING
, NULL
),
328 V(TestingTorNetwork
, BOOL
, "0"),
329 V(PreferTunneledDirConns
, BOOL
, "1"),
330 V(ProtocolWarnings
, BOOL
, "0"),
331 V(PublishServerDescriptor
, CSV
, "1"),
332 V(PublishHidServDescriptors
, BOOL
, "1"),
333 V(ReachableAddresses
, LINELIST
, NULL
),
334 V(ReachableDirAddresses
, LINELIST
, NULL
),
335 V(ReachableORAddresses
, LINELIST
, NULL
),
336 V(RecommendedVersions
, LINELIST
, NULL
),
337 V(RecommendedClientVersions
, LINELIST
, NULL
),
338 V(RecommendedServerVersions
, LINELIST
, NULL
),
339 OBSOLETE("RedirectExit"),
340 V(RefuseUnknownExits
, STRING
, "auto"),
341 V(RejectPlaintextPorts
, CSV
, ""),
342 V(RelayBandwidthBurst
, MEMUNIT
, "0"),
343 V(RelayBandwidthRate
, MEMUNIT
, "0"),
344 OBSOLETE("RendExcludeNodes"),
345 OBSOLETE("RendNodes"),
346 V(RendPostPeriod
, INTERVAL
, "1 hour"),
347 V(RephistTrackTime
, INTERVAL
, "24 hours"),
348 OBSOLETE("RouterFile"),
349 V(RunAsDaemon
, BOOL
, "0"),
350 // V(RunTesting, BOOL, "0"),
351 OBSOLETE("RunTesting"), // currently unused
352 V(SafeLogging
, STRING
, "1"),
353 V(SafeSocks
, BOOL
, "0"),
354 V(ServerDNSAllowBrokenConfig
, BOOL
, "1"),
355 V(ServerDNSAllowNonRFC953Hostnames
, BOOL
,"0"),
356 V(ServerDNSDetectHijacking
, BOOL
, "1"),
357 V(ServerDNSRandomizeCase
, BOOL
, "1"),
358 V(ServerDNSResolvConfFile
, STRING
, NULL
),
359 V(ServerDNSSearchDomains
, BOOL
, "0"),
360 V(ServerDNSTestAddresses
, CSV
,
361 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
362 V(ShutdownWaitLength
, INTERVAL
, "30 seconds"),
363 V(SocksListenAddress
, LINELIST
, NULL
),
364 V(SocksPolicy
, LINELIST
, NULL
),
365 V(SocksPort
, PORT
, "9050"),
366 V(SocksTimeout
, INTERVAL
, "2 minutes"),
367 OBSOLETE("StatusFetchPeriod"),
368 V(StrictNodes
, BOOL
, "0"),
370 V(TestSocks
, BOOL
, "0"),
372 V(TrackHostExits
, CSV
, NULL
),
373 V(TrackHostExitsExpire
, INTERVAL
, "30 minutes"),
374 OBSOLETE("TrafficShaping"),
375 V(TransListenAddress
, LINELIST
, NULL
),
376 V(TransPort
, PORT
, "0"),
377 V(TunnelDirConns
, BOOL
, "1"),
378 V(UpdateBridgesFromAuthority
, BOOL
, "0"),
379 V(UseBridges
, BOOL
, "0"),
380 V(UseEntryGuards
, BOOL
, "1"),
381 V(User
, STRING
, NULL
),
382 VAR("V1AuthoritativeDirectory",BOOL
, V1AuthoritativeDir
, "0"),
383 VAR("V2AuthoritativeDirectory",BOOL
, V2AuthoritativeDir
, "0"),
384 VAR("V3AuthoritativeDirectory",BOOL
, V3AuthoritativeDir
, "0"),
385 V(TestingV3AuthInitialVotingInterval
, INTERVAL
, "30 minutes"),
386 V(TestingV3AuthInitialVoteDelay
, INTERVAL
, "5 minutes"),
387 V(TestingV3AuthInitialDistDelay
, INTERVAL
, "5 minutes"),
388 V(V3AuthVotingInterval
, INTERVAL
, "1 hour"),
389 V(V3AuthVoteDelay
, INTERVAL
, "5 minutes"),
390 V(V3AuthDistDelay
, INTERVAL
, "5 minutes"),
391 V(V3AuthNIntervalsValid
, UINT
, "3"),
392 V(V3AuthUseLegacyKey
, BOOL
, "0"),
393 V(V3BandwidthsFile
, FILENAME
, NULL
),
394 VAR("VersioningAuthoritativeDirectory",BOOL
,VersioningAuthoritativeDir
, "0"),
395 V(VirtualAddrNetwork
, STRING
, "127.192.0.0/10"),
396 V(WarnPlaintextPorts
, CSV
, "23,109,110,143"),
397 VAR("__ReloadTorrcOnSIGHUP", BOOL
, ReloadTorrcOnSIGHUP
, "1"),
398 VAR("__AllDirActionsPrivate", BOOL
, AllDirActionsPrivate
, "0"),
399 VAR("__DisablePredictedCircuits",BOOL
,DisablePredictedCircuits
, "0"),
400 VAR("__LeaveStreamsUnattached",BOOL
, LeaveStreamsUnattached
, "0"),
401 VAR("__HashedControlSessionPassword", LINELIST
, HashedControlSessionPassword
,
403 VAR("__OwningControllerProcess",STRING
,OwningControllerProcess
, NULL
),
404 V(MinUptimeHidServDirectoryV2
, INTERVAL
, "24 hours"),
405 V(_UsingTestNetworkDefaults
, BOOL
, "0"),
407 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
410 /** Override default values with these if the user sets the TestingTorNetwork
412 static config_var_t testing_tor_network_defaults
[] = {
413 V(ServerDNSAllowBrokenConfig
, BOOL
, "1"),
414 V(DirAllowPrivateAddresses
, BOOL
, "1"),
415 V(EnforceDistinctSubnets
, BOOL
, "0"),
416 V(AssumeReachable
, BOOL
, "1"),
417 V(AuthDirMaxServersPerAddr
, UINT
, "0"),
418 V(AuthDirMaxServersPerAuthAddr
,UINT
, "0"),
419 V(ClientDNSRejectInternalAddresses
, BOOL
,"0"),
420 V(ClientRejectInternalAddresses
, BOOL
, "0"),
421 V(ExitPolicyRejectPrivate
, BOOL
, "0"),
422 V(V3AuthVotingInterval
, INTERVAL
, "5 minutes"),
423 V(V3AuthVoteDelay
, INTERVAL
, "20 seconds"),
424 V(V3AuthDistDelay
, INTERVAL
, "20 seconds"),
425 V(TestingV3AuthInitialVotingInterval
, INTERVAL
, "5 minutes"),
426 V(TestingV3AuthInitialVoteDelay
, INTERVAL
, "20 seconds"),
427 V(TestingV3AuthInitialDistDelay
, INTERVAL
, "20 seconds"),
428 V(TestingAuthDirTimeToLearnReachability
, INTERVAL
, "0 minutes"),
429 V(TestingEstimatedDescriptorPropagationTime
, INTERVAL
, "0 minutes"),
430 V(MinUptimeHidServDirectoryV2
, INTERVAL
, "0 minutes"),
431 V(_UsingTestNetworkDefaults
, BOOL
, "1"),
432 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
436 #define VAR(name,conftype,member,initvalue) \
437 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
440 /** Array of "state" variables saved to the ~/.tor/state file. */
441 static config_var_t _state_vars
[] = {
442 V(AccountingBytesReadInInterval
, MEMUNIT
, NULL
),
443 V(AccountingBytesWrittenInInterval
, MEMUNIT
, NULL
),
444 V(AccountingExpectedUsage
, MEMUNIT
, NULL
),
445 V(AccountingIntervalStart
, ISOTIME
, NULL
),
446 V(AccountingSecondsActive
, INTERVAL
, NULL
),
447 V(AccountingSecondsToReachSoftLimit
,INTERVAL
, NULL
),
448 V(AccountingSoftLimitHitAt
, ISOTIME
, NULL
),
449 V(AccountingBytesAtSoftLimit
, MEMUNIT
, NULL
),
451 VAR("EntryGuard", LINELIST_S
, EntryGuards
, NULL
),
452 VAR("EntryGuardDownSince", LINELIST_S
, EntryGuards
, NULL
),
453 VAR("EntryGuardUnlistedSince", LINELIST_S
, EntryGuards
, NULL
),
454 VAR("EntryGuardAddedBy", LINELIST_S
, EntryGuards
, NULL
),
455 V(EntryGuards
, LINELIST_V
, NULL
),
457 V(BWHistoryReadEnds
, ISOTIME
, NULL
),
458 V(BWHistoryReadInterval
, UINT
, "900"),
459 V(BWHistoryReadValues
, CSV
, ""),
460 V(BWHistoryReadMaxima
, CSV
, ""),
461 V(BWHistoryWriteEnds
, ISOTIME
, NULL
),
462 V(BWHistoryWriteInterval
, UINT
, "900"),
463 V(BWHistoryWriteValues
, CSV
, ""),
464 V(BWHistoryWriteMaxima
, CSV
, ""),
465 V(BWHistoryDirReadEnds
, ISOTIME
, NULL
),
466 V(BWHistoryDirReadInterval
, UINT
, "900"),
467 V(BWHistoryDirReadValues
, CSV
, ""),
468 V(BWHistoryDirReadMaxima
, CSV
, ""),
469 V(BWHistoryDirWriteEnds
, ISOTIME
, NULL
),
470 V(BWHistoryDirWriteInterval
, UINT
, "900"),
471 V(BWHistoryDirWriteValues
, CSV
, ""),
472 V(BWHistoryDirWriteMaxima
, CSV
, ""),
474 V(TorVersion
, STRING
, NULL
),
476 V(LastRotatedOnionKey
, ISOTIME
, NULL
),
477 V(LastWritten
, ISOTIME
, NULL
),
479 V(TotalBuildTimes
, UINT
, NULL
),
480 V(CircuitBuildAbandonedCount
, UINT
, "0"),
481 VAR("CircuitBuildTimeBin", LINELIST_S
, BuildtimeHistogram
, NULL
),
482 VAR("BuildtimeHistogram", LINELIST_V
, BuildtimeHistogram
, NULL
),
484 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
491 /** Represents an English description of a configuration variable; used when
492 * generating configuration file comments. */
493 typedef struct config_var_description_t
{
495 const char *description
;
496 } config_var_description_t
;
498 /** Type of a callback to validate whether a given configuration is
499 * well-formed and consistent. See options_trial_assign() for documentation
501 typedef int (*validate_fn_t
)(void*,void*,int,char**);
503 /** Information on the keys, value types, key-to-struct-member mappings,
504 * variable descriptions, validation functions, and abbreviations for a
505 * configuration or storage format. */
507 size_t size
; /**< Size of the struct that everything gets parsed into. */
508 uint32_t magic
; /**< Required 'magic value' to make sure we have a struct
509 * of the right type. */
510 off_t magic_offset
; /**< Offset of the magic value within the struct. */
511 config_abbrev_t
*abbrevs
; /**< List of abbreviations that we expand when
512 * parsing this format. */
513 config_var_t
*vars
; /**< List of variables we recognize, their default
514 * values, and where we stick them in the structure. */
515 validate_fn_t validate_fn
; /**< Function to validate config. */
516 /** If present, extra is a LINELIST variable for unrecognized
517 * lines. Otherwise, unrecognized lines are an error. */
521 /** Macro: assert that <b>cfg</b> has the right magic field for format
523 #define CHECK(fmt, cfg) STMT_BEGIN \
524 tor_assert(fmt && cfg); \
525 tor_assert((fmt)->magic == \
526 *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
530 static char *get_windows_conf_root(void);
532 static void config_line_append(config_line_t
**lst
,
533 const char *key
, const char *val
);
534 static void option_clear(config_format_t
*fmt
, or_options_t
*options
,
536 static void option_reset(config_format_t
*fmt
, or_options_t
*options
,
537 config_var_t
*var
, int use_defaults
);
538 static void config_free(config_format_t
*fmt
, void *options
);
539 static int config_lines_eq(config_line_t
*a
, config_line_t
*b
);
540 static int option_is_same(config_format_t
*fmt
,
541 or_options_t
*o1
, or_options_t
*o2
,
543 static or_options_t
*options_dup(config_format_t
*fmt
, or_options_t
*old
);
544 static int options_validate(or_options_t
*old_options
, or_options_t
*options
,
545 int from_setconf
, char **msg
);
546 static int options_act_reversible(or_options_t
*old_options
, char **msg
);
547 static int options_act(or_options_t
*old_options
);
548 static int options_transition_allowed(or_options_t
*old
, or_options_t
*new,
550 static int options_transition_affects_workers(or_options_t
*old_options
,
551 or_options_t
*new_options
);
552 static int options_transition_affects_descriptor(or_options_t
*old_options
,
553 or_options_t
*new_options
);
554 static int check_nickname_list(const char *lst
, const char *name
, char **msg
);
555 static void config_register_addressmaps(or_options_t
*options
);
557 static int parse_bridge_line(const char *line
, int validate_only
);
558 static int parse_dir_server_line(const char *line
,
559 authority_type_t required_type
,
561 static int validate_data_directory(or_options_t
*options
);
562 static int write_configuration_file(const char *fname
, or_options_t
*options
);
563 static config_line_t
*get_assigned_option(config_format_t
*fmt
,
564 void *options
, const char *key
,
566 static void config_init(config_format_t
*fmt
, void *options
);
567 static int or_state_validate(or_state_t
*old_options
, or_state_t
*options
,
568 int from_setconf
, char **msg
);
569 static int or_state_load(void);
570 static int options_init_logs(or_options_t
*options
, int validate_only
);
572 static int is_listening_on_low_port(int port_option
,
573 const config_line_t
*listen_options
);
575 static uint64_t config_parse_memunit(const char *s
, int *ok
);
576 static int config_parse_interval(const char *s
, int *ok
);
577 static void init_libevent(void);
578 static int opt_streq(const char *s1
, const char *s2
);
580 /** Magic value for or_options_t. */
581 #define OR_OPTIONS_MAGIC 9090909
583 /** Configuration format for or_options_t. */
584 static config_format_t options_format
= {
585 sizeof(or_options_t
),
587 STRUCT_OFFSET(or_options_t
, _magic
),
590 (validate_fn_t
)options_validate
,
594 /** Magic value for or_state_t. */
595 #define OR_STATE_MAGIC 0x57A73f57
597 /** "Extra" variable in the state that receives lines we can't parse. This
598 * lets us preserve options from versions of Tor newer than us. */
599 static config_var_t state_extra_var
= {
600 "__extra", CONFIG_TYPE_LINELIST
, STRUCT_OFFSET(or_state_t
, ExtraLines
), NULL
603 /** Configuration format for or_state_t. */
604 static config_format_t state_format
= {
607 STRUCT_OFFSET(or_state_t
, _magic
),
610 (validate_fn_t
)or_state_validate
,
615 * Functions to read and write the global options pointer.
618 /** Command-line and config-file options. */
619 static or_options_t
*global_options
= NULL
;
620 /** Name of most recently read torrc file. */
621 static char *torrc_fname
= NULL
;
622 /** Persistent serialized state. */
623 static or_state_t
*global_state
= NULL
;
624 /** Configuration Options set by command line. */
625 static config_line_t
*global_cmdline_options
= NULL
;
626 /** Contents of most recently read DirPortFrontPage file. */
627 static char *global_dirfrontpagecontents
= NULL
;
629 /** Return the contents of our frontpage string, or NULL if not configured. */
631 get_dirportfrontpage(void)
633 return global_dirfrontpagecontents
;
636 /** Allocate an empty configuration object of a given format type. */
638 config_alloc(config_format_t
*fmt
)
640 void *opts
= tor_malloc_zero(fmt
->size
);
641 *(uint32_t*)STRUCT_VAR_P(opts
, fmt
->magic_offset
) = fmt
->magic
;
646 /** Return the currently configured options. */
650 tor_assert(global_options
);
651 return global_options
;
654 /** Change the current global options to contain <b>new_val</b> instead of
655 * their current value; take action based on the new value; free the old value
656 * as necessary. Returns 0 on success, -1 on failure.
659 set_options(or_options_t
*new_val
, char **msg
)
661 or_options_t
*old_options
= global_options
;
662 global_options
= new_val
;
663 /* Note that we pass the *old* options below, for comparison. It
664 * pulls the new options directly out of global_options. */
665 if (options_act_reversible(old_options
, msg
)<0) {
667 global_options
= old_options
;
670 if (options_act(old_options
) < 0) { /* acting on the options failed. die. */
672 "Acting on config options left us in a broken state. Dying.");
676 config_free(&options_format
, old_options
);
681 extern const char tor_git_revision
[]; /* from tor_main.c */
683 /** The version of this Tor process, as parsed. */
684 static char *_version
= NULL
;
686 /** Return the current Tor version. */
690 if (_version
== NULL
) {
691 if (strlen(tor_git_revision
)) {
692 size_t len
= strlen(VERSION
)+strlen(tor_git_revision
)+16;
693 _version
= tor_malloc(len
);
694 tor_snprintf(_version
, len
, "%s (git-%s)", VERSION
, tor_git_revision
);
696 _version
= tor_strdup(VERSION
);
702 /** Release additional memory allocated in options
705 or_options_free(or_options_t
*options
)
710 routerset_free(options
->_ExcludeExitNodesUnion
);
711 config_free(&options_format
, options
);
714 /** Release all memory and resources held by global configuration structures.
717 config_free_all(void)
719 or_options_free(global_options
);
720 global_options
= NULL
;
722 config_free(&state_format
, global_state
);
725 config_free_lines(global_cmdline_options
);
726 global_cmdline_options
= NULL
;
728 tor_free(torrc_fname
);
730 tor_free(global_dirfrontpagecontents
);
733 /** Make <b>address</b> -- a piece of information related to our operation as
734 * a client -- safe to log according to the settings in options->SafeLogging,
737 * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
740 safe_str_client(const char *address
)
743 if (get_options()->_SafeLogging
== SAFELOG_SCRUB_ALL
)
749 /** Make <b>address</b> -- a piece of information of unspecified sensitivity
750 * -- safe to log according to the settings in options->SafeLogging, and
753 * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
757 safe_str(const char *address
)
760 if (get_options()->_SafeLogging
!= SAFELOG_SCRUB_NONE
)
766 /** Equivalent to escaped(safe_str_client(address)). See reentrancy note on
767 * escaped(): don't use this outside the main thread, or twice in the same
770 escaped_safe_str_client(const char *address
)
772 if (get_options()->_SafeLogging
== SAFELOG_SCRUB_ALL
)
775 return escaped(address
);
778 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
779 * escaped(): don't use this outside the main thread, or twice in the same
782 escaped_safe_str(const char *address
)
784 if (get_options()->_SafeLogging
!= SAFELOG_SCRUB_NONE
)
787 return escaped(address
);
790 /** Add the default directory authorities directly into the trusted dir list,
791 * but only add them insofar as they share bits with <b>type</b>. */
793 add_default_trusted_dir_authorities(authority_type_t type
)
796 const char *dirservers
[] = {
797 "moria1 orport=9101 no-v2 "
798 "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
799 "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
800 "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
801 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
802 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
803 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
804 "Tonga orport=443 bridge no-v2 82.94.251.203:80 "
805 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
806 "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
807 "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
808 "gabelmoo orport=443 no-v2 "
809 "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
810 "212.112.245.170:80 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
811 "dannenberg orport=443 no-v2 "
812 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
813 "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
814 "urras orport=80 no-v2 v3ident=80550987E1D626E3EBA5E5E75A458DE0626D088C "
815 "208.83.223.34:443 0AD3 FA88 4D18 F89E EA2D 89C0 1937 9E0E 7FD9 4417",
816 "maatuska orport=80 no-v2 "
817 "v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
818 "213.115.239.118:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
821 for (i
=0; dirservers
[i
]; i
++) {
822 if (parse_dir_server_line(dirservers
[i
], type
, 0)<0) {
823 log_err(LD_BUG
, "Couldn't parse internal dirserver line %s",
829 /** Look at all the config options for using alternate directory
830 * authorities, and make sure none of them are broken. Also, warn the
831 * user if we changed any dangerous ones.
834 validate_dir_authorities(or_options_t
*options
, or_options_t
*old_options
)
838 if (options
->DirServers
&&
839 (options
->AlternateDirAuthority
|| options
->AlternateBridgeAuthority
||
840 options
->AlternateHSAuthority
)) {
842 "You cannot set both DirServers and Alternate*Authority.");
846 /* do we want to complain to the user about being partitionable? */
847 if ((options
->DirServers
&&
849 !config_lines_eq(options
->DirServers
, old_options
->DirServers
))) ||
850 (options
->AlternateDirAuthority
&&
852 !config_lines_eq(options
->AlternateDirAuthority
,
853 old_options
->AlternateDirAuthority
)))) {
855 "You have used DirServer or AlternateDirAuthority to "
856 "specify alternate directory authorities in "
857 "your configuration. This is potentially dangerous: it can "
858 "make you look different from all other Tor users, and hurt "
859 "your anonymity. Even if you've specified the same "
860 "authorities as Tor uses by default, the defaults could "
861 "change in the future. Be sure you know what you're doing.");
864 /* Now go through the four ways you can configure an alternate
865 * set of directory authorities, and make sure none are broken. */
866 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
)
867 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
869 for (cl
= options
->AlternateBridgeAuthority
; cl
; cl
= cl
->next
)
870 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
872 for (cl
= options
->AlternateDirAuthority
; cl
; cl
= cl
->next
)
873 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
875 for (cl
= options
->AlternateHSAuthority
; cl
; cl
= cl
->next
)
876 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
881 /** Look at all the config options and assign new dir authorities
885 consider_adding_dir_authorities(or_options_t
*options
,
886 or_options_t
*old_options
)
890 !smartlist_len(router_get_trusted_dir_servers()) || !old_options
||
891 !config_lines_eq(options
->DirServers
, old_options
->DirServers
) ||
892 !config_lines_eq(options
->AlternateBridgeAuthority
,
893 old_options
->AlternateBridgeAuthority
) ||
894 !config_lines_eq(options
->AlternateDirAuthority
,
895 old_options
->AlternateDirAuthority
) ||
896 !config_lines_eq(options
->AlternateHSAuthority
,
897 old_options
->AlternateHSAuthority
);
900 return 0; /* all done */
902 /* Start from a clean slate. */
903 clear_trusted_dir_servers();
905 if (!options
->DirServers
) {
906 /* then we may want some of the defaults */
907 authority_type_t type
= NO_AUTHORITY
;
908 if (!options
->AlternateBridgeAuthority
)
909 type
|= BRIDGE_AUTHORITY
;
910 if (!options
->AlternateDirAuthority
)
911 type
|= V1_AUTHORITY
| V2_AUTHORITY
| V3_AUTHORITY
;
912 if (!options
->AlternateHSAuthority
)
913 type
|= HIDSERV_AUTHORITY
;
914 add_default_trusted_dir_authorities(type
);
917 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
)
918 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
920 for (cl
= options
->AlternateBridgeAuthority
; cl
; cl
= cl
->next
)
921 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
923 for (cl
= options
->AlternateDirAuthority
; cl
; cl
= cl
->next
)
924 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
926 for (cl
= options
->AlternateHSAuthority
; cl
; cl
= cl
->next
)
927 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
932 /** Fetch the active option list, and take actions based on it. All of the
933 * things we do should survive being done repeatedly. If present,
934 * <b>old_options</b> contains the previous value of the options.
936 * Return 0 if all goes well, return -1 if things went badly.
939 options_act_reversible(or_options_t
*old_options
, char **msg
)
941 smartlist_t
*new_listeners
= smartlist_create();
942 smartlist_t
*replaced_listeners
= smartlist_create();
943 static int libevent_initialized
= 0;
944 or_options_t
*options
= get_options();
945 int running_tor
= options
->command
== CMD_RUN_TOR
;
946 int set_conn_limit
= 0;
950 /* Daemonize _first_, since we only want to open most of this stuff in
951 * the subprocess. Libevent bases can't be reliably inherited across
953 if (running_tor
&& options
->RunAsDaemon
) {
954 /* No need to roll back, since you can't change the value. */
958 #ifndef HAVE_SYS_UN_H
959 if (options
->ControlSocket
|| options
->ControlSocketsGroupWritable
) {
960 *msg
= tor_strdup("Unix domain sockets (ControlSocket) not supported "
961 "on this OS/with this build.");
965 if (options
->ControlSocketsGroupWritable
&& !options
->ControlSocket
) {
966 *msg
= tor_strdup("Setting ControlSocketGroupWritable without setting"
967 "a ControlSocket makes no sense.");
973 /* We need to set the connection limit before we can open the listeners. */
974 if (set_max_file_descriptors((unsigned)options
->ConnLimit
,
975 &options
->_ConnLimit
) < 0) {
976 *msg
= tor_strdup("Problem with ConnLimit value. See logs for details.");
981 /* Set up libevent. (We need to do this before we can register the
982 * listeners as listeners.) */
983 if (running_tor
&& !libevent_initialized
) {
985 libevent_initialized
= 1;
988 /* Launch the listeners. (We do this before we setuid, so we can bind to
989 * ports under 1024.) We don't want to rebind if we're hibernating. */
990 if (!we_are_hibernating()) {
991 if (retry_all_listeners(replaced_listeners
, new_listeners
) < 0) {
992 *msg
= tor_strdup("Failed to bind one of the listener ports.");
998 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
999 /* Open /dev/pf before dropping privileges. */
1000 if (options
->TransPort
) {
1001 if (get_pf_socket() < 0) {
1002 *msg
= tor_strdup("Unable to open /dev/pf for transparent proxy.");
1008 /* Attempt to lock all current and future memory with mlockall() only once */
1009 if (options
->DisableAllSwap
) {
1010 if (tor_mlockall() == -1) {
1011 *msg
= tor_strdup("DisableAllSwap failure. Do you have proper "
1017 /* Setuid/setgid as appropriate */
1018 if (options
->User
) {
1019 if (switch_id(options
->User
) != 0) {
1020 /* No need to roll back, since you can't change the value. */
1021 *msg
= tor_strdup("Problem with User value. See logs for details.");
1026 /* Ensure data directory is private; create if possible. */
1027 if (check_private_dir(options
->DataDirectory
,
1028 running_tor
? CPD_CREATE
: CPD_CHECK
)<0) {
1030 "Couldn't access/create private data directory \"%s\"",
1031 options
->DataDirectory
);
1033 /* No need to roll back, since you can't change the value. */
1036 if (directory_caches_v2_dir_info(options
)) {
1037 size_t len
= strlen(options
->DataDirectory
)+32;
1038 char *fn
= tor_malloc(len
);
1039 tor_snprintf(fn
, len
, "%s"PATH_SEPARATOR
"cached-status",
1040 options
->DataDirectory
);
1041 if (check_private_dir(fn
, running_tor
? CPD_CREATE
: CPD_CHECK
) < 0) {
1043 "Couldn't access/create private data directory \"%s\"", fn
);
1050 /* Bail out at this point if we're not going to be a client or server:
1051 * we don't run Tor itself. */
1055 mark_logs_temp(); /* Close current logs once new logs are open. */
1057 if (options_init_logs(options
, 0)<0) { /* Configure the log(s) */
1058 *msg
= tor_strdup("Failed to init Log options. See logs for details.");
1065 log_severity_list_t
*severity
=
1066 tor_malloc_zero(sizeof(log_severity_list_t
));
1068 add_callback_log(severity
, control_event_logmsg
);
1069 control_adjust_event_log_severity();
1072 SMARTLIST_FOREACH(replaced_listeners
, connection_t
*, conn
,
1074 log_notice(LD_NET
, "Closing old %s on %s:%d",
1075 conn_type_to_string(conn
->type
), conn
->address
, conn
->port
);
1076 connection_close_immediate(conn
);
1077 connection_mark_for_close(conn
);
1086 rollback_log_changes();
1087 control_adjust_event_log_severity();
1090 if (set_conn_limit
&& old_options
)
1091 set_max_file_descriptors((unsigned)old_options
->ConnLimit
,
1092 &options
->_ConnLimit
);
1094 SMARTLIST_FOREACH(new_listeners
, connection_t
*, conn
,
1096 log_notice(LD_NET
, "Closing partially-constructed listener %s on %s:%d",
1097 conn_type_to_string(conn
->type
), conn
->address
, conn
->port
);
1098 connection_close_immediate(conn
);
1099 connection_mark_for_close(conn
);
1103 smartlist_free(new_listeners
);
1104 smartlist_free(replaced_listeners
);
1108 /** If we need to have a GEOIP ip-to-country map to run with our configured
1109 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1111 options_need_geoip_info(or_options_t
*options
, const char **reason_out
)
1114 options
->BridgeRelay
&& options
->BridgeRecordUsageByCountry
;
1115 int routerset_usage
=
1116 routerset_needs_geoip(options
->EntryNodes
) ||
1117 routerset_needs_geoip(options
->ExitNodes
) ||
1118 routerset_needs_geoip(options
->ExcludeExitNodes
) ||
1119 routerset_needs_geoip(options
->ExcludeNodes
);
1121 if (routerset_usage
&& reason_out
) {
1122 *reason_out
= "We've been configured to use (or avoid) nodes in certain "
1123 "countries, and we need GEOIP information to figure out which ones they "
1125 } else if (bridge_usage
&& reason_out
) {
1126 *reason_out
= "We've been configured to see which countries can access "
1127 "us as a bridge, and we need GEOIP information to tell which countries "
1130 return bridge_usage
|| routerset_usage
;
1133 /** Return the bandwidthrate that we are going to report to the authorities
1134 * based on the config options. */
1136 get_effective_bwrate(or_options_t
*options
)
1138 uint64_t bw
= options
->BandwidthRate
;
1139 if (bw
> options
->MaxAdvertisedBandwidth
)
1140 bw
= options
->MaxAdvertisedBandwidth
;
1141 if (options
->RelayBandwidthRate
> 0 && bw
> options
->RelayBandwidthRate
)
1142 bw
= options
->RelayBandwidthRate
;
1143 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1144 return (uint32_t)bw
;
1147 /** Return the bandwidthburst that we are going to report to the authorities
1148 * based on the config options. */
1150 get_effective_bwburst(or_options_t
*options
)
1152 uint64_t bw
= options
->BandwidthBurst
;
1153 if (options
->RelayBandwidthBurst
> 0 && bw
> options
->RelayBandwidthBurst
)
1154 bw
= options
->RelayBandwidthBurst
;
1155 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1156 return (uint32_t)bw
;
1159 /** Fetch the active option list, and take actions based on it. All of the
1160 * things we do should survive being done repeatedly. If present,
1161 * <b>old_options</b> contains the previous value of the options.
1163 * Return 0 if all goes well, return -1 if it's time to die.
1165 * Note: We haven't moved all the "act on new configuration" logic
1166 * here yet. Some is still in do_hup() and other places.
1169 options_act(or_options_t
*old_options
)
1172 or_options_t
*options
= get_options();
1173 int running_tor
= options
->command
== CMD_RUN_TOR
;
1175 const int transition_affects_workers
=
1176 old_options
&& options_transition_affects_workers(old_options
, options
);
1178 if (running_tor
&& !have_lockfile()) {
1179 if (try_locking(options
, 1) < 0)
1183 /* We want to reinit keys as needed before we do much of anything else:
1184 keys are important, and other things can depend on them. */
1186 (transition_affects_workers
||
1187 (options
->V3AuthoritativeDir
&& (!old_options
||
1188 !old_options
->V3AuthoritativeDir
)))) {
1189 if (init_keys() < 0) {
1190 log_warn(LD_BUG
,"Error initializing keys; exiting");
1195 if (consider_adding_dir_authorities(options
, old_options
) < 0)
1198 if (options
->Bridges
) {
1200 for (cl
= options
->Bridges
; cl
; cl
= cl
->next
) {
1201 if (parse_bridge_line(cl
->value
, 0)<0) {
1203 "Previously validated Bridge line could not be added!");
1207 sweep_bridge_list();
1210 if (running_tor
&& rend_config_services(options
, 0)<0) {
1212 "Previously validated hidden services line could not be added!");
1216 if (running_tor
&& rend_parse_service_authorization(options
, 0) < 0) {
1217 log_warn(LD_BUG
, "Previously validated client authorization for "
1218 "hidden services could not be added!");
1223 if (! global_state
&& running_tor
) {
1224 if (or_state_load())
1226 rep_hist_load_mtbf_data(time(NULL
));
1229 /* Bail out at this point if we're not going to be a client or server:
1230 * we want to not fork, and to log stuff to stderr. */
1234 /* Finish backgrounding the process */
1235 if (options
->RunAsDaemon
) {
1236 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1237 finish_daemon(options
->DataDirectory
);
1240 /* Write our PID to the PID file. If we do not have write permissions we
1241 * will log a warning */
1242 if (options
->PidFile
)
1243 write_pidfile(options
->PidFile
);
1245 /* Register addressmap directives */
1246 config_register_addressmaps(options
);
1247 parse_virtual_addr_network(options
->VirtualAddrNetwork
, 0, &msg
);
1249 /* Update address policies. */
1250 if (policies_parse_from_options(options
) < 0) {
1251 /* This should be impossible, but let's be sure. */
1252 log_warn(LD_BUG
,"Error parsing already-validated policy options.");
1256 if (init_cookie_authentication(options
->CookieAuthentication
) < 0) {
1257 log_warn(LD_CONFIG
,"Error creating cookie authentication file.");
1261 monitor_owning_controller_process(options
->OwningControllerProcess
);
1263 /* reload keys as needed for rendezvous services. */
1264 if (rend_service_load_keys()<0) {
1265 log_warn(LD_GENERAL
,"Error loading rendezvous service keys");
1269 /* Set up accounting */
1270 if (accounting_parse_options(options
, 0)<0) {
1271 log_warn(LD_CONFIG
,"Error in accounting options");
1274 if (accounting_is_enabled(options
))
1275 configure_accounting(time(NULL
));
1277 /* parse RefuseUnknownExits tristate */
1278 if (!strcmp(options
->RefuseUnknownExits
, "0"))
1279 options
->RefuseUnknownExits_
= 0;
1280 else if (!strcmp(options
->RefuseUnknownExits
, "1"))
1281 options
->RefuseUnknownExits_
= 1;
1282 else if (!strcmp(options
->RefuseUnknownExits
, "auto"))
1283 options
->RefuseUnknownExits_
= -1;
1285 /* Should have caught this in options_validate */
1289 /* Change the cell EWMA settings */
1290 cell_ewma_set_scale_factor(options
, networkstatus_get_latest_consensus());
1292 /* Check for transitions that need action. */
1294 int revise_trackexithosts
= 0;
1295 int revise_automap_entries
= 0;
1296 if ((options
->UseEntryGuards
&& !old_options
->UseEntryGuards
) ||
1297 options
->UseBridges
!= old_options
->UseBridges
||
1298 (options
->UseBridges
&&
1299 !config_lines_eq(options
->Bridges
, old_options
->Bridges
)) ||
1300 !routerset_equal(old_options
->ExcludeNodes
,options
->ExcludeNodes
) ||
1301 !routerset_equal(old_options
->ExcludeExitNodes
,
1302 options
->ExcludeExitNodes
) ||
1303 !routerset_equal(old_options
->EntryNodes
, options
->EntryNodes
) ||
1304 !routerset_equal(old_options
->ExitNodes
, options
->ExitNodes
) ||
1305 options
->StrictNodes
!= old_options
->StrictNodes
) {
1307 "Changed to using entry guards or bridges, or changed "
1308 "preferred or excluded node lists. "
1309 "Abandoning previous circuits.");
1310 circuit_mark_all_unused_circs();
1311 circuit_expire_all_dirty_circs();
1312 revise_trackexithosts
= 1;
1315 if (!smartlist_strings_eq(old_options
->TrackHostExits
,
1316 options
->TrackHostExits
))
1317 revise_trackexithosts
= 1;
1319 if (revise_trackexithosts
)
1320 addressmap_clear_excluded_trackexithosts(options
);
1322 if (!options
->AutomapHostsOnResolve
) {
1323 if (old_options
->AutomapHostsOnResolve
)
1324 revise_automap_entries
= 1;
1326 if (!smartlist_strings_eq(old_options
->AutomapHostsSuffixes
,
1327 options
->AutomapHostsSuffixes
))
1328 revise_automap_entries
= 1;
1329 else if (!opt_streq(old_options
->VirtualAddrNetwork
,
1330 options
->VirtualAddrNetwork
))
1331 revise_automap_entries
= 1;
1334 if (revise_automap_entries
)
1335 addressmap_clear_invalid_automaps(options
);
1337 /* How long should we delay counting bridge stats after becoming a bridge?
1338 * We use this so we don't count people who used our bridge thinking it is
1339 * a relay. If you change this, don't forget to change the log message
1340 * below. It's 4 hours (the time it takes to stop being used by clients)
1341 * plus some extra time for clock skew. */
1342 #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
1344 if (! bool_eq(options
->BridgeRelay
, old_options
->BridgeRelay
)) {
1346 if (options
->BridgeRelay
) {
1347 time_t int_start
= time(NULL
);
1348 if (old_options
->ORPort
== options
->ORPort
) {
1349 int_start
+= RELAY_BRIDGE_STATS_DELAY
;
1352 geoip_bridge_stats_init(int_start
);
1353 log_info(LD_CONFIG
, "We are acting as a bridge now. Starting new "
1354 "GeoIP stats interval%s.", was_relay
? " in 6 "
1355 "hours from now" : "");
1357 geoip_bridge_stats_term();
1358 log_info(LD_GENERAL
, "We are no longer acting as a bridge. "
1359 "Forgetting GeoIP stats.");
1363 if (transition_affects_workers
) {
1364 log_info(LD_GENERAL
,
1365 "Worker-related options changed. Rotating workers.");
1367 if (server_mode(options
) && !server_mode(old_options
)) {
1368 ip_address_changed(0);
1369 if (can_complete_circuit
|| !any_predicted_circuits(time(NULL
)))
1370 inform_testing_reachability();
1372 cpuworkers_rotate();
1380 if (options
->PerConnBWRate
!= old_options
->PerConnBWRate
||
1381 options
->PerConnBWBurst
!= old_options
->PerConnBWBurst
)
1382 connection_or_update_token_buckets(get_connection_array(), options
);
1385 /* Maybe load geoip file */
1386 if (options
->GeoIPFile
&&
1387 ((!old_options
|| !opt_streq(old_options
->GeoIPFile
, options
->GeoIPFile
))
1388 || !geoip_is_loaded())) {
1389 /* XXXX Don't use this "<default>" junk; make our filename options
1390 * understand prefixes somehow. -NM */
1391 /* XXXX023 Reload GeoIPFile on SIGHUP. -NM */
1392 char *actual_fname
= tor_strdup(options
->GeoIPFile
);
1394 if (!strcmp(actual_fname
, "<default>")) {
1395 const char *conf_root
= get_windows_conf_root();
1396 size_t len
= strlen(conf_root
)+16;
1397 tor_free(actual_fname
);
1398 actual_fname
= tor_malloc(len
+1);
1399 tor_snprintf(actual_fname
, len
, "%s\\geoip", conf_root
);
1402 geoip_load_file(actual_fname
, options
);
1403 tor_free(actual_fname
);
1406 if (options
->DirReqStatistics
&& !geoip_is_loaded()) {
1407 /* Check if GeoIP database could be loaded. */
1408 log_warn(LD_CONFIG
, "Configured to measure directory request "
1409 "statistics, but no GeoIP database found!");
1413 if (options
->EntryStatistics
) {
1414 if (should_record_bridge_info(options
)) {
1415 /* Don't allow measuring statistics on entry guards when configured
1417 log_warn(LD_CONFIG
, "Bridges cannot be configured to measure "
1418 "additional GeoIP statistics as entry guards.");
1420 } else if (!geoip_is_loaded()) {
1421 /* Check if GeoIP database could be loaded. */
1422 log_warn(LD_CONFIG
, "Configured to measure entry node statistics, "
1423 "but no GeoIP database found!");
1428 if (options
->CellStatistics
|| options
->DirReqStatistics
||
1429 options
->EntryStatistics
|| options
->ExitPortStatistics
) {
1430 time_t now
= time(NULL
);
1431 if ((!old_options
|| !old_options
->CellStatistics
) &&
1432 options
->CellStatistics
)
1433 rep_hist_buffer_stats_init(now
);
1434 if ((!old_options
|| !old_options
->DirReqStatistics
) &&
1435 options
->DirReqStatistics
)
1436 geoip_dirreq_stats_init(now
);
1437 if ((!old_options
|| !old_options
->EntryStatistics
) &&
1438 options
->EntryStatistics
)
1439 geoip_entry_stats_init(now
);
1440 if ((!old_options
|| !old_options
->ExitPortStatistics
) &&
1441 options
->ExitPortStatistics
)
1442 rep_hist_exit_stats_init(now
);
1444 log_notice(LD_CONFIG
, "Configured to measure statistics. Look for "
1445 "the *-stats files that will first be written to the "
1446 "data directory in 24 hours from now.");
1449 if (old_options
&& old_options
->CellStatistics
&&
1450 !options
->CellStatistics
)
1451 rep_hist_buffer_stats_term();
1452 if (old_options
&& old_options
->DirReqStatistics
&&
1453 !options
->DirReqStatistics
)
1454 geoip_dirreq_stats_term();
1455 if (old_options
&& old_options
->EntryStatistics
&&
1456 !options
->EntryStatistics
)
1457 geoip_entry_stats_term();
1458 if (old_options
&& old_options
->ExitPortStatistics
&&
1459 !options
->ExitPortStatistics
)
1460 rep_hist_exit_stats_term();
1462 /* Check if we need to parse and add the EntryNodes config option. */
1463 if (options
->EntryNodes
&&
1465 !routerset_equal(old_options
->EntryNodes
,options
->EntryNodes
) ||
1466 !routerset_equal(old_options
->ExcludeNodes
,options
->ExcludeNodes
)))
1467 entry_nodes_should_be_added();
1469 /* Since our options changed, we might need to regenerate and upload our
1470 * server descriptor.
1473 options_transition_affects_descriptor(old_options
, options
))
1474 mark_my_descriptor_dirty("config change");
1476 /* We may need to reschedule some directory stuff if our status changed. */
1478 if (authdir_mode_v3(options
) && !authdir_mode_v3(old_options
))
1479 dirvote_recalculate_timing(options
, time(NULL
));
1480 if (!bool_eq(directory_fetches_dir_info_early(options
),
1481 directory_fetches_dir_info_early(old_options
)) ||
1482 !bool_eq(directory_fetches_dir_info_later(options
),
1483 directory_fetches_dir_info_later(old_options
))) {
1484 /* Make sure update_router_have_min_dir_info gets called. */
1485 router_dir_info_changed();
1486 /* We might need to download a new consensus status later or sooner than
1487 * we had expected. */
1488 update_consensus_networkstatus_fetch_time(time(NULL
));
1492 /* Load the webpage we're going to serve every time someone asks for '/' on
1494 tor_free(global_dirfrontpagecontents
);
1495 if (options
->DirPortFrontPage
) {
1496 global_dirfrontpagecontents
=
1497 read_file_to_str(options
->DirPortFrontPage
, 0, NULL
);
1498 if (!global_dirfrontpagecontents
) {
1500 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1501 options
->DirPortFrontPage
);
1509 * Functions to parse config options
1512 /** If <b>option</b> is an official abbreviation for a longer option,
1513 * return the longer option. Otherwise return <b>option</b>.
1514 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1515 * apply abbreviations that work for the config file and the command line.
1516 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1518 expand_abbrev(config_format_t
*fmt
, const char *option
, int command_line
,
1524 for (i
=0; fmt
->abbrevs
[i
].abbreviated
; ++i
) {
1525 /* Abbreviations are case insensitive. */
1526 if (!strcasecmp(option
,fmt
->abbrevs
[i
].abbreviated
) &&
1527 (command_line
|| !fmt
->abbrevs
[i
].commandline_only
)) {
1528 if (warn_obsolete
&& fmt
->abbrevs
[i
].warn
) {
1530 "The configuration option '%s' is deprecated; "
1531 "use '%s' instead.",
1532 fmt
->abbrevs
[i
].abbreviated
,
1533 fmt
->abbrevs
[i
].full
);
1535 /* Keep going through the list in case we want to rewrite it more.
1536 * (We could imagine recursing here, but I don't want to get the
1537 * user into an infinite loop if we craft our list wrong.) */
1538 option
= fmt
->abbrevs
[i
].full
;
1544 /** Helper: Read a list of configuration options from the command line.
1545 * If successful, put them in *<b>result</b> and return 0, and return
1546 * -1 and leave *<b>result</b> alone. */
1548 config_get_commandlines(int argc
, char **argv
, config_line_t
**result
)
1550 config_line_t
*front
= NULL
;
1551 config_line_t
**new = &front
;
1556 if (!strcmp(argv
[i
],"-f") ||
1557 !strcmp(argv
[i
],"--hash-password")) {
1558 i
+= 2; /* command-line option with argument. ignore them. */
1560 } else if (!strcmp(argv
[i
],"--list-fingerprint") ||
1561 !strcmp(argv
[i
],"--verify-config") ||
1562 !strcmp(argv
[i
],"--ignore-missing-torrc") ||
1563 !strcmp(argv
[i
],"--quiet") ||
1564 !strcmp(argv
[i
],"--hush")) {
1565 i
+= 1; /* command-line option. ignore it. */
1567 } else if (!strcmp(argv
[i
],"--nt-service") ||
1568 !strcmp(argv
[i
],"-nt-service")) {
1574 log_warn(LD_CONFIG
,"Command-line option '%s' with no value. Failing.",
1576 config_free_lines(front
);
1580 *new = tor_malloc_zero(sizeof(config_line_t
));
1583 /* Each keyword may be prefixed with one or two dashes. */
1589 (*new)->key
= tor_strdup(expand_abbrev(&options_format
, s
, 1, 1));
1590 (*new)->value
= tor_strdup(argv
[i
+1]);
1591 (*new)->next
= NULL
;
1592 log(LOG_DEBUG
, LD_CONFIG
, "command line: parsed keyword '%s', value '%s'",
1593 (*new)->key
, (*new)->value
);
1595 new = &((*new)->next
);
1602 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1603 * append it to *<b>lst</b>. */
1605 config_line_append(config_line_t
**lst
,
1609 config_line_t
*newline
;
1611 newline
= tor_malloc(sizeof(config_line_t
));
1612 newline
->key
= tor_strdup(key
);
1613 newline
->value
= tor_strdup(val
);
1614 newline
->next
= NULL
;
1616 lst
= &((*lst
)->next
);
1621 /** Helper: parse the config string and strdup into key/value
1622 * strings. Set *result to the list, or NULL if parsing the string
1623 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1624 * misformatted lines. */
1626 config_get_lines(const char *string
, config_line_t
**result
)
1628 config_line_t
*list
= NULL
, **next
;
1634 string
= parse_config_line_from_str(string
, &k
, &v
);
1636 config_free_lines(list
);
1642 /* This list can get long, so we keep a pointer to the end of it
1643 * rather than using config_line_append over and over and getting
1644 * n^2 performance. */
1645 *next
= tor_malloc(sizeof(config_line_t
));
1648 (*next
)->next
= NULL
;
1649 next
= &((*next
)->next
);
1661 * Free all the configuration lines on the linked list <b>front</b>.
1664 config_free_lines(config_line_t
*front
)
1673 tor_free(tmp
->value
);
1678 /** If <b>key</b> is a configuration option, return the corresponding
1679 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1680 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1682 static config_var_t
*
1683 config_find_option(config_format_t
*fmt
, const char *key
)
1686 size_t keylen
= strlen(key
);
1688 return NULL
; /* if they say "--" on the command line, it's not an option */
1689 /* First, check for an exact (case-insensitive) match */
1690 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
1691 if (!strcasecmp(key
, fmt
->vars
[i
].name
)) {
1692 return &fmt
->vars
[i
];
1695 /* If none, check for an abbreviated match */
1696 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
1697 if (!strncasecmp(key
, fmt
->vars
[i
].name
, keylen
)) {
1698 log_warn(LD_CONFIG
, "The abbreviation '%s' is deprecated. "
1699 "Please use '%s' instead",
1700 key
, fmt
->vars
[i
].name
);
1701 return &fmt
->vars
[i
];
1704 /* Okay, unrecognized option */
1708 /** Return the number of option entries in <b>fmt</b>. */
1710 config_count_options(config_format_t
*fmt
)
1713 for (i
=0; fmt
->vars
[i
].name
; ++i
)
1719 * Functions to assign config options.
1722 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1723 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1725 * Called from config_assign_line() and option_reset().
1728 config_assign_value(config_format_t
*fmt
, or_options_t
*options
,
1729 config_line_t
*c
, char **msg
)
1735 CHECK(fmt
, options
);
1737 var
= config_find_option(fmt
, c
->key
);
1740 lvalue
= STRUCT_VAR_P(options
, var
->var_offset
);
1742 switch (var
->type
) {
1744 case CONFIG_TYPE_PORT
:
1745 if (!strcasecmp(c
->value
, "auto")) {
1746 *(int *)lvalue
= CFG_AUTO_PORT
;
1750 case CONFIG_TYPE_UINT
:
1751 i
= (int)tor_parse_long(c
->value
, 10, 0,
1752 var
->type
==CONFIG_TYPE_PORT
? 65535 : INT_MAX
,
1756 "Int keyword '%s %s' is malformed or out of bounds.",
1763 case CONFIG_TYPE_INTERVAL
: {
1764 i
= config_parse_interval(c
->value
, &ok
);
1767 "Interval '%s %s' is malformed or out of bounds.",
1775 case CONFIG_TYPE_MEMUNIT
: {
1776 uint64_t u64
= config_parse_memunit(c
->value
, &ok
);
1779 "Value '%s %s' is malformed or out of bounds.",
1783 *(uint64_t *)lvalue
= u64
;
1787 case CONFIG_TYPE_BOOL
:
1788 i
= (int)tor_parse_long(c
->value
, 10, 0, 1, &ok
, NULL
);
1791 "Boolean '%s %s' expects 0 or 1.",
1798 case CONFIG_TYPE_STRING
:
1799 case CONFIG_TYPE_FILENAME
:
1800 tor_free(*(char **)lvalue
);
1801 *(char **)lvalue
= tor_strdup(c
->value
);
1804 case CONFIG_TYPE_DOUBLE
:
1805 *(double *)lvalue
= atof(c
->value
);
1808 case CONFIG_TYPE_ISOTIME
:
1809 if (parse_iso_time(c
->value
, (time_t *)lvalue
)) {
1811 "Invalid time '%s' for keyword '%s'", c
->value
, c
->key
);
1816 case CONFIG_TYPE_ROUTERSET
:
1817 if (*(routerset_t
**)lvalue
) {
1818 routerset_free(*(routerset_t
**)lvalue
);
1820 *(routerset_t
**)lvalue
= routerset_new();
1821 if (routerset_parse(*(routerset_t
**)lvalue
, c
->value
, c
->key
)<0) {
1822 tor_asprintf(msg
, "Invalid exit list '%s' for option '%s'",
1828 case CONFIG_TYPE_CSV
:
1829 if (*(smartlist_t
**)lvalue
) {
1830 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
1831 smartlist_clear(*(smartlist_t
**)lvalue
);
1833 *(smartlist_t
**)lvalue
= smartlist_create();
1836 smartlist_split_string(*(smartlist_t
**)lvalue
, c
->value
, ",",
1837 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1840 case CONFIG_TYPE_LINELIST
:
1841 case CONFIG_TYPE_LINELIST_S
:
1842 config_line_append((config_line_t
**)lvalue
, c
->key
, c
->value
);
1844 case CONFIG_TYPE_OBSOLETE
:
1845 log_warn(LD_CONFIG
, "Skipping obsolete configuration option '%s'", c
->key
);
1847 case CONFIG_TYPE_LINELIST_V
:
1849 "You may not provide a value for virtual option '%s'", c
->key
);
1858 /** If <b>c</b> is a syntactically valid configuration line, update
1859 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1860 * key, -2 for bad value.
1862 * If <b>clear_first</b> is set, clear the value first. Then if
1863 * <b>use_defaults</b> is set, set the value to the default.
1865 * Called from config_assign().
1868 config_assign_line(config_format_t
*fmt
, or_options_t
*options
,
1869 config_line_t
*c
, int use_defaults
,
1870 int clear_first
, bitarray_t
*options_seen
, char **msg
)
1874 CHECK(fmt
, options
);
1876 var
= config_find_option(fmt
, c
->key
);
1879 void *lvalue
= STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
1881 "Found unrecognized option '%s'; saving it.", c
->key
);
1882 config_line_append((config_line_t
**)lvalue
, c
->key
, c
->value
);
1886 "Unknown option '%s'. Failing.", c
->key
);
1891 /* Put keyword into canonical case. */
1892 if (strcmp(var
->name
, c
->key
)) {
1894 c
->key
= tor_strdup(var
->name
);
1897 if (!strlen(c
->value
)) {
1898 /* reset or clear it, then return */
1900 if (var
->type
== CONFIG_TYPE_LINELIST
||
1901 var
->type
== CONFIG_TYPE_LINELIST_S
) {
1902 /* We got an empty linelist from the torrc or command line.
1903 As a special case, call this an error. Warn and ignore. */
1905 "Linelist option '%s' has no value. Skipping.", c
->key
);
1906 } else { /* not already cleared */
1907 option_reset(fmt
, options
, var
, use_defaults
);
1913 if (options_seen
&& (var
->type
!= CONFIG_TYPE_LINELIST
&&
1914 var
->type
!= CONFIG_TYPE_LINELIST_S
)) {
1915 /* We're tracking which options we've seen, and this option is not
1916 * supposed to occur more than once. */
1917 int var_index
= (int)(var
- fmt
->vars
);
1918 if (bitarray_is_set(options_seen
, var_index
)) {
1919 log_warn(LD_CONFIG
, "Option '%s' used more than once; all but the last "
1920 "value will be ignored.", var
->name
);
1922 bitarray_set(options_seen
, var_index
);
1925 if (config_assign_value(fmt
, options
, c
, msg
) < 0)
1930 /** Restore the option named <b>key</b> in options to its default value.
1931 * Called from config_assign(). */
1933 config_reset_line(config_format_t
*fmt
, or_options_t
*options
,
1934 const char *key
, int use_defaults
)
1938 CHECK(fmt
, options
);
1940 var
= config_find_option(fmt
, key
);
1942 return; /* give error on next pass. */
1944 option_reset(fmt
, options
, var
, use_defaults
);
1947 /** Return true iff key is a valid configuration option. */
1949 option_is_recognized(const char *key
)
1951 config_var_t
*var
= config_find_option(&options_format
, key
);
1952 return (var
!= NULL
);
1955 /** Return the canonical name of a configuration option, or NULL
1956 * if no such option exists. */
1958 option_get_canonical_name(const char *key
)
1960 config_var_t
*var
= config_find_option(&options_format
, key
);
1961 return var
? var
->name
: NULL
;
1964 /** Return a canonical list of the options assigned for key.
1967 option_get_assignment(or_options_t
*options
, const char *key
)
1969 return get_assigned_option(&options_format
, options
, key
, 1);
1972 /** Return true iff value needs to be quoted and escaped to be used in
1973 * a configuration file. */
1975 config_value_needs_escape(const char *value
)
1985 /* Note: quotes and backspaces need special handling when we are using
1986 * quotes, not otherwise, so they don't trigger escaping on their
1990 if (!TOR_ISPRINT(*value
))
1998 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1999 static config_line_t
*
2000 config_lines_dup(const config_line_t
*inp
)
2002 config_line_t
*result
= NULL
;
2003 config_line_t
**next_out
= &result
;
2005 *next_out
= tor_malloc(sizeof(config_line_t
));
2006 (*next_out
)->key
= tor_strdup(inp
->key
);
2007 (*next_out
)->value
= tor_strdup(inp
->value
);
2009 next_out
= &((*next_out
)->next
);
2015 /** Return newly allocated line or lines corresponding to <b>key</b> in the
2016 * configuration <b>options</b>. If <b>escape_val</b> is true and a
2017 * value needs to be quoted before it's put in a config file, quote and
2018 * escape that value. Return NULL if no such key exists. */
2019 static config_line_t
*
2020 get_assigned_option(config_format_t
*fmt
, void *options
,
2021 const char *key
, int escape_val
)
2025 config_line_t
*result
;
2026 tor_assert(options
&& key
);
2028 CHECK(fmt
, options
);
2030 var
= config_find_option(fmt
, key
);
2032 log_warn(LD_CONFIG
, "Unknown option '%s'. Failing.", key
);
2035 value
= STRUCT_VAR_P(options
, var
->var_offset
);
2037 result
= tor_malloc_zero(sizeof(config_line_t
));
2038 result
->key
= tor_strdup(var
->name
);
2041 case CONFIG_TYPE_STRING
:
2042 case CONFIG_TYPE_FILENAME
:
2043 if (*(char**)value
) {
2044 result
->value
= tor_strdup(*(char**)value
);
2046 tor_free(result
->key
);
2051 case CONFIG_TYPE_ISOTIME
:
2052 if (*(time_t*)value
) {
2053 result
->value
= tor_malloc(ISO_TIME_LEN
+1);
2054 format_iso_time(result
->value
, *(time_t*)value
);
2056 tor_free(result
->key
);
2059 escape_val
= 0; /* Can't need escape. */
2061 case CONFIG_TYPE_PORT
:
2062 if (*(int*)value
== CFG_AUTO_PORT
) {
2063 result
->value
= tor_strdup("auto");
2068 case CONFIG_TYPE_INTERVAL
:
2069 case CONFIG_TYPE_UINT
:
2070 /* This means every or_options_t uint or bool element
2071 * needs to be an int. Not, say, a uint16_t or char. */
2072 tor_asprintf(&result
->value
, "%d", *(int*)value
);
2073 escape_val
= 0; /* Can't need escape. */
2075 case CONFIG_TYPE_MEMUNIT
:
2076 tor_asprintf(&result
->value
, U64_FORMAT
,
2077 U64_PRINTF_ARG(*(uint64_t*)value
));
2078 escape_val
= 0; /* Can't need escape. */
2080 case CONFIG_TYPE_DOUBLE
:
2081 tor_asprintf(&result
->value
, "%f", *(double*)value
);
2082 escape_val
= 0; /* Can't need escape. */
2084 case CONFIG_TYPE_BOOL
:
2085 result
->value
= tor_strdup(*(int*)value
? "1" : "0");
2086 escape_val
= 0; /* Can't need escape. */
2088 case CONFIG_TYPE_ROUTERSET
:
2089 result
->value
= routerset_to_string(*(routerset_t
**)value
);
2091 case CONFIG_TYPE_CSV
:
2092 if (*(smartlist_t
**)value
)
2094 smartlist_join_strings(*(smartlist_t
**)value
, ",", 0, NULL
);
2096 result
->value
= tor_strdup("");
2098 case CONFIG_TYPE_OBSOLETE
:
2099 log_fn(LOG_PROTOCOL_WARN
, LD_CONFIG
,
2100 "You asked me for the value of an obsolete config option '%s'.",
2102 tor_free(result
->key
);
2105 case CONFIG_TYPE_LINELIST_S
:
2107 "Can't return context-sensitive '%s' on its own", key
);
2108 tor_free(result
->key
);
2111 case CONFIG_TYPE_LINELIST
:
2112 case CONFIG_TYPE_LINELIST_V
:
2113 tor_free(result
->key
);
2115 result
= config_lines_dup(*(const config_line_t
**)value
);
2118 tor_free(result
->key
);
2120 log_warn(LD_BUG
,"Unknown type %d for known key '%s'",
2126 config_line_t
*line
;
2127 for (line
= result
; line
; line
= line
->next
) {
2128 if (line
->value
&& config_value_needs_escape(line
->value
)) {
2129 char *newval
= esc_for_log(line
->value
);
2130 tor_free(line
->value
);
2131 line
->value
= newval
;
2139 /** Iterate through the linked list of requested options <b>list</b>.
2140 * For each item, convert as appropriate and assign to <b>options</b>.
2141 * If an item is unrecognized, set *msg and return -1 immediately,
2142 * else return 0 for success.
2144 * If <b>clear_first</b>, interpret config options as replacing (not
2145 * extending) their previous values. If <b>clear_first</b> is set,
2146 * then <b>use_defaults</b> to decide if you set to defaults after
2147 * clearing, or make the value 0 or NULL.
2149 * Here are the use cases:
2150 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
2151 * if linelist, replaces current if csv.
2152 * 2. An empty AllowInvalid line in your torrc. Should clear it.
2153 * 3. "RESETCONF AllowInvalid" sets it to default.
2154 * 4. "SETCONF AllowInvalid" makes it NULL.
2155 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
2157 * Use_defaults Clear_first
2159 * 1 0 undefined, don't use
2160 * 0 1 "set to null first"
2161 * 1 1 "set to defaults first"
2162 * Return 0 on success, -1 on bad key, -2 on bad value.
2164 * As an additional special case, if a LINELIST config option has
2165 * no value and clear_first is 0, then warn and ignore it.
2169 There are three call cases for config_assign() currently.
2171 Case one: Torrc entry
2172 options_init_from_torrc() calls config_assign(0, 0)
2173 calls config_assign_line(0, 0).
2174 if value is empty, calls option_reset(0) and returns.
2175 calls config_assign_value(), appends.
2178 options_trial_assign() calls config_assign(0, 1)
2179 calls config_reset_line(0)
2180 calls option_reset(0)
2181 calls option_clear().
2182 calls config_assign_line(0, 1).
2183 if value is empty, returns.
2184 calls config_assign_value(), appends.
2186 Case three: resetconf
2187 options_trial_assign() calls config_assign(1, 1)
2188 calls config_reset_line(1)
2189 calls option_reset(1)
2190 calls option_clear().
2191 calls config_assign_value(default)
2192 calls config_assign_line(1, 1).
2196 config_assign(config_format_t
*fmt
, void *options
, config_line_t
*list
,
2197 int use_defaults
, int clear_first
, char **msg
)
2200 bitarray_t
*options_seen
;
2201 const int n_options
= config_count_options(fmt
);
2203 CHECK(fmt
, options
);
2205 /* pass 1: normalize keys */
2206 for (p
= list
; p
; p
= p
->next
) {
2207 const char *full
= expand_abbrev(fmt
, p
->key
, 0, 1);
2208 if (strcmp(full
,p
->key
)) {
2210 p
->key
= tor_strdup(full
);
2214 /* pass 2: if we're reading from a resetting source, clear all
2215 * mentioned config options, and maybe set to their defaults. */
2217 for (p
= list
; p
; p
= p
->next
)
2218 config_reset_line(fmt
, options
, p
->key
, use_defaults
);
2221 options_seen
= bitarray_init_zero(n_options
);
2222 /* pass 3: assign. */
2225 if ((r
=config_assign_line(fmt
, options
, list
, use_defaults
,
2226 clear_first
, options_seen
, msg
))) {
2227 bitarray_free(options_seen
);
2232 bitarray_free(options_seen
);
2236 /** Try assigning <b>list</b> to the global options. You do this by duping
2237 * options, assigning list to the new one, then validating it. If it's
2238 * ok, then throw out the old one and stick with the new one. Else,
2239 * revert to old and return failure. Return SETOPT_OK on success, or
2240 * a setopt_err_t on failure.
2242 * If not success, point *<b>msg</b> to a newly allocated string describing
2246 options_trial_assign(config_line_t
*list
, int use_defaults
,
2247 int clear_first
, char **msg
)
2250 or_options_t
*trial_options
= options_dup(&options_format
, get_options());
2252 if ((r
=config_assign(&options_format
, trial_options
,
2253 list
, use_defaults
, clear_first
, msg
)) < 0) {
2254 config_free(&options_format
, trial_options
);
2258 if (options_validate(get_options(), trial_options
, 1, msg
) < 0) {
2259 config_free(&options_format
, trial_options
);
2260 return SETOPT_ERR_PARSE
; /*XXX make this a separate return value. */
2263 if (options_transition_allowed(get_options(), trial_options
, msg
) < 0) {
2264 config_free(&options_format
, trial_options
);
2265 return SETOPT_ERR_TRANSITION
;
2268 if (set_options(trial_options
, msg
)<0) {
2269 config_free(&options_format
, trial_options
);
2270 return SETOPT_ERR_SETTING
;
2273 /* we liked it. put it in place. */
2277 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2278 * Called from option_reset() and config_free(). */
2280 option_clear(config_format_t
*fmt
, or_options_t
*options
, config_var_t
*var
)
2282 void *lvalue
= STRUCT_VAR_P(options
, var
->var_offset
);
2283 (void)fmt
; /* unused */
2284 switch (var
->type
) {
2285 case CONFIG_TYPE_STRING
:
2286 case CONFIG_TYPE_FILENAME
:
2287 tor_free(*(char**)lvalue
);
2289 case CONFIG_TYPE_DOUBLE
:
2290 *(double*)lvalue
= 0.0;
2292 case CONFIG_TYPE_ISOTIME
:
2293 *(time_t*)lvalue
= 0;
2295 case CONFIG_TYPE_INTERVAL
:
2296 case CONFIG_TYPE_UINT
:
2297 case CONFIG_TYPE_PORT
:
2298 case CONFIG_TYPE_BOOL
:
2301 case CONFIG_TYPE_MEMUNIT
:
2302 *(uint64_t*)lvalue
= 0;
2304 case CONFIG_TYPE_ROUTERSET
:
2305 if (*(routerset_t
**)lvalue
) {
2306 routerset_free(*(routerset_t
**)lvalue
);
2307 *(routerset_t
**)lvalue
= NULL
;
2310 case CONFIG_TYPE_CSV
:
2311 if (*(smartlist_t
**)lvalue
) {
2312 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
2313 smartlist_free(*(smartlist_t
**)lvalue
);
2314 *(smartlist_t
**)lvalue
= NULL
;
2317 case CONFIG_TYPE_LINELIST
:
2318 case CONFIG_TYPE_LINELIST_S
:
2319 config_free_lines(*(config_line_t
**)lvalue
);
2320 *(config_line_t
**)lvalue
= NULL
;
2322 case CONFIG_TYPE_LINELIST_V
:
2323 /* handled by linelist_s. */
2325 case CONFIG_TYPE_OBSOLETE
:
2330 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2331 * <b>use_defaults</b>, set it to its default value.
2332 * Called by config_init() and option_reset_line() and option_assign_line(). */
2334 option_reset(config_format_t
*fmt
, or_options_t
*options
,
2335 config_var_t
*var
, int use_defaults
)
2339 CHECK(fmt
, options
);
2340 option_clear(fmt
, options
, var
); /* clear it first */
2342 return; /* all done */
2343 if (var
->initvalue
) {
2344 c
= tor_malloc_zero(sizeof(config_line_t
));
2345 c
->key
= tor_strdup(var
->name
);
2346 c
->value
= tor_strdup(var
->initvalue
);
2347 if (config_assign_value(fmt
, options
, c
, &msg
) < 0) {
2348 log_warn(LD_BUG
, "Failed to assign default: %s", msg
);
2349 tor_free(msg
); /* if this happens it's a bug */
2351 config_free_lines(c
);
2355 /** Print a usage message for tor. */
2360 "Copyright (c) 2001-2004, Roger Dingledine\n"
2361 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2362 "Copyright (c) 2007-2011, The Tor Project, Inc.\n\n"
2363 "tor -f <torrc> [args]\n"
2364 "See man page for options, or https://www.torproject.org/ for "
2365 "documentation.\n");
2368 /** Print all non-obsolete torrc options. */
2370 list_torrc_options(void)
2373 smartlist_t
*lines
= smartlist_create();
2374 for (i
= 0; _option_vars
[i
].name
; ++i
) {
2375 config_var_t
*var
= &_option_vars
[i
];
2376 if (var
->type
== CONFIG_TYPE_OBSOLETE
||
2377 var
->type
== CONFIG_TYPE_LINELIST_V
)
2379 printf("%s\n", var
->name
);
2381 smartlist_free(lines
);
2384 /** Last value actually set by resolve_my_address. */
2385 static uint32_t last_resolved_addr
= 0;
2387 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2388 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2389 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2390 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2391 * public IP address.
2394 resolve_my_address(int warn_severity
, or_options_t
*options
,
2395 uint32_t *addr_out
, char **hostname_out
)
2398 uint32_t addr
; /* host order */
2401 int explicit_hostname
=1;
2402 int from_interface
=0;
2403 char tmpbuf
[INET_NTOA_BUF_LEN
];
2404 const char *address
= options
->Address
;
2405 int notice_severity
= warn_severity
<= LOG_NOTICE
?
2406 LOG_NOTICE
: warn_severity
;
2408 tor_assert(addr_out
);
2410 if (address
&& *address
) {
2411 strlcpy(hostname
, address
, sizeof(hostname
));
2412 } else { /* then we need to guess our address */
2413 explicit_ip
= 0; /* it's implicit */
2414 explicit_hostname
= 0; /* it's implicit */
2416 if (gethostname(hostname
, sizeof(hostname
)) < 0) {
2417 log_fn(warn_severity
, LD_NET
,"Error obtaining local hostname");
2420 log_debug(LD_CONFIG
,"Guessed local host name as '%s'",hostname
);
2423 /* now we know hostname. resolve it and keep only the IP address */
2425 if (tor_inet_aton(hostname
, &in
) == 0) {
2426 /* then we have to resolve it */
2428 if (tor_lookup_hostname(hostname
, &addr
)) { /* failed to resolve */
2429 uint32_t interface_ip
; /* host order */
2431 if (explicit_hostname
) {
2432 log_fn(warn_severity
, LD_CONFIG
,
2433 "Could not resolve local Address '%s'. Failing.", hostname
);
2436 log_fn(notice_severity
, LD_CONFIG
,
2437 "Could not resolve guessed local hostname '%s'. "
2438 "Trying something else.", hostname
);
2439 if (get_interface_address(warn_severity
, &interface_ip
)) {
2440 log_fn(warn_severity
, LD_CONFIG
,
2441 "Could not get local interface IP address. Failing.");
2445 in
.s_addr
= htonl(interface_ip
);
2446 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2447 log_fn(notice_severity
, LD_CONFIG
, "Learned IP address '%s' for "
2448 "local interface. Using that.", tmpbuf
);
2449 strlcpy(hostname
, "<guessed from interfaces>", sizeof(hostname
));
2450 } else { /* resolved hostname into addr */
2451 in
.s_addr
= htonl(addr
);
2453 if (!explicit_hostname
&&
2454 is_internal_IP(ntohl(in
.s_addr
), 0)) {
2455 uint32_t interface_ip
;
2457 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2458 log_fn(notice_severity
, LD_CONFIG
, "Guessed local hostname '%s' "
2459 "resolves to a private IP address (%s). Trying something "
2460 "else.", hostname
, tmpbuf
);
2462 if (get_interface_address(warn_severity
, &interface_ip
)) {
2463 log_fn(warn_severity
, LD_CONFIG
,
2464 "Could not get local interface IP address. Too bad.");
2465 } else if (is_internal_IP(interface_ip
, 0)) {
2467 in2
.s_addr
= htonl(interface_ip
);
2468 tor_inet_ntoa(&in2
,tmpbuf
,sizeof(tmpbuf
));
2469 log_fn(notice_severity
, LD_CONFIG
,
2470 "Interface IP address '%s' is a private address too. "
2471 "Ignoring.", tmpbuf
);
2474 in
.s_addr
= htonl(interface_ip
);
2475 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2476 log_fn(notice_severity
, LD_CONFIG
,
2477 "Learned IP address '%s' for local interface."
2478 " Using that.", tmpbuf
);
2479 strlcpy(hostname
, "<guessed from interfaces>", sizeof(hostname
));
2485 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2486 if (is_internal_IP(ntohl(in
.s_addr
), 0)) {
2487 /* make sure we're ok with publishing an internal IP */
2488 if (!options
->DirServers
&& !options
->AlternateDirAuthority
) {
2489 /* if they are using the default dirservers, disallow internal IPs
2491 log_fn(warn_severity
, LD_CONFIG
,
2492 "Address '%s' resolves to private IP address '%s'. "
2493 "Tor servers that use the default DirServers must have public "
2494 "IP addresses.", hostname
, tmpbuf
);
2498 /* even if they've set their own dirservers, require an explicit IP if
2499 * they're using an internal address. */
2500 log_fn(warn_severity
, LD_CONFIG
, "Address '%s' resolves to private "
2501 "IP address '%s'. Please set the Address config option to be "
2502 "the IP address you want to use.", hostname
, tmpbuf
);
2507 log_debug(LD_CONFIG
, "Resolved Address to '%s'.", tmpbuf
);
2508 *addr_out
= ntohl(in
.s_addr
);
2509 if (last_resolved_addr
&& last_resolved_addr
!= *addr_out
) {
2510 /* Leave this as a notice, regardless of the requested severity,
2511 * at least until dynamic IP address support becomes bulletproof. */
2513 "Your IP address seems to have changed to %s. Updating.",
2515 ip_address_changed(0);
2517 if (last_resolved_addr
!= *addr_out
) {
2519 const char *h
= hostname
;
2521 method
= "CONFIGURED";
2523 } else if (explicit_hostname
) {
2524 method
= "RESOLVED";
2525 } else if (from_interface
) {
2526 method
= "INTERFACE";
2529 method
= "GETHOSTNAME";
2531 control_event_server_status(LOG_NOTICE
,
2532 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2533 tmpbuf
, method
, h
?"HOSTNAME=":"", h
);
2535 last_resolved_addr
= *addr_out
;
2537 *hostname_out
= tor_strdup(hostname
);
2541 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2542 * on a private network.
2545 is_local_addr(const tor_addr_t
*addr
)
2547 if (tor_addr_is_internal(addr
, 0))
2549 /* Check whether ip is on the same /24 as we are. */
2550 if (get_options()->EnforceDistinctSubnets
== 0)
2552 if (tor_addr_family(addr
) == AF_INET
) {
2553 /*XXXX023 IP6 what corresponds to an /24? */
2554 uint32_t ip
= tor_addr_to_ipv4h(addr
);
2556 /* It's possible that this next check will hit before the first time
2557 * resolve_my_address actually succeeds. (For clients, it is likely that
2558 * resolve_my_address will never be called at all). In those cases,
2559 * last_resolved_addr will be 0, and so checking to see whether ip is on
2560 * the same /24 as last_resolved_addr will be the same as checking whether
2561 * it was on net 0, which is already done by is_internal_IP.
2563 if ((last_resolved_addr
& (uint32_t)0xffffff00ul
)
2564 == (ip
& (uint32_t)0xffffff00ul
))
2570 /** Release storage held by <b>options</b>. */
2572 config_free(config_format_t
*fmt
, void *options
)
2581 for (i
=0; fmt
->vars
[i
].name
; ++i
)
2582 option_clear(fmt
, options
, &(fmt
->vars
[i
]));
2584 config_line_t
**linep
= STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
2585 config_free_lines(*linep
);
2591 /** Return true iff a and b contain identical keys and values in identical
2594 config_lines_eq(config_line_t
*a
, config_line_t
*b
)
2597 if (strcasecmp(a
->key
, b
->key
) || strcmp(a
->value
, b
->value
))
2607 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2608 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2611 option_is_same(config_format_t
*fmt
,
2612 or_options_t
*o1
, or_options_t
*o2
, const char *name
)
2614 config_line_t
*c1
, *c2
;
2619 c1
= get_assigned_option(fmt
, o1
, name
, 0);
2620 c2
= get_assigned_option(fmt
, o2
, name
, 0);
2621 r
= config_lines_eq(c1
, c2
);
2622 config_free_lines(c1
);
2623 config_free_lines(c2
);
2627 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2628 static or_options_t
*
2629 options_dup(config_format_t
*fmt
, or_options_t
*old
)
2631 or_options_t
*newopts
;
2633 config_line_t
*line
;
2635 newopts
= config_alloc(fmt
);
2636 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2637 if (fmt
->vars
[i
].type
== CONFIG_TYPE_LINELIST_S
)
2639 if (fmt
->vars
[i
].type
== CONFIG_TYPE_OBSOLETE
)
2641 line
= get_assigned_option(fmt
, old
, fmt
->vars
[i
].name
, 0);
2644 if (config_assign(fmt
, newopts
, line
, 0, 0, &msg
) < 0) {
2645 log_err(LD_BUG
, "Config_get_assigned_option() generated "
2646 "something we couldn't config_assign(): %s", msg
);
2651 config_free_lines(line
);
2656 /** Return a new empty or_options_t. Used for testing. */
2660 return config_alloc(&options_format
);
2663 /** Set <b>options</b> to hold reasonable defaults for most options.
2664 * Each option defaults to zero. */
2666 options_init(or_options_t
*options
)
2668 config_init(&options_format
, options
);
2671 /* Check if the port number given in <b>port_option</b> in combination with
2672 * the specified port in <b>listen_options</b> will result in Tor actually
2673 * opening a low port (meaning a port lower than 1024). Return 1 if
2674 * it is, or 0 if it isn't or the concept of a low port isn't applicable for
2675 * the platform we're on. */
2677 is_listening_on_low_port(int port_option
,
2678 const config_line_t
*listen_options
)
2682 (void) listen_options
;
2683 return 0; /* No port is too low for windows. */
2685 const config_line_t
*l
;
2687 if (port_option
== 0)
2688 return 0; /* We're not listening */
2689 if (listen_options
== NULL
)
2690 return (port_option
< 1024);
2692 for (l
= listen_options
; l
; l
= l
->next
) {
2693 parse_addr_port(LOG_WARN
, l
->value
, NULL
, NULL
, &p
);
2702 /** Set all vars in the configuration object <b>options</b> to their default
2705 config_init(config_format_t
*fmt
, void *options
)
2709 CHECK(fmt
, options
);
2711 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2712 var
= &fmt
->vars
[i
];
2713 if (!var
->initvalue
)
2714 continue; /* defaults to NULL or 0 */
2715 option_reset(fmt
, options
, var
, 1);
2719 /** Allocate and return a new string holding the written-out values of the vars
2720 * in 'options'. If 'minimal', do not write out any default-valued vars.
2721 * Else, if comment_defaults, write default values as comments.
2724 config_dump(config_format_t
*fmt
, void *options
, int minimal
,
2725 int comment_defaults
)
2727 smartlist_t
*elements
;
2728 or_options_t
*defaults
;
2729 config_line_t
*line
, *assigned
;
2734 defaults
= config_alloc(fmt
);
2735 config_init(fmt
, defaults
);
2737 /* XXX use a 1 here so we don't add a new log line while dumping */
2738 if (fmt
->validate_fn(NULL
,defaults
, 1, &msg
) < 0) {
2739 log_err(LD_BUG
, "Failed to validate default config.");
2744 elements
= smartlist_create();
2745 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2746 int comment_option
= 0;
2747 if (fmt
->vars
[i
].type
== CONFIG_TYPE_OBSOLETE
||
2748 fmt
->vars
[i
].type
== CONFIG_TYPE_LINELIST_S
)
2750 /* Don't save 'hidden' control variables. */
2751 if (!strcmpstart(fmt
->vars
[i
].name
, "__"))
2753 if (minimal
&& option_is_same(fmt
, options
, defaults
, fmt
->vars
[i
].name
))
2755 else if (comment_defaults
&&
2756 option_is_same(fmt
, options
, defaults
, fmt
->vars
[i
].name
))
2759 line
= assigned
= get_assigned_option(fmt
, options
, fmt
->vars
[i
].name
, 1);
2761 for (; line
; line
= line
->next
) {
2763 tor_asprintf(&tmp
, "%s%s %s\n",
2764 comment_option
? "# " : "",
2765 line
->key
, line
->value
);
2766 smartlist_add(elements
, tmp
);
2768 config_free_lines(assigned
);
2772 line
= *(config_line_t
**)STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
2773 for (; line
; line
= line
->next
) {
2775 tor_asprintf(&tmp
, "%s %s\n", line
->key
, line
->value
);
2776 smartlist_add(elements
, tmp
);
2780 result
= smartlist_join_strings(elements
, "", 0, NULL
);
2781 SMARTLIST_FOREACH(elements
, char *, cp
, tor_free(cp
));
2782 smartlist_free(elements
);
2783 config_free(fmt
, defaults
);
2787 /** Return a string containing a possible configuration file that would give
2788 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2789 * include options that are the same as Tor's defaults.
2792 options_dump(or_options_t
*options
, int minimal
)
2794 return config_dump(&options_format
, options
, minimal
, 0);
2797 /** Return 0 if every element of sl is a string holding a decimal
2798 * representation of a port number, or if sl is NULL.
2799 * Otherwise set *msg and return -1. */
2801 validate_ports_csv(smartlist_t
*sl
, const char *name
, char **msg
)
2809 SMARTLIST_FOREACH(sl
, const char *, cp
,
2812 if (i
< 1 || i
> 65535) {
2813 tor_asprintf(msg
, "Port '%s' out of range in %s", cp
, name
);
2820 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2821 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2825 ensure_bandwidth_cap(uint64_t *value
, const char *desc
, char **msg
)
2827 if (*value
> ROUTER_MAX_DECLARED_BANDWIDTH
) {
2828 /* This handles an understandable special case where somebody says "2gb"
2829 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2832 if (*value
> ROUTER_MAX_DECLARED_BANDWIDTH
) {
2833 tor_asprintf(msg
, "%s ("U64_FORMAT
") must be at most %d",
2834 desc
, U64_PRINTF_ARG(*value
),
2835 ROUTER_MAX_DECLARED_BANDWIDTH
);
2841 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2842 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2843 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2845 * Return 0 on success or -1 if not a recognized authority type (in which
2846 * case the value of _PublishServerDescriptor is undefined). */
2848 compute_publishserverdescriptor(or_options_t
*options
)
2850 smartlist_t
*list
= options
->PublishServerDescriptor
;
2851 authority_type_t
*auth
= &options
->_PublishServerDescriptor
;
2852 *auth
= NO_AUTHORITY
;
2853 if (!list
) /* empty list, answer is none */
2855 SMARTLIST_FOREACH(list
, const char *, string
, {
2856 if (!strcasecmp(string
, "v1"))
2857 *auth
|= V1_AUTHORITY
;
2858 else if (!strcmp(string
, "1"))
2859 if (options
->BridgeRelay
)
2860 *auth
|= BRIDGE_AUTHORITY
;
2862 *auth
|= V2_AUTHORITY
| V3_AUTHORITY
;
2863 else if (!strcasecmp(string
, "v2"))
2864 *auth
|= V2_AUTHORITY
;
2865 else if (!strcasecmp(string
, "v3"))
2866 *auth
|= V3_AUTHORITY
;
2867 else if (!strcasecmp(string
, "bridge"))
2868 *auth
|= BRIDGE_AUTHORITY
;
2869 else if (!strcasecmp(string
, "hidserv"))
2871 "PublishServerDescriptor hidserv is invalid. See "
2872 "PublishHidServDescriptors.");
2873 else if (!strcasecmp(string
, "") || !strcmp(string
, "0"))
2881 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2882 * services can overload the directory system. */
2883 #define MIN_REND_POST_PERIOD (10*60)
2885 /** Highest allowable value for RendPostPeriod. */
2886 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2888 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2889 * will generate too many circuits and potentially overload the network. */
2890 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2892 /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
2893 * will generate too many circuits and potentially overload the network. */
2894 #define MIN_CIRCUIT_STREAM_TIMEOUT 10
2896 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2897 * permissible transition from <b>old_options</b>. Else return -1.
2898 * Should have no side effects, except for normalizing the contents of
2901 * On error, tor_strdup an error explanation into *<b>msg</b>.
2904 * If <b>from_setconf</b>, we were called by the controller, and our
2905 * Log line should stay empty. If it's 0, then give us a default log
2906 * if there are no logs defined.
2909 options_validate(or_options_t
*old_options
, or_options_t
*options
,
2910 int from_setconf
, char **msg
)
2914 const char *uname
= get_uname();
2915 #define REJECT(arg) \
2916 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2917 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2922 if (server_mode(options
) &&
2923 (!strcmpstart(uname
, "Windows 95") ||
2924 !strcmpstart(uname
, "Windows 98") ||
2925 !strcmpstart(uname
, "Windows Me"))) {
2926 log(LOG_WARN
, LD_CONFIG
, "Tor is running as a server, but you are "
2927 "running %s; this probably won't work. See "
2928 "https://wiki.torproject.org/TheOnionRouter/TorFAQ#ServerOS "
2929 "for details.", uname
);
2932 if (options
->ORPort
== 0 && options
->ORListenAddress
!= NULL
)
2933 REJECT("ORPort must be defined if ORListenAddress is defined.");
2935 if (options
->DirPort
== 0 && options
->DirListenAddress
!= NULL
)
2936 REJECT("DirPort must be defined if DirListenAddress is defined.");
2938 if (options
->DNSPort
== 0 && options
->DNSListenAddress
!= NULL
)
2939 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
2941 if (options
->ControlPort
== 0 && options
->ControlListenAddress
!= NULL
)
2942 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
2944 if (options
->TransPort
== 0 && options
->TransListenAddress
!= NULL
)
2945 REJECT("TransPort must be defined if TransListenAddress is defined.");
2947 if (options
->NATDPort
== 0 && options
->NATDListenAddress
!= NULL
)
2948 REJECT("NATDPort must be defined if NATDListenAddress is defined.");
2950 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
2951 * configuration does this. */
2953 for (i
= 0; i
< 3; ++i
) {
2954 int is_socks
= i
==0;
2955 int is_trans
= i
==1;
2956 config_line_t
*line
, *opt
, *old
;
2959 opt
= options
->SocksListenAddress
;
2960 old
= old_options
? old_options
->SocksListenAddress
: NULL
;
2962 } else if (is_trans
) {
2963 opt
= options
->TransListenAddress
;
2964 old
= old_options
? old_options
->TransListenAddress
: NULL
;
2965 tp
= "transparent proxy";
2967 opt
= options
->NATDListenAddress
;
2968 old
= old_options
? old_options
->NATDListenAddress
: NULL
;
2972 for (line
= opt
; line
; line
= line
->next
) {
2973 char *address
= NULL
;
2976 if (parse_addr_port(LOG_WARN
, line
->value
, &address
, &addr
, &port
)<0)
2977 continue; /* We'll warn about this later. */
2978 if (!is_internal_IP(addr
, 1) &&
2979 (!old_options
|| !config_lines_eq(old
, opt
))) {
2981 "You specified a public address '%s' for a %s. Other "
2982 "people on the Internet might find your computer and use it as "
2983 "an open %s. Please don't allow this unless you have "
2984 "a good reason.", address
, tp
, tp
);
2990 if (validate_data_directory(options
)<0)
2991 REJECT("Invalid DataDirectory");
2993 if (options
->Nickname
== NULL
) {
2994 if (server_mode(options
)) {
2995 options
->Nickname
= tor_strdup(UNNAMED_ROUTER_NICKNAME
);
2998 if (!is_legal_nickname(options
->Nickname
)) {
3000 "Nickname '%s' is wrong length or contains illegal characters.",
3006 if (server_mode(options
) && !options
->ContactInfo
)
3007 log(LOG_NOTICE
, LD_CONFIG
, "Your ContactInfo config option is not set. "
3008 "Please consider setting it, so we can contact you if your server is "
3009 "misconfigured or something else goes wrong.");
3011 /* Special case on first boot if no Log options are given. */
3012 if (!options
->Logs
&& !options
->RunAsDaemon
&& !from_setconf
)
3013 config_line_append(&options
->Logs
, "Log", "notice stdout");
3015 if (options_init_logs(options
, 1)<0) /* Validate the log(s) */
3016 REJECT("Failed to validate Log options. See logs for details.");
3018 if (authdir_mode(options
)) {
3019 /* confirm that our address isn't broken, so we can complain now */
3021 if (resolve_my_address(LOG_WARN
, options
, &tmp
, NULL
) < 0)
3022 REJECT("Failed to resolve/guess local address. See logs for details.");
3025 if (strcmp(options
->RefuseUnknownExits
, "0") &&
3026 strcmp(options
->RefuseUnknownExits
, "1") &&
3027 strcmp(options
->RefuseUnknownExits
, "auto")) {
3028 REJECT("RefuseUnknownExits must be 0, 1, or auto");
3032 if (options
->RunAsDaemon
&& torrc_fname
&& path_is_relative(torrc_fname
))
3033 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
3036 if (options
->SocksPort
== 0 && options
->TransPort
== 0 &&
3037 options
->NATDPort
== 0 && options
->ORPort
== 0 &&
3038 options
->DNSPort
== 0 && !options
->RendConfigLines
)
3039 log(LOG_WARN
, LD_CONFIG
,
3040 "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
3041 "undefined, and there aren't any hidden services configured. "
3042 "Tor will still run, but probably won't do anything.");
3044 #ifndef USE_TRANSPARENT
3045 if (options
->TransPort
|| options
->TransListenAddress
)
3046 REJECT("TransPort and TransListenAddress are disabled in this build.");
3049 if (options
->AccountingMax
&&
3050 (is_listening_on_low_port(options
->ORPort
, options
->ORListenAddress
) ||
3051 is_listening_on_low_port(options
->DirPort
, options
->DirListenAddress
)))
3053 log(LOG_WARN
, LD_CONFIG
,
3054 "You have set AccountingMax to use hibernation. You have also "
3055 "chosen a low DirPort or OrPort. This combination can make Tor stop "
3056 "working when it tries to re-attach the port after a period of "
3057 "hibernation. Please choose a different port or turn off "
3058 "hibernation unless you know this combination will work on your "
3062 if (options
->ExcludeExitNodes
|| options
->ExcludeNodes
) {
3063 options
->_ExcludeExitNodesUnion
= routerset_new();
3064 routerset_union(options
->_ExcludeExitNodesUnion
,options
->ExcludeExitNodes
);
3065 routerset_union(options
->_ExcludeExitNodesUnion
,options
->ExcludeNodes
);
3068 if (options
->ExcludeNodes
&& options
->StrictNodes
) {
3069 COMPLAIN("You have asked to exclude certain relays from all positions "
3070 "in your circuits. Expect hidden services and other Tor "
3071 "features to be broken in unpredictable ways.");
3074 if (options
->EntryNodes
&& !routerset_is_list(options
->EntryNodes
)) {
3075 /* XXXX fix this; see entry_guards_prepend_from_config(). */
3076 REJECT("IPs or countries are not yet supported in EntryNodes.");
3079 if (options
->AuthoritativeDir
) {
3080 if (!options
->ContactInfo
&& !options
->TestingTorNetwork
)
3081 REJECT("Authoritative directory servers must set ContactInfo");
3082 if (options
->V1AuthoritativeDir
&& !options
->RecommendedVersions
)
3083 REJECT("V1 authoritative dir servers must set RecommendedVersions.");
3084 if (!options
->RecommendedClientVersions
)
3085 options
->RecommendedClientVersions
=
3086 config_lines_dup(options
->RecommendedVersions
);
3087 if (!options
->RecommendedServerVersions
)
3088 options
->RecommendedServerVersions
=
3089 config_lines_dup(options
->RecommendedVersions
);
3090 if (options
->VersioningAuthoritativeDir
&&
3091 (!options
->RecommendedClientVersions
||
3092 !options
->RecommendedServerVersions
))
3093 REJECT("Versioning authoritative dir servers must set "
3094 "Recommended*Versions.");
3095 if (options
->UseEntryGuards
) {
3096 log_info(LD_CONFIG
, "Authoritative directory servers can't set "
3097 "UseEntryGuards. Disabling.");
3098 options
->UseEntryGuards
= 0;
3100 if (!options
->DownloadExtraInfo
&& authdir_mode_any_main(options
)) {
3101 log_info(LD_CONFIG
, "Authoritative directories always try to download "
3102 "extra-info documents. Setting DownloadExtraInfo.");
3103 options
->DownloadExtraInfo
= 1;
3105 if (!(options
->BridgeAuthoritativeDir
|| options
->HSAuthoritativeDir
||
3106 options
->V1AuthoritativeDir
|| options
->V2AuthoritativeDir
||
3107 options
->V3AuthoritativeDir
))
3108 REJECT("AuthoritativeDir is set, but none of "
3109 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
3110 /* If we have a v3bandwidthsfile and it's broken, complain on startup */
3111 if (options
->V3BandwidthsFile
&& !old_options
) {
3112 dirserv_read_measured_bandwidths(options
->V3BandwidthsFile
, NULL
);
3116 if (options
->AuthoritativeDir
&& !options
->DirPort
)
3117 REJECT("Running as authoritative directory, but no DirPort set.");
3119 if (options
->AuthoritativeDir
&& !options
->ORPort
)
3120 REJECT("Running as authoritative directory, but no ORPort set.");
3122 if (options
->AuthoritativeDir
&& options
->ClientOnly
)
3123 REJECT("Running as authoritative directory, but ClientOnly also set.");
3125 if (options
->FetchDirInfoExtraEarly
&& !options
->FetchDirInfoEarly
)
3126 REJECT("FetchDirInfoExtraEarly requires that you also set "
3127 "FetchDirInfoEarly");
3129 if (options
->HSAuthoritativeDir
&& proxy_mode(options
))
3130 REJECT("Running as authoritative v0 HS directory, but also configured "
3133 if (options
->ConnLimit
<= 0) {
3135 "ConnLimit must be greater than 0, but was set to %d",
3136 options
->ConnLimit
);
3140 if (validate_ports_csv(options
->FirewallPorts
, "FirewallPorts", msg
) < 0)
3143 if (validate_ports_csv(options
->LongLivedPorts
, "LongLivedPorts", msg
) < 0)
3146 if (validate_ports_csv(options
->RejectPlaintextPorts
,
3147 "RejectPlaintextPorts", msg
) < 0)
3150 if (validate_ports_csv(options
->WarnPlaintextPorts
,
3151 "WarnPlaintextPorts", msg
) < 0)
3154 if (options
->FascistFirewall
&& !options
->ReachableAddresses
) {
3155 if (options
->FirewallPorts
&& smartlist_len(options
->FirewallPorts
)) {
3156 /* We already have firewall ports set, so migrate them to
3157 * ReachableAddresses, which will set ReachableORAddresses and
3158 * ReachableDirAddresses if they aren't set explicitly. */
3159 smartlist_t
*instead
= smartlist_create();
3160 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
3161 new_line
->key
= tor_strdup("ReachableAddresses");
3162 /* If we're configured with the old format, we need to prepend some
3164 SMARTLIST_FOREACH(options
->FirewallPorts
, const char *, portno
,
3166 int p
= atoi(portno
);
3170 tor_snprintf(s
, 16, "*:%d", p
);
3171 smartlist_add(instead
, s
);
3173 new_line
->value
= smartlist_join_strings(instead
,",",0,NULL
);
3174 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3175 log(LOG_NOTICE
, LD_CONFIG
,
3176 "Converting FascistFirewall and FirewallPorts "
3177 "config options to new format: \"ReachableAddresses %s\"",
3179 options
->ReachableAddresses
= new_line
;
3180 SMARTLIST_FOREACH(instead
, char *, cp
, tor_free(cp
));
3181 smartlist_free(instead
);
3183 /* We do not have FirewallPorts set, so add 80 to
3184 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3185 if (!options
->ReachableDirAddresses
) {
3186 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
3187 new_line
->key
= tor_strdup("ReachableDirAddresses");
3188 new_line
->value
= tor_strdup("*:80");
3189 options
->ReachableDirAddresses
= new_line
;
3190 log(LOG_NOTICE
, LD_CONFIG
, "Converting FascistFirewall config option "
3191 "to new format: \"ReachableDirAddresses *:80\"");
3193 if (!options
->ReachableORAddresses
) {
3194 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
3195 new_line
->key
= tor_strdup("ReachableORAddresses");
3196 new_line
->value
= tor_strdup("*:443");
3197 options
->ReachableORAddresses
= new_line
;
3198 log(LOG_NOTICE
, LD_CONFIG
, "Converting FascistFirewall config option "
3199 "to new format: \"ReachableORAddresses *:443\"");
3204 for (i
=0; i
<3; i
++) {
3205 config_line_t
**linep
=
3206 (i
==0) ? &options
->ReachableAddresses
:
3207 (i
==1) ? &options
->ReachableORAddresses
:
3208 &options
->ReachableDirAddresses
;
3211 /* We need to end with a reject *:*, not an implicit accept *:* */
3213 if (!strcmp((*linep
)->value
, "reject *:*")) /* already there */
3215 linep
= &((*linep
)->next
);
3217 *linep
= tor_malloc_zero(sizeof(config_line_t
));
3218 (*linep
)->key
= tor_strdup(
3219 (i
==0) ? "ReachableAddresses" :
3220 (i
==1) ? "ReachableORAddresses" :
3221 "ReachableDirAddresses");
3222 (*linep
)->value
= tor_strdup("reject *:*");
3228 if ((options
->ReachableAddresses
||
3229 options
->ReachableORAddresses
||
3230 options
->ReachableDirAddresses
) &&
3231 server_mode(options
))
3232 REJECT("Servers must be able to freely connect to the rest "
3233 "of the Internet, so they must not set Reachable*Addresses "
3234 "or FascistFirewall.");
3236 if (options
->UseBridges
&&
3237 server_mode(options
))
3238 REJECT("Servers must be able to freely connect to the rest "
3239 "of the Internet, so they must not set UseBridges.");
3241 /* If both of these are set, we'll end up with funny behavior where we
3242 * demand enough entrynodes be up and running else we won't build
3243 * circuits, yet we never actually use them. */
3244 if (options
->UseBridges
&& options
->EntryNodes
)
3245 REJECT("You cannot set both UseBridges and EntryNodes.");
3247 options
->_AllowInvalid
= 0;
3248 if (options
->AllowInvalidNodes
) {
3249 SMARTLIST_FOREACH(options
->AllowInvalidNodes
, const char *, cp
, {
3250 if (!strcasecmp(cp
, "entry"))
3251 options
->_AllowInvalid
|= ALLOW_INVALID_ENTRY
;
3252 else if (!strcasecmp(cp
, "exit"))
3253 options
->_AllowInvalid
|= ALLOW_INVALID_EXIT
;
3254 else if (!strcasecmp(cp
, "middle"))
3255 options
->_AllowInvalid
|= ALLOW_INVALID_MIDDLE
;
3256 else if (!strcasecmp(cp
, "introduction"))
3257 options
->_AllowInvalid
|= ALLOW_INVALID_INTRODUCTION
;
3258 else if (!strcasecmp(cp
, "rendezvous"))
3259 options
->_AllowInvalid
|= ALLOW_INVALID_RENDEZVOUS
;
3262 "Unrecognized value '%s' in AllowInvalidNodes", cp
);
3268 if (!options
->SafeLogging
||
3269 !strcasecmp(options
->SafeLogging
, "0")) {
3270 options
->_SafeLogging
= SAFELOG_SCRUB_NONE
;
3271 } else if (!strcasecmp(options
->SafeLogging
, "relay")) {
3272 options
->_SafeLogging
= SAFELOG_SCRUB_RELAY
;
3273 } else if (!strcasecmp(options
->SafeLogging
, "1")) {
3274 options
->_SafeLogging
= SAFELOG_SCRUB_ALL
;
3277 "Unrecognized value '%s' in SafeLogging",
3278 escaped(options
->SafeLogging
));
3282 if (compute_publishserverdescriptor(options
) < 0) {
3283 tor_asprintf(msg
, "Unrecognized value in PublishServerDescriptor");
3287 if ((options
->BridgeRelay
3288 || options
->_PublishServerDescriptor
& BRIDGE_AUTHORITY
)
3289 && (options
->_PublishServerDescriptor
3290 & (V1_AUTHORITY
|V2_AUTHORITY
|V3_AUTHORITY
))) {
3291 REJECT("Bridges are not supposed to publish router descriptors to the "
3292 "directory authorities. Please correct your "
3293 "PublishServerDescriptor line.");
3296 if (options
->BridgeRelay
&& options
->DirPort
) {
3297 log_warn(LD_CONFIG
, "Can't set a DirPort on a bridge relay; disabling "
3299 options
->DirPort
= 0;
3302 if (options
->MinUptimeHidServDirectoryV2
< 0) {
3303 log_warn(LD_CONFIG
, "MinUptimeHidServDirectoryV2 option must be at "
3304 "least 0 seconds. Changing to 0.");
3305 options
->MinUptimeHidServDirectoryV2
= 0;
3308 if (options
->RendPostPeriod
< MIN_REND_POST_PERIOD
) {
3309 log_warn(LD_CONFIG
, "RendPostPeriod option is too short; "
3310 "raising to %d seconds.", MIN_REND_POST_PERIOD
);
3311 options
->RendPostPeriod
= MIN_REND_POST_PERIOD
;
3314 if (options
->RendPostPeriod
> MAX_DIR_PERIOD
) {
3315 log_warn(LD_CONFIG
, "RendPostPeriod is too large; clipping to %ds.",
3317 options
->RendPostPeriod
= MAX_DIR_PERIOD
;
3320 if (options
->MaxCircuitDirtiness
< MIN_MAX_CIRCUIT_DIRTINESS
) {
3321 log_warn(LD_CONFIG
, "MaxCircuitDirtiness option is too short; "
3322 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS
);
3323 options
->MaxCircuitDirtiness
= MIN_MAX_CIRCUIT_DIRTINESS
;
3326 if (options
->CircuitStreamTimeout
&&
3327 options
->CircuitStreamTimeout
< MIN_CIRCUIT_STREAM_TIMEOUT
) {
3328 log_warn(LD_CONFIG
, "CircuitStreamTimeout option is too short; "
3329 "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT
);
3330 options
->CircuitStreamTimeout
= MIN_CIRCUIT_STREAM_TIMEOUT
;
3333 if (options
->KeepalivePeriod
< 1)
3334 REJECT("KeepalivePeriod option must be positive.");
3336 if (ensure_bandwidth_cap(&options
->BandwidthRate
,
3337 "BandwidthRate", msg
) < 0)
3339 if (ensure_bandwidth_cap(&options
->BandwidthBurst
,
3340 "BandwidthBurst", msg
) < 0)
3342 if (ensure_bandwidth_cap(&options
->MaxAdvertisedBandwidth
,
3343 "MaxAdvertisedBandwidth", msg
) < 0)
3345 if (ensure_bandwidth_cap(&options
->RelayBandwidthRate
,
3346 "RelayBandwidthRate", msg
) < 0)
3348 if (ensure_bandwidth_cap(&options
->RelayBandwidthBurst
,
3349 "RelayBandwidthBurst", msg
) < 0)
3351 if (ensure_bandwidth_cap(&options
->PerConnBWRate
,
3352 "PerConnBWRate", msg
) < 0)
3354 if (ensure_bandwidth_cap(&options
->PerConnBWBurst
,
3355 "PerConnBWBurst", msg
) < 0)
3358 if (options
->RelayBandwidthRate
&& !options
->RelayBandwidthBurst
)
3359 options
->RelayBandwidthBurst
= options
->RelayBandwidthRate
;
3360 if (options
->RelayBandwidthBurst
&& !options
->RelayBandwidthRate
)
3361 options
->RelayBandwidthRate
= options
->RelayBandwidthBurst
;
3363 if (server_mode(options
)) {
3364 if (options
->BandwidthRate
< ROUTER_REQUIRED_MIN_BANDWIDTH
) {
3366 "BandwidthRate is set to %d bytes/second. "
3367 "For servers, it must be at least %d.",
3368 (int)options
->BandwidthRate
,
3369 ROUTER_REQUIRED_MIN_BANDWIDTH
);
3371 } else if (options
->MaxAdvertisedBandwidth
<
3372 ROUTER_REQUIRED_MIN_BANDWIDTH
/2) {
3374 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3375 "For servers, it must be at least %d.",
3376 (int)options
->MaxAdvertisedBandwidth
,
3377 ROUTER_REQUIRED_MIN_BANDWIDTH
/2);
3380 if (options
->RelayBandwidthRate
&&
3381 options
->RelayBandwidthRate
< ROUTER_REQUIRED_MIN_BANDWIDTH
) {
3383 "RelayBandwidthRate is set to %d bytes/second. "
3384 "For servers, it must be at least %d.",
3385 (int)options
->RelayBandwidthRate
,
3386 ROUTER_REQUIRED_MIN_BANDWIDTH
);
3391 if (options
->RelayBandwidthRate
> options
->RelayBandwidthBurst
)
3392 REJECT("RelayBandwidthBurst must be at least equal "
3393 "to RelayBandwidthRate.");
3395 if (options
->BandwidthRate
> options
->BandwidthBurst
)
3396 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3398 /* if they set relaybandwidth* really high but left bandwidth*
3399 * at the default, raise the defaults. */
3400 if (options
->RelayBandwidthRate
> options
->BandwidthRate
)
3401 options
->BandwidthRate
= options
->RelayBandwidthRate
;
3402 if (options
->RelayBandwidthBurst
> options
->BandwidthBurst
)
3403 options
->BandwidthBurst
= options
->RelayBandwidthBurst
;
3405 if (accounting_parse_options(options
, 1)<0)
3406 REJECT("Failed to parse accounting options. See logs for details.");
3408 if (options
->HTTPProxy
) { /* parse it now */
3409 if (tor_addr_port_parse(options
->HTTPProxy
,
3410 &options
->HTTPProxyAddr
, &options
->HTTPProxyPort
) < 0)
3411 REJECT("HTTPProxy failed to parse or resolve. Please fix.");
3412 if (options
->HTTPProxyPort
== 0) { /* give it a default */
3413 options
->HTTPProxyPort
= 80;
3417 if (options
->HTTPProxyAuthenticator
) {
3418 if (strlen(options
->HTTPProxyAuthenticator
) >= 512)
3419 REJECT("HTTPProxyAuthenticator is too long (>= 512 chars).");
3422 if (options
->HTTPSProxy
) { /* parse it now */
3423 if (tor_addr_port_parse(options
->HTTPSProxy
,
3424 &options
->HTTPSProxyAddr
, &options
->HTTPSProxyPort
) <0)
3425 REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
3426 if (options
->HTTPSProxyPort
== 0) { /* give it a default */
3427 options
->HTTPSProxyPort
= 443;
3431 if (options
->HTTPSProxyAuthenticator
) {
3432 if (strlen(options
->HTTPSProxyAuthenticator
) >= 512)
3433 REJECT("HTTPSProxyAuthenticator is too long (>= 512 chars).");
3436 if (options
->Socks4Proxy
) { /* parse it now */
3437 if (tor_addr_port_parse(options
->Socks4Proxy
,
3438 &options
->Socks4ProxyAddr
,
3439 &options
->Socks4ProxyPort
) <0)
3440 REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
3441 if (options
->Socks4ProxyPort
== 0) { /* give it a default */
3442 options
->Socks4ProxyPort
= 1080;
3446 if (options
->Socks5Proxy
) { /* parse it now */
3447 if (tor_addr_port_parse(options
->Socks5Proxy
,
3448 &options
->Socks5ProxyAddr
,
3449 &options
->Socks5ProxyPort
) <0)
3450 REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
3451 if (options
->Socks5ProxyPort
== 0) { /* give it a default */
3452 options
->Socks5ProxyPort
= 1080;
3456 if (options
->Socks4Proxy
&& options
->Socks5Proxy
)
3457 REJECT("You cannot specify both Socks4Proxy and SOCKS5Proxy");
3459 if (options
->Socks5ProxyUsername
) {
3462 len
= strlen(options
->Socks5ProxyUsername
);
3463 if (len
< 1 || len
> 255)
3464 REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
3466 if (!options
->Socks5ProxyPassword
)
3467 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3469 len
= strlen(options
->Socks5ProxyPassword
);
3470 if (len
< 1 || len
> 255)
3471 REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
3472 } else if (options
->Socks5ProxyPassword
)
3473 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3475 if (options
->HashedControlPassword
) {
3476 smartlist_t
*sl
= decode_hashed_passwords(options
->HashedControlPassword
);
3478 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3480 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
3485 if (options
->HashedControlSessionPassword
) {
3486 smartlist_t
*sl
= decode_hashed_passwords(
3487 options
->HashedControlSessionPassword
);
3489 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3491 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
3496 if (options
->OwningControllerProcess
) {
3497 const char *validate_pspec_msg
= NULL
;
3498 if (tor_validate_process_specifier(options
->OwningControllerProcess
,
3499 &validate_pspec_msg
)) {
3500 tor_asprintf(msg
, "Bad OwningControllerProcess: %s",
3501 validate_pspec_msg
);
3506 if (options
->ControlListenAddress
) {
3507 int all_are_local
= 1;
3509 for (ln
= options
->ControlListenAddress
; ln
; ln
= ln
->next
) {
3510 if (strcmpstart(ln
->value
, "127."))
3513 if (!all_are_local
) {
3514 if (!options
->HashedControlPassword
&&
3515 !options
->HashedControlSessionPassword
&&
3516 !options
->CookieAuthentication
) {
3518 "You have a ControlListenAddress set to accept "
3519 "unauthenticated connections from a non-local address. "
3520 "This means that programs not running on your computer "
3521 "can reconfigure your Tor, without even having to guess a "
3522 "password. That's so bad that I'm closing your ControlPort "
3523 "for you. If you need to control your Tor remotely, try "
3524 "enabling authentication and using a tool like stunnel or "
3525 "ssh to encrypt remote access.");
3526 options
->ControlPort
= 0;
3528 log_warn(LD_CONFIG
, "You have a ControlListenAddress set to accept "
3529 "connections from a non-local address. This means that "
3530 "programs not running on your computer can reconfigure your "
3531 "Tor. That's pretty bad, since the controller "
3532 "protocol isn't encrypted! Maybe you should just listen on "
3533 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
3534 "remote connections to your control port.");
3539 if (options
->ControlPort
&& !options
->HashedControlPassword
&&
3540 !options
->HashedControlSessionPassword
&&
3541 !options
->CookieAuthentication
) {
3542 log_warn(LD_CONFIG
, "ControlPort is open, but no authentication method "
3543 "has been configured. This means that any program on your "
3544 "computer can reconfigure your Tor. That's bad! You should "
3545 "upgrade your Tor controller as soon as possible.");
3548 if (options
->CookieAuthFileGroupReadable
&& !options
->CookieAuthFile
) {
3549 log_warn(LD_CONFIG
, "CookieAuthFileGroupReadable is set, but will have "
3550 "no effect: you must specify an explicit CookieAuthFile to "
3551 "have it group-readable.");
3554 if (options
->UseEntryGuards
&& ! options
->NumEntryGuards
)
3555 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3557 if (check_nickname_list(options
->MyFamily
, "MyFamily", msg
))
3559 for (cl
= options
->NodeFamilies
; cl
; cl
= cl
->next
) {
3560 if (check_nickname_list(cl
->value
, "NodeFamily", msg
))
3564 if (validate_addr_policies(options
, msg
) < 0)
3567 if (validate_dir_authorities(options
, old_options
) < 0)
3568 REJECT("Directory authority line did not parse. See logs for details.");
3570 if (options
->UseBridges
&& !options
->Bridges
)
3571 REJECT("If you set UseBridges, you must specify at least one bridge.");
3572 if (options
->UseBridges
&& !options
->TunnelDirConns
)
3573 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3574 if (options
->Bridges
) {
3575 for (cl
= options
->Bridges
; cl
; cl
= cl
->next
) {
3576 if (parse_bridge_line(cl
->value
, 1)<0)
3577 REJECT("Bridge line did not parse. See logs for details.");
3581 if (options
->ConstrainedSockets
) {
3582 /* If the user wants to constrain socket buffer use, make sure the desired
3583 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3584 if (options
->ConstrainedSockSize
< MIN_CONSTRAINED_TCP_BUFFER
||
3585 options
->ConstrainedSockSize
> MAX_CONSTRAINED_TCP_BUFFER
||
3586 options
->ConstrainedSockSize
% 1024) {
3588 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3589 "in 1024 byte increments.",
3590 MIN_CONSTRAINED_TCP_BUFFER
, MAX_CONSTRAINED_TCP_BUFFER
);
3593 if (options
->DirPort
) {
3594 /* Providing cached directory entries while system TCP buffers are scarce
3595 * will exacerbate the socket errors. Suggest that this be disabled. */
3596 COMPLAIN("You have requested constrained socket buffers while also "
3597 "serving directory entries via DirPort. It is strongly "
3598 "suggested that you disable serving directory requests when "
3599 "system TCP buffer resources are scarce.");
3603 if (options
->V3AuthVoteDelay
+ options
->V3AuthDistDelay
>=
3604 options
->V3AuthVotingInterval
/2) {
3605 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3606 "V3AuthVotingInterval");
3608 if (options
->V3AuthVoteDelay
< MIN_VOTE_SECONDS
)
3609 REJECT("V3AuthVoteDelay is way too low.");
3610 if (options
->V3AuthDistDelay
< MIN_DIST_SECONDS
)
3611 REJECT("V3AuthDistDelay is way too low.");
3613 if (options
->V3AuthNIntervalsValid
< 2)
3614 REJECT("V3AuthNIntervalsValid must be at least 2.");
3616 if (options
->V3AuthVotingInterval
< MIN_VOTE_INTERVAL
) {
3617 REJECT("V3AuthVotingInterval is insanely low.");
3618 } else if (options
->V3AuthVotingInterval
> 24*60*60) {
3619 REJECT("V3AuthVotingInterval is insanely high.");
3620 } else if (((24*60*60) % options
->V3AuthVotingInterval
) != 0) {
3621 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3624 if (rend_config_services(options
, 1) < 0)
3625 REJECT("Failed to configure rendezvous options. See logs for details.");
3627 /* Parse client-side authorization for hidden services. */
3628 if (rend_parse_service_authorization(options
, 1) < 0)
3629 REJECT("Failed to configure client authorization for hidden services. "
3630 "See logs for details.");
3632 if (parse_virtual_addr_network(options
->VirtualAddrNetwork
, 1, NULL
)<0)
3635 if (options
->PreferTunneledDirConns
&& !options
->TunnelDirConns
)
3636 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3638 if ((options
->Socks4Proxy
|| options
->Socks5Proxy
) &&
3639 !options
->HTTPProxy
&& !options
->PreferTunneledDirConns
)
3640 REJECT("When Socks4Proxy or Socks5Proxy is configured, "
3641 "PreferTunneledDirConns and TunnelDirConns must both be "
3642 "set to 1, or HTTPProxy must be configured.");
3644 if (options
->AutomapHostsSuffixes
) {
3645 SMARTLIST_FOREACH(options
->AutomapHostsSuffixes
, char *, suf
,
3647 size_t len
= strlen(suf
);
3648 if (len
&& suf
[len
-1] == '.')
3653 if (options
->TestingTorNetwork
&& !options
->DirServers
) {
3654 REJECT("TestingTorNetwork may only be configured in combination with "
3655 "a non-default set of DirServers.");
3658 if (options
->AllowSingleHopExits
&& !options
->DirServers
) {
3659 COMPLAIN("You have set AllowSingleHopExits; now your relay will allow "
3660 "others to make one-hop exits. However, since by default most "
3661 "clients avoid relays that set this option, most clients will "
3665 /*XXXX023 checking for defaults manually like this is a bit fragile.*/
3667 /* Keep changes to hard-coded values synchronous to man page and default
3669 if (options
->TestingV3AuthInitialVotingInterval
!= 30*60 &&
3670 !options
->TestingTorNetwork
&& !options
->_UsingTestNetworkDefaults
) {
3671 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
3673 } else if (options
->TestingV3AuthInitialVotingInterval
< MIN_VOTE_INTERVAL
) {
3674 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3675 } else if (((30*60) % options
->TestingV3AuthInitialVotingInterval
) != 0) {
3676 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3680 if (options
->TestingV3AuthInitialVoteDelay
!= 5*60 &&
3681 !options
->TestingTorNetwork
&& !options
->_UsingTestNetworkDefaults
) {
3683 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
3685 } else if (options
->TestingV3AuthInitialVoteDelay
< MIN_VOTE_SECONDS
) {
3686 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3689 if (options
->TestingV3AuthInitialDistDelay
!= 5*60 &&
3690 !options
->TestingTorNetwork
&& !options
->_UsingTestNetworkDefaults
) {
3691 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
3693 } else if (options
->TestingV3AuthInitialDistDelay
< MIN_DIST_SECONDS
) {
3694 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3697 if (options
->TestingV3AuthInitialVoteDelay
+
3698 options
->TestingV3AuthInitialDistDelay
>=
3699 options
->TestingV3AuthInitialVotingInterval
/2) {
3700 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3701 "must be less than half TestingV3AuthInitialVotingInterval");
3704 if (options
->TestingAuthDirTimeToLearnReachability
!= 30*60 &&
3705 !options
->TestingTorNetwork
&& !options
->_UsingTestNetworkDefaults
) {
3706 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
3707 "testing Tor networks!");
3708 } else if (options
->TestingAuthDirTimeToLearnReachability
< 0) {
3709 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3710 } else if (options
->TestingAuthDirTimeToLearnReachability
> 2*60*60) {
3711 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3714 if (options
->TestingEstimatedDescriptorPropagationTime
!= 10*60 &&
3715 !options
->TestingTorNetwork
&& !options
->_UsingTestNetworkDefaults
) {
3716 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
3717 "testing Tor networks!");
3718 } else if (options
->TestingEstimatedDescriptorPropagationTime
< 0) {
3719 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3720 } else if (options
->TestingEstimatedDescriptorPropagationTime
> 60*60) {
3721 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3724 if (options
->TestingTorNetwork
) {
3725 log_warn(LD_CONFIG
, "TestingTorNetwork is set. This will make your node "
3726 "almost unusable in the public Tor network, and is "
3727 "therefore only advised if you are building a "
3728 "testing Tor network!");
3731 if (options
->AccelName
&& !options
->HardwareAccel
)
3732 options
->HardwareAccel
= 1;
3733 if (options
->AccelDir
&& !options
->AccelName
)
3734 REJECT("Can't use hardware crypto accelerator dir without engine name.");
3736 if (options
->PublishServerDescriptor
)
3737 SMARTLIST_FOREACH(options
->PublishServerDescriptor
, const char *, pubdes
, {
3738 if (!strcmp(pubdes
, "1") || !strcmp(pubdes
, "0"))
3739 if (smartlist_len(options
->PublishServerDescriptor
) > 1) {
3740 COMPLAIN("You have passed a list of multiple arguments to the "
3741 "PublishServerDescriptor option that includes 0 or 1. "
3742 "0 or 1 should only be used as the sole argument. "
3743 "This configuration will be rejected in a future release.");
3748 if (options
->BridgeRelay
== 1 && options
->ORPort
== 0)
3749 REJECT("BridgeRelay is 1, ORPort is 0. This is an invalid combination.");
3756 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3759 opt_streq(const char *s1
, const char *s2
)
3763 else if (s1
&& s2
&& !strcmp(s1
,s2
))
3769 /** Check if any of the previous options have changed but aren't allowed to. */
3771 options_transition_allowed(or_options_t
*old
, or_options_t
*new_val
,
3777 if (!opt_streq(old
->PidFile
, new_val
->PidFile
)) {
3778 *msg
= tor_strdup("PidFile is not allowed to change.");
3782 if (old
->RunAsDaemon
!= new_val
->RunAsDaemon
) {
3783 *msg
= tor_strdup("While Tor is running, changing RunAsDaemon "
3788 if (strcmp(old
->DataDirectory
,new_val
->DataDirectory
)!=0) {
3790 "While Tor is running, changing DataDirectory "
3791 "(\"%s\"->\"%s\") is not allowed.",
3792 old
->DataDirectory
, new_val
->DataDirectory
);
3796 if (!opt_streq(old
->User
, new_val
->User
)) {
3797 *msg
= tor_strdup("While Tor is running, changing User is not allowed.");
3801 if ((old
->HardwareAccel
!= new_val
->HardwareAccel
)
3802 || !opt_streq(old
->AccelName
, new_val
->AccelName
)
3803 || !opt_streq(old
->AccelDir
, new_val
->AccelDir
)) {
3804 *msg
= tor_strdup("While Tor is running, changing OpenSSL hardware "
3805 "acceleration engine is not allowed.");
3809 if (old
->TestingTorNetwork
!= new_val
->TestingTorNetwork
) {
3810 *msg
= tor_strdup("While Tor is running, changing TestingTorNetwork "
3815 if (old
->DisableAllSwap
!= new_val
->DisableAllSwap
) {
3816 *msg
= tor_strdup("While Tor is running, changing DisableAllSwap "
3824 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3825 * will require us to rotate the CPU and DNS workers; else return 0. */
3827 options_transition_affects_workers(or_options_t
*old_options
,
3828 or_options_t
*new_options
)
3830 if (!opt_streq(old_options
->DataDirectory
, new_options
->DataDirectory
) ||
3831 old_options
->NumCPUs
!= new_options
->NumCPUs
||
3832 old_options
->ORPort
!= new_options
->ORPort
||
3833 old_options
->ServerDNSSearchDomains
!=
3834 new_options
->ServerDNSSearchDomains
||
3835 old_options
->_SafeLogging
!= new_options
->_SafeLogging
||
3836 old_options
->ClientOnly
!= new_options
->ClientOnly
||
3837 public_server_mode(old_options
) != public_server_mode(new_options
) ||
3838 !config_lines_eq(old_options
->Logs
, new_options
->Logs
) ||
3839 old_options
->LogMessageDomains
!= new_options
->LogMessageDomains
)
3842 /* Check whether log options match. */
3844 /* Nothing that changed matters. */
3848 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3849 * will require us to generate a new descriptor; else return 0. */
3851 options_transition_affects_descriptor(or_options_t
*old_options
,
3852 or_options_t
*new_options
)
3854 /* XXX We can be smarter here. If your DirPort isn't being
3855 * published and you just turned it off, no need to republish. Etc. */
3856 if (!opt_streq(old_options
->DataDirectory
, new_options
->DataDirectory
) ||
3857 !opt_streq(old_options
->Nickname
,new_options
->Nickname
) ||
3858 !opt_streq(old_options
->Address
,new_options
->Address
) ||
3859 !config_lines_eq(old_options
->ExitPolicy
,new_options
->ExitPolicy
) ||
3860 old_options
->ExitPolicyRejectPrivate
!=
3861 new_options
->ExitPolicyRejectPrivate
||
3862 old_options
->ORPort
!= new_options
->ORPort
||
3863 old_options
->DirPort
!= new_options
->DirPort
||
3864 old_options
->ClientOnly
!= new_options
->ClientOnly
||
3865 old_options
->_PublishServerDescriptor
!=
3866 new_options
->_PublishServerDescriptor
||
3867 get_effective_bwrate(old_options
) != get_effective_bwrate(new_options
) ||
3868 get_effective_bwburst(old_options
) !=
3869 get_effective_bwburst(new_options
) ||
3870 !opt_streq(old_options
->ContactInfo
, new_options
->ContactInfo
) ||
3871 !opt_streq(old_options
->MyFamily
, new_options
->MyFamily
) ||
3872 !opt_streq(old_options
->AccountingStart
, new_options
->AccountingStart
) ||
3873 old_options
->AccountingMax
!= new_options
->AccountingMax
)
3880 /** Return the directory on windows where we expect to find our application
3883 get_windows_conf_root(void)
3885 static int is_set
= 0;
3886 static char path
[MAX_PATH
+1];
3887 TCHAR tpath
[MAX_PATH
] = {0};
3896 /* Find X:\documents and settings\username\application data\ .
3897 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3899 #ifdef ENABLE_LOCAL_APPDATA
3900 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
3902 #define APPDATA_PATH CSIDL_APPDATA
3904 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL
, APPDATA_PATH
, &idl
))) {
3905 getcwd(path
,MAX_PATH
);
3908 "I couldn't find your application data folder: are you "
3909 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3913 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3914 result
= SHGetPathFromIDList(idl
, tpath
);
3916 wcstombs(path
,tpath
,MAX_PATH
);
3918 strlcpy(path
,tpath
,sizeof(path
));
3921 /* Now we need to free the memory that the path-idl was stored in. In
3922 * typical Windows fashion, we can't just call 'free()' on it. */
3925 m
->lpVtbl
->Free(m
, idl
);
3926 m
->lpVtbl
->Release(m
);
3928 if (!SUCCEEDED(result
)) {
3931 strlcat(path
,"\\tor",MAX_PATH
);
3937 /** Return the default location for our torrc file. */
3939 get_default_conf_file(void)
3942 static char path
[MAX_PATH
+1];
3943 strlcpy(path
, get_windows_conf_root(), MAX_PATH
);
3944 strlcat(path
,"\\torrc",MAX_PATH
);
3947 return (CONFDIR
"/torrc");
3951 /** Verify whether lst is a string containing valid-looking comma-separated
3952 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3955 check_nickname_list(const char *lst
, const char *name
, char **msg
)
3962 sl
= smartlist_create();
3964 smartlist_split_string(sl
, lst
, ",",
3965 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
|SPLIT_STRIP_SPACE
, 0);
3967 SMARTLIST_FOREACH(sl
, const char *, s
,
3969 if (!is_legal_nickname_or_hexdigest(s
)) {
3970 tor_asprintf(msg
, "Invalid nickname '%s' in %s line", s
, name
);
3975 SMARTLIST_FOREACH(sl
, char *, s
, tor_free(s
));
3980 /** Learn config file name from command line arguments, or use the default */
3982 find_torrc_filename(int argc
, char **argv
,
3983 int *using_default_torrc
, int *ignore_missing_torrc
)
3988 for (i
= 1; i
< argc
; ++i
) {
3989 if (i
< argc
-1 && !strcmp(argv
[i
],"-f")) {
3991 log(LOG_WARN
, LD_CONFIG
, "Duplicate -f options on command line.");
3994 fname
= expand_filename(argv
[i
+1]);
3995 *using_default_torrc
= 0;
3997 } else if (!strcmp(argv
[i
],"--ignore-missing-torrc")) {
3998 *ignore_missing_torrc
= 1;
4002 if (*using_default_torrc
) {
4003 /* didn't find one, try CONFDIR */
4004 const char *dflt
= get_default_conf_file();
4005 if (dflt
&& file_status(dflt
) == FN_FILE
) {
4006 fname
= tor_strdup(dflt
);
4010 fn
= expand_filename("~/.torrc");
4011 if (fn
&& file_status(fn
) == FN_FILE
) {
4015 fname
= tor_strdup(dflt
);
4018 fname
= tor_strdup(dflt
);
4025 /** Load torrc from disk, setting torrc_fname if successful */
4027 load_torrc_from_disk(int argc
, char **argv
)
4031 int using_default_torrc
= 1;
4032 int ignore_missing_torrc
= 0;
4034 fname
= find_torrc_filename(argc
, argv
,
4035 &using_default_torrc
, &ignore_missing_torrc
);
4037 log(LOG_DEBUG
, LD_CONFIG
, "Opening config file \"%s\"", fname
);
4039 tor_free(torrc_fname
);
4040 torrc_fname
= fname
;
4042 /* Open config file */
4043 if (file_status(fname
) != FN_FILE
||
4044 !(cf
= read_file_to_str(fname
,0,NULL
))) {
4045 if (using_default_torrc
== 1 || ignore_missing_torrc
) {
4046 log(LOG_NOTICE
, LD_CONFIG
, "Configuration file \"%s\" not present, "
4047 "using reasonable defaults.", fname
);
4048 tor_free(fname
); /* sets fname to NULL */
4050 cf
= tor_strdup("");
4052 log(LOG_WARN
, LD_CONFIG
,
4053 "Unable to open configuration file \"%s\".", fname
);
4065 /** Read a configuration file into <b>options</b>, finding the configuration
4066 * file location based on the command line. After loading the file
4067 * call options_init_from_string() to load the config.
4068 * Return 0 if success, -1 if failure. */
4070 options_init_from_torrc(int argc
, char **argv
)
4073 int i
, retval
, command
;
4074 static char **backup_argv
;
4075 static int backup_argc
;
4076 char *command_arg
= NULL
;
4079 if (argv
) { /* first time we're called. save command line args */
4082 } else { /* we're reloading. need to clean up old options first. */
4086 if (argc
> 1 && (!strcmp(argv
[1], "-h") || !strcmp(argv
[1],"--help"))) {
4090 if (argc
> 1 && !strcmp(argv
[1], "--list-torrc-options")) {
4091 /* For documenting validating whether we've documented everything. */
4092 list_torrc_options();
4096 if (argc
> 1 && (!strcmp(argv
[1],"--version"))) {
4097 printf("Tor version %s.\n",get_version());
4100 if (argc
> 1 && (!strcmp(argv
[1],"--digests"))) {
4101 printf("Tor version %s.\n",get_version());
4102 printf("%s", libor_get_digests());
4103 printf("%s", tor_get_digests());
4107 /* Go through command-line variables */
4108 if (!global_cmdline_options
) {
4109 /* Or we could redo the list every time we pass this place.
4110 * It does not really matter */
4111 if (config_get_commandlines(argc
, argv
, &global_cmdline_options
) < 0) {
4116 command
= CMD_RUN_TOR
;
4117 for (i
= 1; i
< argc
; ++i
) {
4118 if (!strcmp(argv
[i
],"--list-fingerprint")) {
4119 command
= CMD_LIST_FINGERPRINT
;
4120 } else if (!strcmp(argv
[i
],"--hash-password")) {
4121 command
= CMD_HASH_PASSWORD
;
4122 command_arg
= tor_strdup( (i
< argc
-1) ? argv
[i
+1] : "");
4124 } else if (!strcmp(argv
[i
],"--verify-config")) {
4125 command
= CMD_VERIFY_CONFIG
;
4129 if (command
== CMD_HASH_PASSWORD
) {
4130 cf
= tor_strdup("");
4132 cf
= load_torrc_from_disk(argc
, argv
);
4137 retval
= options_init_from_string(cf
, command
, command_arg
, &errmsg
);
4146 log(LOG_WARN
,LD_CONFIG
,"%s", errmsg
);
4152 /** Load the options from the configuration in <b>cf</b>, validate
4153 * them for consistency and take actions based on them.
4155 * Return 0 if success, negative on error:
4156 * * -1 for general errors.
4157 * * -2 for failure to parse/validate,
4158 * * -3 for transition not allowed
4159 * * -4 for error while setting the new options
4162 options_init_from_string(const char *cf
,
4163 int command
, const char *command_arg
,
4166 or_options_t
*oldoptions
, *newoptions
;
4169 setopt_err_t err
= SETOPT_ERR_MISC
;
4172 oldoptions
= global_options
; /* get_options unfortunately asserts if
4173 this is the first time we run*/
4175 newoptions
= tor_malloc_zero(sizeof(or_options_t
));
4176 newoptions
->_magic
= OR_OPTIONS_MAGIC
;
4177 options_init(newoptions
);
4178 newoptions
->command
= command
;
4179 newoptions
->command_arg
= command_arg
;
4181 /* get config lines, assign them */
4182 retval
= config_get_lines(cf
, &cl
);
4184 err
= SETOPT_ERR_PARSE
;
4187 retval
= config_assign(&options_format
, newoptions
, cl
, 0, 0, msg
);
4188 config_free_lines(cl
);
4190 err
= SETOPT_ERR_PARSE
;
4194 /* Go through command-line variables too */
4195 retval
= config_assign(&options_format
, newoptions
,
4196 global_cmdline_options
, 0, 0, msg
);
4198 err
= SETOPT_ERR_PARSE
;
4202 /* If this is a testing network configuration, change defaults
4203 * for a list of dependent config options, re-initialize newoptions
4204 * with the new defaults, and assign all options to it second time. */
4205 if (newoptions
->TestingTorNetwork
) {
4206 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4207 * this? We could, for example, make the parsing algorithm do two passes
4208 * over the configuration. If it finds any "suite" options like
4209 * TestingTorNetwork, it could change the defaults before its second pass.
4210 * Not urgent so long as this seems to work, but at any sign of trouble,
4211 * let's clean it up. -NM */
4213 /* Change defaults. */
4215 for (i
= 0; testing_tor_network_defaults
[i
].name
; ++i
) {
4216 config_var_t
*new_var
= &testing_tor_network_defaults
[i
];
4217 config_var_t
*old_var
=
4218 config_find_option(&options_format
, new_var
->name
);
4219 tor_assert(new_var
);
4220 tor_assert(old_var
);
4221 old_var
->initvalue
= new_var
->initvalue
;
4224 /* Clear newoptions and re-initialize them with new defaults. */
4225 config_free(&options_format
, newoptions
);
4226 newoptions
= tor_malloc_zero(sizeof(or_options_t
));
4227 newoptions
->_magic
= OR_OPTIONS_MAGIC
;
4228 options_init(newoptions
);
4229 newoptions
->command
= command
;
4230 newoptions
->command_arg
= command_arg
;
4232 /* Assign all options a second time. */
4233 retval
= config_get_lines(cf
, &cl
);
4235 err
= SETOPT_ERR_PARSE
;
4238 retval
= config_assign(&options_format
, newoptions
, cl
, 0, 0, msg
);
4239 config_free_lines(cl
);
4241 err
= SETOPT_ERR_PARSE
;
4244 retval
= config_assign(&options_format
, newoptions
,
4245 global_cmdline_options
, 0, 0, msg
);
4247 err
= SETOPT_ERR_PARSE
;
4252 /* Validate newoptions */
4253 if (options_validate(oldoptions
, newoptions
, 0, msg
) < 0) {
4254 err
= SETOPT_ERR_PARSE
; /*XXX make this a separate return value.*/
4258 if (options_transition_allowed(oldoptions
, newoptions
, msg
) < 0) {
4259 err
= SETOPT_ERR_TRANSITION
;
4263 if (set_options(newoptions
, msg
)) {
4264 err
= SETOPT_ERR_SETTING
;
4265 goto err
; /* frees and replaces old options */
4271 config_free(&options_format
, newoptions
);
4273 char *old_msg
= *msg
;
4274 tor_asprintf(msg
, "Failed to parse/validate config: %s", old_msg
);
4280 /** Return the location for our configuration file.
4283 get_torrc_fname(void)
4288 return get_default_conf_file();
4291 /** Adjust the address map based on the MapAddress elements in the
4292 * configuration <b>options</b>
4295 config_register_addressmaps(or_options_t
*options
)
4301 addressmap_clear_configured();
4302 elts
= smartlist_create();
4303 for (opt
= options
->AddressMap
; opt
; opt
= opt
->next
) {
4304 smartlist_split_string(elts
, opt
->value
, NULL
,
4305 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
4306 if (smartlist_len(elts
) >= 2) {
4307 from
= smartlist_get(elts
,0);
4308 to
= smartlist_get(elts
,1);
4309 if (address_is_invalid_destination(to
, 1)) {
4311 "Skipping invalid argument '%s' to MapAddress", to
);
4313 addressmap_register(from
, tor_strdup(to
), 0, ADDRMAPSRC_TORRC
);
4314 if (smartlist_len(elts
)>2) {
4315 log_warn(LD_CONFIG
,"Ignoring extra arguments to MapAddress.");
4319 log_warn(LD_CONFIG
,"MapAddress '%s' has too few arguments. Ignoring.",
4322 SMARTLIST_FOREACH(elts
, char*, cp
, tor_free(cp
));
4323 smartlist_clear(elts
);
4325 smartlist_free(elts
);
4329 * Initialize the logs based on the configuration file.
4332 options_init_logs(or_options_t
*options
, int validate_only
)
4341 options
->RunAsDaemon
;
4345 elts
= smartlist_create();
4347 for (opt
= options
->Logs
; opt
; opt
= opt
->next
) {
4348 log_severity_list_t
*severity
;
4349 const char *cfg
= opt
->value
;
4350 severity
= tor_malloc_zero(sizeof(log_severity_list_t
));
4351 if (parse_log_severity_config(&cfg
, severity
) < 0) {
4352 log_warn(LD_CONFIG
, "Couldn't parse log levels in Log option 'Log %s'",
4354 ok
= 0; goto cleanup
;
4357 smartlist_split_string(elts
, cfg
, NULL
,
4358 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
4360 if (smartlist_len(elts
) == 0)
4361 smartlist_add(elts
, tor_strdup("stdout"));
4363 if (smartlist_len(elts
) == 1 &&
4364 (!strcasecmp(smartlist_get(elts
,0), "stdout") ||
4365 !strcasecmp(smartlist_get(elts
,0), "stderr"))) {
4366 int err
= smartlist_len(elts
) &&
4367 !strcasecmp(smartlist_get(elts
,0), "stderr");
4368 if (!validate_only
) {
4371 "Can't log to %s with RunAsDaemon set; skipping stdout",
4372 err
?"stderr":"stdout");
4374 add_stream_log(severity
, err
?"<stderr>":"<stdout>",
4375 fileno(err
?stderr
:stdout
));
4380 if (smartlist_len(elts
) == 1 &&
4381 !strcasecmp(smartlist_get(elts
,0), "syslog")) {
4382 #ifdef HAVE_SYSLOG_H
4383 if (!validate_only
) {
4384 add_syslog_log(severity
);
4387 log_warn(LD_CONFIG
, "Syslog is not supported on this system. Sorry.");
4392 if (smartlist_len(elts
) == 2 &&
4393 !strcasecmp(smartlist_get(elts
,0), "file")) {
4394 if (!validate_only
) {
4395 char *fname
= expand_filename(smartlist_get(elts
, 1));
4396 if (add_file_log(severity
, fname
) < 0) {
4397 log_warn(LD_CONFIG
, "Couldn't open file for 'Log %s': %s",
4398 opt
->value
, strerror(errno
));
4406 log_warn(LD_CONFIG
, "Bad syntax on file Log option 'Log %s'",
4408 ok
= 0; goto cleanup
;
4411 SMARTLIST_FOREACH(elts
, char*, cp
, tor_free(cp
));
4412 smartlist_clear(elts
);
4415 smartlist_free(elts
);
4417 if (ok
&& !validate_only
)
4418 logs_set_domain_logging(options
->LogMessageDomains
);
4423 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4424 * if the line is well-formed, and -1 if it isn't. If
4425 * <b>validate_only</b> is 0, and the line is well-formed, then add
4426 * the bridge described in the line to our internal bridge list. */
4428 parse_bridge_line(const char *line
, int validate_only
)
4430 smartlist_t
*items
= NULL
;
4432 char *addrport
=NULL
, *fingerprint
=NULL
;
4435 char digest
[DIGEST_LEN
];
4437 items
= smartlist_create();
4438 smartlist_split_string(items
, line
, NULL
,
4439 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, -1);
4440 if (smartlist_len(items
) < 1) {
4441 log_warn(LD_CONFIG
, "Too few arguments to Bridge line.");
4444 addrport
= smartlist_get(items
, 0);
4445 smartlist_del_keeporder(items
, 0);
4446 if (tor_addr_port_parse(addrport
, &addr
, &port
)<0) {
4447 log_warn(LD_CONFIG
, "Error parsing Bridge address '%s'", addrport
);
4452 "Bridge address '%s' has no port; using default port 443.",
4457 if (smartlist_len(items
)) {
4458 fingerprint
= smartlist_join_strings(items
, "", 0, NULL
);
4459 if (strlen(fingerprint
) != HEX_DIGEST_LEN
) {
4460 log_warn(LD_CONFIG
, "Key digest for Bridge is wrong length.");
4463 if (base16_decode(digest
, DIGEST_LEN
, fingerprint
, HEX_DIGEST_LEN
)<0) {
4464 log_warn(LD_CONFIG
, "Unable to decode Bridge key digest.");
4469 if (!validate_only
) {
4470 log_debug(LD_DIR
, "Bridge at %s:%d (%s)", fmt_addr(&addr
),
4472 fingerprint
? fingerprint
: "no key listed");
4473 bridge_add_from_config(&addr
, port
, fingerprint
? digest
: NULL
);
4483 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
4484 smartlist_free(items
);
4486 tor_free(fingerprint
);
4490 /** Read the contents of a DirServer line from <b>line</b>. If
4491 * <b>validate_only</b> is 0, and the line is well-formed, and it
4492 * shares any bits with <b>required_type</b> or <b>required_type</b>
4493 * is 0, then add the dirserver described in the line (minus whatever
4494 * bits it's missing) as a valid authority. Return 0 on success,
4495 * or -1 if the line isn't well-formed or if we can't add it. */
4497 parse_dir_server_line(const char *line
, authority_type_t required_type
,
4500 smartlist_t
*items
= NULL
;
4502 char *addrport
=NULL
, *address
=NULL
, *nickname
=NULL
, *fingerprint
=NULL
;
4503 uint16_t dir_port
= 0, or_port
= 0;
4504 char digest
[DIGEST_LEN
];
4505 char v3_digest
[DIGEST_LEN
];
4506 authority_type_t type
= V2_AUTHORITY
;
4507 int is_not_hidserv_authority
= 0, is_not_v2_authority
= 0;
4509 items
= smartlist_create();
4510 smartlist_split_string(items
, line
, NULL
,
4511 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, -1);
4512 if (smartlist_len(items
) < 1) {
4513 log_warn(LD_CONFIG
, "No arguments on DirServer line.");
4517 if (is_legal_nickname(smartlist_get(items
, 0))) {
4518 nickname
= smartlist_get(items
, 0);
4519 smartlist_del_keeporder(items
, 0);
4522 while (smartlist_len(items
)) {
4523 char *flag
= smartlist_get(items
, 0);
4524 if (TOR_ISDIGIT(flag
[0]))
4526 if (!strcasecmp(flag
, "v1")) {
4527 type
|= (V1_AUTHORITY
| HIDSERV_AUTHORITY
);
4528 } else if (!strcasecmp(flag
, "hs")) {
4529 type
|= HIDSERV_AUTHORITY
;
4530 } else if (!strcasecmp(flag
, "no-hs")) {
4531 is_not_hidserv_authority
= 1;
4532 } else if (!strcasecmp(flag
, "bridge")) {
4533 type
|= BRIDGE_AUTHORITY
;
4534 } else if (!strcasecmp(flag
, "no-v2")) {
4535 is_not_v2_authority
= 1;
4536 } else if (!strcasecmpstart(flag
, "orport=")) {
4538 char *portstring
= flag
+ strlen("orport=");
4539 or_port
= (uint16_t) tor_parse_long(portstring
, 10, 1, 65535, &ok
, NULL
);
4541 log_warn(LD_CONFIG
, "Invalid orport '%s' on DirServer line.",
4543 } else if (!strcasecmpstart(flag
, "v3ident=")) {
4544 char *idstr
= flag
+ strlen("v3ident=");
4545 if (strlen(idstr
) != HEX_DIGEST_LEN
||
4546 base16_decode(v3_digest
, DIGEST_LEN
, idstr
, HEX_DIGEST_LEN
)<0) {
4547 log_warn(LD_CONFIG
, "Bad v3 identity digest '%s' on DirServer line",
4550 type
|= V3_AUTHORITY
;
4553 log_warn(LD_CONFIG
, "Unrecognized flag '%s' on DirServer line",
4557 smartlist_del_keeporder(items
, 0);
4559 if (is_not_hidserv_authority
)
4560 type
&= ~HIDSERV_AUTHORITY
;
4561 if (is_not_v2_authority
)
4562 type
&= ~V2_AUTHORITY
;
4564 if (smartlist_len(items
) < 2) {
4565 log_warn(LD_CONFIG
, "Too few arguments to DirServer line.");
4568 addrport
= smartlist_get(items
, 0);
4569 smartlist_del_keeporder(items
, 0);
4570 if (parse_addr_port(LOG_WARN
, addrport
, &address
, NULL
, &dir_port
)<0) {
4571 log_warn(LD_CONFIG
, "Error parsing DirServer address '%s'", addrport
);
4575 log_warn(LD_CONFIG
, "Missing port in DirServer address '%s'",addrport
);
4579 fingerprint
= smartlist_join_strings(items
, "", 0, NULL
);
4580 if (strlen(fingerprint
) != HEX_DIGEST_LEN
) {
4581 log_warn(LD_CONFIG
, "Key digest for DirServer is wrong length %d.",
4582 (int)strlen(fingerprint
));
4585 if (!strcmp(fingerprint
, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4586 /* a known bad fingerprint. refuse to use it. We can remove this
4587 * clause once Tor 0.1.2.17 is obsolete. */
4588 log_warn(LD_CONFIG
, "Dangerous dirserver line. To correct, erase your "
4589 "torrc file (%s), or reinstall Tor and use the default torrc.",
4593 if (base16_decode(digest
, DIGEST_LEN
, fingerprint
, HEX_DIGEST_LEN
)<0) {
4594 log_warn(LD_CONFIG
, "Unable to decode DirServer key digest.");
4598 if (!validate_only
&& (!required_type
|| required_type
& type
)) {
4600 type
&= required_type
; /* pare down what we think of them as an
4602 log_debug(LD_DIR
, "Trusted %d dirserver at %s:%d (%s)", (int)type
,
4603 address
, (int)dir_port
, (char*)smartlist_get(items
,0));
4604 if (!add_trusted_dir_server(nickname
, address
, dir_port
, or_port
,
4605 digest
, v3_digest
, type
))
4616 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
4617 smartlist_free(items
);
4621 tor_free(fingerprint
);
4625 /** Adjust the value of options->DataDirectory, or fill it in if it's
4626 * absent. Return 0 on success, -1 on failure. */
4628 normalize_data_directory(or_options_t
*options
)
4632 if (options
->DataDirectory
)
4633 return 0; /* all set */
4634 p
= tor_malloc(MAX_PATH
);
4635 strlcpy(p
,get_windows_conf_root(),MAX_PATH
);
4636 options
->DataDirectory
= p
;
4639 const char *d
= options
->DataDirectory
;
4643 if (strncmp(d
,"~/",2) == 0) {
4644 char *fn
= expand_filename(d
);
4646 log_warn(LD_CONFIG
,"Failed to expand filename \"%s\".", d
);
4649 if (!options
->DataDirectory
&& !strcmp(fn
,"/.tor")) {
4650 /* If our homedir is /, we probably don't want to use it. */
4651 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4654 "Default DataDirectory is \"~/.tor\". This expands to "
4655 "\"%s\", which is probably not what you want. Using "
4656 "\"%s"PATH_SEPARATOR
"tor\" instead
", fn, LOCALSTATEDIR);
4658 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor
");
4660 tor_free(options->DataDirectory);
4661 options->DataDirectory = fn;
4667 /** Check and normalize the value of options->DataDirectory; return 0 if it
4668 * is sane, -1 otherwise. */
4670 validate_data_directory(or_options_t *options)
4672 if (normalize_data_directory(options) < 0)
4674 tor_assert(options->DataDirectory);
4675 if (strlen(options->DataDirectory) > (512-128)) {
4676 log_warn(LD_CONFIG, "DataDirectory is too
long.");
4682 /** This string must remain the same forevermore. It is how we
4683 * recognize that the torrc file doesn't need to be backed up. */
4684 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4685 "if you edit it, comments will not be preserved"
4686 /** This string can change; it tries to give the reader an idea
4687 * that editing this file by hand is not a good plan. */
4688 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4689 "to torrc.orig.1 or similar, and Tor will ignore it"
4691 /** Save a configuration file for the configuration in <b>options</b>
4692 * into the file <b>fname</b>. If the file already exists, and
4693 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4694 * replace it. Return 0 on success, -1 on failure. */
4696 write_configuration_file(const char *fname, or_options_t *options)
4698 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4699 int rename_old = 0, r;
4703 switch (file_status(fname)) {
4705 old_val = read_file_to_str(fname, 0, NULL);
4706 if (!old_val || strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4717 "Config file \"%s\" is not a file? Failing.", fname);
4721 if (!(new_conf = options_dump(options, 1))) {
4722 log_warn(LD_BUG, "Couldn't get configuration string");
4726 tor_asprintf(&new_val, "%s\n%s\n\n%s",
4727 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4731 size_t fn_tmp_len = strlen(fname)+32;
4733 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4734 fn_tmp = tor_malloc(fn_tmp_len);
4736 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4737 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4741 if (file_status(fn_tmp) == FN_NOENT)
4745 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4746 if (rename(fname, fn_tmp) < 0) {
4748 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4749 fname, fn_tmp, strerror(errno));
4756 if (write_str_to_file(fname, new_val, 0) < 0)
4770 * Save the current configuration file value to disk. Return 0 on
4771 * success, -1 on failure.
4774 options_save_current(void)
4776 /* This fails if we can't write to our configuration file.
4778 * If we try falling back to datadirectory or something, we have a better
4779 * chance of saving the configuration, but a better chance of doing
4780 * something the user never expected. */
4781 return write_configuration_file(get_torrc_fname(), get_options());
4784 /** Mapping from a unit name to a multiplier for converting that unit into a
4785 * base unit. Used by config_parse_unit. */
4786 struct unit_table_t {
4787 const char *unit; /**< The name of the unit */
4788 uint64_t multiplier; /**< How many of the base unit appear in this unit */
4791 /** Table to map the names of memory units to the number of bytes they
4793 static struct unit_table_t memory_units[] = {
4800 { "kbytes", 1<<10 },
4801 { "kilobyte", 1<<10 },
4802 { "kilobytes", 1<<10 },
4806 { "mbytes", 1<<20 },
4807 { "megabyte", 1<<20 },
4808 { "megabytes", 1<<20 },
4811 { "gbytes", 1<<30 },
4812 { "gigabyte", 1<<30 },
4813 { "gigabytes", 1<<30 },
4814 { "tb", U64_LITERAL(1)<<40 },
4815 { "terabyte", U64_LITERAL(1)<<40 },
4816 { "terabytes", U64_LITERAL(1)<<40 },
4820 /** Table to map the names of time units to the number of seconds they
4822 static struct unit_table_t time_units[] = {
4830 { "day", 24*60*60 },
4831 { "days", 24*60*60 },
4832 { "week", 7*24*60*60 },
4833 { "weeks", 7*24*60*60 },
4837 /** Parse a string <b>val</b> containing a number, zero or more
4838 * spaces, and an optional unit string. If the unit appears in the
4839 * table <b>u</b>, then multiply the number by the unit multiplier.
4840 * On success, set *<b>ok</b> to 1 and return this product.
4841 * Otherwise, set *<b>ok</b> to 0.
4844 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4853 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4854 if (!*ok || (cp && *cp == '.')) {
4855 d = tor_parse_double(val, 0, UINT64_MAX, ok, &cp);
4863 v = use_float ? DBL_TO_U64(d) : v;
4867 cp = (char*) eat_whitespace(cp);
4869 for ( ;u->unit;++u) {
4870 if (!strcasecmp(u->unit, cp)) {
4872 v = u->multiplier * d;
4879 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4889 /** Parse a string in the format "number unit", where unit is a unit of
4890 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4891 * and return the number of bytes specified. Otherwise, set
4892 * *<b>ok</b> to false and return 0. */
4894 config_parse_memunit(const char *s, int *ok)
4896 uint64_t u = config_parse_units(s, memory_units, ok);
4900 /** Parse a string in the format "number unit", where unit is a unit of time.
4901 * On success, set *<b>ok</b> to true and return the number of seconds in
4902 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4905 config_parse_interval(const char *s, int *ok)
4908 r = config_parse_units(s, time_units, ok);
4912 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4920 * Initialize the libevent library.
4925 const char *badness=NULL;
4927 configure_libevent_logging();
4928 /* If the kernel complains that some method (say, epoll) doesn't
4929 * exist, we don't care about it, since libevent will cope.
4931 suppress_libevent_log_msg("Function not implemented");
4933 tor_check_libevent_header_compatibility();
4935 tor_libevent_initialize();
4937 suppress_libevent_log_msg(NULL);
4939 tor_check_libevent_version(tor_libevent_get_method(),
4940 get_options()->ORPort != 0,
4943 const char *v = tor_libevent_get_version_str();
4944 const char *m = tor_libevent_get_method();
4945 control_event_general_status(LOG_WARN,
4946 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
4951 /** Return the persistent state struct for this Tor. */
4955 tor_assert(global_state);
4956 return global_state;
4959 /** Return a newly allocated string holding a filename relative to the data
4960 * directory. If <b>sub1</b> is present, it is the first path component after
4961 * the data directory. If <b>sub2</b> is also present, it is the second path
4962 * component after the data directory. If <b>suffix</b> is present, it
4963 * is appended to the filename.
4966 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
4967 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
4968 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
4969 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
4971 * Note: Consider using the get_datadir_fname* macros in or.h.
4974 options_get_datadir_fname2_suffix(or_options_t *options,
4975 const char *sub1, const char *sub2,
4980 tor_assert(options);
4981 tor_assert(options->DataDirectory);
4982 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
4983 len = strlen(options->DataDirectory);
4985 len += strlen(sub1)+1;
4987 len += strlen(sub2)+1;
4990 len += strlen(suffix);
4992 fname = tor_malloc(len);
4995 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
4996 options->DataDirectory, sub1, sub2);
4998 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
4999 options->DataDirectory, sub1);
5002 strlcpy(fname, options->DataDirectory, len);
5005 strlcat(fname, suffix, len);
5009 /** Return 0 if every setting in <b>state</b> is reasonable, and a
5010 * permissible transition from <b>old_state</b>. Else warn and return -1.
5011 * Should have no side effects, except for normalizing the contents of
5014 /* XXX from_setconf is here because of bug 238 */
5016 or_state_validate(or_state_t *old_state, or_state_t *state,
5017 int from_setconf, char **msg)
5019 /* We don't use these; only options do. Still, we need to match that
5021 (void) from_setconf;
5024 if (entry_guards_parse_state(state, 0, msg)<0)
5030 /** Replace the current persistent state with <b>new_state</b> */
5032 or_state_set(or_state_t *new_state)
5036 tor_assert(new_state);
5037 config_free(&state_format, global_state);
5038 global_state = new_state;
5039 if (entry_guards_parse_state(global_state, 1, &err)<0) {
5040 log_warn(LD_GENERAL,"%s",err);
5044 if (rep_hist_load_state(global_state, &err)<0) {
5045 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
5049 if (circuit_build_times_parse_state(&circ_times, global_state) < 0) {
5056 * Save a broken state file to a backup location.
5059 or_state_save_broken(char *fname)
5062 file_status_t status;
5063 size_t len = strlen(fname)+16;
5064 char *fname2 = tor_malloc(len);
5065 for (i = 0; i < 100; ++i) {
5066 tor_snprintf(fname2, len, "%s.%d", fname, i);
5067 status = file_status(fname2);
5068 if (status == FN_NOENT)
5072 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
5073 "state files to move aside. Discarding the old state file.",
5077 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
5078 "to \"%s\". This could be a bug in Tor; please tell "
5079 "the developers.", fname, fname2);
5080 if (rename(fname, fname2) < 0) {
5081 log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
5082 "OS gave an error of %s", strerror(errno));
5088 /** Reload the persistent state from disk, generating a new state as needed.
5089 * Return 0 on success, less than 0 on failure.
5094 or_state_t *new_state = NULL;
5095 char *contents = NULL, *fname;
5096 char *errmsg = NULL;
5097 int r = -1, badstate = 0;
5099 fname = get_datadir_fname("state");
5100 switch (file_status(fname)) {
5102 if (!(contents = read_file_to_str(fname, 0, NULL))) {
5103 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
5112 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
5115 new_state = tor_malloc_zero(sizeof(or_state_t));
5116 new_state->_magic = OR_STATE_MAGIC;
5117 config_init(&state_format, new_state);
5119 config_line_t *lines=NULL;
5121 if (config_get_lines(contents, &lines)<0)
5123 assign_retval = config_assign(&state_format, new_state,
5124 lines, 0, 0, &errmsg);
5125 config_free_lines(lines);
5126 if (assign_retval<0)
5129 log_warn(LD_GENERAL, "%s", errmsg);
5134 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
5138 log_warn(LD_GENERAL, "%s", errmsg);
5142 if (badstate && !contents) {
5143 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
5144 " This is a bug in Tor.");
5146 } else if (badstate && contents) {
5147 or_state_save_broken(fname);
5150 config_free(&state_format, new_state);
5152 new_state = tor_malloc_zero(sizeof(or_state_t));
5153 new_state->_magic = OR_STATE_MAGIC;
5154 config_init(&state_format, new_state);
5155 } else if (contents) {
5156 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
5158 log_info(LD_GENERAL, "Initialized state");
5160 if (or_state_set(new_state) == -1) {
5161 or_state_save_broken(fname);
5165 global_state->next_write = 0;
5166 or_state_save(time(NULL));
5174 config_free(&state_format, new_state);
5179 /** Did the last time we tried to write the state file fail? If so, we
5180 * should consider disabling such features as preemptive circuit generation
5181 * to compute circuit-build-time. */
5182 static int last_state_file_write_failed = 0;
5184 /** Return whether the state file failed to write last time we tried. */
5186 did_last_state_file_write_fail(void)
5188 return last_state_file_write_failed;
5191 /** If writing the state to disk fails, try again after this many seconds. */
5192 #define STATE_WRITE_RETRY_INTERVAL 3600
5194 /** If we're a relay, how often should we checkpoint our state file even
5195 * if nothing else dirties it? This will checkpoint ongoing stats like
5196 * bandwidth used, per-country user stats, etc. */
5197 #define STATE_RELAY_CHECKPOINT_INTERVAL (12*60*60)
5199 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
5201 or_state_save(time_t now)
5203 char *state, *contents;
5204 char tbuf[ISO_TIME_LEN+1];
5207 tor_assert(global_state);
5209 if (global_state->next_write > now)
5212 /* Call everything else that might dirty the state even more, in order
5213 * to avoid redundant writes. */
5214 entry_guards_update_state(global_state);
5215 rep_hist_update_state(global_state);
5216 circuit_build_times_update_state(&circ_times, global_state);
5217 if (accounting_is_enabled(get_options()))
5218 accounting_run_housekeeping(now);
5220 global_state->LastWritten = now;
5222 tor_free(global_state->TorVersion);
5223 tor_asprintf(&global_state->TorVersion, "Tor %s", get_version());
5225 state = config_dump(&state_format, global_state, 1, 0);
5226 format_local_iso_time(tbuf, now);
5227 tor_asprintf(&contents,
5228 "# Tor state file last generated on %s local time\n"
5229 "# Other times below are in GMT\n"
5230 "# You *do not* need to edit this file.\n\n%s",
5233 fname = get_datadir_fname("state");
5234 if (write_str_to_file(fname, contents, 0)<0) {
5235 log_warn(LD_FS, "Unable to write state to file \"%s\"; "
5236 "will try again later", fname);
5237 last_state_file_write_failed = 1;
5240 /* Try again after STATE_WRITE_RETRY_INTERVAL (or sooner, if the state
5241 * changes sooner). */
5242 global_state->next_write = now + STATE_WRITE_RETRY_INTERVAL;
5246 last_state_file_write_failed = 0;
5247 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
5251 if (server_mode(get_options()))
5252 global_state->next_write = now + STATE_RELAY_CHECKPOINT_INTERVAL;
5254 global_state->next_write = TIME_MAX;
5259 /** Given a file name check to see whether the file exists but has not been
5260 * modified for a very long time. If so, remove it. */
5262 remove_file_if_very_old(const char *fname, time_t now)
5264 #define VERY_OLD_FILE_AGE (28*24*60*60)
5267 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
5268 char buf[ISO_TIME_LEN+1];
5269 format_local_iso_time(buf, st.st_mtime);
5270 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
5271 "Removing it.", fname, buf);
5276 /** Helper to implement GETINFO functions about configuration variables (not
5277 * their values). Given a "config/names" question, set *<b>answer</b> to a
5278 * new string describing the supported configuration variables and their
5281 getinfo_helper_config(control_connection_t *conn,
5282 const char *question, char **answer,
5283 const char **errmsg)
5287 if (!strcmp(question, "config/names")) {
5288 smartlist_t *sl = smartlist_create();
5290 for (i = 0; _option_vars[i].name; ++i) {
5291 config_var_t *var = &_option_vars[i];
5294 switch (var->type) {
5295 case CONFIG_TYPE_STRING: type = "String"; break;
5296 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
5297 case CONFIG_TYPE_UINT: type = "Integer"; break;
5298 case CONFIG_TYPE_PORT: type = "Port"; break;
5299 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
5300 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
5301 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
5302 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
5303 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
5304 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
5305 case CONFIG_TYPE_CSV: type = "CommaList"; break;
5306 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
5307 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
5308 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
5310 case CONFIG_TYPE_OBSOLETE:
5315 tor_asprintf(&line, "%s %s\n",var->name,type);
5316 smartlist_add(sl, line);
5318 *answer = smartlist_join_strings(sl, "", 0, NULL);
5319 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));