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-2010, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
9 * \brief Code to parse and interpret configuration files.
12 #define CONFIG_PRIVATE
15 #include "circuitbuild.h"
16 #include "circuitlist.h"
18 #include "connection.h"
19 #include "connection_edge.h"
20 #include "connection_or.h"
22 #include "cpuworker.h"
27 #include "hibernate.h"
29 #include "networkstatus.h"
32 #include "rendclient.h"
33 #include "rendservice.h"
36 #include "routerlist.h"
41 /** Enumeration of types which option values can take */
42 typedef enum config_type_t
{
43 CONFIG_TYPE_STRING
= 0, /**< An arbitrary string. */
44 CONFIG_TYPE_FILENAME
, /**< A filename: some prefixes get expanded. */
45 CONFIG_TYPE_UINT
, /**< A non-negative integer less than MAX_INT */
46 CONFIG_TYPE_INTERVAL
, /**< A number of seconds, with optional units*/
47 CONFIG_TYPE_MEMUNIT
, /**< A number of bytes, with optional units*/
48 CONFIG_TYPE_DOUBLE
, /**< A floating-point value */
49 CONFIG_TYPE_BOOL
, /**< A boolean value, expressed as 0 or 1. */
50 CONFIG_TYPE_ISOTIME
, /**< An ISO-formatted time relative to GMT. */
51 CONFIG_TYPE_CSV
, /**< A list of strings, separated by commas and
52 * optional whitespace. */
53 CONFIG_TYPE_LINELIST
, /**< Uninterpreted config lines */
54 CONFIG_TYPE_LINELIST_S
, /**< Uninterpreted, context-sensitive config lines,
55 * mixed with other keywords. */
56 CONFIG_TYPE_LINELIST_V
, /**< Catch-all "virtual" option to summarize
57 * context-sensitive config lines when fetching.
59 CONFIG_TYPE_ROUTERSET
, /**< A list of router names, addrs, and fps,
60 * parsed into a routerset_t. */
61 CONFIG_TYPE_OBSOLETE
, /**< Obsolete (ignored) option. */
64 /** An abbreviation for a configuration option allowed on the command line. */
65 typedef struct config_abbrev_t
{
66 const char *abbreviated
;
72 /* Handy macro for declaring "In the config file or on the command line,
73 * you can abbreviate <b>tok</b>s as <b>tok</b>". */
74 #define PLURAL(tok) { #tok, #tok "s", 0, 0 }
76 /** A list of abbreviations and aliases to map command-line options, obsolete
77 * option names, or alternative option names, to their current values. */
78 static config_abbrev_t _option_abbrevs
[] = {
83 PLURAL(LongLivedPort
),
84 PLURAL(HiddenServiceNode
),
85 PLURAL(HiddenServiceExcludeNode
),
88 PLURAL(RendExcludeNode
),
89 PLURAL(StrictEntryNode
),
90 PLURAL(StrictExitNode
),
93 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
94 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
95 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
96 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
97 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
98 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
99 { "MaxConn", "ConnLimit", 0, 1},
100 { "ORBindAddress", "ORListenAddress", 0, 0},
101 { "DirBindAddress", "DirListenAddress", 0, 0},
102 { "SocksBindAddress", "SocksListenAddress", 0, 0},
103 { "UseHelperNodes", "UseEntryGuards", 0, 0},
104 { "NumHelperNodes", "NumEntryGuards", 0, 0},
105 { "UseEntryNodes", "UseEntryGuards", 0, 0},
106 { "NumEntryNodes", "NumEntryGuards", 0, 0},
107 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
108 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
109 { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0},
110 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
111 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
112 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
113 { "StrictEntryNodes", "StrictNodes", 0, 1},
114 { "StrictExitNodes", "StrictNodes", 0, 1},
118 /** A list of state-file "abbreviations," for compatibility. */
119 static config_abbrev_t _state_abbrevs
[] = {
120 { "AccountingBytesReadInterval", "AccountingBytesReadInInterval", 0, 0 },
121 { "HelperNode", "EntryGuard", 0, 0 },
122 { "HelperNodeDownSince", "EntryGuardDownSince", 0, 0 },
123 { "HelperNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
124 { "EntryNode", "EntryGuard", 0, 0 },
125 { "EntryNodeDownSince", "EntryGuardDownSince", 0, 0 },
126 { "EntryNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
131 /** A variable allowed in the configuration file or on the command line. */
132 typedef struct config_var_t
{
133 const char *name
; /**< The full keyword (case insensitive). */
134 config_type_t type
; /**< How to interpret the type and turn it into a
136 off_t var_offset
; /**< Offset of the corresponding member of or_options_t. */
137 const char *initvalue
; /**< String (or null) describing initial value. */
140 /** An entry for config_vars: "The option <b>name</b> has type
141 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
142 * or_options_t.<b>member</b>"
144 #define VAR(name,conftype,member,initvalue) \
145 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
147 /** As VAR, but the option name and member name are the same. */
148 #define V(member,conftype,initvalue) \
149 VAR(#member, conftype, member, initvalue)
150 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
151 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
153 /** Array of configuration options. Until we disallow nonstandard
154 * abbreviations, order is significant, since the first matching option will
157 static config_var_t _option_vars
[] = {
158 OBSOLETE("AccountingMaxKB"),
159 V(AccountingMax
, MEMUNIT
, "0 bytes"),
160 V(AccountingStart
, STRING
, NULL
),
161 V(Address
, STRING
, NULL
),
162 V(AllowDotExit
, BOOL
, "0"),
163 V(AllowInvalidNodes
, CSV
, "middle,rendezvous"),
164 V(AllowNonRFC953Hostnames
, BOOL
, "0"),
165 V(AllowSingleHopCircuits
, BOOL
, "0"),
166 V(AllowSingleHopExits
, BOOL
, "0"),
167 V(AlternateBridgeAuthority
, LINELIST
, NULL
),
168 V(AlternateDirAuthority
, LINELIST
, NULL
),
169 V(AlternateHSAuthority
, LINELIST
, NULL
),
170 V(AssumeReachable
, BOOL
, "0"),
171 V(AuthDirBadDir
, LINELIST
, NULL
),
172 V(AuthDirBadExit
, LINELIST
, NULL
),
173 V(AuthDirInvalid
, LINELIST
, NULL
),
174 V(AuthDirReject
, LINELIST
, NULL
),
175 V(AuthDirRejectUnlisted
, BOOL
, "0"),
176 V(AuthDirListBadDirs
, BOOL
, "0"),
177 V(AuthDirListBadExits
, BOOL
, "0"),
178 V(AuthDirMaxServersPerAddr
, UINT
, "2"),
179 V(AuthDirMaxServersPerAuthAddr
,UINT
, "5"),
180 VAR("AuthoritativeDirectory", BOOL
, AuthoritativeDir
, "0"),
181 V(AutomapHostsOnResolve
, BOOL
, "0"),
182 V(AutomapHostsSuffixes
, CSV
, ".onion,.exit"),
183 V(AvoidDiskWrites
, BOOL
, "0"),
184 V(BandwidthBurst
, MEMUNIT
, "10 MB"),
185 V(BandwidthRate
, MEMUNIT
, "5 MB"),
186 V(BridgeAuthoritativeDir
, BOOL
, "0"),
187 VAR("Bridge", LINELIST
, Bridges
, NULL
),
188 V(BridgePassword
, STRING
, NULL
),
189 V(BridgeRecordUsageByCountry
, BOOL
, "1"),
190 V(BridgeRelay
, BOOL
, "0"),
191 V(CellStatistics
, BOOL
, "0"),
192 V(LearnCircuitBuildTimeout
, BOOL
, "1"),
193 V(CircuitBuildTimeout
, INTERVAL
, "0"),
194 V(CircuitIdleTimeout
, INTERVAL
, "1 hour"),
195 V(CircuitStreamTimeout
, INTERVAL
, "0"),
196 V(CircuitPriorityHalflife
, DOUBLE
, "-100.0"), /*negative:'Use default'*/
197 V(ClientDNSRejectInternalAddresses
, BOOL
,"1"),
198 V(ClientOnly
, BOOL
, "0"),
199 V(ConsensusParams
, STRING
, NULL
),
200 V(ConnLimit
, UINT
, "1000"),
201 V(ConstrainedSockets
, BOOL
, "0"),
202 V(ConstrainedSockSize
, MEMUNIT
, "8192"),
203 V(ContactInfo
, STRING
, NULL
),
204 V(ControlListenAddress
, LINELIST
, NULL
),
205 V(ControlPort
, UINT
, "0"),
206 V(ControlSocket
, LINELIST
, NULL
),
207 V(CookieAuthentication
, BOOL
, "0"),
208 V(CookieAuthFileGroupReadable
, BOOL
, "0"),
209 V(CookieAuthFile
, STRING
, NULL
),
210 V(DataDirectory
, FILENAME
, NULL
),
211 OBSOLETE("DebugLogFile"),
212 V(DirAllowPrivateAddresses
, BOOL
, NULL
),
213 V(TestingAuthDirTimeToLearnReachability
, INTERVAL
, "30 minutes"),
214 V(DirListenAddress
, LINELIST
, NULL
),
215 OBSOLETE("DirFetchPeriod"),
216 V(DirPolicy
, LINELIST
, NULL
),
217 V(DirPort
, UINT
, "0"),
218 V(DirPortFrontPage
, FILENAME
, NULL
),
219 OBSOLETE("DirPostPeriod"),
220 OBSOLETE("DirRecordUsageByCountry"),
221 OBSOLETE("DirRecordUsageGranularity"),
222 OBSOLETE("DirRecordUsageRetainIPs"),
223 OBSOLETE("DirRecordUsageSaveInterval"),
224 V(DirReqStatistics
, BOOL
, "0"),
225 VAR("DirServer", LINELIST
, DirServers
, NULL
),
226 V(DisableAllSwap
, BOOL
, "0"),
227 V(DNSPort
, UINT
, "0"),
228 V(DNSListenAddress
, LINELIST
, NULL
),
229 V(DownloadExtraInfo
, BOOL
, "0"),
230 V(EnforceDistinctSubnets
, BOOL
, "1"),
231 V(EntryNodes
, ROUTERSET
, NULL
),
232 V(EntryStatistics
, BOOL
, "0"),
233 V(TestingEstimatedDescriptorPropagationTime
, INTERVAL
, "10 minutes"),
234 V(ExcludeNodes
, ROUTERSET
, NULL
),
235 V(ExcludeExitNodes
, ROUTERSET
, NULL
),
236 V(ExcludeSingleHopRelays
, BOOL
, "1"),
237 V(ExitNodes
, ROUTERSET
, NULL
),
238 V(ExitPolicy
, LINELIST
, NULL
),
239 V(ExitPolicyRejectPrivate
, BOOL
, "1"),
240 V(ExitPortStatistics
, BOOL
, "0"),
241 V(ExtraInfoStatistics
, BOOL
, "0"),
244 V(FallbackNetworkstatusFile
, FILENAME
, "fallback-consensus"),
246 V(FallbackNetworkstatusFile
, FILENAME
,
247 SHARE_DATADIR PATH_SEPARATOR
"tor" PATH_SEPARATOR
"fallback-consensus"),
249 V(FascistFirewall
, BOOL
, "0"),
250 V(FirewallPorts
, CSV
, ""),
251 V(FastFirstHopPK
, BOOL
, "1"),
252 V(FetchDirInfoEarly
, BOOL
, "0"),
253 V(FetchDirInfoExtraEarly
, BOOL
, "0"),
254 V(FetchServerDescriptors
, BOOL
, "1"),
255 V(FetchHidServDescriptors
, BOOL
, "1"),
256 V(FetchUselessDescriptors
, BOOL
, "0"),
258 V(GeoIPFile
, FILENAME
, "<default>"),
260 V(GeoIPFile
, FILENAME
,
261 SHARE_DATADIR PATH_SEPARATOR
"tor" PATH_SEPARATOR
"geoip"),
264 V(HardwareAccel
, BOOL
, "0"),
265 V(AccelName
, STRING
, NULL
),
266 V(AccelDir
, FILENAME
, NULL
),
267 V(HashedControlPassword
, LINELIST
, NULL
),
268 V(HidServDirectoryV2
, BOOL
, "1"),
269 VAR("HiddenServiceDir", LINELIST_S
, RendConfigLines
, NULL
),
270 OBSOLETE("HiddenServiceExcludeNodes"),
271 OBSOLETE("HiddenServiceNodes"),
272 VAR("HiddenServiceOptions",LINELIST_V
, RendConfigLines
, NULL
),
273 VAR("HiddenServicePort", LINELIST_S
, RendConfigLines
, NULL
),
274 VAR("HiddenServiceVersion",LINELIST_S
, RendConfigLines
, NULL
),
275 VAR("HiddenServiceAuthorizeClient",LINELIST_S
,RendConfigLines
, NULL
),
276 V(HidServAuth
, LINELIST
, NULL
),
277 V(HSAuthoritativeDir
, BOOL
, "0"),
278 OBSOLETE("HSAuthorityRecordStats"),
279 V(HttpProxy
, STRING
, NULL
),
280 V(HttpProxyAuthenticator
, STRING
, NULL
),
281 V(HttpsProxy
, STRING
, NULL
),
282 V(HttpsProxyAuthenticator
, STRING
, NULL
),
283 V(Socks4Proxy
, STRING
, NULL
),
284 V(Socks5Proxy
, STRING
, NULL
),
285 V(Socks5ProxyUsername
, STRING
, NULL
),
286 V(Socks5ProxyPassword
, STRING
, NULL
),
287 OBSOLETE("IgnoreVersion"),
288 V(KeepalivePeriod
, INTERVAL
, "5 minutes"),
289 VAR("Log", LINELIST
, Logs
, NULL
),
290 OBSOLETE("LinkPadding"),
291 OBSOLETE("LogLevel"),
293 V(LongLivedPorts
, CSV
,
294 "21,22,706,1863,5050,5190,5222,5223,6667,6697,8300"),
295 VAR("MapAddress", LINELIST
, AddressMap
, NULL
),
296 V(MaxAdvertisedBandwidth
, MEMUNIT
, "1 GB"),
297 V(MaxCircuitDirtiness
, INTERVAL
, "10 minutes"),
298 V(MaxOnionsPending
, UINT
, "100"),
299 OBSOLETE("MonthlyAccountingStart"),
300 V(MyFamily
, STRING
, NULL
),
301 V(NewCircuitPeriod
, INTERVAL
, "30 seconds"),
302 VAR("NamingAuthoritativeDirectory",BOOL
, NamingAuthoritativeDir
, "0"),
303 V(NatdListenAddress
, LINELIST
, NULL
),
304 V(NatdPort
, UINT
, "0"),
305 V(Nickname
, STRING
, NULL
),
306 V(WarnUnsafeSocks
, BOOL
, "1"),
307 V(NoPublish
, BOOL
, "0"),
308 VAR("NodeFamily", LINELIST
, NodeFamilies
, NULL
),
309 V(NumCpus
, UINT
, "1"),
310 V(NumEntryGuards
, UINT
, "3"),
311 V(ORListenAddress
, LINELIST
, NULL
),
312 V(ORPort
, UINT
, "0"),
313 V(OutboundBindAddress
, STRING
, NULL
),
314 OBSOLETE("PathlenCoinWeight"),
315 V(PerConnBWBurst
, MEMUNIT
, "0"),
316 V(PerConnBWRate
, MEMUNIT
, "0"),
317 V(PidFile
, STRING
, NULL
),
318 V(TestingTorNetwork
, BOOL
, "0"),
319 V(PreferTunneledDirConns
, BOOL
, "1"),
320 V(ProtocolWarnings
, BOOL
, "0"),
321 V(PublishServerDescriptor
, CSV
, "1"),
322 V(PublishHidServDescriptors
, BOOL
, "1"),
323 V(ReachableAddresses
, LINELIST
, NULL
),
324 V(ReachableDirAddresses
, LINELIST
, NULL
),
325 V(ReachableORAddresses
, LINELIST
, NULL
),
326 V(RecommendedVersions
, LINELIST
, NULL
),
327 V(RecommendedClientVersions
, LINELIST
, NULL
),
328 V(RecommendedServerVersions
, LINELIST
, NULL
),
329 OBSOLETE("RedirectExit"),
330 V(RefuseUnknownExits
, BOOL
, "0"),
331 V(RejectPlaintextPorts
, CSV
, ""),
332 V(RelayBandwidthBurst
, MEMUNIT
, "0"),
333 V(RelayBandwidthRate
, MEMUNIT
, "0"),
334 OBSOLETE("RendExcludeNodes"),
335 OBSOLETE("RendNodes"),
336 V(RendPostPeriod
, INTERVAL
, "1 hour"),
337 V(RephistTrackTime
, INTERVAL
, "24 hours"),
338 OBSOLETE("RouterFile"),
339 V(RunAsDaemon
, BOOL
, "0"),
340 V(RunTesting
, BOOL
, "0"),
341 V(SafeLogging
, STRING
, "1"),
342 V(SafeSocks
, BOOL
, "0"),
343 V(ServerDNSAllowBrokenConfig
, BOOL
, "1"),
344 V(ServerDNSAllowNonRFC953Hostnames
, BOOL
,"0"),
345 V(ServerDNSDetectHijacking
, BOOL
, "1"),
346 V(ServerDNSRandomizeCase
, BOOL
, "1"),
347 V(ServerDNSResolvConfFile
, STRING
, NULL
),
348 V(ServerDNSSearchDomains
, BOOL
, "0"),
349 V(ServerDNSTestAddresses
, CSV
,
350 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
351 V(ShutdownWaitLength
, INTERVAL
, "30 seconds"),
352 V(SocksListenAddress
, LINELIST
, NULL
),
353 V(SocksPolicy
, LINELIST
, NULL
),
354 V(SocksPort
, UINT
, "9050"),
355 V(SocksTimeout
, INTERVAL
, "2 minutes"),
356 OBSOLETE("StatusFetchPeriod"),
357 V(StrictNodes
, BOOL
, "0"),
359 V(TestSocks
, BOOL
, "0"),
361 V(TrackHostExits
, CSV
, NULL
),
362 V(TrackHostExitsExpire
, INTERVAL
, "30 minutes"),
363 OBSOLETE("TrafficShaping"),
364 V(TransListenAddress
, LINELIST
, NULL
),
365 V(TransPort
, UINT
, "0"),
366 V(TunnelDirConns
, BOOL
, "1"),
367 V(UpdateBridgesFromAuthority
, BOOL
, "0"),
368 V(UseBridges
, BOOL
, "0"),
369 V(UseEntryGuards
, BOOL
, "1"),
370 V(User
, STRING
, NULL
),
371 VAR("V1AuthoritativeDirectory",BOOL
, V1AuthoritativeDir
, "0"),
372 VAR("V2AuthoritativeDirectory",BOOL
, V2AuthoritativeDir
, "0"),
373 VAR("V3AuthoritativeDirectory",BOOL
, V3AuthoritativeDir
, "0"),
374 V(TestingV3AuthInitialVotingInterval
, INTERVAL
, "30 minutes"),
375 V(TestingV3AuthInitialVoteDelay
, INTERVAL
, "5 minutes"),
376 V(TestingV3AuthInitialDistDelay
, INTERVAL
, "5 minutes"),
377 V(V3AuthVotingInterval
, INTERVAL
, "1 hour"),
378 V(V3AuthVoteDelay
, INTERVAL
, "5 minutes"),
379 V(V3AuthDistDelay
, INTERVAL
, "5 minutes"),
380 V(V3AuthNIntervalsValid
, UINT
, "3"),
381 V(V3AuthUseLegacyKey
, BOOL
, "0"),
382 V(V3BandwidthsFile
, FILENAME
, NULL
),
383 VAR("VersioningAuthoritativeDirectory",BOOL
,VersioningAuthoritativeDir
, "0"),
384 V(VirtualAddrNetwork
, STRING
, "127.192.0.0/10"),
385 V(WarnPlaintextPorts
, CSV
, "23,109,110,143"),
386 VAR("__ReloadTorrcOnSIGHUP", BOOL
, ReloadTorrcOnSIGHUP
, "1"),
387 VAR("__AllDirActionsPrivate", BOOL
, AllDirActionsPrivate
, "0"),
388 VAR("__DisablePredictedCircuits",BOOL
,DisablePredictedCircuits
, "0"),
389 VAR("__LeaveStreamsUnattached",BOOL
, LeaveStreamsUnattached
, "0"),
390 VAR("__HashedControlSessionPassword", LINELIST
, HashedControlSessionPassword
,
392 V(MinUptimeHidServDirectoryV2
, INTERVAL
, "24 hours"),
394 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
397 /** Override default values with these if the user sets the TestingTorNetwork
399 static config_var_t testing_tor_network_defaults
[] = {
400 V(ServerDNSAllowBrokenConfig
, BOOL
, "1"),
401 V(DirAllowPrivateAddresses
, BOOL
, "1"),
402 V(EnforceDistinctSubnets
, BOOL
, "0"),
403 V(AssumeReachable
, BOOL
, "1"),
404 V(AuthDirMaxServersPerAddr
, UINT
, "0"),
405 V(AuthDirMaxServersPerAuthAddr
,UINT
, "0"),
406 V(ClientDNSRejectInternalAddresses
, BOOL
,"0"),
407 V(ExitPolicyRejectPrivate
, BOOL
, "0"),
408 V(V3AuthVotingInterval
, INTERVAL
, "5 minutes"),
409 V(V3AuthVoteDelay
, INTERVAL
, "20 seconds"),
410 V(V3AuthDistDelay
, INTERVAL
, "20 seconds"),
411 V(TestingV3AuthInitialVotingInterval
, INTERVAL
, "5 minutes"),
412 V(TestingV3AuthInitialVoteDelay
, INTERVAL
, "20 seconds"),
413 V(TestingV3AuthInitialDistDelay
, INTERVAL
, "20 seconds"),
414 V(TestingAuthDirTimeToLearnReachability
, INTERVAL
, "0 minutes"),
415 V(TestingEstimatedDescriptorPropagationTime
, INTERVAL
, "0 minutes"),
416 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
420 #define VAR(name,conftype,member,initvalue) \
421 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
424 /** Array of "state" variables saved to the ~/.tor/state file. */
425 static config_var_t _state_vars
[] = {
426 V(AccountingBytesReadInInterval
, MEMUNIT
, NULL
),
427 V(AccountingBytesWrittenInInterval
, MEMUNIT
, NULL
),
428 V(AccountingExpectedUsage
, MEMUNIT
, NULL
),
429 V(AccountingIntervalStart
, ISOTIME
, NULL
),
430 V(AccountingSecondsActive
, INTERVAL
, NULL
),
431 V(AccountingSecondsToReachSoftLimit
,INTERVAL
, NULL
),
432 V(AccountingSoftLimitHitAt
, ISOTIME
, NULL
),
433 V(AccountingBytesAtSoftLimit
, MEMUNIT
, NULL
),
435 VAR("EntryGuard", LINELIST_S
, EntryGuards
, NULL
),
436 VAR("EntryGuardDownSince", LINELIST_S
, EntryGuards
, NULL
),
437 VAR("EntryGuardUnlistedSince", LINELIST_S
, EntryGuards
, NULL
),
438 VAR("EntryGuardAddedBy", LINELIST_S
, EntryGuards
, NULL
),
439 V(EntryGuards
, LINELIST_V
, NULL
),
441 V(BWHistoryReadEnds
, ISOTIME
, NULL
),
442 V(BWHistoryReadInterval
, UINT
, "900"),
443 V(BWHistoryReadValues
, CSV
, ""),
444 V(BWHistoryWriteEnds
, ISOTIME
, NULL
),
445 V(BWHistoryWriteInterval
, UINT
, "900"),
446 V(BWHistoryWriteValues
, CSV
, ""),
447 V(BWHistoryDirReadEnds
, ISOTIME
, NULL
),
448 V(BWHistoryDirReadInterval
, UINT
, "900"),
449 V(BWHistoryDirReadValues
, CSV
, ""),
450 V(BWHistoryDirWriteEnds
, ISOTIME
, NULL
),
451 V(BWHistoryDirWriteInterval
, UINT
, "900"),
452 V(BWHistoryDirWriteValues
, CSV
, ""),
454 V(TorVersion
, STRING
, NULL
),
456 V(LastRotatedOnionKey
, ISOTIME
, NULL
),
457 V(LastWritten
, ISOTIME
, NULL
),
459 V(TotalBuildTimes
, UINT
, NULL
),
460 V(CircuitBuildAbandonedCount
, UINT
, "0"),
461 VAR("CircuitBuildTimeBin", LINELIST_S
, BuildtimeHistogram
, NULL
),
462 VAR("BuildtimeHistogram", LINELIST_V
, BuildtimeHistogram
, NULL
),
464 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
471 /** Represents an English description of a configuration variable; used when
472 * generating configuration file comments. */
473 typedef struct config_var_description_t
{
475 const char *description
;
476 } config_var_description_t
;
478 /** Type of a callback to validate whether a given configuration is
479 * well-formed and consistent. See options_trial_assign() for documentation
481 typedef int (*validate_fn_t
)(void*,void*,int,char**);
483 /** Information on the keys, value types, key-to-struct-member mappings,
484 * variable descriptions, validation functions, and abbreviations for a
485 * configuration or storage format. */
487 size_t size
; /**< Size of the struct that everything gets parsed into. */
488 uint32_t magic
; /**< Required 'magic value' to make sure we have a struct
489 * of the right type. */
490 off_t magic_offset
; /**< Offset of the magic value within the struct. */
491 config_abbrev_t
*abbrevs
; /**< List of abbreviations that we expand when
492 * parsing this format. */
493 config_var_t
*vars
; /**< List of variables we recognize, their default
494 * values, and where we stick them in the structure. */
495 validate_fn_t validate_fn
; /**< Function to validate config. */
496 /** If present, extra is a LINELIST variable for unrecognized
497 * lines. Otherwise, unrecognized lines are an error. */
501 /** Macro: assert that <b>cfg</b> has the right magic field for format
503 #define CHECK(fmt, cfg) STMT_BEGIN \
504 tor_assert(fmt && cfg); \
505 tor_assert((fmt)->magic == \
506 *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
510 static char *get_windows_conf_root(void);
512 static void config_line_append(config_line_t
**lst
,
513 const char *key
, const char *val
);
514 static void option_clear(config_format_t
*fmt
, or_options_t
*options
,
516 static void option_reset(config_format_t
*fmt
, or_options_t
*options
,
517 config_var_t
*var
, int use_defaults
);
518 static void config_free(config_format_t
*fmt
, void *options
);
519 static int config_lines_eq(config_line_t
*a
, config_line_t
*b
);
520 static int option_is_same(config_format_t
*fmt
,
521 or_options_t
*o1
, or_options_t
*o2
,
523 static or_options_t
*options_dup(config_format_t
*fmt
, or_options_t
*old
);
524 static int options_validate(or_options_t
*old_options
, or_options_t
*options
,
525 int from_setconf
, char **msg
);
526 static int options_act_reversible(or_options_t
*old_options
, char **msg
);
527 static int options_act(or_options_t
*old_options
);
528 static int options_transition_allowed(or_options_t
*old
, or_options_t
*new,
530 static int options_transition_affects_workers(or_options_t
*old_options
,
531 or_options_t
*new_options
);
532 static int options_transition_affects_descriptor(or_options_t
*old_options
,
533 or_options_t
*new_options
);
534 static int check_nickname_list(const char *lst
, const char *name
, char **msg
);
535 static void config_register_addressmaps(or_options_t
*options
);
537 static int parse_bridge_line(const char *line
, int validate_only
);
538 static int parse_dir_server_line(const char *line
,
539 authority_type_t required_type
,
541 static int validate_data_directory(or_options_t
*options
);
542 static int write_configuration_file(const char *fname
, or_options_t
*options
);
543 static config_line_t
*get_assigned_option(config_format_t
*fmt
,
544 void *options
, const char *key
,
546 static void config_init(config_format_t
*fmt
, void *options
);
547 static int or_state_validate(or_state_t
*old_options
, or_state_t
*options
,
548 int from_setconf
, char **msg
);
549 static int or_state_load(void);
550 static int options_init_logs(or_options_t
*options
, int validate_only
);
552 static int is_listening_on_low_port(uint16_t port_option
,
553 const config_line_t
*listen_options
);
555 static uint64_t config_parse_memunit(const char *s
, int *ok
);
556 static int config_parse_interval(const char *s
, int *ok
);
557 static void init_libevent(void);
558 static int opt_streq(const char *s1
, const char *s2
);
560 /** Magic value for or_options_t. */
561 #define OR_OPTIONS_MAGIC 9090909
563 /** Configuration format for or_options_t. */
564 static config_format_t options_format
= {
565 sizeof(or_options_t
),
567 STRUCT_OFFSET(or_options_t
, _magic
),
570 (validate_fn_t
)options_validate
,
574 /** Magic value for or_state_t. */
575 #define OR_STATE_MAGIC 0x57A73f57
577 /** "Extra" variable in the state that receives lines we can't parse. This
578 * lets us preserve options from versions of Tor newer than us. */
579 static config_var_t state_extra_var
= {
580 "__extra", CONFIG_TYPE_LINELIST
, STRUCT_OFFSET(or_state_t
, ExtraLines
), NULL
583 /** Configuration format for or_state_t. */
584 static config_format_t state_format
= {
587 STRUCT_OFFSET(or_state_t
, _magic
),
590 (validate_fn_t
)or_state_validate
,
595 * Functions to read and write the global options pointer.
598 /** Command-line and config-file options. */
599 static or_options_t
*global_options
= NULL
;
600 /** Name of most recently read torrc file. */
601 static char *torrc_fname
= NULL
;
602 /** Persistent serialized state. */
603 static or_state_t
*global_state
= NULL
;
604 /** Configuration Options set by command line. */
605 static config_line_t
*global_cmdline_options
= NULL
;
606 /** Contents of most recently read DirPortFrontPage file. */
607 static char *global_dirfrontpagecontents
= NULL
;
609 /** Return the contents of our frontpage string, or NULL if not configured. */
611 get_dirportfrontpage(void)
613 return global_dirfrontpagecontents
;
616 /** Allocate an empty configuration object of a given format type. */
618 config_alloc(config_format_t
*fmt
)
620 void *opts
= tor_malloc_zero(fmt
->size
);
621 *(uint32_t*)STRUCT_VAR_P(opts
, fmt
->magic_offset
) = fmt
->magic
;
626 /** Return the currently configured options. */
630 tor_assert(global_options
);
631 return global_options
;
634 /** Change the current global options to contain <b>new_val</b> instead of
635 * their current value; take action based on the new value; free the old value
636 * as necessary. Returns 0 on success, -1 on failure.
639 set_options(or_options_t
*new_val
, char **msg
)
641 or_options_t
*old_options
= global_options
;
642 global_options
= new_val
;
643 /* Note that we pass the *old* options below, for comparison. It
644 * pulls the new options directly out of global_options. */
645 if (options_act_reversible(old_options
, msg
)<0) {
647 global_options
= old_options
;
650 if (options_act(old_options
) < 0) { /* acting on the options failed. die. */
652 "Acting on config options left us in a broken state. Dying.");
656 config_free(&options_format
, old_options
);
661 extern const char tor_git_revision
[]; /* from tor_main.c */
663 /** The version of this Tor process, as parsed. */
664 static char *_version
= NULL
;
666 /** Return the current Tor version. */
670 if (_version
== NULL
) {
671 if (strlen(tor_git_revision
)) {
672 size_t len
= strlen(VERSION
)+strlen(tor_git_revision
)+16;
673 _version
= tor_malloc(len
);
674 tor_snprintf(_version
, len
, "%s (git-%s)", VERSION
, tor_git_revision
);
676 _version
= tor_strdup(VERSION
);
682 /** Release additional memory allocated in options
685 or_options_free(or_options_t
*options
)
690 routerset_free(options
->_ExcludeExitNodesUnion
);
691 config_free(&options_format
, options
);
694 /** Release all memory and resources held by global configuration structures.
697 config_free_all(void)
699 or_options_free(global_options
);
700 global_options
= NULL
;
702 config_free(&state_format
, global_state
);
705 config_free_lines(global_cmdline_options
);
706 global_cmdline_options
= NULL
;
708 tor_free(torrc_fname
);
710 tor_free(global_dirfrontpagecontents
);
713 /** Make <b>address</b> -- a piece of information related to our operation as
714 * a client -- safe to log according to the settings in options->SafeLogging,
717 * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
720 safe_str_client(const char *address
)
723 if (get_options()->_SafeLogging
== SAFELOG_SCRUB_ALL
)
729 /** Make <b>address</b> -- a piece of information of unspecified sensitivity
730 * -- safe to log according to the settings in options->SafeLogging, and
733 * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
737 safe_str(const char *address
)
740 if (get_options()->_SafeLogging
!= SAFELOG_SCRUB_NONE
)
746 /** Equivalent to escaped(safe_str_client(address)). See reentrancy note on
747 * escaped(): don't use this outside the main thread, or twice in the same
750 escaped_safe_str_client(const char *address
)
752 if (get_options()->_SafeLogging
== SAFELOG_SCRUB_ALL
)
755 return escaped(address
);
758 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
759 * escaped(): don't use this outside the main thread, or twice in the same
762 escaped_safe_str(const char *address
)
764 if (get_options()->_SafeLogging
!= SAFELOG_SCRUB_NONE
)
767 return escaped(address
);
770 /** Add the default directory authorities directly into the trusted dir list,
771 * but only add them insofar as they share bits with <b>type</b>. */
773 add_default_trusted_dir_authorities(authority_type_t type
)
776 const char *dirservers
[] = {
777 "moria1 orport=9101 no-v2 "
778 "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
779 "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
780 "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
781 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
782 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
783 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
784 "Tonga orport=443 bridge no-v2 82.94.251.203:80 "
785 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
786 "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
787 "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
788 "gabelmoo orport=8080 no-v2 "
789 "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
790 "80.190.246.100:8180 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
791 "dannenberg orport=443 no-v2 "
792 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
793 "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
794 "urras orport=80 no-v2 v3ident=80550987E1D626E3EBA5E5E75A458DE0626D088C "
795 "208.83.223.34:443 0AD3 FA88 4D18 F89E EA2D 89C0 1937 9E0E 7FD9 4417",
796 "maatuska orport=80 no-v2 "
797 "v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
798 "213.115.239.118:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
801 for (i
=0; dirservers
[i
]; i
++) {
802 if (parse_dir_server_line(dirservers
[i
], type
, 0)<0) {
803 log_err(LD_BUG
, "Couldn't parse internal dirserver line %s",
809 /** Look at all the config options for using alternate directory
810 * authorities, and make sure none of them are broken. Also, warn the
811 * user if we changed any dangerous ones.
814 validate_dir_authorities(or_options_t
*options
, or_options_t
*old_options
)
818 if (options
->DirServers
&&
819 (options
->AlternateDirAuthority
|| options
->AlternateBridgeAuthority
||
820 options
->AlternateHSAuthority
)) {
822 "You cannot set both DirServers and Alternate*Authority.");
826 /* do we want to complain to the user about being partitionable? */
827 if ((options
->DirServers
&&
829 !config_lines_eq(options
->DirServers
, old_options
->DirServers
))) ||
830 (options
->AlternateDirAuthority
&&
832 !config_lines_eq(options
->AlternateDirAuthority
,
833 old_options
->AlternateDirAuthority
)))) {
835 "You have used DirServer or AlternateDirAuthority to "
836 "specify alternate directory authorities in "
837 "your configuration. This is potentially dangerous: it can "
838 "make you look different from all other Tor users, and hurt "
839 "your anonymity. Even if you've specified the same "
840 "authorities as Tor uses by default, the defaults could "
841 "change in the future. Be sure you know what you're doing.");
844 /* Now go through the four ways you can configure an alternate
845 * set of directory authorities, and make sure none are broken. */
846 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
)
847 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
849 for (cl
= options
->AlternateBridgeAuthority
; cl
; cl
= cl
->next
)
850 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
852 for (cl
= options
->AlternateDirAuthority
; cl
; cl
= cl
->next
)
853 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
855 for (cl
= options
->AlternateHSAuthority
; cl
; cl
= cl
->next
)
856 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
861 /** Look at all the config options and assign new dir authorities
865 consider_adding_dir_authorities(or_options_t
*options
,
866 or_options_t
*old_options
)
870 !smartlist_len(router_get_trusted_dir_servers()) || !old_options
||
871 !config_lines_eq(options
->DirServers
, old_options
->DirServers
) ||
872 !config_lines_eq(options
->AlternateBridgeAuthority
,
873 old_options
->AlternateBridgeAuthority
) ||
874 !config_lines_eq(options
->AlternateDirAuthority
,
875 old_options
->AlternateDirAuthority
) ||
876 !config_lines_eq(options
->AlternateHSAuthority
,
877 old_options
->AlternateHSAuthority
);
880 return 0; /* all done */
882 /* Start from a clean slate. */
883 clear_trusted_dir_servers();
885 if (!options
->DirServers
) {
886 /* then we may want some of the defaults */
887 authority_type_t type
= NO_AUTHORITY
;
888 if (!options
->AlternateBridgeAuthority
)
889 type
|= BRIDGE_AUTHORITY
;
890 if (!options
->AlternateDirAuthority
)
891 type
|= V1_AUTHORITY
| V2_AUTHORITY
| V3_AUTHORITY
;
892 if (!options
->AlternateHSAuthority
)
893 type
|= HIDSERV_AUTHORITY
;
894 add_default_trusted_dir_authorities(type
);
897 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
)
898 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
900 for (cl
= options
->AlternateBridgeAuthority
; cl
; cl
= cl
->next
)
901 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
903 for (cl
= options
->AlternateDirAuthority
; cl
; cl
= cl
->next
)
904 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
906 for (cl
= options
->AlternateHSAuthority
; cl
; cl
= cl
->next
)
907 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
912 /** Fetch the active option list, and take actions based on it. All of the
913 * things we do should survive being done repeatedly. If present,
914 * <b>old_options</b> contains the previous value of the options.
916 * Return 0 if all goes well, return -1 if things went badly.
919 options_act_reversible(or_options_t
*old_options
, char **msg
)
921 smartlist_t
*new_listeners
= smartlist_create();
922 smartlist_t
*replaced_listeners
= smartlist_create();
923 static int libevent_initialized
= 0;
924 or_options_t
*options
= get_options();
925 int running_tor
= options
->command
== CMD_RUN_TOR
;
926 int set_conn_limit
= 0;
930 /* Daemonize _first_, since we only want to open most of this stuff in
931 * the subprocess. Libevent bases can't be reliably inherited across
933 if (running_tor
&& options
->RunAsDaemon
) {
934 /* No need to roll back, since you can't change the value. */
938 #ifndef HAVE_SYS_UN_H
939 if (options
->ControlSocket
) {
940 *msg
= tor_strdup("Unix domain sockets (ControlSocket) not supported"
941 " on this OS/with this build.");
947 /* We need to set the connection limit before we can open the listeners. */
948 if (set_max_file_descriptors((unsigned)options
->ConnLimit
,
949 &options
->_ConnLimit
) < 0) {
950 *msg
= tor_strdup("Problem with ConnLimit value. See logs for details.");
955 /* Set up libevent. (We need to do this before we can register the
956 * listeners as listeners.) */
957 if (running_tor
&& !libevent_initialized
) {
959 libevent_initialized
= 1;
962 /* Launch the listeners. (We do this before we setuid, so we can bind to
963 * ports under 1024.) We don't want to rebind if we're hibernating. */
964 if (!we_are_hibernating()) {
965 if (retry_all_listeners(replaced_listeners
, new_listeners
) < 0) {
966 *msg
= tor_strdup("Failed to bind one of the listener ports.");
972 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
973 /* Open /dev/pf before dropping privileges. */
974 if (options
->TransPort
) {
975 if (get_pf_socket() < 0) {
976 *msg
= tor_strdup("Unable to open /dev/pf for transparent proxy.");
982 /* Attempt to lock all current and future memory with mlockall() only once */
983 if (options
->DisableAllSwap
) {
984 if (tor_mlockall() == -1) {
985 *msg
= tor_strdup("DisableAllSwap failure. Do you have proper "
991 /* Setuid/setgid as appropriate */
993 if (switch_id(options
->User
) != 0) {
994 /* No need to roll back, since you can't change the value. */
995 *msg
= tor_strdup("Problem with User value. See logs for details.");
1000 /* Ensure data directory is private; create if possible. */
1001 if (check_private_dir(options
->DataDirectory
,
1002 running_tor
? CPD_CREATE
: CPD_CHECK
)<0) {
1004 "Couldn't access/create private data directory \"%s\"",
1005 options
->DataDirectory
);
1007 /* No need to roll back, since you can't change the value. */
1010 if (directory_caches_v2_dir_info(options
)) {
1011 size_t len
= strlen(options
->DataDirectory
)+32;
1012 char *fn
= tor_malloc(len
);
1013 tor_snprintf(fn
, len
, "%s"PATH_SEPARATOR
"cached-status",
1014 options
->DataDirectory
);
1015 if (check_private_dir(fn
, running_tor
? CPD_CREATE
: CPD_CHECK
) < 0) {
1017 "Couldn't access/create private data directory \"%s\"", fn
);
1024 /* Bail out at this point if we're not going to be a client or server:
1025 * we don't run Tor itself. */
1029 mark_logs_temp(); /* Close current logs once new logs are open. */
1031 if (options_init_logs(options
, 0)<0) { /* Configure the log(s) */
1032 *msg
= tor_strdup("Failed to init Log options. See logs for details.");
1039 log_severity_list_t
*severity
=
1040 tor_malloc_zero(sizeof(log_severity_list_t
));
1042 add_callback_log(severity
, control_event_logmsg
);
1043 control_adjust_event_log_severity();
1046 SMARTLIST_FOREACH(replaced_listeners
, connection_t
*, conn
,
1048 log_notice(LD_NET
, "Closing old %s on %s:%d",
1049 conn_type_to_string(conn
->type
), conn
->address
, conn
->port
);
1050 connection_close_immediate(conn
);
1051 connection_mark_for_close(conn
);
1060 rollback_log_changes();
1061 control_adjust_event_log_severity();
1064 if (set_conn_limit
&& old_options
)
1065 set_max_file_descriptors((unsigned)old_options
->ConnLimit
,
1066 &options
->_ConnLimit
);
1068 SMARTLIST_FOREACH(new_listeners
, connection_t
*, conn
,
1070 log_notice(LD_NET
, "Closing partially-constructed listener %s on %s:%d",
1071 conn_type_to_string(conn
->type
), conn
->address
, conn
->port
);
1072 connection_close_immediate(conn
);
1073 connection_mark_for_close(conn
);
1077 smartlist_free(new_listeners
);
1078 smartlist_free(replaced_listeners
);
1082 /** If we need to have a GEOIP ip-to-country map to run with our configured
1083 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1085 options_need_geoip_info(or_options_t
*options
, const char **reason_out
)
1088 options
->BridgeRelay
&& options
->BridgeRecordUsageByCountry
;
1089 int routerset_usage
=
1090 routerset_needs_geoip(options
->EntryNodes
) ||
1091 routerset_needs_geoip(options
->ExitNodes
) ||
1092 routerset_needs_geoip(options
->ExcludeExitNodes
) ||
1093 routerset_needs_geoip(options
->ExcludeNodes
);
1095 if (routerset_usage
&& reason_out
) {
1096 *reason_out
= "We've been configured to use (or avoid) nodes in certain "
1097 "countries, and we need GEOIP information to figure out which ones they "
1099 } else if (bridge_usage
&& reason_out
) {
1100 *reason_out
= "We've been configured to see which countries can access "
1101 "us as a bridge, and we need GEOIP information to tell which countries "
1104 return bridge_usage
|| routerset_usage
;
1107 /** Return the bandwidthrate that we are going to report to the authorities
1108 * based on the config options. */
1110 get_effective_bwrate(or_options_t
*options
)
1112 uint64_t bw
= options
->BandwidthRate
;
1113 if (bw
> options
->MaxAdvertisedBandwidth
)
1114 bw
= options
->MaxAdvertisedBandwidth
;
1115 if (options
->RelayBandwidthRate
> 0 && bw
> options
->RelayBandwidthRate
)
1116 bw
= options
->RelayBandwidthRate
;
1117 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1118 return (uint32_t)bw
;
1121 /** Return the bandwidthburst that we are going to report to the authorities
1122 * based on the config options. */
1124 get_effective_bwburst(or_options_t
*options
)
1126 uint64_t bw
= options
->BandwidthBurst
;
1127 if (options
->RelayBandwidthBurst
> 0 && bw
> options
->RelayBandwidthBurst
)
1128 bw
= options
->RelayBandwidthBurst
;
1129 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1130 return (uint32_t)bw
;
1133 /** Fetch the active option list, and take actions based on it. All of the
1134 * things we do should survive being done repeatedly. If present,
1135 * <b>old_options</b> contains the previous value of the options.
1137 * Return 0 if all goes well, return -1 if it's time to die.
1139 * Note: We haven't moved all the "act on new configuration" logic
1140 * here yet. Some is still in do_hup() and other places.
1143 options_act(or_options_t
*old_options
)
1146 or_options_t
*options
= get_options();
1147 int running_tor
= options
->command
== CMD_RUN_TOR
;
1150 if (running_tor
&& !have_lockfile()) {
1151 if (try_locking(options
, 1) < 0)
1155 if (consider_adding_dir_authorities(options
, old_options
) < 0)
1158 if (options
->Bridges
) {
1159 clear_bridge_list();
1160 for (cl
= options
->Bridges
; cl
; cl
= cl
->next
) {
1161 if (parse_bridge_line(cl
->value
, 0)<0) {
1163 "Previously validated Bridge line could not be added!");
1169 if (running_tor
&& rend_config_services(options
, 0)<0) {
1171 "Previously validated hidden services line could not be added!");
1175 if (running_tor
&& rend_parse_service_authorization(options
, 0) < 0) {
1176 log_warn(LD_BUG
, "Previously validated client authorization for "
1177 "hidden services could not be added!");
1182 if (! global_state
&& running_tor
) {
1183 if (or_state_load())
1185 rep_hist_load_mtbf_data(time(NULL
));
1188 /* Bail out at this point if we're not going to be a client or server:
1189 * we want to not fork, and to log stuff to stderr. */
1193 /* Finish backgrounding the process */
1194 if (options
->RunAsDaemon
) {
1195 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1196 finish_daemon(options
->DataDirectory
);
1199 /* Write our PID to the PID file. If we do not have write permissions we
1200 * will log a warning */
1201 if (options
->PidFile
)
1202 write_pidfile(options
->PidFile
);
1204 /* Register addressmap directives */
1205 config_register_addressmaps(options
);
1206 parse_virtual_addr_network(options
->VirtualAddrNetwork
, 0, &msg
);
1208 /* Update address policies. */
1209 if (policies_parse_from_options(options
) < 0) {
1210 /* This should be impossible, but let's be sure. */
1211 log_warn(LD_BUG
,"Error parsing already-validated policy options.");
1215 if (init_cookie_authentication(options
->CookieAuthentication
) < 0) {
1216 log_warn(LD_CONFIG
,"Error creating cookie authentication file.");
1220 /* reload keys as needed for rendezvous services. */
1221 if (rend_service_load_keys()<0) {
1222 log_warn(LD_GENERAL
,"Error loading rendezvous service keys");
1226 /* Set up accounting */
1227 if (accounting_parse_options(options
, 0)<0) {
1228 log_warn(LD_CONFIG
,"Error in accounting options");
1231 if (accounting_is_enabled(options
))
1232 configure_accounting(time(NULL
));
1234 /* Change the cell EWMA settings */
1235 cell_ewma_set_scale_factor(options
, networkstatus_get_latest_consensus());
1237 /* Check for transitions that need action. */
1240 if ((options
->UseEntryGuards
&& !old_options
->UseEntryGuards
) ||
1241 (options
->ExcludeNodes
&&
1242 !routerset_equal(old_options
->ExcludeNodes
,options
->ExcludeNodes
)) ||
1243 (options
->ExcludeExitNodes
&&
1244 !routerset_equal(old_options
->ExcludeExitNodes
,
1245 options
->ExcludeExitNodes
)) ||
1246 (options
->EntryNodes
&&
1247 !routerset_equal(old_options
->EntryNodes
, options
->EntryNodes
)) ||
1248 (options
->ExitNodes
&&
1249 !routerset_equal(old_options
->ExitNodes
, options
->ExitNodes
)) ||
1250 options
->StrictNodes
!= old_options
->StrictNodes
) {
1252 "Changed to using entry guards, or changed preferred or "
1253 "excluded node lists. Abandoning previous circuits.");
1254 circuit_mark_all_unused_circs();
1255 circuit_expire_all_dirty_circs();
1258 /* How long should we delay counting bridge stats after becoming a bridge?
1259 * We use this so we don't count people who used our bridge thinking it is
1260 * a relay. If you change this, don't forget to change the log message
1261 * below. It's 4 hours (the time it takes to stop being used by clients)
1262 * plus some extra time for clock skew. */
1263 #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
1265 if (! bool_eq(options
->BridgeRelay
, old_options
->BridgeRelay
)) {
1267 if (options
->BridgeRelay
) {
1268 time_t int_start
= time(NULL
);
1269 if (old_options
->ORPort
== options
->ORPort
) {
1270 int_start
+= RELAY_BRIDGE_STATS_DELAY
;
1273 geoip_bridge_stats_init(int_start
);
1274 log_info(LD_CONFIG
, "We are acting as a bridge now. Starting new "
1275 "GeoIP stats interval%s.", was_relay
? " in 6 "
1276 "hours from now" : "");
1278 geoip_bridge_stats_term();
1279 log_info(LD_GENERAL
, "We are no longer acting as a bridge. "
1280 "Forgetting GeoIP stats.");
1284 if (options_transition_affects_workers(old_options
, options
)) {
1285 log_info(LD_GENERAL
,
1286 "Worker-related options changed. Rotating workers.");
1287 if (server_mode(options
) && !server_mode(old_options
)) {
1288 if (init_keys() < 0) {
1289 log_warn(LD_BUG
,"Error initializing keys; exiting");
1292 ip_address_changed(0);
1293 if (can_complete_circuit
|| !any_predicted_circuits(time(NULL
)))
1294 inform_testing_reachability();
1296 cpuworkers_rotate();
1304 if (options
->V3AuthoritativeDir
&& !old_options
->V3AuthoritativeDir
)
1307 if (options
->PerConnBWRate
!= old_options
->PerConnBWRate
||
1308 options
->PerConnBWBurst
!= old_options
->PerConnBWBurst
)
1309 connection_or_update_token_buckets(get_connection_array(), options
);
1312 /* Maybe load geoip file */
1313 if (options
->GeoIPFile
&&
1314 ((!old_options
|| !opt_streq(old_options
->GeoIPFile
, options
->GeoIPFile
))
1315 || !geoip_is_loaded())) {
1316 /* XXXX Don't use this "<default>" junk; make our filename options
1317 * understand prefixes somehow. -NM */
1318 /* XXXX021 Reload GeoIPFile on SIGHUP. -NM */
1319 char *actual_fname
= tor_strdup(options
->GeoIPFile
);
1321 if (!strcmp(actual_fname
, "<default>")) {
1322 const char *conf_root
= get_windows_conf_root();
1323 size_t len
= strlen(conf_root
)+16;
1324 tor_free(actual_fname
);
1325 actual_fname
= tor_malloc(len
+1);
1326 tor_snprintf(actual_fname
, len
, "%s\\geoip", conf_root
);
1329 geoip_load_file(actual_fname
, options
);
1330 tor_free(actual_fname
);
1333 if (options
->DirReqStatistics
&& !geoip_is_loaded()) {
1334 /* Check if GeoIP database could be loaded. */
1335 log_warn(LD_CONFIG
, "Configured to measure directory request "
1336 "statistics, but no GeoIP database found!");
1340 if (options
->EntryStatistics
) {
1341 if (should_record_bridge_info(options
)) {
1342 /* Don't allow measuring statistics on entry guards when configured
1344 log_warn(LD_CONFIG
, "Bridges cannot be configured to measure "
1345 "additional GeoIP statistics as entry guards.");
1347 } else if (!geoip_is_loaded()) {
1348 /* Check if GeoIP database could be loaded. */
1349 log_warn(LD_CONFIG
, "Configured to measure entry node statistics, "
1350 "but no GeoIP database found!");
1355 if (options
->CellStatistics
|| options
->DirReqStatistics
||
1356 options
->EntryStatistics
|| options
->ExitPortStatistics
) {
1357 time_t now
= time(NULL
);
1358 if ((!old_options
|| !old_options
->CellStatistics
) &&
1359 options
->CellStatistics
)
1360 rep_hist_buffer_stats_init(now
);
1361 if ((!old_options
|| !old_options
->DirReqStatistics
) &&
1362 options
->DirReqStatistics
)
1363 geoip_dirreq_stats_init(now
);
1364 if ((!old_options
|| !old_options
->EntryStatistics
) &&
1365 options
->EntryStatistics
)
1366 geoip_entry_stats_init(now
);
1367 if ((!old_options
|| !old_options
->ExitPortStatistics
) &&
1368 options
->ExitPortStatistics
)
1369 rep_hist_exit_stats_init(now
);
1371 log_notice(LD_CONFIG
, "Configured to measure statistics. Look for "
1372 "the *-stats files that will first be written to the "
1373 "data directory in 24 hours from now.");
1376 if (old_options
&& old_options
->CellStatistics
&&
1377 !options
->CellStatistics
)
1378 rep_hist_buffer_stats_term();
1379 if (old_options
&& old_options
->DirReqStatistics
&&
1380 !options
->DirReqStatistics
)
1381 geoip_dirreq_stats_term();
1382 if (old_options
&& old_options
->EntryStatistics
&&
1383 !options
->EntryStatistics
)
1384 geoip_entry_stats_term();
1385 if (old_options
&& old_options
->ExitPortStatistics
&&
1386 !options
->ExitPortStatistics
)
1387 rep_hist_exit_stats_term();
1389 /* Check if we need to parse and add the EntryNodes config option. */
1390 if (options
->EntryNodes
&&
1392 (!routerset_equal(old_options
->EntryNodes
,options
->EntryNodes
))))
1393 entry_nodes_should_be_added();
1395 /* Since our options changed, we might need to regenerate and upload our
1396 * server descriptor.
1399 options_transition_affects_descriptor(old_options
, options
))
1400 mark_my_descriptor_dirty();
1402 /* We may need to reschedule some directory stuff if our status changed. */
1404 if (authdir_mode_v3(options
) && !authdir_mode_v3(old_options
))
1405 dirvote_recalculate_timing(options
, time(NULL
));
1406 if (!bool_eq(directory_fetches_dir_info_early(options
),
1407 directory_fetches_dir_info_early(old_options
)) ||
1408 !bool_eq(directory_fetches_dir_info_later(options
),
1409 directory_fetches_dir_info_later(old_options
))) {
1410 /* Make sure update_router_have_min_dir_info gets called. */
1411 router_dir_info_changed();
1412 /* We might need to download a new consensus status later or sooner than
1413 * we had expected. */
1414 update_consensus_networkstatus_fetch_time(time(NULL
));
1418 /* Load the webpage we're going to serve every time someone asks for '/' on
1420 tor_free(global_dirfrontpagecontents
);
1421 if (options
->DirPortFrontPage
) {
1422 global_dirfrontpagecontents
=
1423 read_file_to_str(options
->DirPortFrontPage
, 0, NULL
);
1424 if (!global_dirfrontpagecontents
) {
1426 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1427 options
->DirPortFrontPage
);
1435 * Functions to parse config options
1438 /** If <b>option</b> is an official abbreviation for a longer option,
1439 * return the longer option. Otherwise return <b>option</b>.
1440 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1441 * apply abbreviations that work for the config file and the command line.
1442 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1444 expand_abbrev(config_format_t
*fmt
, const char *option
, int command_line
,
1450 for (i
=0; fmt
->abbrevs
[i
].abbreviated
; ++i
) {
1451 /* Abbreviations are case insensitive. */
1452 if (!strcasecmp(option
,fmt
->abbrevs
[i
].abbreviated
) &&
1453 (command_line
|| !fmt
->abbrevs
[i
].commandline_only
)) {
1454 if (warn_obsolete
&& fmt
->abbrevs
[i
].warn
) {
1456 "The configuration option '%s' is deprecated; "
1457 "use '%s' instead.",
1458 fmt
->abbrevs
[i
].abbreviated
,
1459 fmt
->abbrevs
[i
].full
);
1461 /* Keep going through the list in case we want to rewrite it more.
1462 * (We could imagine recursing here, but I don't want to get the
1463 * user into an infinite loop if we craft our list wrong.) */
1464 option
= fmt
->abbrevs
[i
].full
;
1470 /** Helper: Read a list of configuration options from the command line.
1471 * If successful, put them in *<b>result</b> and return 0, and return
1472 * -1 and leave *<b>result</b> alone. */
1474 config_get_commandlines(int argc
, char **argv
, config_line_t
**result
)
1476 config_line_t
*front
= NULL
;
1477 config_line_t
**new = &front
;
1482 if (!strcmp(argv
[i
],"-f") ||
1483 !strcmp(argv
[i
],"--hash-password")) {
1484 i
+= 2; /* command-line option with argument. ignore them. */
1486 } else if (!strcmp(argv
[i
],"--list-fingerprint") ||
1487 !strcmp(argv
[i
],"--verify-config") ||
1488 !strcmp(argv
[i
],"--ignore-missing-torrc") ||
1489 !strcmp(argv
[i
],"--quiet") ||
1490 !strcmp(argv
[i
],"--hush")) {
1491 i
+= 1; /* command-line option. ignore it. */
1493 } else if (!strcmp(argv
[i
],"--nt-service") ||
1494 !strcmp(argv
[i
],"-nt-service")) {
1500 log_warn(LD_CONFIG
,"Command-line option '%s' with no value. Failing.",
1502 config_free_lines(front
);
1506 *new = tor_malloc_zero(sizeof(config_line_t
));
1509 /* Each keyword may be prefixed with one or two dashes. */
1515 (*new)->key
= tor_strdup(expand_abbrev(&options_format
, s
, 1, 1));
1516 (*new)->value
= tor_strdup(argv
[i
+1]);
1517 (*new)->next
= NULL
;
1518 log(LOG_DEBUG
, LD_CONFIG
, "command line: parsed keyword '%s', value '%s'",
1519 (*new)->key
, (*new)->value
);
1521 new = &((*new)->next
);
1528 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1529 * append it to *<b>lst</b>. */
1531 config_line_append(config_line_t
**lst
,
1535 config_line_t
*newline
;
1537 newline
= tor_malloc(sizeof(config_line_t
));
1538 newline
->key
= tor_strdup(key
);
1539 newline
->value
= tor_strdup(val
);
1540 newline
->next
= NULL
;
1542 lst
= &((*lst
)->next
);
1547 /** Helper: parse the config string and strdup into key/value
1548 * strings. Set *result to the list, or NULL if parsing the string
1549 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1550 * misformatted lines. */
1552 config_get_lines(const char *string
, config_line_t
**result
)
1554 config_line_t
*list
= NULL
, **next
;
1560 string
= parse_config_line_from_str(string
, &k
, &v
);
1562 config_free_lines(list
);
1568 /* This list can get long, so we keep a pointer to the end of it
1569 * rather than using config_line_append over and over and getting
1570 * n^2 performance. */
1571 *next
= tor_malloc(sizeof(config_line_t
));
1574 (*next
)->next
= NULL
;
1575 next
= &((*next
)->next
);
1587 * Free all the configuration lines on the linked list <b>front</b>.
1590 config_free_lines(config_line_t
*front
)
1599 tor_free(tmp
->value
);
1604 /** If <b>key</b> is a configuration option, return the corresponding
1605 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1606 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1608 static config_var_t
*
1609 config_find_option(config_format_t
*fmt
, const char *key
)
1612 size_t keylen
= strlen(key
);
1614 return NULL
; /* if they say "--" on the command line, it's not an option */
1615 /* First, check for an exact (case-insensitive) match */
1616 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
1617 if (!strcasecmp(key
, fmt
->vars
[i
].name
)) {
1618 return &fmt
->vars
[i
];
1621 /* If none, check for an abbreviated match */
1622 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
1623 if (!strncasecmp(key
, fmt
->vars
[i
].name
, keylen
)) {
1624 log_warn(LD_CONFIG
, "The abbreviation '%s' is deprecated. "
1625 "Please use '%s' instead",
1626 key
, fmt
->vars
[i
].name
);
1627 return &fmt
->vars
[i
];
1630 /* Okay, unrecognized option */
1634 /** Return the number of option entries in <b>fmt</b>. */
1636 config_count_options(config_format_t
*fmt
)
1639 for (i
=0; fmt
->vars
[i
].name
; ++i
)
1645 * Functions to assign config options.
1648 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1649 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1651 * Called from config_assign_line() and option_reset().
1654 config_assign_value(config_format_t
*fmt
, or_options_t
*options
,
1655 config_line_t
*c
, char **msg
)
1661 CHECK(fmt
, options
);
1663 var
= config_find_option(fmt
, c
->key
);
1666 lvalue
= STRUCT_VAR_P(options
, var
->var_offset
);
1668 switch (var
->type
) {
1670 case CONFIG_TYPE_UINT
:
1671 i
= (int)tor_parse_long(c
->value
, 10, 0, INT_MAX
, &ok
, NULL
);
1674 "Int keyword '%s %s' is malformed or out of bounds.",
1681 case CONFIG_TYPE_INTERVAL
: {
1682 i
= config_parse_interval(c
->value
, &ok
);
1685 "Interval '%s %s' is malformed or out of bounds.",
1693 case CONFIG_TYPE_MEMUNIT
: {
1694 uint64_t u64
= config_parse_memunit(c
->value
, &ok
);
1697 "Value '%s %s' is malformed or out of bounds.",
1701 *(uint64_t *)lvalue
= u64
;
1705 case CONFIG_TYPE_BOOL
:
1706 i
= (int)tor_parse_long(c
->value
, 10, 0, 1, &ok
, NULL
);
1709 "Boolean '%s %s' expects 0 or 1.",
1716 case CONFIG_TYPE_STRING
:
1717 case CONFIG_TYPE_FILENAME
:
1718 tor_free(*(char **)lvalue
);
1719 *(char **)lvalue
= tor_strdup(c
->value
);
1722 case CONFIG_TYPE_DOUBLE
:
1723 *(double *)lvalue
= atof(c
->value
);
1726 case CONFIG_TYPE_ISOTIME
:
1727 if (parse_iso_time(c
->value
, (time_t *)lvalue
)) {
1729 "Invalid time '%s' for keyword '%s'", c
->value
, c
->key
);
1734 case CONFIG_TYPE_ROUTERSET
:
1735 if (*(routerset_t
**)lvalue
) {
1736 routerset_free(*(routerset_t
**)lvalue
);
1738 *(routerset_t
**)lvalue
= routerset_new();
1739 if (routerset_parse(*(routerset_t
**)lvalue
, c
->value
, c
->key
)<0) {
1740 tor_asprintf(msg
, "Invalid exit list '%s' for option '%s'",
1746 case CONFIG_TYPE_CSV
:
1747 if (*(smartlist_t
**)lvalue
) {
1748 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
1749 smartlist_clear(*(smartlist_t
**)lvalue
);
1751 *(smartlist_t
**)lvalue
= smartlist_create();
1754 smartlist_split_string(*(smartlist_t
**)lvalue
, c
->value
, ",",
1755 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1758 case CONFIG_TYPE_LINELIST
:
1759 case CONFIG_TYPE_LINELIST_S
:
1760 config_line_append((config_line_t
**)lvalue
, c
->key
, c
->value
);
1762 case CONFIG_TYPE_OBSOLETE
:
1763 log_warn(LD_CONFIG
, "Skipping obsolete configuration option '%s'", c
->key
);
1765 case CONFIG_TYPE_LINELIST_V
:
1767 "You may not provide a value for virtual option '%s'", c
->key
);
1776 /** If <b>c</b> is a syntactically valid configuration line, update
1777 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1778 * key, -2 for bad value.
1780 * If <b>clear_first</b> is set, clear the value first. Then if
1781 * <b>use_defaults</b> is set, set the value to the default.
1783 * Called from config_assign().
1786 config_assign_line(config_format_t
*fmt
, or_options_t
*options
,
1787 config_line_t
*c
, int use_defaults
,
1788 int clear_first
, bitarray_t
*options_seen
, char **msg
)
1792 CHECK(fmt
, options
);
1794 var
= config_find_option(fmt
, c
->key
);
1797 void *lvalue
= STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
1799 "Found unrecognized option '%s'; saving it.", c
->key
);
1800 config_line_append((config_line_t
**)lvalue
, c
->key
, c
->value
);
1804 "Unknown option '%s'. Failing.", c
->key
);
1809 /* Put keyword into canonical case. */
1810 if (strcmp(var
->name
, c
->key
)) {
1812 c
->key
= tor_strdup(var
->name
);
1815 if (!strlen(c
->value
)) {
1816 /* reset or clear it, then return */
1818 if (var
->type
== CONFIG_TYPE_LINELIST
||
1819 var
->type
== CONFIG_TYPE_LINELIST_S
) {
1820 /* We got an empty linelist from the torrc or command line.
1821 As a special case, call this an error. Warn and ignore. */
1823 "Linelist option '%s' has no value. Skipping.", c
->key
);
1824 } else { /* not already cleared */
1825 option_reset(fmt
, options
, var
, use_defaults
);
1831 if (options_seen
&& (var
->type
!= CONFIG_TYPE_LINELIST
&&
1832 var
->type
!= CONFIG_TYPE_LINELIST_S
)) {
1833 /* We're tracking which options we've seen, and this option is not
1834 * supposed to occur more than once. */
1835 int var_index
= (int)(var
- fmt
->vars
);
1836 if (bitarray_is_set(options_seen
, var_index
)) {
1837 log_warn(LD_CONFIG
, "Option '%s' used more than once; all but the last "
1838 "value will be ignored.", var
->name
);
1840 bitarray_set(options_seen
, var_index
);
1843 if (config_assign_value(fmt
, options
, c
, msg
) < 0)
1848 /** Restore the option named <b>key</b> in options to its default value.
1849 * Called from config_assign(). */
1851 config_reset_line(config_format_t
*fmt
, or_options_t
*options
,
1852 const char *key
, int use_defaults
)
1856 CHECK(fmt
, options
);
1858 var
= config_find_option(fmt
, key
);
1860 return; /* give error on next pass. */
1862 option_reset(fmt
, options
, var
, use_defaults
);
1865 /** Return true iff key is a valid configuration option. */
1867 option_is_recognized(const char *key
)
1869 config_var_t
*var
= config_find_option(&options_format
, key
);
1870 return (var
!= NULL
);
1873 /** Return the canonical name of a configuration option, or NULL
1874 * if no such option exists. */
1876 option_get_canonical_name(const char *key
)
1878 config_var_t
*var
= config_find_option(&options_format
, key
);
1879 return var
? var
->name
: NULL
;
1882 /** Return a canonical list of the options assigned for key.
1885 option_get_assignment(or_options_t
*options
, const char *key
)
1887 return get_assigned_option(&options_format
, options
, key
, 1);
1890 /** Return true iff value needs to be quoted and escaped to be used in
1891 * a configuration file. */
1893 config_value_needs_escape(const char *value
)
1903 /* Note: quotes and backspaces need special handling when we are using
1904 * quotes, not otherwise, so they don't trigger escaping on their
1908 if (!TOR_ISPRINT(*value
))
1916 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1917 static config_line_t
*
1918 config_lines_dup(const config_line_t
*inp
)
1920 config_line_t
*result
= NULL
;
1921 config_line_t
**next_out
= &result
;
1923 *next_out
= tor_malloc(sizeof(config_line_t
));
1924 (*next_out
)->key
= tor_strdup(inp
->key
);
1925 (*next_out
)->value
= tor_strdup(inp
->value
);
1927 next_out
= &((*next_out
)->next
);
1933 /** Return newly allocated line or lines corresponding to <b>key</b> in the
1934 * configuration <b>options</b>. If <b>escape_val</b> is true and a
1935 * value needs to be quoted before it's put in a config file, quote and
1936 * escape that value. Return NULL if no such key exists. */
1937 static config_line_t
*
1938 get_assigned_option(config_format_t
*fmt
, void *options
,
1939 const char *key
, int escape_val
)
1943 config_line_t
*result
;
1944 tor_assert(options
&& key
);
1946 CHECK(fmt
, options
);
1948 var
= config_find_option(fmt
, key
);
1950 log_warn(LD_CONFIG
, "Unknown option '%s'. Failing.", key
);
1953 value
= STRUCT_VAR_P(options
, var
->var_offset
);
1955 result
= tor_malloc_zero(sizeof(config_line_t
));
1956 result
->key
= tor_strdup(var
->name
);
1959 case CONFIG_TYPE_STRING
:
1960 case CONFIG_TYPE_FILENAME
:
1961 if (*(char**)value
) {
1962 result
->value
= tor_strdup(*(char**)value
);
1964 tor_free(result
->key
);
1969 case CONFIG_TYPE_ISOTIME
:
1970 if (*(time_t*)value
) {
1971 result
->value
= tor_malloc(ISO_TIME_LEN
+1);
1972 format_iso_time(result
->value
, *(time_t*)value
);
1974 tor_free(result
->key
);
1977 escape_val
= 0; /* Can't need escape. */
1979 case CONFIG_TYPE_INTERVAL
:
1980 case CONFIG_TYPE_UINT
:
1981 /* This means every or_options_t uint or bool element
1982 * needs to be an int. Not, say, a uint16_t or char. */
1983 tor_asprintf(&result
->value
, "%d", *(int*)value
);
1984 escape_val
= 0; /* Can't need escape. */
1986 case CONFIG_TYPE_MEMUNIT
:
1987 tor_asprintf(&result
->value
, U64_FORMAT
,
1988 U64_PRINTF_ARG(*(uint64_t*)value
));
1989 escape_val
= 0; /* Can't need escape. */
1991 case CONFIG_TYPE_DOUBLE
:
1992 tor_asprintf(&result
->value
, "%f", *(double*)value
);
1993 escape_val
= 0; /* Can't need escape. */
1995 case CONFIG_TYPE_BOOL
:
1996 result
->value
= tor_strdup(*(int*)value
? "1" : "0");
1997 escape_val
= 0; /* Can't need escape. */
1999 case CONFIG_TYPE_ROUTERSET
:
2000 result
->value
= routerset_to_string(*(routerset_t
**)value
);
2002 case CONFIG_TYPE_CSV
:
2003 if (*(smartlist_t
**)value
)
2005 smartlist_join_strings(*(smartlist_t
**)value
, ",", 0, NULL
);
2007 result
->value
= tor_strdup("");
2009 case CONFIG_TYPE_OBSOLETE
:
2010 log_fn(LOG_PROTOCOL_WARN
, LD_CONFIG
,
2011 "You asked me for the value of an obsolete config option '%s'.",
2013 tor_free(result
->key
);
2016 case CONFIG_TYPE_LINELIST_S
:
2018 "Can't return context-sensitive '%s' on its own", key
);
2019 tor_free(result
->key
);
2022 case CONFIG_TYPE_LINELIST
:
2023 case CONFIG_TYPE_LINELIST_V
:
2024 tor_free(result
->key
);
2026 result
= config_lines_dup(*(const config_line_t
**)value
);
2029 tor_free(result
->key
);
2031 log_warn(LD_BUG
,"Unknown type %d for known key '%s'",
2037 config_line_t
*line
;
2038 for (line
= result
; line
; line
= line
->next
) {
2039 if (line
->value
&& config_value_needs_escape(line
->value
)) {
2040 char *newval
= esc_for_log(line
->value
);
2041 tor_free(line
->value
);
2042 line
->value
= newval
;
2050 /** Iterate through the linked list of requested options <b>list</b>.
2051 * For each item, convert as appropriate and assign to <b>options</b>.
2052 * If an item is unrecognized, set *msg and return -1 immediately,
2053 * else return 0 for success.
2055 * If <b>clear_first</b>, interpret config options as replacing (not
2056 * extending) their previous values. If <b>clear_first</b> is set,
2057 * then <b>use_defaults</b> to decide if you set to defaults after
2058 * clearing, or make the value 0 or NULL.
2060 * Here are the use cases:
2061 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
2062 * if linelist, replaces current if csv.
2063 * 2. An empty AllowInvalid line in your torrc. Should clear it.
2064 * 3. "RESETCONF AllowInvalid" sets it to default.
2065 * 4. "SETCONF AllowInvalid" makes it NULL.
2066 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
2068 * Use_defaults Clear_first
2070 * 1 0 undefined, don't use
2071 * 0 1 "set to null first"
2072 * 1 1 "set to defaults first"
2073 * Return 0 on success, -1 on bad key, -2 on bad value.
2075 * As an additional special case, if a LINELIST config option has
2076 * no value and clear_first is 0, then warn and ignore it.
2080 There are three call cases for config_assign() currently.
2082 Case one: Torrc entry
2083 options_init_from_torrc() calls config_assign(0, 0)
2084 calls config_assign_line(0, 0).
2085 if value is empty, calls option_reset(0) and returns.
2086 calls config_assign_value(), appends.
2089 options_trial_assign() calls config_assign(0, 1)
2090 calls config_reset_line(0)
2091 calls option_reset(0)
2092 calls option_clear().
2093 calls config_assign_line(0, 1).
2094 if value is empty, returns.
2095 calls config_assign_value(), appends.
2097 Case three: resetconf
2098 options_trial_assign() calls config_assign(1, 1)
2099 calls config_reset_line(1)
2100 calls option_reset(1)
2101 calls option_clear().
2102 calls config_assign_value(default)
2103 calls config_assign_line(1, 1).
2107 config_assign(config_format_t
*fmt
, void *options
, config_line_t
*list
,
2108 int use_defaults
, int clear_first
, char **msg
)
2111 bitarray_t
*options_seen
;
2112 const int n_options
= config_count_options(fmt
);
2114 CHECK(fmt
, options
);
2116 /* pass 1: normalize keys */
2117 for (p
= list
; p
; p
= p
->next
) {
2118 const char *full
= expand_abbrev(fmt
, p
->key
, 0, 1);
2119 if (strcmp(full
,p
->key
)) {
2121 p
->key
= tor_strdup(full
);
2125 /* pass 2: if we're reading from a resetting source, clear all
2126 * mentioned config options, and maybe set to their defaults. */
2128 for (p
= list
; p
; p
= p
->next
)
2129 config_reset_line(fmt
, options
, p
->key
, use_defaults
);
2132 options_seen
= bitarray_init_zero(n_options
);
2133 /* pass 3: assign. */
2136 if ((r
=config_assign_line(fmt
, options
, list
, use_defaults
,
2137 clear_first
, options_seen
, msg
))) {
2138 bitarray_free(options_seen
);
2143 bitarray_free(options_seen
);
2147 /** Try assigning <b>list</b> to the global options. You do this by duping
2148 * options, assigning list to the new one, then validating it. If it's
2149 * ok, then throw out the old one and stick with the new one. Else,
2150 * revert to old and return failure. Return SETOPT_OK on success, or
2151 * a setopt_err_t on failure.
2153 * If not success, point *<b>msg</b> to a newly allocated string describing
2157 options_trial_assign(config_line_t
*list
, int use_defaults
,
2158 int clear_first
, char **msg
)
2161 or_options_t
*trial_options
= options_dup(&options_format
, get_options());
2163 if ((r
=config_assign(&options_format
, trial_options
,
2164 list
, use_defaults
, clear_first
, msg
)) < 0) {
2165 config_free(&options_format
, trial_options
);
2169 if (options_validate(get_options(), trial_options
, 1, msg
) < 0) {
2170 config_free(&options_format
, trial_options
);
2171 return SETOPT_ERR_PARSE
; /*XXX make this a separate return value. */
2174 if (options_transition_allowed(get_options(), trial_options
, msg
) < 0) {
2175 config_free(&options_format
, trial_options
);
2176 return SETOPT_ERR_TRANSITION
;
2179 if (set_options(trial_options
, msg
)<0) {
2180 config_free(&options_format
, trial_options
);
2181 return SETOPT_ERR_SETTING
;
2184 /* we liked it. put it in place. */
2188 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2189 * Called from option_reset() and config_free(). */
2191 option_clear(config_format_t
*fmt
, or_options_t
*options
, config_var_t
*var
)
2193 void *lvalue
= STRUCT_VAR_P(options
, var
->var_offset
);
2194 (void)fmt
; /* unused */
2195 switch (var
->type
) {
2196 case CONFIG_TYPE_STRING
:
2197 case CONFIG_TYPE_FILENAME
:
2198 tor_free(*(char**)lvalue
);
2200 case CONFIG_TYPE_DOUBLE
:
2201 *(double*)lvalue
= 0.0;
2203 case CONFIG_TYPE_ISOTIME
:
2204 *(time_t*)lvalue
= 0;
2206 case CONFIG_TYPE_INTERVAL
:
2207 case CONFIG_TYPE_UINT
:
2208 case CONFIG_TYPE_BOOL
:
2211 case CONFIG_TYPE_MEMUNIT
:
2212 *(uint64_t*)lvalue
= 0;
2214 case CONFIG_TYPE_ROUTERSET
:
2215 if (*(routerset_t
**)lvalue
) {
2216 routerset_free(*(routerset_t
**)lvalue
);
2217 *(routerset_t
**)lvalue
= NULL
;
2220 case CONFIG_TYPE_CSV
:
2221 if (*(smartlist_t
**)lvalue
) {
2222 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
2223 smartlist_free(*(smartlist_t
**)lvalue
);
2224 *(smartlist_t
**)lvalue
= NULL
;
2227 case CONFIG_TYPE_LINELIST
:
2228 case CONFIG_TYPE_LINELIST_S
:
2229 config_free_lines(*(config_line_t
**)lvalue
);
2230 *(config_line_t
**)lvalue
= NULL
;
2232 case CONFIG_TYPE_LINELIST_V
:
2233 /* handled by linelist_s. */
2235 case CONFIG_TYPE_OBSOLETE
:
2240 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2241 * <b>use_defaults</b>, set it to its default value.
2242 * Called by config_init() and option_reset_line() and option_assign_line(). */
2244 option_reset(config_format_t
*fmt
, or_options_t
*options
,
2245 config_var_t
*var
, int use_defaults
)
2249 CHECK(fmt
, options
);
2250 option_clear(fmt
, options
, var
); /* clear it first */
2252 return; /* all done */
2253 if (var
->initvalue
) {
2254 c
= tor_malloc_zero(sizeof(config_line_t
));
2255 c
->key
= tor_strdup(var
->name
);
2256 c
->value
= tor_strdup(var
->initvalue
);
2257 if (config_assign_value(fmt
, options
, c
, &msg
) < 0) {
2258 log_warn(LD_BUG
, "Failed to assign default: %s", msg
);
2259 tor_free(msg
); /* if this happens it's a bug */
2261 config_free_lines(c
);
2265 /** Print a usage message for tor. */
2270 "Copyright (c) 2001-2004, Roger Dingledine\n"
2271 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2272 "Copyright (c) 2007-2010, The Tor Project, Inc.\n\n"
2273 "tor -f <torrc> [args]\n"
2274 "See man page for options, or https://www.torproject.org/ for "
2275 "documentation.\n");
2278 /** Print all non-obsolete torrc options. */
2280 list_torrc_options(void)
2283 smartlist_t
*lines
= smartlist_create();
2284 for (i
= 0; _option_vars
[i
].name
; ++i
) {
2285 config_var_t
*var
= &_option_vars
[i
];
2286 if (var
->type
== CONFIG_TYPE_OBSOLETE
||
2287 var
->type
== CONFIG_TYPE_LINELIST_V
)
2289 printf("%s\n", var
->name
);
2291 smartlist_free(lines
);
2294 /** Last value actually set by resolve_my_address. */
2295 static uint32_t last_resolved_addr
= 0;
2297 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2298 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2299 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2300 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2301 * public IP address.
2304 resolve_my_address(int warn_severity
, or_options_t
*options
,
2305 uint32_t *addr_out
, char **hostname_out
)
2308 uint32_t addr
; /* host order */
2311 int explicit_hostname
=1;
2312 int from_interface
=0;
2313 char tmpbuf
[INET_NTOA_BUF_LEN
];
2314 const char *address
= options
->Address
;
2315 int notice_severity
= warn_severity
<= LOG_NOTICE
?
2316 LOG_NOTICE
: warn_severity
;
2318 tor_assert(addr_out
);
2320 if (address
&& *address
) {
2321 strlcpy(hostname
, address
, sizeof(hostname
));
2322 } else { /* then we need to guess our address */
2323 explicit_ip
= 0; /* it's implicit */
2324 explicit_hostname
= 0; /* it's implicit */
2326 if (gethostname(hostname
, sizeof(hostname
)) < 0) {
2327 log_fn(warn_severity
, LD_NET
,"Error obtaining local hostname");
2330 log_debug(LD_CONFIG
,"Guessed local host name as '%s'",hostname
);
2333 /* now we know hostname. resolve it and keep only the IP address */
2335 if (tor_inet_aton(hostname
, &in
) == 0) {
2336 /* then we have to resolve it */
2338 if (tor_lookup_hostname(hostname
, &addr
)) { /* failed to resolve */
2339 uint32_t interface_ip
; /* host order */
2341 if (explicit_hostname
) {
2342 log_fn(warn_severity
, LD_CONFIG
,
2343 "Could not resolve local Address '%s'. Failing.", hostname
);
2346 log_fn(notice_severity
, LD_CONFIG
,
2347 "Could not resolve guessed local hostname '%s'. "
2348 "Trying something else.", hostname
);
2349 if (get_interface_address(warn_severity
, &interface_ip
)) {
2350 log_fn(warn_severity
, LD_CONFIG
,
2351 "Could not get local interface IP address. Failing.");
2355 in
.s_addr
= htonl(interface_ip
);
2356 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2357 log_fn(notice_severity
, LD_CONFIG
, "Learned IP address '%s' for "
2358 "local interface. Using that.", tmpbuf
);
2359 strlcpy(hostname
, "<guessed from interfaces>", sizeof(hostname
));
2360 } else { /* resolved hostname into addr */
2361 in
.s_addr
= htonl(addr
);
2363 if (!explicit_hostname
&&
2364 is_internal_IP(ntohl(in
.s_addr
), 0)) {
2365 uint32_t interface_ip
;
2367 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2368 log_fn(notice_severity
, LD_CONFIG
, "Guessed local hostname '%s' "
2369 "resolves to a private IP address (%s). Trying something "
2370 "else.", hostname
, tmpbuf
);
2372 if (get_interface_address(warn_severity
, &interface_ip
)) {
2373 log_fn(warn_severity
, LD_CONFIG
,
2374 "Could not get local interface IP address. Too bad.");
2375 } else if (is_internal_IP(interface_ip
, 0)) {
2377 in2
.s_addr
= htonl(interface_ip
);
2378 tor_inet_ntoa(&in2
,tmpbuf
,sizeof(tmpbuf
));
2379 log_fn(notice_severity
, LD_CONFIG
,
2380 "Interface IP address '%s' is a private address too. "
2381 "Ignoring.", tmpbuf
);
2384 in
.s_addr
= htonl(interface_ip
);
2385 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2386 log_fn(notice_severity
, LD_CONFIG
,
2387 "Learned IP address '%s' for local interface."
2388 " Using that.", tmpbuf
);
2389 strlcpy(hostname
, "<guessed from interfaces>", sizeof(hostname
));
2395 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2396 if (is_internal_IP(ntohl(in
.s_addr
), 0) &&
2397 options
->_PublishServerDescriptor
) {
2398 /* make sure we're ok with publishing an internal IP */
2399 if (!options
->DirServers
&& !options
->AlternateDirAuthority
) {
2400 /* if they are using the default dirservers, disallow internal IPs
2402 log_fn(warn_severity
, LD_CONFIG
,
2403 "Address '%s' resolves to private IP address '%s'. "
2404 "Tor servers that use the default DirServers must have public "
2405 "IP addresses.", hostname
, tmpbuf
);
2409 /* even if they've set their own dirservers, require an explicit IP if
2410 * they're using an internal address. */
2411 log_fn(warn_severity
, LD_CONFIG
, "Address '%s' resolves to private "
2412 "IP address '%s'. Please set the Address config option to be "
2413 "the IP address you want to use.", hostname
, tmpbuf
);
2418 log_debug(LD_CONFIG
, "Resolved Address to '%s'.", tmpbuf
);
2419 *addr_out
= ntohl(in
.s_addr
);
2420 if (last_resolved_addr
&& last_resolved_addr
!= *addr_out
) {
2421 /* Leave this as a notice, regardless of the requested severity,
2422 * at least until dynamic IP address support becomes bulletproof. */
2424 "Your IP address seems to have changed to %s. Updating.",
2426 ip_address_changed(0);
2428 if (last_resolved_addr
!= *addr_out
) {
2430 const char *h
= hostname
;
2432 method
= "CONFIGURED";
2434 } else if (explicit_hostname
) {
2435 method
= "RESOLVED";
2436 } else if (from_interface
) {
2437 method
= "INTERFACE";
2440 method
= "GETHOSTNAME";
2442 control_event_server_status(LOG_NOTICE
,
2443 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2444 tmpbuf
, method
, h
?"HOSTNAME=":"", h
);
2446 last_resolved_addr
= *addr_out
;
2448 *hostname_out
= tor_strdup(hostname
);
2452 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2453 * on a private network.
2456 is_local_addr(const tor_addr_t
*addr
)
2458 if (tor_addr_is_internal(addr
, 0))
2460 /* Check whether ip is on the same /24 as we are. */
2461 if (get_options()->EnforceDistinctSubnets
== 0)
2463 if (tor_addr_family(addr
) == AF_INET
) {
2464 /*XXXX022 IP6 what corresponds to an /24? */
2465 uint32_t ip
= tor_addr_to_ipv4h(addr
);
2467 /* It's possible that this next check will hit before the first time
2468 * resolve_my_address actually succeeds. (For clients, it is likely that
2469 * resolve_my_address will never be called at all). In those cases,
2470 * last_resolved_addr will be 0, and so checking to see whether ip is on
2471 * the same /24 as last_resolved_addr will be the same as checking whether
2472 * it was on net 0, which is already done by is_internal_IP.
2474 if ((last_resolved_addr
& (uint32_t)0xffffff00ul
)
2475 == (ip
& (uint32_t)0xffffff00ul
))
2481 /** Called when we don't have a nickname set. Try to guess a good nickname
2482 * based on the hostname, and return it in a newly allocated string. If we
2483 * can't, return NULL and let the caller warn if it wants to. */
2485 get_default_nickname(void)
2487 static const char * const bad_default_nicknames
[] = {
2491 char localhostname
[256];
2492 char *cp
, *out
, *outp
;
2495 if (gethostname(localhostname
, sizeof(localhostname
)) < 0)
2498 /* Put it in lowercase; stop at the first dot. */
2499 if ((cp
= strchr(localhostname
, '.')))
2501 tor_strlower(localhostname
);
2503 /* Strip invalid characters. */
2505 out
= outp
= tor_malloc(strlen(localhostname
) + 1);
2507 if (strchr(LEGAL_NICKNAME_CHARACTERS
, *cp
))
2514 /* Enforce length. */
2515 if (strlen(out
) > MAX_NICKNAME_LEN
)
2516 out
[MAX_NICKNAME_LEN
]='\0';
2518 /* Check for dumb names. */
2519 for (i
= 0; bad_default_nicknames
[i
]; ++i
) {
2520 if (!strcmp(out
, bad_default_nicknames
[i
])) {
2529 /** Release storage held by <b>options</b>. */
2531 config_free(config_format_t
*fmt
, void *options
)
2540 for (i
=0; fmt
->vars
[i
].name
; ++i
)
2541 option_clear(fmt
, options
, &(fmt
->vars
[i
]));
2543 config_line_t
**linep
= STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
2544 config_free_lines(*linep
);
2550 /** Return true iff a and b contain identical keys and values in identical
2553 config_lines_eq(config_line_t
*a
, config_line_t
*b
)
2556 if (strcasecmp(a
->key
, b
->key
) || strcmp(a
->value
, b
->value
))
2566 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2567 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2570 option_is_same(config_format_t
*fmt
,
2571 or_options_t
*o1
, or_options_t
*o2
, const char *name
)
2573 config_line_t
*c1
, *c2
;
2578 c1
= get_assigned_option(fmt
, o1
, name
, 0);
2579 c2
= get_assigned_option(fmt
, o2
, name
, 0);
2580 r
= config_lines_eq(c1
, c2
);
2581 config_free_lines(c1
);
2582 config_free_lines(c2
);
2586 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2587 static or_options_t
*
2588 options_dup(config_format_t
*fmt
, or_options_t
*old
)
2590 or_options_t
*newopts
;
2592 config_line_t
*line
;
2594 newopts
= config_alloc(fmt
);
2595 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2596 if (fmt
->vars
[i
].type
== CONFIG_TYPE_LINELIST_S
)
2598 if (fmt
->vars
[i
].type
== CONFIG_TYPE_OBSOLETE
)
2600 line
= get_assigned_option(fmt
, old
, fmt
->vars
[i
].name
, 0);
2603 if (config_assign(fmt
, newopts
, line
, 0, 0, &msg
) < 0) {
2604 log_err(LD_BUG
, "Config_get_assigned_option() generated "
2605 "something we couldn't config_assign(): %s", msg
);
2610 config_free_lines(line
);
2615 /** Return a new empty or_options_t. Used for testing. */
2619 return config_alloc(&options_format
);
2622 /** Set <b>options</b> to hold reasonable defaults for most options.
2623 * Each option defaults to zero. */
2625 options_init(or_options_t
*options
)
2627 config_init(&options_format
, options
);
2630 /* Check if the port number given in <b>port_option</b> in combination with
2631 * the specified port in <b>listen_options</b> will result in Tor actually
2632 * opening a low port (meaning a port lower than 1024). Return 1 if
2633 * it is, or 0 if it isn't or the concept of a low port isn't applicable for
2634 * the platform we're on. */
2636 is_listening_on_low_port(uint16_t port_option
,
2637 const config_line_t
*listen_options
)
2641 (void) listen_options
;
2642 return 0; /* No port is too low for windows. */
2644 const config_line_t
*l
;
2646 if (port_option
== 0)
2647 return 0; /* We're not listening */
2648 if (listen_options
== NULL
)
2649 return (port_option
< 1024);
2651 for (l
= listen_options
; l
; l
= l
->next
) {
2652 parse_addr_port(LOG_WARN
, l
->value
, NULL
, NULL
, &p
);
2661 /** Set all vars in the configuration object <b>options</b> to their default
2664 config_init(config_format_t
*fmt
, void *options
)
2668 CHECK(fmt
, options
);
2670 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2671 var
= &fmt
->vars
[i
];
2672 if (!var
->initvalue
)
2673 continue; /* defaults to NULL or 0 */
2674 option_reset(fmt
, options
, var
, 1);
2678 /** Allocate and return a new string holding the written-out values of the vars
2679 * in 'options'. If 'minimal', do not write out any default-valued vars.
2680 * Else, if comment_defaults, write default values as comments.
2683 config_dump(config_format_t
*fmt
, void *options
, int minimal
,
2684 int comment_defaults
)
2686 smartlist_t
*elements
;
2687 or_options_t
*defaults
;
2688 config_line_t
*line
, *assigned
;
2693 defaults
= config_alloc(fmt
);
2694 config_init(fmt
, defaults
);
2696 /* XXX use a 1 here so we don't add a new log line while dumping */
2697 if (fmt
->validate_fn(NULL
,defaults
, 1, &msg
) < 0) {
2698 log_err(LD_BUG
, "Failed to validate default config.");
2703 elements
= smartlist_create();
2704 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2705 int comment_option
= 0;
2706 if (fmt
->vars
[i
].type
== CONFIG_TYPE_OBSOLETE
||
2707 fmt
->vars
[i
].type
== CONFIG_TYPE_LINELIST_S
)
2709 /* Don't save 'hidden' control variables. */
2710 if (!strcmpstart(fmt
->vars
[i
].name
, "__"))
2712 if (minimal
&& option_is_same(fmt
, options
, defaults
, fmt
->vars
[i
].name
))
2714 else if (comment_defaults
&&
2715 option_is_same(fmt
, options
, defaults
, fmt
->vars
[i
].name
))
2718 line
= assigned
= get_assigned_option(fmt
, options
, fmt
->vars
[i
].name
, 1);
2720 for (; line
; line
= line
->next
) {
2722 tor_asprintf(&tmp
, "%s%s %s\n",
2723 comment_option
? "# " : "",
2724 line
->key
, line
->value
);
2725 smartlist_add(elements
, tmp
);
2727 config_free_lines(assigned
);
2731 line
= *(config_line_t
**)STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
2732 for (; line
; line
= line
->next
) {
2734 tor_asprintf(&tmp
, "%s %s\n", line
->key
, line
->value
);
2735 smartlist_add(elements
, tmp
);
2739 result
= smartlist_join_strings(elements
, "", 0, NULL
);
2740 SMARTLIST_FOREACH(elements
, char *, cp
, tor_free(cp
));
2741 smartlist_free(elements
);
2742 config_free(fmt
, defaults
);
2746 /** Return a string containing a possible configuration file that would give
2747 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2748 * include options that are the same as Tor's defaults.
2751 options_dump(or_options_t
*options
, int minimal
)
2753 return config_dump(&options_format
, options
, minimal
, 0);
2756 /** Return 0 if every element of sl is a string holding a decimal
2757 * representation of a port number, or if sl is NULL.
2758 * Otherwise set *msg and return -1. */
2760 validate_ports_csv(smartlist_t
*sl
, const char *name
, char **msg
)
2768 SMARTLIST_FOREACH(sl
, const char *, cp
,
2771 if (i
< 1 || i
> 65535) {
2772 tor_asprintf(msg
, "Port '%s' out of range in %s", cp
, name
);
2779 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2780 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2784 ensure_bandwidth_cap(uint64_t *value
, const char *desc
, char **msg
)
2786 if (*value
> ROUTER_MAX_DECLARED_BANDWIDTH
) {
2787 /* This handles an understandable special case where somebody says "2gb"
2788 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2791 if (*value
> ROUTER_MAX_DECLARED_BANDWIDTH
) {
2792 tor_asprintf(msg
, "%s ("U64_FORMAT
") must be at most %d",
2793 desc
, U64_PRINTF_ARG(*value
),
2794 ROUTER_MAX_DECLARED_BANDWIDTH
);
2800 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2801 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2802 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2804 * Return 0 on success or -1 if not a recognized authority type (in which
2805 * case the value of _PublishServerDescriptor is undefined). */
2807 compute_publishserverdescriptor(or_options_t
*options
)
2809 smartlist_t
*list
= options
->PublishServerDescriptor
;
2810 authority_type_t
*auth
= &options
->_PublishServerDescriptor
;
2811 *auth
= NO_AUTHORITY
;
2812 if (!list
) /* empty list, answer is none */
2814 SMARTLIST_FOREACH(list
, const char *, string
, {
2815 if (!strcasecmp(string
, "v1"))
2816 *auth
|= V1_AUTHORITY
;
2817 else if (!strcmp(string
, "1"))
2818 if (options
->BridgeRelay
)
2819 *auth
|= BRIDGE_AUTHORITY
;
2821 *auth
|= V2_AUTHORITY
| V3_AUTHORITY
;
2822 else if (!strcasecmp(string
, "v2"))
2823 *auth
|= V2_AUTHORITY
;
2824 else if (!strcasecmp(string
, "v3"))
2825 *auth
|= V3_AUTHORITY
;
2826 else if (!strcasecmp(string
, "bridge"))
2827 *auth
|= BRIDGE_AUTHORITY
;
2828 else if (!strcasecmp(string
, "hidserv"))
2829 *auth
|= HIDSERV_AUTHORITY
;
2830 else if (!strcasecmp(string
, "") || !strcmp(string
, "0"))
2838 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2839 * services can overload the directory system. */
2840 #define MIN_REND_POST_PERIOD (10*60)
2842 /** Highest allowable value for RendPostPeriod. */
2843 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2845 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2846 * will generate too many circuits and potentially overload the network. */
2847 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2849 /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
2850 * will generate too many circuits and potentially overload the network. */
2851 #define MIN_CIRCUIT_STREAM_TIMEOUT 10
2853 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2854 * permissible transition from <b>old_options</b>. Else return -1.
2855 * Should have no side effects, except for normalizing the contents of
2858 * On error, tor_strdup an error explanation into *<b>msg</b>.
2861 * If <b>from_setconf</b>, we were called by the controller, and our
2862 * Log line should stay empty. If it's 0, then give us a default log
2863 * if there are no logs defined.
2866 options_validate(or_options_t
*old_options
, or_options_t
*options
,
2867 int from_setconf
, char **msg
)
2871 const char *uname
= get_uname();
2872 #define REJECT(arg) \
2873 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2874 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2879 if (options
->ORPort
< 0 || options
->ORPort
> 65535)
2880 REJECT("ORPort option out of bounds.");
2882 if (server_mode(options
) &&
2883 (!strcmpstart(uname
, "Windows 95") ||
2884 !strcmpstart(uname
, "Windows 98") ||
2885 !strcmpstart(uname
, "Windows Me"))) {
2886 log(LOG_WARN
, LD_CONFIG
, "Tor is running as a server, but you are "
2887 "running %s; this probably won't work. See "
2888 "https://wiki.torproject.org/TheOnionRouter/TorFAQ#ServerOS "
2889 "for details.", uname
);
2892 if (options
->ORPort
== 0 && options
->ORListenAddress
!= NULL
)
2893 REJECT("ORPort must be defined if ORListenAddress is defined.");
2895 if (options
->DirPort
== 0 && options
->DirListenAddress
!= NULL
)
2896 REJECT("DirPort must be defined if DirListenAddress is defined.");
2898 if (options
->DNSPort
== 0 && options
->DNSListenAddress
!= NULL
)
2899 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
2901 if (options
->ControlPort
== 0 && options
->ControlListenAddress
!= NULL
)
2902 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
2904 if (options
->TransPort
== 0 && options
->TransListenAddress
!= NULL
)
2905 REJECT("TransPort must be defined if TransListenAddress is defined.");
2907 if (options
->NatdPort
== 0 && options
->NatdListenAddress
!= NULL
)
2908 REJECT("NatdPort must be defined if NatdListenAddress is defined.");
2910 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
2911 * configuration does this. */
2913 for (i
= 0; i
< 3; ++i
) {
2914 int is_socks
= i
==0;
2915 int is_trans
= i
==1;
2916 config_line_t
*line
, *opt
, *old
;
2919 opt
= options
->SocksListenAddress
;
2920 old
= old_options
? old_options
->SocksListenAddress
: NULL
;
2922 } else if (is_trans
) {
2923 opt
= options
->TransListenAddress
;
2924 old
= old_options
? old_options
->TransListenAddress
: NULL
;
2925 tp
= "transparent proxy";
2927 opt
= options
->NatdListenAddress
;
2928 old
= old_options
? old_options
->NatdListenAddress
: NULL
;
2932 for (line
= opt
; line
; line
= line
->next
) {
2933 char *address
= NULL
;
2936 if (parse_addr_port(LOG_WARN
, line
->value
, &address
, &addr
, &port
)<0)
2937 continue; /* We'll warn about this later. */
2938 if (!is_internal_IP(addr
, 1) &&
2939 (!old_options
|| !config_lines_eq(old
, opt
))) {
2941 "You specified a public address '%s' for a %s. Other "
2942 "people on the Internet might find your computer and use it as "
2943 "an open %s. Please don't allow this unless you have "
2944 "a good reason.", address
, tp
, tp
);
2950 if (validate_data_directory(options
)<0)
2951 REJECT("Invalid DataDirectory");
2953 if (options
->Nickname
== NULL
) {
2954 if (server_mode(options
)) {
2955 if (!(options
->Nickname
= get_default_nickname())) {
2956 log_notice(LD_CONFIG
, "Couldn't pick a nickname based on "
2957 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME
);
2958 options
->Nickname
= tor_strdup(UNNAMED_ROUTER_NICKNAME
);
2960 log_notice(LD_CONFIG
, "Choosing default nickname '%s'",
2965 if (!is_legal_nickname(options
->Nickname
)) {
2967 "Nickname '%s' is wrong length or contains illegal characters.",
2973 if (server_mode(options
) && !options
->ContactInfo
)
2974 log(LOG_NOTICE
, LD_CONFIG
, "Your ContactInfo config option is not set. "
2975 "Please consider setting it, so we can contact you if your server is "
2976 "misconfigured or something else goes wrong.");
2978 /* Special case on first boot if no Log options are given. */
2979 if (!options
->Logs
&& !options
->RunAsDaemon
&& !from_setconf
)
2980 config_line_append(&options
->Logs
, "Log", "notice stdout");
2982 if (options_init_logs(options
, 1)<0) /* Validate the log(s) */
2983 REJECT("Failed to validate Log options. See logs for details.");
2985 if (options
->NoPublish
) {
2986 log(LOG_WARN
, LD_CONFIG
,
2987 "NoPublish is obsolete. Use PublishServerDescriptor instead.");
2988 SMARTLIST_FOREACH(options
->PublishServerDescriptor
, char *, s
,
2990 smartlist_clear(options
->PublishServerDescriptor
);
2993 if (authdir_mode(options
)) {
2994 /* confirm that our address isn't broken, so we can complain now */
2996 if (resolve_my_address(LOG_WARN
, options
, &tmp
, NULL
) < 0)
2997 REJECT("Failed to resolve/guess local address. See logs for details.");
3001 if (options
->RunAsDaemon
&& torrc_fname
&& path_is_relative(torrc_fname
))
3002 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
3005 if (options
->SocksPort
< 0 || options
->SocksPort
> 65535)
3006 REJECT("SocksPort option out of bounds.");
3008 if (options
->DNSPort
< 0 || options
->DNSPort
> 65535)
3009 REJECT("DNSPort option out of bounds.");
3011 if (options
->TransPort
< 0 || options
->TransPort
> 65535)
3012 REJECT("TransPort option out of bounds.");
3014 if (options
->NatdPort
< 0 || options
->NatdPort
> 65535)
3015 REJECT("NatdPort option out of bounds.");
3017 if (options
->SocksPort
== 0 && options
->TransPort
== 0 &&
3018 options
->NatdPort
== 0 && options
->ORPort
== 0 &&
3019 options
->DNSPort
== 0 && !options
->RendConfigLines
)
3020 log(LOG_WARN
, LD_CONFIG
,
3021 "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
3022 "undefined, and there aren't any hidden services configured. "
3023 "Tor will still run, but probably won't do anything.");
3025 if (options
->ControlPort
< 0 || options
->ControlPort
> 65535)
3026 REJECT("ControlPort option out of bounds.");
3028 if (options
->DirPort
< 0 || options
->DirPort
> 65535)
3029 REJECT("DirPort option out of bounds.");
3031 #ifndef USE_TRANSPARENT
3032 if (options
->TransPort
|| options
->TransListenAddress
)
3033 REJECT("TransPort and TransListenAddress are disabled in this build.");
3036 if (options
->AccountingMax
&&
3037 (is_listening_on_low_port(options
->ORPort
, options
->ORListenAddress
) ||
3038 is_listening_on_low_port(options
->DirPort
, options
->DirListenAddress
)))
3040 log(LOG_WARN
, LD_CONFIG
,
3041 "You have set AccountingMax to use hibernation. You have also "
3042 "chosen a low DirPort or OrPort. This combination can make Tor stop "
3043 "working when it tries to re-attach the port after a period of "
3044 "hibernation. Please choose a different port or turn off "
3045 "hibernation unless you know this combination will work on your "
3049 if (options
->ExcludeExitNodes
|| options
->ExcludeNodes
) {
3050 options
->_ExcludeExitNodesUnion
= routerset_new();
3051 routerset_union(options
->_ExcludeExitNodesUnion
,options
->ExcludeExitNodes
);
3052 routerset_union(options
->_ExcludeExitNodesUnion
,options
->ExcludeNodes
);
3055 if (options
->ExcludeNodes
&& options
->StrictNodes
) {
3056 COMPLAIN("You have asked to exclude certain relays from all positions "
3057 "in your circuits. Expect hidden services and other Tor "
3058 "features to be broken in unpredictable ways.");
3061 if (options
->EntryNodes
&& !routerset_is_list(options
->EntryNodes
)) {
3062 /* XXXX fix this; see entry_guards_prepend_from_config(). */
3063 REJECT("IPs or countries are not yet supported in EntryNodes.");
3066 if (options
->AuthoritativeDir
) {
3067 if (!options
->ContactInfo
&& !options
->TestingTorNetwork
)
3068 REJECT("Authoritative directory servers must set ContactInfo");
3069 if (options
->V1AuthoritativeDir
&& !options
->RecommendedVersions
)
3070 REJECT("V1 authoritative dir servers must set RecommendedVersions.");
3071 if (!options
->RecommendedClientVersions
)
3072 options
->RecommendedClientVersions
=
3073 config_lines_dup(options
->RecommendedVersions
);
3074 if (!options
->RecommendedServerVersions
)
3075 options
->RecommendedServerVersions
=
3076 config_lines_dup(options
->RecommendedVersions
);
3077 if (options
->VersioningAuthoritativeDir
&&
3078 (!options
->RecommendedClientVersions
||
3079 !options
->RecommendedServerVersions
))
3080 REJECT("Versioning authoritative dir servers must set "
3081 "Recommended*Versions.");
3082 if (options
->UseEntryGuards
) {
3083 log_info(LD_CONFIG
, "Authoritative directory servers can't set "
3084 "UseEntryGuards. Disabling.");
3085 options
->UseEntryGuards
= 0;
3087 if (!options
->DownloadExtraInfo
&& authdir_mode_any_main(options
)) {
3088 log_info(LD_CONFIG
, "Authoritative directories always try to download "
3089 "extra-info documents. Setting DownloadExtraInfo.");
3090 options
->DownloadExtraInfo
= 1;
3092 if (!(options
->BridgeAuthoritativeDir
|| options
->HSAuthoritativeDir
||
3093 options
->V1AuthoritativeDir
|| options
->V2AuthoritativeDir
||
3094 options
->V3AuthoritativeDir
))
3095 REJECT("AuthoritativeDir is set, but none of "
3096 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
3097 /* If we have a v3bandwidthsfile and it's broken, complain on startup */
3098 if (options
->V3BandwidthsFile
&& !old_options
) {
3099 dirserv_read_measured_bandwidths(options
->V3BandwidthsFile
, NULL
);
3103 if (options
->AuthoritativeDir
&& !options
->DirPort
)
3104 REJECT("Running as authoritative directory, but no DirPort set.");
3106 if (options
->AuthoritativeDir
&& !options
->ORPort
)
3107 REJECT("Running as authoritative directory, but no ORPort set.");
3109 if (options
->AuthoritativeDir
&& options
->ClientOnly
)
3110 REJECT("Running as authoritative directory, but ClientOnly also set.");
3112 if (options
->FetchDirInfoExtraEarly
&& !options
->FetchDirInfoEarly
)
3113 REJECT("FetchDirInfoExtraEarly requires that you also set "
3114 "FetchDirInfoEarly");
3116 if (options
->ConnLimit
<= 0) {
3118 "ConnLimit must be greater than 0, but was set to %d",
3119 options
->ConnLimit
);
3123 if (validate_ports_csv(options
->FirewallPorts
, "FirewallPorts", msg
) < 0)
3126 if (validate_ports_csv(options
->LongLivedPorts
, "LongLivedPorts", msg
) < 0)
3129 if (validate_ports_csv(options
->RejectPlaintextPorts
,
3130 "RejectPlaintextPorts", msg
) < 0)
3133 if (validate_ports_csv(options
->WarnPlaintextPorts
,
3134 "WarnPlaintextPorts", msg
) < 0)
3137 if (options
->FascistFirewall
&& !options
->ReachableAddresses
) {
3138 if (options
->FirewallPorts
&& smartlist_len(options
->FirewallPorts
)) {
3139 /* We already have firewall ports set, so migrate them to
3140 * ReachableAddresses, which will set ReachableORAddresses and
3141 * ReachableDirAddresses if they aren't set explicitly. */
3142 smartlist_t
*instead
= smartlist_create();
3143 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
3144 new_line
->key
= tor_strdup("ReachableAddresses");
3145 /* If we're configured with the old format, we need to prepend some
3147 SMARTLIST_FOREACH(options
->FirewallPorts
, const char *, portno
,
3149 int p
= atoi(portno
);
3153 tor_snprintf(s
, 16, "*:%d", p
);
3154 smartlist_add(instead
, s
);
3156 new_line
->value
= smartlist_join_strings(instead
,",",0,NULL
);
3157 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3158 log(LOG_NOTICE
, LD_CONFIG
,
3159 "Converting FascistFirewall and FirewallPorts "
3160 "config options to new format: \"ReachableAddresses %s\"",
3162 options
->ReachableAddresses
= new_line
;
3163 SMARTLIST_FOREACH(instead
, char *, cp
, tor_free(cp
));
3164 smartlist_free(instead
);
3166 /* We do not have FirewallPorts set, so add 80 to
3167 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3168 if (!options
->ReachableDirAddresses
) {
3169 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
3170 new_line
->key
= tor_strdup("ReachableDirAddresses");
3171 new_line
->value
= tor_strdup("*:80");
3172 options
->ReachableDirAddresses
= new_line
;
3173 log(LOG_NOTICE
, LD_CONFIG
, "Converting FascistFirewall config option "
3174 "to new format: \"ReachableDirAddresses *:80\"");
3176 if (!options
->ReachableORAddresses
) {
3177 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
3178 new_line
->key
= tor_strdup("ReachableORAddresses");
3179 new_line
->value
= tor_strdup("*:443");
3180 options
->ReachableORAddresses
= new_line
;
3181 log(LOG_NOTICE
, LD_CONFIG
, "Converting FascistFirewall config option "
3182 "to new format: \"ReachableORAddresses *:443\"");
3187 for (i
=0; i
<3; i
++) {
3188 config_line_t
**linep
=
3189 (i
==0) ? &options
->ReachableAddresses
:
3190 (i
==1) ? &options
->ReachableORAddresses
:
3191 &options
->ReachableDirAddresses
;
3194 /* We need to end with a reject *:*, not an implicit accept *:* */
3196 if (!strcmp((*linep
)->value
, "reject *:*")) /* already there */
3198 linep
= &((*linep
)->next
);
3200 *linep
= tor_malloc_zero(sizeof(config_line_t
));
3201 (*linep
)->key
= tor_strdup(
3202 (i
==0) ? "ReachableAddresses" :
3203 (i
==1) ? "ReachableORAddresses" :
3204 "ReachableDirAddresses");
3205 (*linep
)->value
= tor_strdup("reject *:*");
3211 if ((options
->ReachableAddresses
||
3212 options
->ReachableORAddresses
||
3213 options
->ReachableDirAddresses
) &&
3214 server_mode(options
))
3215 REJECT("Servers must be able to freely connect to the rest "
3216 "of the Internet, so they must not set Reachable*Addresses "
3217 "or FascistFirewall.");
3219 if (options
->UseBridges
&&
3220 server_mode(options
))
3221 REJECT("Servers must be able to freely connect to the rest "
3222 "of the Internet, so they must not set UseBridges.");
3224 options
->_AllowInvalid
= 0;
3225 if (options
->AllowInvalidNodes
) {
3226 SMARTLIST_FOREACH(options
->AllowInvalidNodes
, const char *, cp
, {
3227 if (!strcasecmp(cp
, "entry"))
3228 options
->_AllowInvalid
|= ALLOW_INVALID_ENTRY
;
3229 else if (!strcasecmp(cp
, "exit"))
3230 options
->_AllowInvalid
|= ALLOW_INVALID_EXIT
;
3231 else if (!strcasecmp(cp
, "middle"))
3232 options
->_AllowInvalid
|= ALLOW_INVALID_MIDDLE
;
3233 else if (!strcasecmp(cp
, "introduction"))
3234 options
->_AllowInvalid
|= ALLOW_INVALID_INTRODUCTION
;
3235 else if (!strcasecmp(cp
, "rendezvous"))
3236 options
->_AllowInvalid
|= ALLOW_INVALID_RENDEZVOUS
;
3239 "Unrecognized value '%s' in AllowInvalidNodes", cp
);
3245 if (!options
->SafeLogging
||
3246 !strcasecmp(options
->SafeLogging
, "0")) {
3247 options
->_SafeLogging
= SAFELOG_SCRUB_NONE
;
3248 } else if (!strcasecmp(options
->SafeLogging
, "relay")) {
3249 options
->_SafeLogging
= SAFELOG_SCRUB_RELAY
;
3250 } else if (!strcasecmp(options
->SafeLogging
, "1")) {
3251 options
->_SafeLogging
= SAFELOG_SCRUB_ALL
;
3254 "Unrecognized value '%s' in SafeLogging",
3255 escaped(options
->SafeLogging
));
3259 if (compute_publishserverdescriptor(options
) < 0) {
3260 tor_asprintf(msg
, "Unrecognized value in PublishServerDescriptor");
3264 if ((options
->BridgeRelay
3265 || options
->_PublishServerDescriptor
& BRIDGE_AUTHORITY
)
3266 && (options
->_PublishServerDescriptor
3267 & (V1_AUTHORITY
|V2_AUTHORITY
|V3_AUTHORITY
))) {
3268 REJECT("Bridges are not supposed to publish router descriptors to the "
3269 "directory authorities. Please correct your "
3270 "PublishServerDescriptor line.");
3273 if (options
->MinUptimeHidServDirectoryV2
< 0) {
3274 log_warn(LD_CONFIG
, "MinUptimeHidServDirectoryV2 option must be at "
3275 "least 0 seconds. Changing to 0.");
3276 options
->MinUptimeHidServDirectoryV2
= 0;
3279 if (options
->RendPostPeriod
< MIN_REND_POST_PERIOD
) {
3280 log_warn(LD_CONFIG
, "RendPostPeriod option is too short; "
3281 "raising to %d seconds.", MIN_REND_POST_PERIOD
);
3282 options
->RendPostPeriod
= MIN_REND_POST_PERIOD
;
3285 if (options
->RendPostPeriod
> MAX_DIR_PERIOD
) {
3286 log_warn(LD_CONFIG
, "RendPostPeriod is too large; clipping to %ds.",
3288 options
->RendPostPeriod
= MAX_DIR_PERIOD
;
3291 if (options
->MaxCircuitDirtiness
< MIN_MAX_CIRCUIT_DIRTINESS
) {
3292 log_warn(LD_CONFIG
, "MaxCircuitDirtiness option is too short; "
3293 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS
);
3294 options
->MaxCircuitDirtiness
= MIN_MAX_CIRCUIT_DIRTINESS
;
3297 if (options
->CircuitStreamTimeout
&&
3298 options
->CircuitStreamTimeout
< MIN_CIRCUIT_STREAM_TIMEOUT
) {
3299 log_warn(LD_CONFIG
, "CircuitStreamTimeout option is too short; "
3300 "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT
);
3301 options
->CircuitStreamTimeout
= MIN_CIRCUIT_STREAM_TIMEOUT
;
3304 if (options
->KeepalivePeriod
< 1)
3305 REJECT("KeepalivePeriod option must be positive.");
3307 if (ensure_bandwidth_cap(&options
->BandwidthRate
,
3308 "BandwidthRate", msg
) < 0)
3310 if (ensure_bandwidth_cap(&options
->BandwidthBurst
,
3311 "BandwidthBurst", msg
) < 0)
3313 if (ensure_bandwidth_cap(&options
->MaxAdvertisedBandwidth
,
3314 "MaxAdvertisedBandwidth", msg
) < 0)
3316 if (ensure_bandwidth_cap(&options
->RelayBandwidthRate
,
3317 "RelayBandwidthRate", msg
) < 0)
3319 if (ensure_bandwidth_cap(&options
->RelayBandwidthBurst
,
3320 "RelayBandwidthBurst", msg
) < 0)
3322 if (ensure_bandwidth_cap(&options
->PerConnBWRate
,
3323 "PerConnBWRate", msg
) < 0)
3325 if (ensure_bandwidth_cap(&options
->PerConnBWBurst
,
3326 "PerConnBWBurst", msg
) < 0)
3329 if (server_mode(options
)) {
3330 if (options
->BandwidthRate
< ROUTER_REQUIRED_MIN_BANDWIDTH
) {
3332 "BandwidthRate is set to %d bytes/second. "
3333 "For servers, it must be at least %d.",
3334 (int)options
->BandwidthRate
,
3335 ROUTER_REQUIRED_MIN_BANDWIDTH
);
3337 } else if (options
->MaxAdvertisedBandwidth
<
3338 ROUTER_REQUIRED_MIN_BANDWIDTH
/2) {
3340 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3341 "For servers, it must be at least %d.",
3342 (int)options
->MaxAdvertisedBandwidth
,
3343 ROUTER_REQUIRED_MIN_BANDWIDTH
/2);
3346 if (options
->RelayBandwidthRate
&&
3347 options
->RelayBandwidthRate
< ROUTER_REQUIRED_MIN_BANDWIDTH
) {
3349 "RelayBandwidthRate is set to %d bytes/second. "
3350 "For servers, it must be at least %d.",
3351 (int)options
->RelayBandwidthRate
,
3352 ROUTER_REQUIRED_MIN_BANDWIDTH
);
3357 if (options
->RelayBandwidthRate
&& !options
->RelayBandwidthBurst
)
3358 options
->RelayBandwidthBurst
= options
->RelayBandwidthRate
;
3360 if (options
->RelayBandwidthRate
> options
->RelayBandwidthBurst
)
3361 REJECT("RelayBandwidthBurst must be at least equal "
3362 "to RelayBandwidthRate.");
3364 if (options
->BandwidthRate
> options
->BandwidthBurst
)
3365 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3367 /* if they set relaybandwidth* really high but left bandwidth*
3368 * at the default, raise the defaults. */
3369 if (options
->RelayBandwidthRate
> options
->BandwidthRate
)
3370 options
->BandwidthRate
= options
->RelayBandwidthRate
;
3371 if (options
->RelayBandwidthBurst
> options
->BandwidthBurst
)
3372 options
->BandwidthBurst
= options
->RelayBandwidthBurst
;
3374 if (accounting_parse_options(options
, 1)<0)
3375 REJECT("Failed to parse accounting options. See logs for details.");
3377 if (options
->HttpProxy
) { /* parse it now */
3378 if (tor_addr_port_parse(options
->HttpProxy
,
3379 &options
->HttpProxyAddr
, &options
->HttpProxyPort
) < 0)
3380 REJECT("HttpProxy failed to parse or resolve. Please fix.");
3381 if (options
->HttpProxyPort
== 0) { /* give it a default */
3382 options
->HttpProxyPort
= 80;
3386 if (options
->HttpProxyAuthenticator
) {
3387 if (strlen(options
->HttpProxyAuthenticator
) >= 48)
3388 REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
3391 if (options
->HttpsProxy
) { /* parse it now */
3392 if (tor_addr_port_parse(options
->HttpsProxy
,
3393 &options
->HttpsProxyAddr
, &options
->HttpsProxyPort
) <0)
3394 REJECT("HttpsProxy failed to parse or resolve. Please fix.");
3395 if (options
->HttpsProxyPort
== 0) { /* give it a default */
3396 options
->HttpsProxyPort
= 443;
3400 if (options
->HttpsProxyAuthenticator
) {
3401 if (strlen(options
->HttpsProxyAuthenticator
) >= 48)
3402 REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
3405 if (options
->Socks4Proxy
) { /* parse it now */
3406 if (tor_addr_port_parse(options
->Socks4Proxy
,
3407 &options
->Socks4ProxyAddr
,
3408 &options
->Socks4ProxyPort
) <0)
3409 REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
3410 if (options
->Socks4ProxyPort
== 0) { /* give it a default */
3411 options
->Socks4ProxyPort
= 1080;
3415 if (options
->Socks5Proxy
) { /* parse it now */
3416 if (tor_addr_port_parse(options
->Socks5Proxy
,
3417 &options
->Socks5ProxyAddr
,
3418 &options
->Socks5ProxyPort
) <0)
3419 REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
3420 if (options
->Socks5ProxyPort
== 0) { /* give it a default */
3421 options
->Socks5ProxyPort
= 1080;
3425 if (options
->Socks4Proxy
&& options
->Socks5Proxy
)
3426 REJECT("You cannot specify both Socks4Proxy and SOCKS5Proxy");
3428 if (options
->Socks5ProxyUsername
) {
3431 len
= strlen(options
->Socks5ProxyUsername
);
3432 if (len
< 1 || len
> 255)
3433 REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
3435 if (!options
->Socks5ProxyPassword
)
3436 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3438 len
= strlen(options
->Socks5ProxyPassword
);
3439 if (len
< 1 || len
> 255)
3440 REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
3441 } else if (options
->Socks5ProxyPassword
)
3442 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3444 if (options
->HashedControlPassword
) {
3445 smartlist_t
*sl
= decode_hashed_passwords(options
->HashedControlPassword
);
3447 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3449 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
3454 if (options
->HashedControlSessionPassword
) {
3455 smartlist_t
*sl
= decode_hashed_passwords(
3456 options
->HashedControlSessionPassword
);
3458 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3460 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
3465 if (options
->ControlListenAddress
) {
3466 int all_are_local
= 1;
3468 for (ln
= options
->ControlListenAddress
; ln
; ln
= ln
->next
) {
3469 if (strcmpstart(ln
->value
, "127."))
3472 if (!all_are_local
) {
3473 if (!options
->HashedControlPassword
&&
3474 !options
->HashedControlSessionPassword
&&
3475 !options
->CookieAuthentication
) {
3477 "You have a ControlListenAddress set to accept "
3478 "unauthenticated connections from a non-local address. "
3479 "This means that programs not running on your computer "
3480 "can reconfigure your Tor, without even having to guess a "
3481 "password. That's so bad that I'm closing your ControlPort "
3482 "for you. If you need to control your Tor remotely, try "
3483 "enabling authentication and using a tool like stunnel or "
3484 "ssh to encrypt remote access.");
3485 options
->ControlPort
= 0;
3487 log_warn(LD_CONFIG
, "You have a ControlListenAddress set to accept "
3488 "connections from a non-local address. This means that "
3489 "programs not running on your computer can reconfigure your "
3490 "Tor. That's pretty bad, since the controller "
3491 "protocol isn't encrypted! Maybe you should just listen on "
3492 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
3493 "remote connections to your control port.");
3498 if (options
->ControlPort
&& !options
->HashedControlPassword
&&
3499 !options
->HashedControlSessionPassword
&&
3500 !options
->CookieAuthentication
) {
3501 log_warn(LD_CONFIG
, "ControlPort is open, but no authentication method "
3502 "has been configured. This means that any program on your "
3503 "computer can reconfigure your Tor. That's bad! You should "
3504 "upgrade your Tor controller as soon as possible.");
3507 if (options
->CookieAuthFileGroupReadable
&& !options
->CookieAuthFile
) {
3508 log_warn(LD_CONFIG
, "You set the CookieAuthFileGroupReadable but did "
3509 "not configure a the path for the cookie file via "
3510 "CookieAuthFile. This means your cookie will not be group "
3514 if (options
->UseEntryGuards
&& ! options
->NumEntryGuards
)
3515 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3517 if (check_nickname_list(options
->MyFamily
, "MyFamily", msg
))
3519 for (cl
= options
->NodeFamilies
; cl
; cl
= cl
->next
) {
3520 if (check_nickname_list(cl
->value
, "NodeFamily", msg
))
3524 if (validate_addr_policies(options
, msg
) < 0)
3527 if (validate_dir_authorities(options
, old_options
) < 0)
3528 REJECT("Directory authority line did not parse. See logs for details.");
3530 if (options
->UseBridges
&& !options
->Bridges
)
3531 REJECT("If you set UseBridges, you must specify at least one bridge.");
3532 if (options
->UseBridges
&& !options
->TunnelDirConns
)
3533 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3534 if (options
->Bridges
) {
3535 for (cl
= options
->Bridges
; cl
; cl
= cl
->next
) {
3536 if (parse_bridge_line(cl
->value
, 1)<0)
3537 REJECT("Bridge line did not parse. See logs for details.");
3541 if (options
->ConstrainedSockets
) {
3542 /* If the user wants to constrain socket buffer use, make sure the desired
3543 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3544 if (options
->ConstrainedSockSize
< MIN_CONSTRAINED_TCP_BUFFER
||
3545 options
->ConstrainedSockSize
> MAX_CONSTRAINED_TCP_BUFFER
||
3546 options
->ConstrainedSockSize
% 1024) {
3548 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3549 "in 1024 byte increments.",
3550 MIN_CONSTRAINED_TCP_BUFFER
, MAX_CONSTRAINED_TCP_BUFFER
);
3553 if (options
->DirPort
) {
3554 /* Providing cached directory entries while system TCP buffers are scarce
3555 * will exacerbate the socket errors. Suggest that this be disabled. */
3556 COMPLAIN("You have requested constrained socket buffers while also "
3557 "serving directory entries via DirPort. It is strongly "
3558 "suggested that you disable serving directory requests when "
3559 "system TCP buffer resources are scarce.");
3563 if (options
->V3AuthVoteDelay
+ options
->V3AuthDistDelay
>=
3564 options
->V3AuthVotingInterval
/2) {
3565 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3566 "V3AuthVotingInterval");
3568 if (options
->V3AuthVoteDelay
< MIN_VOTE_SECONDS
)
3569 REJECT("V3AuthVoteDelay is way too low.");
3570 if (options
->V3AuthDistDelay
< MIN_DIST_SECONDS
)
3571 REJECT("V3AuthDistDelay is way too low.");
3573 if (options
->V3AuthNIntervalsValid
< 2)
3574 REJECT("V3AuthNIntervalsValid must be at least 2.");
3576 if (options
->V3AuthVotingInterval
< MIN_VOTE_INTERVAL
) {
3577 REJECT("V3AuthVotingInterval is insanely low.");
3578 } else if (options
->V3AuthVotingInterval
> 24*60*60) {
3579 REJECT("V3AuthVotingInterval is insanely high.");
3580 } else if (((24*60*60) % options
->V3AuthVotingInterval
) != 0) {
3581 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3584 if (rend_config_services(options
, 1) < 0)
3585 REJECT("Failed to configure rendezvous options. See logs for details.");
3587 /* Parse client-side authorization for hidden services. */
3588 if (rend_parse_service_authorization(options
, 1) < 0)
3589 REJECT("Failed to configure client authorization for hidden services. "
3590 "See logs for details.");
3592 if (parse_virtual_addr_network(options
->VirtualAddrNetwork
, 1, NULL
)<0)
3595 if (options
->PreferTunneledDirConns
&& !options
->TunnelDirConns
)
3596 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3598 if ((options
->Socks4Proxy
|| options
->Socks5Proxy
) &&
3599 !options
->HttpProxy
&& !options
->PreferTunneledDirConns
)
3600 REJECT("When Socks4Proxy or Socks5Proxy is configured, "
3601 "PreferTunneledDirConns and TunnelDirConns must both be "
3602 "set to 1, or HttpProxy must be configured.");
3604 if (options
->AutomapHostsSuffixes
) {
3605 SMARTLIST_FOREACH(options
->AutomapHostsSuffixes
, char *, suf
,
3607 size_t len
= strlen(suf
);
3608 if (len
&& suf
[len
-1] == '.')
3613 if (options
->TestingTorNetwork
&& !options
->DirServers
) {
3614 REJECT("TestingTorNetwork may only be configured in combination with "
3615 "a non-default set of DirServers.");
3618 /*XXXX022 checking for defaults manually like this is a bit fragile.*/
3620 /* Keep changes to hard-coded values synchronous to man page and default
3622 if (options
->TestingV3AuthInitialVotingInterval
!= 30*60 &&
3623 !options
->TestingTorNetwork
) {
3624 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
3626 } else if (options
->TestingV3AuthInitialVotingInterval
< MIN_VOTE_INTERVAL
) {
3627 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3628 } else if (((30*60) % options
->TestingV3AuthInitialVotingInterval
) != 0) {
3629 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3633 if (options
->TestingV3AuthInitialVoteDelay
!= 5*60 &&
3634 !options
->TestingTorNetwork
) {
3635 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
3637 } else if (options
->TestingV3AuthInitialVoteDelay
< MIN_VOTE_SECONDS
) {
3638 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3641 if (options
->TestingV3AuthInitialDistDelay
!= 5*60 &&
3642 !options
->TestingTorNetwork
) {
3643 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
3645 } else if (options
->TestingV3AuthInitialDistDelay
< MIN_DIST_SECONDS
) {
3646 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3649 if (options
->TestingV3AuthInitialVoteDelay
+
3650 options
->TestingV3AuthInitialDistDelay
>=
3651 options
->TestingV3AuthInitialVotingInterval
/2) {
3652 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3653 "must be less than half TestingV3AuthInitialVotingInterval");
3656 if (options
->TestingAuthDirTimeToLearnReachability
!= 30*60 &&
3657 !options
->TestingTorNetwork
) {
3658 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
3659 "testing Tor networks!");
3660 } else if (options
->TestingAuthDirTimeToLearnReachability
< 0) {
3661 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3662 } else if (options
->TestingAuthDirTimeToLearnReachability
> 2*60*60) {
3663 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3666 if (options
->TestingEstimatedDescriptorPropagationTime
!= 10*60 &&
3667 !options
->TestingTorNetwork
) {
3668 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
3669 "testing Tor networks!");
3670 } else if (options
->TestingEstimatedDescriptorPropagationTime
< 0) {
3671 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3672 } else if (options
->TestingEstimatedDescriptorPropagationTime
> 60*60) {
3673 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3676 if (options
->TestingTorNetwork
) {
3677 log_warn(LD_CONFIG
, "TestingTorNetwork is set. This will make your node "
3678 "almost unusable in the public Tor network, and is "
3679 "therefore only advised if you are building a "
3680 "testing Tor network!");
3683 if (options
->AccelName
&& !options
->HardwareAccel
)
3684 options
->HardwareAccel
= 1;
3685 if (options
->AccelDir
&& !options
->AccelName
)
3686 REJECT("Can't use hardware crypto accelerator dir without engine name.");
3688 if (options
->PublishServerDescriptor
)
3689 SMARTLIST_FOREACH(options
->PublishServerDescriptor
, const char *, pubdes
, {
3690 if (!strcmp(pubdes
, "1") || !strcmp(pubdes
, "0"))
3691 if (smartlist_len(options
->PublishServerDescriptor
) > 1) {
3692 COMPLAIN("You have passed a list of multiple arguments to the "
3693 "PublishServerDescriptor option that includes 0 or 1. "
3694 "0 or 1 should only be used as the sole argument. "
3695 "This configuration will be rejected in a future release.");
3700 if (options
->BridgeRelay
== 1 && options
->ORPort
== 0)
3701 REJECT("BridgeRelay is 1, ORPort is 0. This is an invalid combination.");
3708 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3711 opt_streq(const char *s1
, const char *s2
)
3715 else if (s1
&& s2
&& !strcmp(s1
,s2
))
3721 /** Check if any of the previous options have changed but aren't allowed to. */
3723 options_transition_allowed(or_options_t
*old
, or_options_t
*new_val
,
3729 if (!opt_streq(old
->PidFile
, new_val
->PidFile
)) {
3730 *msg
= tor_strdup("PidFile is not allowed to change.");
3734 if (old
->RunAsDaemon
!= new_val
->RunAsDaemon
) {
3735 *msg
= tor_strdup("While Tor is running, changing RunAsDaemon "
3740 if (strcmp(old
->DataDirectory
,new_val
->DataDirectory
)!=0) {
3742 "While Tor is running, changing DataDirectory "
3743 "(\"%s\"->\"%s\") is not allowed.",
3744 old
->DataDirectory
, new_val
->DataDirectory
);
3748 if (!opt_streq(old
->User
, new_val
->User
)) {
3749 *msg
= tor_strdup("While Tor is running, changing User is not allowed.");
3753 if ((old
->HardwareAccel
!= new_val
->HardwareAccel
)
3754 || !opt_streq(old
->AccelName
, new_val
->AccelName
)
3755 || !opt_streq(old
->AccelDir
, new_val
->AccelDir
)) {
3756 *msg
= tor_strdup("While Tor is running, changing OpenSSL hardware "
3757 "acceleration engine is not allowed.");
3761 if (old
->TestingTorNetwork
!= new_val
->TestingTorNetwork
) {
3762 *msg
= tor_strdup("While Tor is running, changing TestingTorNetwork "
3767 if (old
->DisableAllSwap
!= new_val
->DisableAllSwap
) {
3768 *msg
= tor_strdup("While Tor is running, changing DisableAllSwap "
3776 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3777 * will require us to rotate the CPU and DNS workers; else return 0. */
3779 options_transition_affects_workers(or_options_t
*old_options
,
3780 or_options_t
*new_options
)
3782 if (!opt_streq(old_options
->DataDirectory
, new_options
->DataDirectory
) ||
3783 old_options
->NumCpus
!= new_options
->NumCpus
||
3784 old_options
->ORPort
!= new_options
->ORPort
||
3785 old_options
->ServerDNSSearchDomains
!=
3786 new_options
->ServerDNSSearchDomains
||
3787 old_options
->SafeLogging
!= new_options
->SafeLogging
||
3788 old_options
->ClientOnly
!= new_options
->ClientOnly
||
3789 !config_lines_eq(old_options
->Logs
, new_options
->Logs
))
3792 /* Check whether log options match. */
3794 /* Nothing that changed matters. */
3798 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3799 * will require us to generate a new descriptor; else return 0. */
3801 options_transition_affects_descriptor(or_options_t
*old_options
,
3802 or_options_t
*new_options
)
3804 /* XXX We can be smarter here. If your DirPort isn't being
3805 * published and you just turned it off, no need to republish. Etc. */
3806 if (!opt_streq(old_options
->DataDirectory
, new_options
->DataDirectory
) ||
3807 !opt_streq(old_options
->Nickname
,new_options
->Nickname
) ||
3808 !opt_streq(old_options
->Address
,new_options
->Address
) ||
3809 !config_lines_eq(old_options
->ExitPolicy
,new_options
->ExitPolicy
) ||
3810 old_options
->ExitPolicyRejectPrivate
!=
3811 new_options
->ExitPolicyRejectPrivate
||
3812 old_options
->ORPort
!= new_options
->ORPort
||
3813 old_options
->DirPort
!= new_options
->DirPort
||
3814 old_options
->ClientOnly
!= new_options
->ClientOnly
||
3815 old_options
->NoPublish
!= new_options
->NoPublish
||
3816 old_options
->_PublishServerDescriptor
!=
3817 new_options
->_PublishServerDescriptor
||
3818 get_effective_bwrate(old_options
) != get_effective_bwrate(new_options
) ||
3819 get_effective_bwburst(old_options
) !=
3820 get_effective_bwburst(new_options
) ||
3821 !opt_streq(old_options
->ContactInfo
, new_options
->ContactInfo
) ||
3822 !opt_streq(old_options
->MyFamily
, new_options
->MyFamily
) ||
3823 !opt_streq(old_options
->AccountingStart
, new_options
->AccountingStart
) ||
3824 old_options
->AccountingMax
!= new_options
->AccountingMax
)
3831 /** Return the directory on windows where we expect to find our application
3834 get_windows_conf_root(void)
3836 static int is_set
= 0;
3837 static char path
[MAX_PATH
+1];
3838 TCHAR tpath
[MAX_PATH
] = {0};
3847 /* Find X:\documents and settings\username\application data\ .
3848 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3850 #ifdef ENABLE_LOCAL_APPDATA
3851 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
3853 #define APPDATA_PATH CSIDL_APPDATA
3855 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL
, APPDATA_PATH
, &idl
))) {
3856 getcwd(path
,MAX_PATH
);
3859 "I couldn't find your application data folder: are you "
3860 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3864 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3865 result
= SHGetPathFromIDList(idl
, tpath
);
3867 wcstombs(path
,tpath
,MAX_PATH
);
3869 strlcpy(path
,tpath
,sizeof(path
));
3872 /* Now we need to free the memory that the path-idl was stored in. In
3873 * typical Windows fashion, we can't just call 'free()' on it. */
3876 m
->lpVtbl
->Free(m
, idl
);
3877 m
->lpVtbl
->Release(m
);
3879 if (!SUCCEEDED(result
)) {
3882 strlcat(path
,"\\tor",MAX_PATH
);
3888 /** Return the default location for our torrc file. */
3890 get_default_conf_file(void)
3893 static char path
[MAX_PATH
+1];
3894 strlcpy(path
, get_windows_conf_root(), MAX_PATH
);
3895 strlcat(path
,"\\torrc",MAX_PATH
);
3898 return (CONFDIR
"/torrc");
3902 /** Verify whether lst is a string containing valid-looking comma-separated
3903 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3906 check_nickname_list(const char *lst
, const char *name
, char **msg
)
3913 sl
= smartlist_create();
3915 smartlist_split_string(sl
, lst
, ",",
3916 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
|SPLIT_STRIP_SPACE
, 0);
3918 SMARTLIST_FOREACH(sl
, const char *, s
,
3920 if (!is_legal_nickname_or_hexdigest(s
)) {
3921 tor_asprintf(msg
, "Invalid nickname '%s' in %s line", s
, name
);
3926 SMARTLIST_FOREACH(sl
, char *, s
, tor_free(s
));
3931 /** Learn config file name from command line arguments, or use the default */
3933 find_torrc_filename(int argc
, char **argv
,
3934 int *using_default_torrc
, int *ignore_missing_torrc
)
3939 for (i
= 1; i
< argc
; ++i
) {
3940 if (i
< argc
-1 && !strcmp(argv
[i
],"-f")) {
3942 log(LOG_WARN
, LD_CONFIG
, "Duplicate -f options on command line.");
3945 fname
= expand_filename(argv
[i
+1]);
3946 *using_default_torrc
= 0;
3948 } else if (!strcmp(argv
[i
],"--ignore-missing-torrc")) {
3949 *ignore_missing_torrc
= 1;
3953 if (*using_default_torrc
) {
3954 /* didn't find one, try CONFDIR */
3955 const char *dflt
= get_default_conf_file();
3956 if (dflt
&& file_status(dflt
) == FN_FILE
) {
3957 fname
= tor_strdup(dflt
);
3961 fn
= expand_filename("~/.torrc");
3962 if (fn
&& file_status(fn
) == FN_FILE
) {
3966 fname
= tor_strdup(dflt
);
3969 fname
= tor_strdup(dflt
);
3976 /** Load torrc from disk, setting torrc_fname if successful */
3978 load_torrc_from_disk(int argc
, char **argv
)
3982 int using_default_torrc
= 1;
3983 int ignore_missing_torrc
= 0;
3985 fname
= find_torrc_filename(argc
, argv
,
3986 &using_default_torrc
, &ignore_missing_torrc
);
3988 log(LOG_DEBUG
, LD_CONFIG
, "Opening config file \"%s\"", fname
);
3990 tor_free(torrc_fname
);
3991 torrc_fname
= fname
;
3993 /* Open config file */
3994 if (file_status(fname
) != FN_FILE
||
3995 !(cf
= read_file_to_str(fname
,0,NULL
))) {
3996 if (using_default_torrc
== 1 || ignore_missing_torrc
) {
3997 log(LOG_NOTICE
, LD_CONFIG
, "Configuration file \"%s\" not present, "
3998 "using reasonable defaults.", fname
);
3999 tor_free(fname
); /* sets fname to NULL */
4001 cf
= tor_strdup("");
4003 log(LOG_WARN
, LD_CONFIG
,
4004 "Unable to open configuration file \"%s\".", fname
);
4016 /** Read a configuration file into <b>options</b>, finding the configuration
4017 * file location based on the command line. After loading the file
4018 * call options_init_from_string() to load the config.
4019 * Return 0 if success, -1 if failure. */
4021 options_init_from_torrc(int argc
, char **argv
)
4024 int i
, retval
, command
;
4025 static char **backup_argv
;
4026 static int backup_argc
;
4027 char *command_arg
= NULL
;
4030 if (argv
) { /* first time we're called. save command line args */
4033 } else { /* we're reloading. need to clean up old options first. */
4037 if (argc
> 1 && (!strcmp(argv
[1], "-h") || !strcmp(argv
[1],"--help"))) {
4041 if (argc
> 1 && !strcmp(argv
[1], "--list-torrc-options")) {
4042 /* For documenting validating whether we've documented everything. */
4043 list_torrc_options();
4047 if (argc
> 1 && (!strcmp(argv
[1],"--version"))) {
4048 printf("Tor version %s.\n",get_version());
4051 if (argc
> 1 && (!strcmp(argv
[1],"--digests"))) {
4052 printf("Tor version %s.\n",get_version());
4053 printf("%s", libor_get_digests());
4054 printf("%s", tor_get_digests());
4058 /* Go through command-line variables */
4059 if (!global_cmdline_options
) {
4060 /* Or we could redo the list every time we pass this place.
4061 * It does not really matter */
4062 if (config_get_commandlines(argc
, argv
, &global_cmdline_options
) < 0) {
4067 command
= CMD_RUN_TOR
;
4068 for (i
= 1; i
< argc
; ++i
) {
4069 if (!strcmp(argv
[i
],"--list-fingerprint")) {
4070 command
= CMD_LIST_FINGERPRINT
;
4071 } else if (!strcmp(argv
[i
],"--hash-password")) {
4072 command
= CMD_HASH_PASSWORD
;
4073 command_arg
= tor_strdup( (i
< argc
-1) ? argv
[i
+1] : "");
4075 } else if (!strcmp(argv
[i
],"--verify-config")) {
4076 command
= CMD_VERIFY_CONFIG
;
4080 if (command
== CMD_HASH_PASSWORD
) {
4081 cf
= tor_strdup("");
4083 cf
= load_torrc_from_disk(argc
, argv
);
4088 retval
= options_init_from_string(cf
, command
, command_arg
, &errmsg
);
4097 log(LOG_WARN
,LD_CONFIG
,"%s", errmsg
);
4103 /** Load the options from the configuration in <b>cf</b>, validate
4104 * them for consistency and take actions based on them.
4106 * Return 0 if success, negative on error:
4107 * * -1 for general errors.
4108 * * -2 for failure to parse/validate,
4109 * * -3 for transition not allowed
4110 * * -4 for error while setting the new options
4113 options_init_from_string(const char *cf
,
4114 int command
, const char *command_arg
,
4117 or_options_t
*oldoptions
, *newoptions
;
4120 setopt_err_t err
= SETOPT_ERR_MISC
;
4123 oldoptions
= global_options
; /* get_options unfortunately asserts if
4124 this is the first time we run*/
4126 newoptions
= tor_malloc_zero(sizeof(or_options_t
));
4127 newoptions
->_magic
= OR_OPTIONS_MAGIC
;
4128 options_init(newoptions
);
4129 newoptions
->command
= command
;
4130 newoptions
->command_arg
= command_arg
;
4132 /* get config lines, assign them */
4133 retval
= config_get_lines(cf
, &cl
);
4135 err
= SETOPT_ERR_PARSE
;
4138 retval
= config_assign(&options_format
, newoptions
, cl
, 0, 0, msg
);
4139 config_free_lines(cl
);
4141 err
= SETOPT_ERR_PARSE
;
4145 /* Go through command-line variables too */
4146 retval
= config_assign(&options_format
, newoptions
,
4147 global_cmdline_options
, 0, 0, msg
);
4149 err
= SETOPT_ERR_PARSE
;
4153 /* If this is a testing network configuration, change defaults
4154 * for a list of dependent config options, re-initialize newoptions
4155 * with the new defaults, and assign all options to it second time. */
4156 if (newoptions
->TestingTorNetwork
) {
4157 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4158 * this? We could, for example, make the parsing algorithm do two passes
4159 * over the configuration. If it finds any "suite" options like
4160 * TestingTorNetwork, it could change the defaults before its second pass.
4161 * Not urgent so long as this seems to work, but at any sign of trouble,
4162 * let's clean it up. -NM */
4164 /* Change defaults. */
4166 for (i
= 0; testing_tor_network_defaults
[i
].name
; ++i
) {
4167 config_var_t
*new_var
= &testing_tor_network_defaults
[i
];
4168 config_var_t
*old_var
=
4169 config_find_option(&options_format
, new_var
->name
);
4170 tor_assert(new_var
);
4171 tor_assert(old_var
);
4172 old_var
->initvalue
= new_var
->initvalue
;
4175 /* Clear newoptions and re-initialize them with new defaults. */
4176 config_free(&options_format
, newoptions
);
4177 newoptions
= tor_malloc_zero(sizeof(or_options_t
));
4178 newoptions
->_magic
= OR_OPTIONS_MAGIC
;
4179 options_init(newoptions
);
4180 newoptions
->command
= command
;
4181 newoptions
->command_arg
= command_arg
;
4183 /* Assign all options a second time. */
4184 retval
= config_get_lines(cf
, &cl
);
4186 err
= SETOPT_ERR_PARSE
;
4189 retval
= config_assign(&options_format
, newoptions
, cl
, 0, 0, msg
);
4190 config_free_lines(cl
);
4192 err
= SETOPT_ERR_PARSE
;
4195 retval
= config_assign(&options_format
, newoptions
,
4196 global_cmdline_options
, 0, 0, msg
);
4198 err
= SETOPT_ERR_PARSE
;
4203 /* Validate newoptions */
4204 if (options_validate(oldoptions
, newoptions
, 0, msg
) < 0) {
4205 err
= SETOPT_ERR_PARSE
; /*XXX make this a separate return value.*/
4209 if (options_transition_allowed(oldoptions
, newoptions
, msg
) < 0) {
4210 err
= SETOPT_ERR_TRANSITION
;
4214 if (set_options(newoptions
, msg
)) {
4215 err
= SETOPT_ERR_SETTING
;
4216 goto err
; /* frees and replaces old options */
4222 config_free(&options_format
, newoptions
);
4224 char *old_msg
= *msg
;
4225 tor_asprintf(msg
, "Failed to parse/validate config: %s", old_msg
);
4231 /** Return the location for our configuration file.
4234 get_torrc_fname(void)
4239 return get_default_conf_file();
4242 /** Adjust the address map based on the MapAddress elements in the
4243 * configuration <b>options</b>
4246 config_register_addressmaps(or_options_t
*options
)
4252 addressmap_clear_configured();
4253 elts
= smartlist_create();
4254 for (opt
= options
->AddressMap
; opt
; opt
= opt
->next
) {
4255 smartlist_split_string(elts
, opt
->value
, NULL
,
4256 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
4257 if (smartlist_len(elts
) >= 2) {
4258 from
= smartlist_get(elts
,0);
4259 to
= smartlist_get(elts
,1);
4260 if (address_is_invalid_destination(to
, 1)) {
4262 "Skipping invalid argument '%s' to MapAddress", to
);
4264 addressmap_register(from
, tor_strdup(to
), 0, ADDRMAPSRC_TORRC
);
4265 if (smartlist_len(elts
)>2) {
4266 log_warn(LD_CONFIG
,"Ignoring extra arguments to MapAddress.");
4270 log_warn(LD_CONFIG
,"MapAddress '%s' has too few arguments. Ignoring.",
4273 SMARTLIST_FOREACH(elts
, char*, cp
, tor_free(cp
));
4274 smartlist_clear(elts
);
4276 smartlist_free(elts
);
4280 * Initialize the logs based on the configuration file.
4283 options_init_logs(or_options_t
*options
, int validate_only
)
4292 options
->RunAsDaemon
;
4296 elts
= smartlist_create();
4298 for (opt
= options
->Logs
; opt
; opt
= opt
->next
) {
4299 log_severity_list_t
*severity
;
4300 const char *cfg
= opt
->value
;
4301 severity
= tor_malloc_zero(sizeof(log_severity_list_t
));
4302 if (parse_log_severity_config(&cfg
, severity
) < 0) {
4303 log_warn(LD_CONFIG
, "Couldn't parse log levels in Log option 'Log %s'",
4305 ok
= 0; goto cleanup
;
4308 smartlist_split_string(elts
, cfg
, NULL
,
4309 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
4311 if (smartlist_len(elts
) == 0)
4312 smartlist_add(elts
, tor_strdup("stdout"));
4314 if (smartlist_len(elts
) == 1 &&
4315 (!strcasecmp(smartlist_get(elts
,0), "stdout") ||
4316 !strcasecmp(smartlist_get(elts
,0), "stderr"))) {
4317 int err
= smartlist_len(elts
) &&
4318 !strcasecmp(smartlist_get(elts
,0), "stderr");
4319 if (!validate_only
) {
4322 "Can't log to %s with RunAsDaemon set; skipping stdout",
4323 err
?"stderr":"stdout");
4325 add_stream_log(severity
, err
?"<stderr>":"<stdout>",
4326 fileno(err
?stderr
:stdout
));
4331 if (smartlist_len(elts
) == 1 &&
4332 !strcasecmp(smartlist_get(elts
,0), "syslog")) {
4333 #ifdef HAVE_SYSLOG_H
4334 if (!validate_only
) {
4335 add_syslog_log(severity
);
4338 log_warn(LD_CONFIG
, "Syslog is not supported on this system. Sorry.");
4343 if (smartlist_len(elts
) == 2 &&
4344 !strcasecmp(smartlist_get(elts
,0), "file")) {
4345 if (!validate_only
) {
4346 if (add_file_log(severity
, smartlist_get(elts
, 1)) < 0) {
4347 log_warn(LD_CONFIG
, "Couldn't open file for 'Log %s': %s",
4348 opt
->value
, strerror(errno
));
4355 log_warn(LD_CONFIG
, "Bad syntax on file Log option 'Log %s'",
4357 ok
= 0; goto cleanup
;
4360 SMARTLIST_FOREACH(elts
, char*, cp
, tor_free(cp
));
4361 smartlist_clear(elts
);
4364 smartlist_free(elts
);
4369 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4370 * if the line is well-formed, and -1 if it isn't. If
4371 * <b>validate_only</b> is 0, and the line is well-formed, then add
4372 * the bridge described in the line to our internal bridge list. */
4374 parse_bridge_line(const char *line
, int validate_only
)
4376 smartlist_t
*items
= NULL
;
4378 char *addrport
=NULL
, *fingerprint
=NULL
;
4381 char digest
[DIGEST_LEN
];
4383 items
= smartlist_create();
4384 smartlist_split_string(items
, line
, NULL
,
4385 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, -1);
4386 if (smartlist_len(items
) < 1) {
4387 log_warn(LD_CONFIG
, "Too few arguments to Bridge line.");
4390 addrport
= smartlist_get(items
, 0);
4391 smartlist_del_keeporder(items
, 0);
4392 if (tor_addr_port_parse(addrport
, &addr
, &port
)<0) {
4393 log_warn(LD_CONFIG
, "Error parsing Bridge address '%s'", addrport
);
4398 "Bridge address '%s' has no port; using default port 443.",
4403 if (smartlist_len(items
)) {
4404 fingerprint
= smartlist_join_strings(items
, "", 0, NULL
);
4405 if (strlen(fingerprint
) != HEX_DIGEST_LEN
) {
4406 log_warn(LD_CONFIG
, "Key digest for Bridge is wrong length.");
4409 if (base16_decode(digest
, DIGEST_LEN
, fingerprint
, HEX_DIGEST_LEN
)<0) {
4410 log_warn(LD_CONFIG
, "Unable to decode Bridge key digest.");
4415 if (!validate_only
) {
4416 log_debug(LD_DIR
, "Bridge at %s:%d (%s)", fmt_addr(&addr
),
4418 fingerprint
? fingerprint
: "no key listed");
4419 bridge_add_from_config(&addr
, port
, fingerprint
? digest
: NULL
);
4429 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
4430 smartlist_free(items
);
4432 tor_free(fingerprint
);
4436 /** Read the contents of a DirServer line from <b>line</b>. If
4437 * <b>validate_only</b> is 0, and the line is well-formed, and it
4438 * shares any bits with <b>required_type</b> or <b>required_type</b>
4439 * is 0, then add the dirserver described in the line (minus whatever
4440 * bits it's missing) as a valid authority. Return 0 on success,
4441 * or -1 if the line isn't well-formed or if we can't add it. */
4443 parse_dir_server_line(const char *line
, authority_type_t required_type
,
4446 smartlist_t
*items
= NULL
;
4448 char *addrport
=NULL
, *address
=NULL
, *nickname
=NULL
, *fingerprint
=NULL
;
4449 uint16_t dir_port
= 0, or_port
= 0;
4450 char digest
[DIGEST_LEN
];
4451 char v3_digest
[DIGEST_LEN
];
4452 authority_type_t type
= V2_AUTHORITY
;
4453 int is_not_hidserv_authority
= 0, is_not_v2_authority
= 0;
4455 items
= smartlist_create();
4456 smartlist_split_string(items
, line
, NULL
,
4457 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, -1);
4458 if (smartlist_len(items
) < 1) {
4459 log_warn(LD_CONFIG
, "No arguments on DirServer line.");
4463 if (is_legal_nickname(smartlist_get(items
, 0))) {
4464 nickname
= smartlist_get(items
, 0);
4465 smartlist_del_keeporder(items
, 0);
4468 while (smartlist_len(items
)) {
4469 char *flag
= smartlist_get(items
, 0);
4470 if (TOR_ISDIGIT(flag
[0]))
4472 if (!strcasecmp(flag
, "v1")) {
4473 type
|= (V1_AUTHORITY
| HIDSERV_AUTHORITY
);
4474 } else if (!strcasecmp(flag
, "hs")) {
4475 type
|= HIDSERV_AUTHORITY
;
4476 } else if (!strcasecmp(flag
, "no-hs")) {
4477 is_not_hidserv_authority
= 1;
4478 } else if (!strcasecmp(flag
, "bridge")) {
4479 type
|= BRIDGE_AUTHORITY
;
4480 } else if (!strcasecmp(flag
, "no-v2")) {
4481 is_not_v2_authority
= 1;
4482 } else if (!strcasecmpstart(flag
, "orport=")) {
4484 char *portstring
= flag
+ strlen("orport=");
4485 or_port
= (uint16_t) tor_parse_long(portstring
, 10, 1, 65535, &ok
, NULL
);
4487 log_warn(LD_CONFIG
, "Invalid orport '%s' on DirServer line.",
4489 } else if (!strcasecmpstart(flag
, "v3ident=")) {
4490 char *idstr
= flag
+ strlen("v3ident=");
4491 if (strlen(idstr
) != HEX_DIGEST_LEN
||
4492 base16_decode(v3_digest
, DIGEST_LEN
, idstr
, HEX_DIGEST_LEN
)<0) {
4493 log_warn(LD_CONFIG
, "Bad v3 identity digest '%s' on DirServer line",
4496 type
|= V3_AUTHORITY
;
4499 log_warn(LD_CONFIG
, "Unrecognized flag '%s' on DirServer line",
4503 smartlist_del_keeporder(items
, 0);
4505 if (is_not_hidserv_authority
)
4506 type
&= ~HIDSERV_AUTHORITY
;
4507 if (is_not_v2_authority
)
4508 type
&= ~V2_AUTHORITY
;
4510 if (smartlist_len(items
) < 2) {
4511 log_warn(LD_CONFIG
, "Too few arguments to DirServer line.");
4514 addrport
= smartlist_get(items
, 0);
4515 smartlist_del_keeporder(items
, 0);
4516 if (parse_addr_port(LOG_WARN
, addrport
, &address
, NULL
, &dir_port
)<0) {
4517 log_warn(LD_CONFIG
, "Error parsing DirServer address '%s'", addrport
);
4521 log_warn(LD_CONFIG
, "Missing port in DirServer address '%s'",addrport
);
4525 fingerprint
= smartlist_join_strings(items
, "", 0, NULL
);
4526 if (strlen(fingerprint
) != HEX_DIGEST_LEN
) {
4527 log_warn(LD_CONFIG
, "Key digest for DirServer is wrong length %d.",
4528 (int)strlen(fingerprint
));
4531 if (!strcmp(fingerprint
, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4532 /* a known bad fingerprint. refuse to use it. We can remove this
4533 * clause once Tor 0.1.2.17 is obsolete. */
4534 log_warn(LD_CONFIG
, "Dangerous dirserver line. To correct, erase your "
4535 "torrc file (%s), or reinstall Tor and use the default torrc.",
4539 if (base16_decode(digest
, DIGEST_LEN
, fingerprint
, HEX_DIGEST_LEN
)<0) {
4540 log_warn(LD_CONFIG
, "Unable to decode DirServer key digest.");
4544 if (!validate_only
&& (!required_type
|| required_type
& type
)) {
4546 type
&= required_type
; /* pare down what we think of them as an
4548 log_debug(LD_DIR
, "Trusted %d dirserver at %s:%d (%s)", (int)type
,
4549 address
, (int)dir_port
, (char*)smartlist_get(items
,0));
4550 if (!add_trusted_dir_server(nickname
, address
, dir_port
, or_port
,
4551 digest
, v3_digest
, type
))
4562 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
4563 smartlist_free(items
);
4567 tor_free(fingerprint
);
4571 /** Adjust the value of options->DataDirectory, or fill it in if it's
4572 * absent. Return 0 on success, -1 on failure. */
4574 normalize_data_directory(or_options_t
*options
)
4578 if (options
->DataDirectory
)
4579 return 0; /* all set */
4580 p
= tor_malloc(MAX_PATH
);
4581 strlcpy(p
,get_windows_conf_root(),MAX_PATH
);
4582 options
->DataDirectory
= p
;
4585 const char *d
= options
->DataDirectory
;
4589 if (strncmp(d
,"~/",2) == 0) {
4590 char *fn
= expand_filename(d
);
4592 log_warn(LD_CONFIG
,"Failed to expand filename \"%s\".", d
);
4595 if (!options
->DataDirectory
&& !strcmp(fn
,"/.tor")) {
4596 /* If our homedir is /, we probably don't want to use it. */
4597 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4600 "Default DataDirectory is \"~/.tor\". This expands to "
4601 "\"%s\", which is probably not what you want. Using "
4602 "\"%s"PATH_SEPARATOR
"tor\" instead
", fn, LOCALSTATEDIR);
4604 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor
");
4606 tor_free(options->DataDirectory);
4607 options->DataDirectory = fn;
4613 /** Check and normalize the value of options->DataDirectory; return 0 if it
4614 * is sane, -1 otherwise. */
4616 validate_data_directory(or_options_t *options)
4618 if (normalize_data_directory(options) < 0)
4620 tor_assert(options->DataDirectory);
4621 if (strlen(options->DataDirectory) > (512-128)) {
4622 log_warn(LD_CONFIG, "DataDirectory is too
long.");
4628 /** This string must remain the same forevermore. It is how we
4629 * recognize that the torrc file doesn't need to be backed up. */
4630 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4631 "if you edit it, comments will not be preserved"
4632 /** This string can change; it tries to give the reader an idea
4633 * that editing this file by hand is not a good plan. */
4634 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4635 "to torrc.orig.1 or similar, and Tor will ignore it"
4637 /** Save a configuration file for the configuration in <b>options</b>
4638 * into the file <b>fname</b>. If the file already exists, and
4639 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4640 * replace it. Return 0 on success, -1 on failure. */
4642 write_configuration_file(const char *fname, or_options_t *options)
4644 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4645 int rename_old = 0, r;
4649 switch (file_status(fname)) {
4651 old_val = read_file_to_str(fname, 0, NULL);
4652 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4663 "Config file \"%s\" is not a file? Failing.", fname);
4667 if (!(new_conf = options_dump(options, 1))) {
4668 log_warn(LD_BUG, "Couldn't get configuration string");
4672 tor_asprintf(&new_val, "%s\n%s\n\n%s",
4673 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4677 size_t fn_tmp_len = strlen(fname)+32;
4679 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4680 fn_tmp = tor_malloc(fn_tmp_len);
4682 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4683 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4687 if (file_status(fn_tmp) == FN_NOENT)
4691 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4692 if (rename(fname, fn_tmp) < 0) {
4694 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4695 fname, fn_tmp, strerror(errno));
4702 if (write_str_to_file(fname, new_val, 0) < 0)
4716 * Save the current configuration file value to disk. Return 0 on
4717 * success, -1 on failure.
4720 options_save_current(void)
4722 /* This fails if we can't write to our configuration file.
4724 * If we try falling back to datadirectory or something, we have a better
4725 * chance of saving the configuration, but a better chance of doing
4726 * something the user never expected. */
4727 return write_configuration_file(get_torrc_fname(), get_options());
4730 /** Mapping from a unit name to a multiplier for converting that unit into a
4732 struct unit_table_t {
4734 uint64_t multiplier;
4737 /** Table to map the names of memory units to the number of bytes they
4739 static struct unit_table_t memory_units[] = {
4746 { "kbytes", 1<<10 },
4747 { "kilobyte", 1<<10 },
4748 { "kilobytes", 1<<10 },
4752 { "mbytes", 1<<20 },
4753 { "megabyte", 1<<20 },
4754 { "megabytes", 1<<20 },
4757 { "gbytes", 1<<30 },
4758 { "gigabyte", 1<<30 },
4759 { "gigabytes", 1<<30 },
4760 { "tb", U64_LITERAL(1)<<40 },
4761 { "terabyte", U64_LITERAL(1)<<40 },
4762 { "terabytes", U64_LITERAL(1)<<40 },
4766 /** Table to map the names of time units to the number of seconds they
4768 static struct unit_table_t time_units[] = {
4776 { "day", 24*60*60 },
4777 { "days", 24*60*60 },
4778 { "week", 7*24*60*60 },
4779 { "weeks", 7*24*60*60 },
4783 /** Parse a string <b>val</b> containing a number, zero or more
4784 * spaces, and an optional unit string. If the unit appears in the
4785 * table <b>u</b>, then multiply the number by the unit multiplier.
4786 * On success, set *<b>ok</b> to 1 and return this product.
4787 * Otherwise, set *<b>ok</b> to 0.
4790 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4799 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4800 if (!*ok || (cp && *cp == '.')) {
4801 d = tor_parse_double(val, 0, UINT64_MAX, ok, &cp);
4809 v = use_float ? DBL_TO_U64(d) : v;
4813 cp = (char*) eat_whitespace(cp);
4815 for ( ;u->unit;++u) {
4816 if (!strcasecmp(u->unit, cp)) {
4818 v = u->multiplier * d;
4825 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4835 /** Parse a string in the format "number unit", where unit is a unit of
4836 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4837 * and return the number of bytes specified. Otherwise, set
4838 * *<b>ok</b> to false and return 0. */
4840 config_parse_memunit(const char *s, int *ok)
4842 uint64_t u = config_parse_units(s, memory_units, ok);
4846 /** Parse a string in the format "number unit", where unit is a unit of time.
4847 * On success, set *<b>ok</b> to true and return the number of seconds in
4848 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4851 config_parse_interval(const char *s, int *ok)
4854 r = config_parse_units(s, time_units, ok);
4858 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4866 * Initialize the libevent library.
4871 const char *badness=NULL;
4873 configure_libevent_logging();
4874 /* If the kernel complains that some method (say, epoll) doesn't
4875 * exist, we don't care about it, since libevent will cope.
4877 suppress_libevent_log_msg("Function not implemented");
4879 tor_check_libevent_header_compatibility();
4881 tor_libevent_initialize();
4883 suppress_libevent_log_msg(NULL);
4885 tor_check_libevent_version(tor_libevent_get_method(),
4886 get_options()->ORPort != 0,
4889 const char *v = tor_libevent_get_version_str();
4890 const char *m = tor_libevent_get_method();
4891 control_event_general_status(LOG_WARN,
4892 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
4897 /** Return the persistent state struct for this Tor. */
4901 tor_assert(global_state);
4902 return global_state;
4905 /** Return a newly allocated string holding a filename relative to the data
4906 * directory. If <b>sub1</b> is present, it is the first path component after
4907 * the data directory. If <b>sub2</b> is also present, it is the second path
4908 * component after the data directory. If <b>suffix</b> is present, it
4909 * is appended to the filename.
4912 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
4913 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
4914 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
4915 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
4917 * Note: Consider using the get_datadir_fname* macros in or.h.
4920 options_get_datadir_fname2_suffix(or_options_t *options,
4921 const char *sub1, const char *sub2,
4926 tor_assert(options);
4927 tor_assert(options->DataDirectory);
4928 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
4929 len = strlen(options->DataDirectory);
4931 len += strlen(sub1)+1;
4933 len += strlen(sub2)+1;
4936 len += strlen(suffix);
4938 fname = tor_malloc(len);
4941 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
4942 options->DataDirectory, sub1, sub2);
4944 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
4945 options->DataDirectory, sub1);
4948 strlcpy(fname, options->DataDirectory, len);
4951 strlcat(fname, suffix, len);
4955 /** Return 0 if every setting in <b>state</b> is reasonable, and a
4956 * permissible transition from <b>old_state</b>. Else warn and return -1.
4957 * Should have no side effects, except for normalizing the contents of
4960 /* XXX from_setconf is here because of bug 238 */
4962 or_state_validate(or_state_t *old_state, or_state_t *state,
4963 int from_setconf, char **msg)
4965 /* We don't use these; only options do. Still, we need to match that
4967 (void) from_setconf;
4970 if (entry_guards_parse_state(state, 0, msg)<0)
4976 /** Replace the current persistent state with <b>new_state</b> */
4978 or_state_set(or_state_t *new_state)
4982 tor_assert(new_state);
4983 config_free(&state_format, global_state);
4984 global_state = new_state;
4985 if (entry_guards_parse_state(global_state, 1, &err)<0) {
4986 log_warn(LD_GENERAL,"%s",err);
4990 if (rep_hist_load_state(global_state, &err)<0) {
4991 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
4995 if (circuit_build_times_parse_state(&circ_times, global_state) < 0) {
5002 * Save a broken state file to a backup location.
5005 or_state_save_broken(char *fname)
5008 file_status_t status;
5009 size_t len = strlen(fname)+16;
5010 char *fname2 = tor_malloc(len);
5011 for (i = 0; i < 100; ++i) {
5012 tor_snprintf(fname2, len, "%s.%d", fname, i);
5013 status = file_status(fname2);
5014 if (status == FN_NOENT)
5018 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
5019 "state files to move aside. Discarding the old state file.",
5023 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
5024 "to \"%s\". This could be a bug in Tor; please tell "
5025 "the developers.", fname, fname2);
5026 if (rename(fname, fname2) < 0) {
5027 log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
5028 "OS gave an error of %s", strerror(errno));
5034 /** Reload the persistent state from disk, generating a new state as needed.
5035 * Return 0 on success, less than 0 on failure.
5040 or_state_t *new_state = NULL;
5041 char *contents = NULL, *fname;
5042 char *errmsg = NULL;
5043 int r = -1, badstate = 0;
5045 fname = get_datadir_fname("state");
5046 switch (file_status(fname)) {
5048 if (!(contents = read_file_to_str(fname, 0, NULL))) {
5049 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
5058 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
5061 new_state = tor_malloc_zero(sizeof(or_state_t));
5062 new_state->_magic = OR_STATE_MAGIC;
5063 config_init(&state_format, new_state);
5065 config_line_t *lines=NULL;
5067 if (config_get_lines(contents, &lines)<0)
5069 assign_retval = config_assign(&state_format, new_state,
5070 lines, 0, 0, &errmsg);
5071 config_free_lines(lines);
5072 if (assign_retval<0)
5075 log_warn(LD_GENERAL, "%s", errmsg);
5080 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
5084 log_warn(LD_GENERAL, "%s", errmsg);
5088 if (badstate && !contents) {
5089 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
5090 " This is a bug in Tor.");
5092 } else if (badstate && contents) {
5093 or_state_save_broken(fname);
5096 config_free(&state_format, new_state);
5098 new_state = tor_malloc_zero(sizeof(or_state_t));
5099 new_state->_magic = OR_STATE_MAGIC;
5100 config_init(&state_format, new_state);
5101 } else if (contents) {
5102 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
5104 log_info(LD_GENERAL, "Initialized state");
5106 if (or_state_set(new_state) == -1) {
5107 or_state_save_broken(fname);
5111 global_state->next_write = 0;
5112 or_state_save(time(NULL));
5120 config_free(&state_format, new_state);
5125 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
5127 or_state_save(time_t now)
5129 char *state, *contents;
5130 char tbuf[ISO_TIME_LEN+1];
5133 tor_assert(global_state);
5135 if (global_state->next_write > now)
5138 /* Call everything else that might dirty the state even more, in order
5139 * to avoid redundant writes. */
5140 entry_guards_update_state(global_state);
5141 rep_hist_update_state(global_state);
5142 circuit_build_times_update_state(&circ_times, global_state);
5143 if (accounting_is_enabled(get_options()))
5144 accounting_run_housekeeping(now);
5146 tor_free(global_state->TorVersion);
5147 tor_asprintf(&global_state->TorVersion, "Tor %s", get_version());
5149 state = config_dump(&state_format, global_state, 1, 0);
5150 format_local_iso_time(tbuf, time(NULL));
5151 tor_asprintf(&contents,
5152 "# Tor state file last generated on %s local time\n"
5153 "# Other times below are in GMT\n"
5154 "# You *do not* need to edit this file.\n\n%s",
5157 fname = get_datadir_fname("state");
5158 if (write_str_to_file(fname, contents, 0)<0) {
5159 log_warn(LD_FS, "Unable to write state to file \"%s\"", fname);
5160 global_state->LastWritten = -1;
5166 global_state->LastWritten = time(NULL);
5167 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
5171 global_state->next_write = TIME_MAX;
5175 /** Given a file name check to see whether the file exists but has not been
5176 * modified for a very long time. If so, remove it. */
5178 remove_file_if_very_old(const char *fname, time_t now)
5180 #define VERY_OLD_FILE_AGE (28*24*60*60)
5183 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
5184 char buf[ISO_TIME_LEN+1];
5185 format_local_iso_time(buf, st.st_mtime);
5186 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
5187 "Removing it.", fname, buf);
5192 /** Helper to implement GETINFO functions about configuration variables (not
5193 * their values). Given a "config/names" question, set *<b>answer</b> to a
5194 * new string describing the supported configuration variables and their
5197 getinfo_helper_config(control_connection_t *conn,
5198 const char *question, char **answer,
5199 const char **errmsg)
5203 if (!strcmp(question, "config/names")) {
5204 smartlist_t *sl = smartlist_create();
5206 for (i = 0; _option_vars[i].name; ++i) {
5207 config_var_t *var = &_option_vars[i];
5210 switch (var->type) {
5211 case CONFIG_TYPE_STRING: type = "String"; break;
5212 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
5213 case CONFIG_TYPE_UINT: type = "Integer"; break;
5214 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
5215 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
5216 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
5217 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
5218 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
5219 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
5220 case CONFIG_TYPE_CSV: type = "CommaList"; break;
5221 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
5222 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
5223 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
5225 case CONFIG_TYPE_OBSOLETE:
5230 tor_asprintf(&line, "%s %s\n",var->name,type);
5231 smartlist_add(sl, line);
5233 *answer = smartlist_join_strings(sl, "", 0, NULL);
5234 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));