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-2009, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
9 * \brief Code to parse and interpret configuration files.
12 #define CONFIG_PRIVATE
19 /** Enumeration of types which option values can take */
20 typedef enum config_type_t
{
21 CONFIG_TYPE_STRING
= 0, /**< An arbitrary string. */
22 CONFIG_TYPE_FILENAME
, /**< A filename: some prefixes get expanded. */
23 CONFIG_TYPE_UINT
, /**< A non-negative integer less than MAX_INT */
24 CONFIG_TYPE_INTERVAL
, /**< A number of seconds, with optional units*/
25 CONFIG_TYPE_MEMUNIT
, /**< A number of bytes, with optional units*/
26 CONFIG_TYPE_DOUBLE
, /**< A floating-point value */
27 CONFIG_TYPE_BOOL
, /**< A boolean value, expressed as 0 or 1. */
28 CONFIG_TYPE_ISOTIME
, /**< An ISO-formatted time relative to GMT. */
29 CONFIG_TYPE_CSV
, /**< A list of strings, separated by commas and
30 * optional whitespace. */
31 CONFIG_TYPE_LINELIST
, /**< Uninterpreted config lines */
32 CONFIG_TYPE_LINELIST_S
, /**< Uninterpreted, context-sensitive config lines,
33 * mixed with other keywords. */
34 CONFIG_TYPE_LINELIST_V
, /**< Catch-all "virtual" option to summarize
35 * context-sensitive config lines when fetching.
37 CONFIG_TYPE_ROUTERSET
, /**< A list of router names, addrs, and fps,
38 * parsed into a routerset_t. */
39 CONFIG_TYPE_OBSOLETE
, /**< Obsolete (ignored) option. */
42 /** An abbreviation for a configuration option allowed on the command line. */
43 typedef struct config_abbrev_t
{
44 const char *abbreviated
;
50 /* Handy macro for declaring "In the config file or on the command line,
51 * you can abbreviate <b>tok</b>s as <b>tok</b>". */
52 #define PLURAL(tok) { #tok, #tok "s", 0, 0 }
54 /** A list of abbreviations and aliases to map command-line options, obsolete
55 * option names, or alternative option names, to their current values. */
56 static config_abbrev_t _option_abbrevs
[] = {
61 PLURAL(LongLivedPort
),
62 PLURAL(HiddenServiceNode
),
63 PLURAL(HiddenServiceExcludeNode
),
66 PLURAL(RendExcludeNode
),
67 PLURAL(StrictEntryNode
),
68 PLURAL(StrictExitNode
),
70 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
71 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
72 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
73 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
74 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
75 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
76 { "MaxConn", "ConnLimit", 0, 1},
77 { "ORBindAddress", "ORListenAddress", 0, 0},
78 { "DirBindAddress", "DirListenAddress", 0, 0},
79 { "SocksBindAddress", "SocksListenAddress", 0, 0},
80 { "UseHelperNodes", "UseEntryGuards", 0, 0},
81 { "NumHelperNodes", "NumEntryGuards", 0, 0},
82 { "UseEntryNodes", "UseEntryGuards", 0, 0},
83 { "NumEntryNodes", "NumEntryGuards", 0, 0},
84 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
85 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
86 { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0 },
87 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
88 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
89 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
93 /** A list of state-file "abbreviations," for compatibility. */
94 static config_abbrev_t _state_abbrevs
[] = {
95 { "AccountingBytesReadInterval", "AccountingBytesReadInInterval", 0, 0 },
96 { "HelperNode", "EntryGuard", 0, 0 },
97 { "HelperNodeDownSince", "EntryGuardDownSince", 0, 0 },
98 { "HelperNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
99 { "EntryNode", "EntryGuard", 0, 0 },
100 { "EntryNodeDownSince", "EntryGuardDownSince", 0, 0 },
101 { "EntryNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
106 /** A variable allowed in the configuration file or on the command line. */
107 typedef struct config_var_t
{
108 const char *name
; /**< The full keyword (case insensitive). */
109 config_type_t type
; /**< How to interpret the type and turn it into a
111 off_t var_offset
; /**< Offset of the corresponding member of or_options_t. */
112 const char *initvalue
; /**< String (or null) describing initial value. */
115 /** An entry for config_vars: "The option <b>name</b> has type
116 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
117 * or_options_t.<b>member</b>"
119 #define VAR(name,conftype,member,initvalue) \
120 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
122 /** As VAR, but the option name and member name are the same. */
123 #define V(member,conftype,initvalue) \
124 VAR(#member, conftype, member, initvalue)
125 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
126 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
128 /** Array of configuration options. Until we disallow nonstandard
129 * abbreviations, order is significant, since the first matching option will
132 static config_var_t _option_vars
[] = {
133 OBSOLETE("AccountingMaxKB"),
134 V(AccountingMax
, MEMUNIT
, "0 bytes"),
135 V(AccountingStart
, STRING
, NULL
),
136 V(Address
, STRING
, NULL
),
137 V(AllowDotExit
, BOOL
, "0"),
138 V(AllowInvalidNodes
, CSV
, "middle,rendezvous"),
139 V(AllowNonRFC953Hostnames
, BOOL
, "0"),
140 V(AllowSingleHopCircuits
, BOOL
, "0"),
141 V(AllowSingleHopExits
, BOOL
, "0"),
142 V(AlternateBridgeAuthority
, LINELIST
, NULL
),
143 V(AlternateDirAuthority
, LINELIST
, NULL
),
144 V(AlternateHSAuthority
, LINELIST
, NULL
),
145 V(AssumeReachable
, BOOL
, "0"),
146 V(AuthDirBadDir
, LINELIST
, NULL
),
147 V(AuthDirBadExit
, LINELIST
, NULL
),
148 V(AuthDirInvalid
, LINELIST
, NULL
),
149 V(AuthDirReject
, LINELIST
, NULL
),
150 V(AuthDirRejectUnlisted
, BOOL
, "0"),
151 V(AuthDirListBadDirs
, BOOL
, "0"),
152 V(AuthDirListBadExits
, BOOL
, "0"),
153 V(AuthDirMaxServersPerAddr
, UINT
, "2"),
154 V(AuthDirMaxServersPerAuthAddr
,UINT
, "5"),
155 VAR("AuthoritativeDirectory", BOOL
, AuthoritativeDir
, "0"),
156 V(AutomapHostsOnResolve
, BOOL
, "0"),
157 V(AutomapHostsSuffixes
, CSV
, ".onion,.exit"),
158 V(AvoidDiskWrites
, BOOL
, "0"),
159 V(BandwidthBurst
, MEMUNIT
, "10 MB"),
160 V(BandwidthRate
, MEMUNIT
, "5 MB"),
161 V(BridgeAuthoritativeDir
, BOOL
, "0"),
162 VAR("Bridge", LINELIST
, Bridges
, NULL
),
163 V(BridgePassword
, STRING
, NULL
),
164 V(BridgeRecordUsageByCountry
, BOOL
, "1"),
165 V(BridgeRelay
, BOOL
, "0"),
166 V(CellStatistics
, BOOL
, "0"),
167 V(CircuitBuildTimeout
, INTERVAL
, "0"),
168 V(CircuitIdleTimeout
, INTERVAL
, "1 hour"),
169 V(CircuitStreamTimeout
, INTERVAL
, "0"),
170 V(ClientDNSRejectInternalAddresses
, BOOL
,"1"),
171 V(ClientOnly
, BOOL
, "0"),
172 V(ConsensusParams
, STRING
, NULL
),
173 V(ConnLimit
, UINT
, "1000"),
174 V(ConstrainedSockets
, BOOL
, "0"),
175 V(ConstrainedSockSize
, MEMUNIT
, "8192"),
176 V(ContactInfo
, STRING
, NULL
),
177 V(ControlListenAddress
, LINELIST
, NULL
),
178 V(ControlPort
, UINT
, "0"),
179 V(ControlSocket
, LINELIST
, NULL
),
180 V(CookieAuthentication
, BOOL
, "0"),
181 V(CookieAuthFileGroupReadable
, BOOL
, "0"),
182 V(CookieAuthFile
, STRING
, NULL
),
183 V(DataDirectory
, FILENAME
, NULL
),
184 OBSOLETE("DebugLogFile"),
185 V(DirAllowPrivateAddresses
, BOOL
, NULL
),
186 V(TestingAuthDirTimeToLearnReachability
, INTERVAL
, "30 minutes"),
187 V(DirListenAddress
, LINELIST
, NULL
),
188 OBSOLETE("DirFetchPeriod"),
189 V(DirPolicy
, LINELIST
, NULL
),
190 V(DirPort
, UINT
, "0"),
191 V(DirPortFrontPage
, FILENAME
, NULL
),
192 OBSOLETE("DirPostPeriod"),
193 OBSOLETE("DirRecordUsageByCountry"),
194 OBSOLETE("DirRecordUsageGranularity"),
195 OBSOLETE("DirRecordUsageRetainIPs"),
196 OBSOLETE("DirRecordUsageSaveInterval"),
197 V(DirReqStatistics
, BOOL
, "0"),
198 VAR("DirServer", LINELIST
, DirServers
, NULL
),
199 V(DisableAllSwap
, BOOL
, "0"),
200 V(DNSPort
, UINT
, "0"),
201 V(DNSListenAddress
, LINELIST
, NULL
),
202 V(DownloadExtraInfo
, BOOL
, "0"),
203 V(EnforceDistinctSubnets
, BOOL
, "1"),
204 V(EntryNodes
, ROUTERSET
, NULL
),
205 V(EntryStatistics
, BOOL
, "0"),
206 V(TestingEstimatedDescriptorPropagationTime
, INTERVAL
, "10 minutes"),
207 V(ExcludeNodes
, ROUTERSET
, NULL
),
208 V(ExcludeExitNodes
, ROUTERSET
, NULL
),
209 V(ExcludeSingleHopRelays
, BOOL
, "1"),
210 V(ExitNodes
, ROUTERSET
, NULL
),
211 V(ExitPolicy
, LINELIST
, NULL
),
212 V(ExitPolicyRejectPrivate
, BOOL
, "1"),
213 V(ExitPortStatistics
, BOOL
, "0"),
214 V(ExtraInfoStatistics
, BOOL
, "0"),
215 V(FallbackNetworkstatusFile
, FILENAME
,
216 SHARE_DATADIR PATH_SEPARATOR
"tor" PATH_SEPARATOR
"fallback-consensus"),
217 V(FascistFirewall
, BOOL
, "0"),
218 V(FirewallPorts
, CSV
, ""),
219 V(FastFirstHopPK
, BOOL
, "1"),
220 V(FetchDirInfoEarly
, BOOL
, "0"),
221 V(FetchDirInfoExtraEarly
, BOOL
, "0"),
222 V(FetchServerDescriptors
, BOOL
, "1"),
223 V(FetchHidServDescriptors
, BOOL
, "1"),
224 V(FetchUselessDescriptors
, BOOL
, "0"),
226 V(GeoIPFile
, FILENAME
, "<default>"),
228 V(GeoIPFile
, FILENAME
,
229 SHARE_DATADIR PATH_SEPARATOR
"tor" PATH_SEPARATOR
"geoip"),
232 V(HardwareAccel
, BOOL
, "0"),
233 V(AccelName
, STRING
, NULL
),
234 V(AccelDir
, FILENAME
, NULL
),
235 V(HashedControlPassword
, LINELIST
, NULL
),
236 V(HidServDirectoryV2
, BOOL
, "1"),
237 VAR("HiddenServiceDir", LINELIST_S
, RendConfigLines
, NULL
),
238 OBSOLETE("HiddenServiceExcludeNodes"),
239 OBSOLETE("HiddenServiceNodes"),
240 VAR("HiddenServiceOptions",LINELIST_V
, RendConfigLines
, NULL
),
241 VAR("HiddenServicePort", LINELIST_S
, RendConfigLines
, NULL
),
242 VAR("HiddenServiceVersion",LINELIST_S
, RendConfigLines
, NULL
),
243 VAR("HiddenServiceAuthorizeClient",LINELIST_S
,RendConfigLines
, NULL
),
244 V(HidServAuth
, LINELIST
, NULL
),
245 V(HSAuthoritativeDir
, BOOL
, "0"),
246 V(HSAuthorityRecordStats
, BOOL
, "0"),
247 V(HttpProxy
, STRING
, NULL
),
248 V(HttpProxyAuthenticator
, STRING
, NULL
),
249 V(HttpsProxy
, STRING
, NULL
),
250 V(HttpsProxyAuthenticator
, STRING
, NULL
),
251 V(Socks4Proxy
, STRING
, NULL
),
252 V(Socks5Proxy
, STRING
, NULL
),
253 V(Socks5ProxyUsername
, STRING
, NULL
),
254 V(Socks5ProxyPassword
, STRING
, NULL
),
255 OBSOLETE("IgnoreVersion"),
256 V(KeepalivePeriod
, INTERVAL
, "5 minutes"),
257 VAR("Log", LINELIST
, Logs
, NULL
),
258 OBSOLETE("LinkPadding"),
259 OBSOLETE("LogLevel"),
261 V(LongLivedPorts
, CSV
,
262 "21,22,706,1863,5050,5190,5222,5223,6667,6697,8300"),
263 VAR("MapAddress", LINELIST
, AddressMap
, NULL
),
264 V(MaxAdvertisedBandwidth
, MEMUNIT
, "1 GB"),
265 V(MaxCircuitDirtiness
, INTERVAL
, "10 minutes"),
266 V(MaxOnionsPending
, UINT
, "100"),
267 OBSOLETE("MonthlyAccountingStart"),
268 V(MyFamily
, STRING
, NULL
),
269 V(NewCircuitPeriod
, INTERVAL
, "30 seconds"),
270 VAR("NamingAuthoritativeDirectory",BOOL
, NamingAuthoritativeDir
, "0"),
271 V(NatdListenAddress
, LINELIST
, NULL
),
272 V(NatdPort
, UINT
, "0"),
273 V(Nickname
, STRING
, NULL
),
274 V(NoPublish
, BOOL
, "0"),
275 VAR("NodeFamily", LINELIST
, NodeFamilies
, NULL
),
276 V(NumCpus
, UINT
, "1"),
277 V(NumEntryGuards
, UINT
, "3"),
278 V(ORListenAddress
, LINELIST
, NULL
),
279 V(ORPort
, UINT
, "0"),
280 V(OutboundBindAddress
, STRING
, NULL
),
281 OBSOLETE("PathlenCoinWeight"),
282 V(PidFile
, STRING
, NULL
),
283 V(TestingTorNetwork
, BOOL
, "0"),
284 V(PreferTunneledDirConns
, BOOL
, "1"),
285 V(ProtocolWarnings
, BOOL
, "0"),
286 V(PublishServerDescriptor
, CSV
, "1"),
287 V(PublishHidServDescriptors
, BOOL
, "1"),
288 V(ReachableAddresses
, LINELIST
, NULL
),
289 V(ReachableDirAddresses
, LINELIST
, NULL
),
290 V(ReachableORAddresses
, LINELIST
, NULL
),
291 V(RecommendedVersions
, LINELIST
, NULL
),
292 V(RecommendedClientVersions
, LINELIST
, NULL
),
293 V(RecommendedServerVersions
, LINELIST
, NULL
),
294 OBSOLETE("RedirectExit"),
295 V(RejectPlaintextPorts
, CSV
, ""),
296 V(RelayBandwidthBurst
, MEMUNIT
, "0"),
297 V(RelayBandwidthRate
, MEMUNIT
, "0"),
298 OBSOLETE("RendExcludeNodes"),
299 OBSOLETE("RendNodes"),
300 V(RendPostPeriod
, INTERVAL
, "1 hour"),
301 V(RephistTrackTime
, INTERVAL
, "24 hours"),
302 OBSOLETE("RouterFile"),
303 V(RunAsDaemon
, BOOL
, "0"),
304 V(RunTesting
, BOOL
, "0"),
305 V(SafeLogging
, BOOL
, "1"),
306 V(SafeSocks
, BOOL
, "0"),
307 V(ServerDNSAllowBrokenConfig
, BOOL
, "1"),
308 V(ServerDNSAllowNonRFC953Hostnames
, BOOL
,"0"),
309 V(ServerDNSDetectHijacking
, BOOL
, "1"),
310 V(ServerDNSRandomizeCase
, BOOL
, "1"),
311 V(ServerDNSResolvConfFile
, STRING
, NULL
),
312 V(ServerDNSSearchDomains
, BOOL
, "0"),
313 V(ServerDNSTestAddresses
, CSV
,
314 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
315 V(ShutdownWaitLength
, INTERVAL
, "30 seconds"),
316 V(SocksListenAddress
, LINELIST
, NULL
),
317 V(SocksPolicy
, LINELIST
, NULL
),
318 V(SocksPort
, UINT
, "9050"),
319 V(SocksTimeout
, INTERVAL
, "2 minutes"),
320 OBSOLETE("StatusFetchPeriod"),
321 V(StrictEntryNodes
, BOOL
, "0"),
322 V(StrictExitNodes
, BOOL
, "0"),
324 V(TestSocks
, BOOL
, "0"),
326 V(TrackHostExits
, CSV
, NULL
),
327 V(TrackHostExitsExpire
, INTERVAL
, "30 minutes"),
328 OBSOLETE("TrafficShaping"),
329 V(TransListenAddress
, LINELIST
, NULL
),
330 V(TransPort
, UINT
, "0"),
331 V(TunnelDirConns
, BOOL
, "1"),
332 V(UpdateBridgesFromAuthority
, BOOL
, "0"),
333 V(UseBridges
, BOOL
, "0"),
334 V(UseEntryGuards
, BOOL
, "1"),
335 V(User
, STRING
, NULL
),
336 VAR("V1AuthoritativeDirectory",BOOL
, V1AuthoritativeDir
, "0"),
337 VAR("V2AuthoritativeDirectory",BOOL
, V2AuthoritativeDir
, "0"),
338 VAR("V3AuthoritativeDirectory",BOOL
, V3AuthoritativeDir
, "0"),
339 V(TestingV3AuthInitialVotingInterval
, INTERVAL
, "30 minutes"),
340 V(TestingV3AuthInitialVoteDelay
, INTERVAL
, "5 minutes"),
341 V(TestingV3AuthInitialDistDelay
, INTERVAL
, "5 minutes"),
342 V(V3AuthVotingInterval
, INTERVAL
, "1 hour"),
343 V(V3AuthVoteDelay
, INTERVAL
, "5 minutes"),
344 V(V3AuthDistDelay
, INTERVAL
, "5 minutes"),
345 V(V3AuthNIntervalsValid
, UINT
, "3"),
346 V(V3AuthUseLegacyKey
, BOOL
, "0"),
347 V(V3BandwidthsFile
, FILENAME
, NULL
),
348 VAR("VersioningAuthoritativeDirectory",BOOL
,VersioningAuthoritativeDir
, "0"),
349 V(VirtualAddrNetwork
, STRING
, "127.192.0.0/10"),
350 V(WarnPlaintextPorts
, CSV
, "23,109,110,143"),
351 VAR("__ReloadTorrcOnSIGHUP", BOOL
, ReloadTorrcOnSIGHUP
, "1"),
352 VAR("__AllDirActionsPrivate", BOOL
, AllDirActionsPrivate
, "0"),
353 VAR("__DisablePredictedCircuits",BOOL
,DisablePredictedCircuits
, "0"),
354 VAR("__LeaveStreamsUnattached",BOOL
, LeaveStreamsUnattached
, "0"),
355 VAR("__HashedControlSessionPassword", LINELIST
, HashedControlSessionPassword
,
357 V(MinUptimeHidServDirectoryV2
, INTERVAL
, "24 hours"),
359 /* Options for EWMA selection of circuit to write from */
360 VAR("EWMASignificance", DOUBLE
, EWMASignificance
, "-1.0"),
361 VAR("EWMAInterval", DOUBLE
, EWMAInterval
, "-1.0"),
363 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
366 /** Override default values with these if the user sets the TestingTorNetwork
368 static config_var_t testing_tor_network_defaults
[] = {
369 V(ServerDNSAllowBrokenConfig
, BOOL
, "1"),
370 V(DirAllowPrivateAddresses
, BOOL
, "1"),
371 V(EnforceDistinctSubnets
, BOOL
, "0"),
372 V(AssumeReachable
, BOOL
, "1"),
373 V(AuthDirMaxServersPerAddr
, UINT
, "0"),
374 V(AuthDirMaxServersPerAuthAddr
,UINT
, "0"),
375 V(ClientDNSRejectInternalAddresses
, BOOL
,"0"),
376 V(ExitPolicyRejectPrivate
, BOOL
, "0"),
377 V(V3AuthVotingInterval
, INTERVAL
, "5 minutes"),
378 V(V3AuthVoteDelay
, INTERVAL
, "20 seconds"),
379 V(V3AuthDistDelay
, INTERVAL
, "20 seconds"),
380 V(TestingV3AuthInitialVotingInterval
, INTERVAL
, "5 minutes"),
381 V(TestingV3AuthInitialVoteDelay
, INTERVAL
, "20 seconds"),
382 V(TestingV3AuthInitialDistDelay
, INTERVAL
, "20 seconds"),
383 V(TestingAuthDirTimeToLearnReachability
, INTERVAL
, "0 minutes"),
384 V(TestingEstimatedDescriptorPropagationTime
, INTERVAL
, "0 minutes"),
385 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
389 #define VAR(name,conftype,member,initvalue) \
390 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
393 /** Array of "state" variables saved to the ~/.tor/state file. */
394 static config_var_t _state_vars
[] = {
395 V(AccountingBytesReadInInterval
, MEMUNIT
, NULL
),
396 V(AccountingBytesWrittenInInterval
, MEMUNIT
, NULL
),
397 V(AccountingExpectedUsage
, MEMUNIT
, NULL
),
398 V(AccountingIntervalStart
, ISOTIME
, NULL
),
399 V(AccountingSecondsActive
, INTERVAL
, NULL
),
401 VAR("EntryGuard", LINELIST_S
, EntryGuards
, NULL
),
402 VAR("EntryGuardDownSince", LINELIST_S
, EntryGuards
, NULL
),
403 VAR("EntryGuardUnlistedSince", LINELIST_S
, EntryGuards
, NULL
),
404 VAR("EntryGuardAddedBy", LINELIST_S
, EntryGuards
, NULL
),
405 V(EntryGuards
, LINELIST_V
, NULL
),
407 V(BWHistoryReadEnds
, ISOTIME
, NULL
),
408 V(BWHistoryReadInterval
, UINT
, "900"),
409 V(BWHistoryReadValues
, CSV
, ""),
410 V(BWHistoryWriteEnds
, ISOTIME
, NULL
),
411 V(BWHistoryWriteInterval
, UINT
, "900"),
412 V(BWHistoryWriteValues
, CSV
, ""),
414 V(TorVersion
, STRING
, NULL
),
416 V(LastRotatedOnionKey
, ISOTIME
, NULL
),
417 V(LastWritten
, ISOTIME
, NULL
),
419 V(TotalBuildTimes
, UINT
, NULL
),
420 VAR("CircuitBuildTimeBin", LINELIST_S
, BuildtimeHistogram
, NULL
),
421 VAR("BuildtimeHistogram", LINELIST_V
, BuildtimeHistogram
, NULL
),
423 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
430 /** Represents an English description of a configuration variable; used when
431 * generating configuration file comments. */
432 typedef struct config_var_description_t
{
434 const char *description
;
435 } config_var_description_t
;
437 /** Descriptions of the configuration options, to be displayed by online
439 /* XXXX022 did anybody want this? at all? If not, kill it.*/
440 static config_var_description_t options_description
[] = {
441 /* ==== general options */
442 { "AvoidDiskWrites", "If non-zero, try to write to disk less frequently than"
443 " we would otherwise." },
444 { "BandwidthRate", "A token bucket limits the average incoming bandwidth on "
445 "this node to the specified number of bytes per second." },
446 { "BandwidthBurst", "Limit the maximum token buffer size (also known as "
447 "burst) to the given number of bytes." },
448 { "ConnLimit", "Minimum number of simultaneous sockets we must have." },
449 { "ConstrainedSockets", "Shrink tx and rx buffers for sockets to avoid "
450 "system limits on vservers and related environments. See man page for "
451 "more information regarding this option." },
452 { "ConstrainedSockSize", "Limit socket buffers to this size when "
453 "ConstrainedSockets is enabled." },
454 /* ControlListenAddress */
455 { "ControlPort", "If set, Tor will accept connections from the same machine "
456 "(localhost only) on this port, and allow those connections to control "
457 "the Tor process using the Tor Control Protocol (described in "
458 "control-spec.txt).", },
459 { "CookieAuthentication", "If this option is set to 1, don't allow any "
460 "connections to the control port except when the connecting process "
461 "can read a file that Tor creates in its data directory." },
462 { "DataDirectory", "Store working data, state, keys, and caches here." },
463 { "DirServer", "Tor only trusts directories signed with one of these "
464 "servers' keys. Used to override the standard list of directory "
466 { "DisableAllSwap", "Tor will attempt a simple memory lock that "
467 "will prevent leaking of all information in memory to the swap file." },
468 /* { "FastFirstHopPK", "" }, */
469 /* FetchServerDescriptors, FetchHidServDescriptors,
470 * FetchUselessDescriptors */
471 { "HardwareAccel", "If set, Tor tries to use hardware crypto accelerators "
473 { "AccelName", "If set, try to use hardware crypto accelerator with this "
475 { "AccelDir", "If set, look in this directory for the dynamic hardware "
476 "engine in addition to OpenSSL default path." },
477 /* HashedControlPassword */
478 { "HTTPProxy", "Force Tor to make all HTTP directory requests through this "
479 "host:port (or host:80 if port is not set)." },
480 { "HTTPProxyAuthenticator", "A username:password pair to be used with "
482 { "HTTPSProxy", "Force Tor to make all TLS (SSL) connections through this "
483 "host:port (or host:80 if port is not set)." },
484 { "HTTPSProxyAuthenticator", "A username:password pair to be used with "
486 { "KeepalivePeriod", "Send a padding cell every N seconds to keep firewalls "
487 "from closing our connections while Tor is not in use." },
488 { "Log", "Where to send logging messages. Format is "
489 "minSeverity[-maxSeverity] (stderr|stdout|syslog|file FILENAME)." },
490 { "OutboundBindAddress", "Make all outbound connections originate from the "
491 "provided IP address (only useful for multiple network interfaces)." },
492 { "PIDFile", "On startup, write our PID to this file. On clean shutdown, "
493 "remove the file." },
494 { "PreferTunneledDirConns", "If non-zero, avoid directory servers that "
495 "don't support tunneled connections." },
496 /* PreferTunneledDirConns */
497 /* ProtocolWarnings */
498 /* RephistTrackTime */
499 { "RunAsDaemon", "If set, Tor forks and daemonizes to the background when "
500 "started. Unix only." },
501 { "SafeLogging", "If set to 0, Tor logs potentially sensitive strings "
502 "rather than replacing them with the string [scrubbed]." },
503 { "TunnelDirConns", "If non-zero, when a directory server we contact "
504 "supports it, we will build a one-hop circuit and make an encrypted "
505 "connection via its ORPort." },
506 { "User", "On startup, setuid to this user." },
508 /* ==== client options */
509 { "AllowInvalidNodes", "Where on our circuits should Tor allow servers "
510 "that the directory authorities haven't called \"valid\"?" },
511 { "AllowNonRFC953Hostnames", "If set to 1, we don't automatically reject "
512 "hostnames for having invalid characters." },
513 /* CircuitBuildTimeout, CircuitIdleTimeout */
514 { "ClientOnly", "If set to 1, Tor will under no circumstances run as a "
515 "server, even if ORPort is enabled." },
516 { "EntryNodes", "A list of preferred entry nodes to use for the first hop "
517 "in circuits, when possible." },
518 /* { "EnforceDistinctSubnets" , "" }, */
519 { "ExitNodes", "A list of preferred nodes to use for the last hop in "
520 "circuits, when possible." },
521 { "ExcludeNodes", "A list of nodes never to use when building a circuit." },
522 { "FascistFirewall", "If set, Tor will only create outgoing connections to "
523 "servers running on the ports listed in FirewallPorts." },
524 { "FirewallPorts", "A list of ports that we can connect to. Only used "
525 "when FascistFirewall is set." },
526 { "LongLivedPorts", "A list of ports for services that tend to require "
527 "high-uptime connections." },
528 { "MapAddress", "Force Tor to treat all requests for one address as if "
529 "they were for another." },
530 { "NewCircuitPeriod", "Force Tor to consider whether to build a new circuit "
531 "every NUM seconds." },
532 { "MaxCircuitDirtiness", "Do not attach new streams to a circuit that has "
533 "been used more than this many seconds ago." },
534 /* NatdPort, NatdListenAddress */
535 { "NodeFamily", "A list of servers that constitute a 'family' and should "
536 "never be used in the same circuit." },
537 { "NumEntryGuards", "How many entry guards should we keep at a time?" },
538 /* PathlenCoinWeight */
539 { "ReachableAddresses", "Addresses we can connect to, as IP/bits:port-port. "
540 "By default, we assume all addresses are reachable." },
541 /* reachablediraddresses, reachableoraddresses. */
543 { "SOCKSPort", "The port where we listen for SOCKS connections from "
545 { "SOCKSListenAddress", "Bind to this address to listen to connections from "
546 "SOCKS-speaking applications." },
547 { "SOCKSPolicy", "Set an entry policy to limit which addresses can connect "
548 "to the SOCKSPort." },
550 { "StrictExitNodes", "If set, Tor will fail to operate when none of the "
551 "configured ExitNodes can be used." },
552 { "StrictEntryNodes", "If set, Tor will fail to operate when none of the "
553 "configured EntryNodes can be used." },
555 { "TrackHostsExit", "Hosts and domains which should, if possible, be "
556 "accessed from the same exit node each time we connect to them." },
557 { "TrackHostsExitExpire", "Time after which we forget which exit we were "
558 "using to connect to hosts in TrackHostsExit." },
559 /* "TransPort", "TransListenAddress */
560 { "UseEntryGuards", "Set to 0 if we want to pick from the whole set of "
561 "servers for the first position in each circuit, rather than picking a "
562 "set of 'Guards' to prevent profiling attacks." },
564 /* === server options */
565 { "Address", "The advertised (external) address we should use." },
566 /* Accounting* options. */
567 /* AssumeReachable */
568 { "ContactInfo", "Administrative contact information to advertise for this "
570 { "ExitPolicy", "Address/port ranges for which to accept or reject outgoing "
571 "connections on behalf of Tor users." },
572 /* { "ExitPolicyRejectPrivate, "" }, */
573 { "MaxAdvertisedBandwidth", "If set, we will not advertise more than this "
574 "amount of bandwidth for our bandwidth rate, regardless of how much "
575 "bandwidth we actually detect." },
576 { "MaxOnionsPending", "Reject new attempts to extend circuits when we "
577 "already have this many pending." },
578 { "MyFamily", "Declare a list of other servers as belonging to the same "
579 "family as this one, so that clients will not use two from the same "
580 "family in the same circuit." },
581 { "Nickname", "Set the server nickname." },
582 { "NoPublish", "{DEPRECATED}" },
583 { "NumCPUs", "How many processes to use at once for public-key crypto." },
584 { "ORPort", "Advertise this port to listen for connections from Tor clients "
586 { "ORListenAddress", "Bind to this address to listen for connections from "
587 "clients and servers, instead of the default 0.0.0.0:ORPort." },
588 { "PublishServerDescriptor", "Set to 0 to keep the server from "
589 "uploading info to the directory authorities." },
590 /* ServerDNS: DetectHijacking, ResolvConfFile, SearchDomains */
591 { "ShutdownWaitLength", "Wait this long for clients to finish when "
592 "shutting down because of a SIGINT." },
594 /* === directory cache options */
595 { "DirPort", "Serve directory information from this port, and act as a "
596 "directory cache." },
597 { "DirPortFrontPage", "Serve a static html disclaimer on DirPort." },
598 { "DirListenAddress", "Bind to this address to listen for connections from "
599 "clients and servers, instead of the default 0.0.0.0:DirPort." },
600 { "DirPolicy", "Set a policy to limit who can connect to the directory "
603 /* Authority options: AuthDirBadExit, AuthDirInvalid, AuthDirReject,
604 * AuthDirRejectUnlisted, AuthDirListBadExits, AuthoritativeDirectory,
605 * DirAllowPrivateAddresses, HSAuthoritativeDir,
606 * NamingAuthoritativeDirectory, RecommendedVersions,
607 * RecommendedClientVersions, RecommendedServerVersions, RendPostPeriod,
608 * RunTesting, V1AuthoritativeDirectory, VersioningAuthoritativeDirectory, */
610 /* Hidden service options: HiddenService: dir,excludenodes, nodes,
611 * options, port. PublishHidServDescriptor */
613 /* Circuit build time histogram options */
614 { "CircuitBuildTimeBin", "Histogram of recent circuit build times"},
615 { "TotalBuildTimes", "Total number of buildtimes in histogram"},
617 /* Nonpersistent options: __LeaveStreamsUnattached, __AllDirActionsPrivate */
621 /** Online description of state variables. */
622 static config_var_description_t state_description
[] = {
623 { "AccountingBytesReadInInterval",
624 "How many bytes have we read in this accounting period?" },
625 { "AccountingBytesWrittenInInterval",
626 "How many bytes have we written in this accounting period?" },
627 { "AccountingExpectedUsage",
628 "How many bytes did we expect to use per minute? (0 for no estimate.)" },
629 { "AccountingIntervalStart", "When did this accounting period begin?" },
630 { "AccountingSecondsActive", "How long have we been awake in this period?" },
632 { "BWHistoryReadEnds", "When does the last-recorded read-interval end?" },
633 { "BWHistoryReadInterval", "How long is each read-interval (in seconds)?" },
634 { "BWHistoryReadValues", "Number of bytes read in each interval." },
635 { "BWHistoryWriteEnds", "When does the last-recorded write-interval end?" },
636 { "BWHistoryWriteInterval", "How long is each write-interval (in seconds)?"},
637 { "BWHistoryWriteValues", "Number of bytes written in each interval." },
639 { "EntryGuard", "One of the nodes we have chosen as a fixed entry" },
640 { "EntryGuardDownSince",
641 "The last entry guard has been unreachable since this time." },
642 { "EntryGuardUnlistedSince",
643 "The last entry guard has been unusable since this time." },
645 { "LastRotatedOnionKey",
646 "The last time at which we changed the medium-term private key used for "
647 "building circuits." },
648 { "LastWritten", "When was this state file last regenerated?" },
650 { "TorVersion", "Which version of Tor generated this state file?" },
654 /** Type of a callback to validate whether a given configuration is
655 * well-formed and consistent. See options_trial_assign() for documentation
657 typedef int (*validate_fn_t
)(void*,void*,int,char**);
659 /** Information on the keys, value types, key-to-struct-member mappings,
660 * variable descriptions, validation functions, and abbreviations for a
661 * configuration or storage format. */
663 size_t size
; /**< Size of the struct that everything gets parsed into. */
664 uint32_t magic
; /**< Required 'magic value' to make sure we have a struct
665 * of the right type. */
666 off_t magic_offset
; /**< Offset of the magic value within the struct. */
667 config_abbrev_t
*abbrevs
; /**< List of abbreviations that we expand when
668 * parsing this format. */
669 config_var_t
*vars
; /**< List of variables we recognize, their default
670 * values, and where we stick them in the structure. */
671 validate_fn_t validate_fn
; /**< Function to validate config. */
672 /** Documentation for configuration variables. */
673 config_var_description_t
*descriptions
;
674 /** If present, extra is a LINELIST variable for unrecognized
675 * lines. Otherwise, unrecognized lines are an error. */
679 /** Macro: assert that <b>cfg</b> has the right magic field for format
681 #define CHECK(fmt, cfg) STMT_BEGIN \
682 tor_assert(fmt && cfg); \
683 tor_assert((fmt)->magic == \
684 *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
688 static char *get_windows_conf_root(void);
690 static void config_line_append(config_line_t
**lst
,
691 const char *key
, const char *val
);
692 static void option_clear(config_format_t
*fmt
, or_options_t
*options
,
694 static void option_reset(config_format_t
*fmt
, or_options_t
*options
,
695 config_var_t
*var
, int use_defaults
);
696 static void config_free(config_format_t
*fmt
, void *options
);
697 static int config_lines_eq(config_line_t
*a
, config_line_t
*b
);
698 static int option_is_same(config_format_t
*fmt
,
699 or_options_t
*o1
, or_options_t
*o2
,
701 static or_options_t
*options_dup(config_format_t
*fmt
, or_options_t
*old
);
702 static int options_validate(or_options_t
*old_options
, or_options_t
*options
,
703 int from_setconf
, char **msg
);
704 static int options_act_reversible(or_options_t
*old_options
, char **msg
);
705 static int options_act(or_options_t
*old_options
);
706 static int options_transition_allowed(or_options_t
*old
, or_options_t
*new,
708 static int options_transition_affects_workers(or_options_t
*old_options
,
709 or_options_t
*new_options
);
710 static int options_transition_affects_descriptor(or_options_t
*old_options
,
711 or_options_t
*new_options
);
712 static int check_nickname_list(const char *lst
, const char *name
, char **msg
);
713 static void config_register_addressmaps(or_options_t
*options
);
715 static int parse_bridge_line(const char *line
, int validate_only
);
716 static int parse_dir_server_line(const char *line
,
717 authority_type_t required_type
,
719 static int validate_data_directory(or_options_t
*options
);
720 static int write_configuration_file(const char *fname
, or_options_t
*options
);
721 static config_line_t
*get_assigned_option(config_format_t
*fmt
,
722 void *options
, const char *key
,
724 static void config_init(config_format_t
*fmt
, void *options
);
725 static int or_state_validate(or_state_t
*old_options
, or_state_t
*options
,
726 int from_setconf
, char **msg
);
727 static int or_state_load(void);
728 static int options_init_logs(or_options_t
*options
, int validate_only
);
730 static int is_listening_on_low_port(uint16_t port_option
,
731 const config_line_t
*listen_options
);
733 static uint64_t config_parse_memunit(const char *s
, int *ok
);
734 static int config_parse_interval(const char *s
, int *ok
);
735 static void init_libevent(void);
736 static int opt_streq(const char *s1
, const char *s2
);
738 /** Magic value for or_options_t. */
739 #define OR_OPTIONS_MAGIC 9090909
741 /** Configuration format for or_options_t. */
742 static config_format_t options_format
= {
743 sizeof(or_options_t
),
745 STRUCT_OFFSET(or_options_t
, _magic
),
748 (validate_fn_t
)options_validate
,
753 /** Magic value for or_state_t. */
754 #define OR_STATE_MAGIC 0x57A73f57
756 /** "Extra" variable in the state that receives lines we can't parse. This
757 * lets us preserve options from versions of Tor newer than us. */
758 static config_var_t state_extra_var
= {
759 "__extra", CONFIG_TYPE_LINELIST
, STRUCT_OFFSET(or_state_t
, ExtraLines
), NULL
762 /** Configuration format for or_state_t. */
763 static config_format_t state_format
= {
766 STRUCT_OFFSET(or_state_t
, _magic
),
769 (validate_fn_t
)or_state_validate
,
775 * Functions to read and write the global options pointer.
778 /** Command-line and config-file options. */
779 static or_options_t
*global_options
= NULL
;
780 /** Name of most recently read torrc file. */
781 static char *torrc_fname
= NULL
;
782 /** Persistent serialized state. */
783 static or_state_t
*global_state
= NULL
;
784 /** Configuration Options set by command line. */
785 static config_line_t
*global_cmdline_options
= NULL
;
786 /** Contents of most recently read DirPortFrontPage file. */
787 static char *global_dirfrontpagecontents
= NULL
;
789 /** Return the contents of our frontpage string, or NULL if not configured. */
791 get_dirportfrontpage(void)
793 return global_dirfrontpagecontents
;
796 /** Allocate an empty configuration object of a given format type. */
798 config_alloc(config_format_t
*fmt
)
800 void *opts
= tor_malloc_zero(fmt
->size
);
801 *(uint32_t*)STRUCT_VAR_P(opts
, fmt
->magic_offset
) = fmt
->magic
;
806 /** Return the currently configured options. */
810 tor_assert(global_options
);
811 return global_options
;
814 /** Change the current global options to contain <b>new_val</b> instead of
815 * their current value; take action based on the new value; free the old value
816 * as necessary. Returns 0 on success, -1 on failure.
819 set_options(or_options_t
*new_val
, char **msg
)
821 or_options_t
*old_options
= global_options
;
822 global_options
= new_val
;
823 /* Note that we pass the *old* options below, for comparison. It
824 * pulls the new options directly out of global_options. */
825 if (options_act_reversible(old_options
, msg
)<0) {
827 global_options
= old_options
;
830 if (options_act(old_options
) < 0) { /* acting on the options failed. die. */
832 "Acting on config options left us in a broken state. Dying.");
836 config_free(&options_format
, old_options
);
841 extern const char tor_git_revision
[]; /* from tor_main.c */
843 /** The version of this Tor process, as parsed. */
844 static char *_version
= NULL
;
846 /** Return the current Tor version. */
850 if (_version
== NULL
) {
851 if (strlen(tor_git_revision
)) {
852 size_t len
= strlen(VERSION
)+strlen(tor_git_revision
)+16;
853 _version
= tor_malloc(len
);
854 tor_snprintf(_version
, len
, "%s (git-%s)", VERSION
, tor_git_revision
);
856 _version
= tor_strdup(VERSION
);
862 /** Release additional memory allocated in options
865 or_options_free(or_options_t
*options
)
870 routerset_free(options
->_ExcludeExitNodesUnion
);
871 config_free(&options_format
, options
);
874 /** Release all memory and resources held by global configuration structures.
877 config_free_all(void)
879 or_options_free(global_options
);
880 global_options
= NULL
;
882 config_free(&state_format
, global_state
);
885 config_free_lines(global_cmdline_options
);
886 global_cmdline_options
= NULL
;
888 tor_free(torrc_fname
);
890 tor_free(global_dirfrontpagecontents
);
893 /** If options->SafeLogging is on, return a not very useful string,
894 * else return address.
897 safe_str(const char *address
)
900 if (get_options()->SafeLogging
)
906 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
907 * escaped(): don't use this outside the main thread, or twice in the same
910 escaped_safe_str(const char *address
)
912 if (get_options()->SafeLogging
)
915 return escaped(address
);
918 /** Add the default directory authorities directly into the trusted dir list,
919 * but only add them insofar as they share bits with <b>type</b>. */
921 add_default_trusted_dir_authorities(authority_type_t type
)
924 const char *dirservers
[] = {
925 "moria1 v1 orport=9001 v3ident=E2A2AF570166665D738736D0DD58169CC61D8A8B "
926 "128.31.0.39:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441",
927 "moria2 v1 orport=9002 128.31.0.34:9032 "
928 "719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF",
929 "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
930 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
931 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
932 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
933 "Tonga orport=443 bridge no-v2 82.94.251.203:80 "
934 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
935 "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
936 "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
937 "gabelmoo orport=443 no-v2 "
938 "v3ident=81349FC1F2DBA2C2C11B45CB9706637D480AB913 "
939 "80.190.246.100:80 6833 3D07 61BC F397 A587 A0C0 B963 E4A9 E99E C4D3",
940 "dannenberg orport=443 no-v2 "
941 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
942 "213.73.91.31:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
943 "urras orport=80 no-v2 v3ident=80550987E1D626E3EBA5E5E75A458DE0626D088C "
944 "208.83.223.34:443 0AD3 FA88 4D18 F89E EA2D 89C0 1937 9E0E 7FD9 4417",
947 for (i
=0; dirservers
[i
]; i
++) {
948 if (parse_dir_server_line(dirservers
[i
], type
, 0)<0) {
949 log_err(LD_BUG
, "Couldn't parse internal dirserver line %s",
955 /** Look at all the config options for using alternate directory
956 * authorities, and make sure none of them are broken. Also, warn the
957 * user if we changed any dangerous ones.
960 validate_dir_authorities(or_options_t
*options
, or_options_t
*old_options
)
964 if (options
->DirServers
&&
965 (options
->AlternateDirAuthority
|| options
->AlternateBridgeAuthority
||
966 options
->AlternateHSAuthority
)) {
968 "You cannot set both DirServers and Alternate*Authority.");
972 /* do we want to complain to the user about being partitionable? */
973 if ((options
->DirServers
&&
975 !config_lines_eq(options
->DirServers
, old_options
->DirServers
))) ||
976 (options
->AlternateDirAuthority
&&
978 !config_lines_eq(options
->AlternateDirAuthority
,
979 old_options
->AlternateDirAuthority
)))) {
981 "You have used DirServer or AlternateDirAuthority to "
982 "specify alternate directory authorities in "
983 "your configuration. This is potentially dangerous: it can "
984 "make you look different from all other Tor users, and hurt "
985 "your anonymity. Even if you've specified the same "
986 "authorities as Tor uses by default, the defaults could "
987 "change in the future. Be sure you know what you're doing.");
990 /* Now go through the four ways you can configure an alternate
991 * set of directory authorities, and make sure none are broken. */
992 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
)
993 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
995 for (cl
= options
->AlternateBridgeAuthority
; cl
; cl
= cl
->next
)
996 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
998 for (cl
= options
->AlternateDirAuthority
; cl
; cl
= cl
->next
)
999 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
1001 for (cl
= options
->AlternateHSAuthority
; cl
; cl
= cl
->next
)
1002 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
1007 /** Look at all the config options and assign new dir authorities
1011 consider_adding_dir_authorities(or_options_t
*options
,
1012 or_options_t
*old_options
)
1015 int need_to_update
=
1016 !smartlist_len(router_get_trusted_dir_servers()) || !old_options
||
1017 !config_lines_eq(options
->DirServers
, old_options
->DirServers
) ||
1018 !config_lines_eq(options
->AlternateBridgeAuthority
,
1019 old_options
->AlternateBridgeAuthority
) ||
1020 !config_lines_eq(options
->AlternateDirAuthority
,
1021 old_options
->AlternateDirAuthority
) ||
1022 !config_lines_eq(options
->AlternateHSAuthority
,
1023 old_options
->AlternateHSAuthority
);
1025 if (!need_to_update
)
1026 return 0; /* all done */
1028 /* Start from a clean slate. */
1029 clear_trusted_dir_servers();
1031 if (!options
->DirServers
) {
1032 /* then we may want some of the defaults */
1033 authority_type_t type
= NO_AUTHORITY
;
1034 if (!options
->AlternateBridgeAuthority
)
1035 type
|= BRIDGE_AUTHORITY
;
1036 if (!options
->AlternateDirAuthority
)
1037 type
|= V1_AUTHORITY
| V2_AUTHORITY
| V3_AUTHORITY
;
1038 if (!options
->AlternateHSAuthority
)
1039 type
|= HIDSERV_AUTHORITY
;
1040 add_default_trusted_dir_authorities(type
);
1043 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
)
1044 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
1046 for (cl
= options
->AlternateBridgeAuthority
; cl
; cl
= cl
->next
)
1047 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
1049 for (cl
= options
->AlternateDirAuthority
; cl
; cl
= cl
->next
)
1050 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
1052 for (cl
= options
->AlternateHSAuthority
; cl
; cl
= cl
->next
)
1053 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
1058 /** Fetch the active option list, and take actions based on it. All of the
1059 * things we do should survive being done repeatedly. If present,
1060 * <b>old_options</b> contains the previous value of the options.
1062 * Return 0 if all goes well, return -1 if things went badly.
1065 options_act_reversible(or_options_t
*old_options
, char **msg
)
1067 smartlist_t
*new_listeners
= smartlist_create();
1068 smartlist_t
*replaced_listeners
= smartlist_create();
1069 static int libevent_initialized
= 0;
1070 or_options_t
*options
= get_options();
1071 int running_tor
= options
->command
== CMD_RUN_TOR
;
1072 int set_conn_limit
= 0;
1074 int logs_marked
= 0;
1076 /* Daemonize _first_, since we only want to open most of this stuff in
1077 * the subprocess. Libevent bases can't be reliably inherited across
1079 if (running_tor
&& options
->RunAsDaemon
) {
1080 /* No need to roll back, since you can't change the value. */
1084 #ifndef HAVE_SYS_UN_H
1085 if (options
->ControlSocket
) {
1086 *msg
= tor_strdup("Unix domain sockets (ControlSocket) not supported"
1087 " on this OS/with this build.");
1093 /* We need to set the connection limit before we can open the listeners. */
1094 if (set_max_file_descriptors((unsigned)options
->ConnLimit
,
1095 &options
->_ConnLimit
) < 0) {
1096 *msg
= tor_strdup("Problem with ConnLimit value. See logs for details.");
1101 /* Set up libevent. (We need to do this before we can register the
1102 * listeners as listeners.) */
1103 if (running_tor
&& !libevent_initialized
) {
1105 libevent_initialized
= 1;
1108 /* Launch the listeners. (We do this before we setuid, so we can bind to
1109 * ports under 1024.) */
1110 if (retry_all_listeners(replaced_listeners
, new_listeners
) < 0) {
1111 *msg
= tor_strdup("Failed to bind one of the listener ports.");
1116 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1117 /* Open /dev/pf before dropping privileges. */
1118 if (options
->TransPort
) {
1119 if (get_pf_socket() < 0) {
1120 *msg
= tor_strdup("Unable to open /dev/pf for transparent proxy.");
1126 /* Attempt to lock all current and future memory with mlockall() only once */
1127 if (options
->DisableAllSwap
) {
1128 if (tor_mlockall() == -1) {
1129 *msg
= tor_strdup("DisableAllSwap failure. Do you have proper "
1135 /* Setuid/setgid as appropriate */
1136 if (options
->User
) {
1137 if (switch_id(options
->User
) != 0) {
1138 /* No need to roll back, since you can't change the value. */
1139 *msg
= tor_strdup("Problem with User value. See logs for details.");
1144 /* Ensure data directory is private; create if possible. */
1145 if (check_private_dir(options
->DataDirectory
,
1146 running_tor
? CPD_CREATE
: CPD_CHECK
)<0) {
1148 int tmp
= tor_snprintf(buf
, sizeof(buf
),
1149 "Couldn't access/create private data directory \"%s\"",
1150 options
->DataDirectory
);
1151 *msg
= tor_strdup(tmp
>= 0 ? buf
: "internal error");
1153 /* No need to roll back, since you can't change the value. */
1156 if (directory_caches_v2_dir_info(options
)) {
1157 size_t len
= strlen(options
->DataDirectory
)+32;
1158 char *fn
= tor_malloc(len
);
1159 tor_snprintf(fn
, len
, "%s"PATH_SEPARATOR
"cached-status",
1160 options
->DataDirectory
);
1161 if (check_private_dir(fn
, running_tor
? CPD_CREATE
: CPD_CHECK
) < 0) {
1163 int tmp
= tor_snprintf(buf
, sizeof(buf
),
1164 "Couldn't access/create private data directory \"%s\"", fn
);
1165 *msg
= tor_strdup(tmp
>= 0 ? buf
: "internal error");
1172 /* Bail out at this point if we're not going to be a client or server:
1173 * we don't run Tor itself. */
1177 mark_logs_temp(); /* Close current logs once new logs are open. */
1179 if (options_init_logs(options
, 0)<0) { /* Configure the log(s) */
1180 *msg
= tor_strdup("Failed to init Log options. See logs for details.");
1187 log_severity_list_t
*severity
=
1188 tor_malloc_zero(sizeof(log_severity_list_t
));
1190 add_callback_log(severity
, control_event_logmsg
);
1191 control_adjust_event_log_severity();
1194 SMARTLIST_FOREACH(replaced_listeners
, connection_t
*, conn
,
1196 log_notice(LD_NET
, "Closing old %s on %s:%d",
1197 conn_type_to_string(conn
->type
), conn
->address
, conn
->port
);
1198 connection_close_immediate(conn
);
1199 connection_mark_for_close(conn
);
1208 rollback_log_changes();
1209 control_adjust_event_log_severity();
1212 if (set_conn_limit
&& old_options
)
1213 set_max_file_descriptors((unsigned)old_options
->ConnLimit
,
1214 &options
->_ConnLimit
);
1216 SMARTLIST_FOREACH(new_listeners
, connection_t
*, conn
,
1218 log_notice(LD_NET
, "Closing partially-constructed listener %s on %s:%d",
1219 conn_type_to_string(conn
->type
), conn
->address
, conn
->port
);
1220 connection_close_immediate(conn
);
1221 connection_mark_for_close(conn
);
1225 smartlist_free(new_listeners
);
1226 smartlist_free(replaced_listeners
);
1230 /** If we need to have a GEOIP ip-to-country map to run with our configured
1231 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1233 options_need_geoip_info(or_options_t
*options
, const char **reason_out
)
1236 options
->BridgeRelay
&& options
->BridgeRecordUsageByCountry
;
1237 int routerset_usage
=
1238 routerset_needs_geoip(options
->EntryNodes
) ||
1239 routerset_needs_geoip(options
->ExitNodes
) ||
1240 routerset_needs_geoip(options
->ExcludeExitNodes
) ||
1241 routerset_needs_geoip(options
->ExcludeNodes
);
1243 if (routerset_usage
&& reason_out
) {
1244 *reason_out
= "We've been configured to use (or avoid) nodes in certain "
1245 "countries, and we need GEOIP information to figure out which ones they "
1247 } else if (bridge_usage
&& reason_out
) {
1248 *reason_out
= "We've been configured to see which countries can access "
1249 "us as a bridge, and we need GEOIP information to tell which countries "
1252 return bridge_usage
|| routerset_usage
;
1255 /** Return the bandwidthrate that we are going to report to the authorities
1256 * based on the config options. */
1258 get_effective_bwrate(or_options_t
*options
)
1260 uint64_t bw
= options
->BandwidthRate
;
1261 if (bw
> options
->MaxAdvertisedBandwidth
)
1262 bw
= options
->MaxAdvertisedBandwidth
;
1263 if (options
->RelayBandwidthRate
> 0 && bw
> options
->RelayBandwidthRate
)
1264 bw
= options
->RelayBandwidthRate
;
1265 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1266 return (uint32_t)bw
;
1269 /** Return the bandwidthburst that we are going to report to the authorities
1270 * based on the config options. */
1272 get_effective_bwburst(or_options_t
*options
)
1274 uint64_t bw
= options
->BandwidthBurst
;
1275 if (options
->RelayBandwidthBurst
> 0 && bw
> options
->RelayBandwidthBurst
)
1276 bw
= options
->RelayBandwidthBurst
;
1277 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1278 return (uint32_t)bw
;
1281 /** Fetch the active option list, and take actions based on it. All of the
1282 * things we do should survive being done repeatedly. If present,
1283 * <b>old_options</b> contains the previous value of the options.
1285 * Return 0 if all goes well, return -1 if it's time to die.
1287 * Note: We haven't moved all the "act on new configuration" logic
1288 * here yet. Some is still in do_hup() and other places.
1291 options_act(or_options_t
*old_options
)
1294 or_options_t
*options
= get_options();
1295 int running_tor
= options
->command
== CMD_RUN_TOR
;
1298 if (running_tor
&& !have_lockfile()) {
1299 if (try_locking(options
, 1) < 0)
1303 if (consider_adding_dir_authorities(options
, old_options
) < 0)
1306 if (options
->Bridges
) {
1307 clear_bridge_list();
1308 for (cl
= options
->Bridges
; cl
; cl
= cl
->next
) {
1309 if (parse_bridge_line(cl
->value
, 0)<0) {
1311 "Previously validated Bridge line could not be added!");
1317 if (running_tor
&& rend_config_services(options
, 0)<0) {
1319 "Previously validated hidden services line could not be added!");
1323 if (running_tor
&& rend_parse_service_authorization(options
, 0) < 0) {
1324 log_warn(LD_BUG
, "Previously validated client authorization for "
1325 "hidden services could not be added!");
1330 if (! global_state
&& running_tor
) {
1331 if (or_state_load())
1333 rep_hist_load_mtbf_data(time(NULL
));
1336 /* Bail out at this point if we're not going to be a client or server:
1337 * we want to not fork, and to log stuff to stderr. */
1341 /* Finish backgrounding the process */
1342 if (options
->RunAsDaemon
) {
1343 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1344 finish_daemon(options
->DataDirectory
);
1347 /* Write our PID to the PID file. If we do not have write permissions we
1348 * will log a warning */
1349 if (options
->PidFile
)
1350 write_pidfile(options
->PidFile
);
1352 /* Register addressmap directives */
1353 config_register_addressmaps(options
);
1354 parse_virtual_addr_network(options
->VirtualAddrNetwork
, 0, &msg
);
1356 /* Update address policies. */
1357 if (policies_parse_from_options(options
) < 0) {
1358 /* This should be impossible, but let's be sure. */
1359 log_warn(LD_BUG
,"Error parsing already-validated policy options.");
1363 if (init_cookie_authentication(options
->CookieAuthentication
) < 0) {
1364 log_warn(LD_CONFIG
,"Error creating cookie authentication file.");
1368 /* reload keys as needed for rendezvous services. */
1369 if (rend_service_load_keys()<0) {
1370 log_warn(LD_GENERAL
,"Error loading rendezvous service keys");
1374 /* Set up accounting */
1375 if (accounting_parse_options(options
, 0)<0) {
1376 log_warn(LD_CONFIG
,"Error in accounting options");
1379 if (accounting_is_enabled(options
))
1380 configure_accounting(time(NULL
));
1382 /* Check for transitions that need action. */
1384 if (options
->UseEntryGuards
&& !old_options
->UseEntryGuards
) {
1386 "Switching to entry guards; abandoning previous circuits");
1387 circuit_mark_all_unused_circs();
1388 circuit_expire_all_dirty_circs();
1391 if (! bool_eq(options
->BridgeRelay
, old_options
->BridgeRelay
)) {
1392 log_info(LD_GENERAL
, "Bridge status changed. Forgetting GeoIP stats.");
1393 geoip_remove_old_clients(time(NULL
)+(2*60*60));
1396 if (options_transition_affects_workers(old_options
, options
)) {
1397 log_info(LD_GENERAL
,
1398 "Worker-related options changed. Rotating workers.");
1399 if (server_mode(options
) && !server_mode(old_options
)) {
1400 if (init_keys() < 0) {
1401 log_warn(LD_BUG
,"Error initializing keys; exiting");
1404 ip_address_changed(0);
1405 if (has_completed_circuit
|| !any_predicted_circuits(time(NULL
)))
1406 inform_testing_reachability();
1408 cpuworkers_rotate();
1416 if (options
->V3AuthoritativeDir
&& !old_options
->V3AuthoritativeDir
)
1420 /* Maybe load geoip file */
1421 if (options
->GeoIPFile
&&
1422 ((!old_options
|| !opt_streq(old_options
->GeoIPFile
, options
->GeoIPFile
))
1423 || !geoip_is_loaded())) {
1424 /* XXXX Don't use this "<default>" junk; make our filename options
1425 * understand prefixes somehow. -NM */
1426 /* XXXX021 Reload GeoIPFile on SIGHUP. -NM */
1427 char *actual_fname
= tor_strdup(options
->GeoIPFile
);
1429 if (!strcmp(actual_fname
, "<default>")) {
1430 const char *conf_root
= get_windows_conf_root();
1431 size_t len
= strlen(conf_root
)+16;
1432 tor_free(actual_fname
);
1433 actual_fname
= tor_malloc(len
+1);
1434 tor_snprintf(actual_fname
, len
, "%s\\geoip", conf_root
);
1437 geoip_load_file(actual_fname
, options
);
1438 tor_free(actual_fname
);
1441 if (options
->DirReqStatistics
&& !geoip_is_loaded()) {
1442 /* Check if GeoIP database could be loaded. */
1443 log_warn(LD_CONFIG
, "Configured to measure directory request "
1444 "statistics, but no GeoIP database found!");
1448 if (options
->EntryStatistics
) {
1449 if (should_record_bridge_info(options
)) {
1450 /* Don't allow measuring statistics on entry guards when configured
1452 log_warn(LD_CONFIG
, "Bridges cannot be configured to measure "
1453 "additional GeoIP statistics as entry guards.");
1455 } else if (!geoip_is_loaded()) {
1456 /* Check if GeoIP database could be loaded. */
1457 log_warn(LD_CONFIG
, "Configured to measure entry node statistics, "
1458 "but no GeoIP database found!");
1463 /* Check if we need to parse and add the EntryNodes config option. */
1464 if (options
->EntryNodes
&&
1466 (!routerset_equal(old_options
->EntryNodes
,options
->EntryNodes
))))
1467 entry_nodes_should_be_added();
1469 /* Since our options changed, we might need to regenerate and upload our
1470 * server descriptor.
1473 options_transition_affects_descriptor(old_options
, options
))
1474 mark_my_descriptor_dirty();
1476 /* We may need to reschedule some directory stuff if our status changed. */
1478 if (authdir_mode_v3(options
) && !authdir_mode_v3(old_options
))
1479 dirvote_recalculate_timing(options
, time(NULL
));
1480 if (!bool_eq(directory_fetches_dir_info_early(options
),
1481 directory_fetches_dir_info_early(old_options
)) ||
1482 !bool_eq(directory_fetches_dir_info_later(options
),
1483 directory_fetches_dir_info_later(old_options
))) {
1484 /* Make sure update_router_have_min_dir_info gets called. */
1485 router_dir_info_changed();
1486 /* We might need to download a new consensus status later or sooner than
1487 * we had expected. */
1488 update_consensus_networkstatus_fetch_time(time(NULL
));
1492 /* Load the webpage we're going to serve every time someone asks for '/' on
1494 tor_free(global_dirfrontpagecontents
);
1495 if (options
->DirPortFrontPage
) {
1496 global_dirfrontpagecontents
=
1497 read_file_to_str(options
->DirPortFrontPage
, 0, NULL
);
1498 if (!global_dirfrontpagecontents
) {
1500 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1501 options
->DirPortFrontPage
);
1509 * Functions to parse config options
1512 /** If <b>option</b> is an official abbreviation for a longer option,
1513 * return the longer option. Otherwise return <b>option</b>.
1514 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1515 * apply abbreviations that work for the config file and the command line.
1516 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1518 expand_abbrev(config_format_t
*fmt
, const char *option
, int command_line
,
1524 for (i
=0; fmt
->abbrevs
[i
].abbreviated
; ++i
) {
1525 /* Abbreviations are case insensitive. */
1526 if (!strcasecmp(option
,fmt
->abbrevs
[i
].abbreviated
) &&
1527 (command_line
|| !fmt
->abbrevs
[i
].commandline_only
)) {
1528 if (warn_obsolete
&& fmt
->abbrevs
[i
].warn
) {
1530 "The configuration option '%s' is deprecated; "
1531 "use '%s' instead.",
1532 fmt
->abbrevs
[i
].abbreviated
,
1533 fmt
->abbrevs
[i
].full
);
1535 /* Keep going through the list in case we want to rewrite it more.
1536 * (We could imagine recursing here, but I don't want to get the
1537 * user into an infinite loop if we craft our list wrong.) */
1538 option
= fmt
->abbrevs
[i
].full
;
1544 /** Helper: Read a list of configuration options from the command line.
1545 * If successful, put them in *<b>result</b> and return 0, and return
1546 * -1 and leave *<b>result</b> alone. */
1548 config_get_commandlines(int argc
, char **argv
, config_line_t
**result
)
1550 config_line_t
*front
= NULL
;
1551 config_line_t
**new = &front
;
1556 if (!strcmp(argv
[i
],"-f") ||
1557 !strcmp(argv
[i
],"--hash-password")) {
1558 i
+= 2; /* command-line option with argument. ignore them. */
1560 } else if (!strcmp(argv
[i
],"--list-fingerprint") ||
1561 !strcmp(argv
[i
],"--verify-config") ||
1562 !strcmp(argv
[i
],"--ignore-missing-torrc") ||
1563 !strcmp(argv
[i
],"--quiet") ||
1564 !strcmp(argv
[i
],"--hush")) {
1565 i
+= 1; /* command-line option. ignore it. */
1567 } else if (!strcmp(argv
[i
],"--nt-service") ||
1568 !strcmp(argv
[i
],"-nt-service")) {
1574 log_warn(LD_CONFIG
,"Command-line option '%s' with no value. Failing.",
1576 config_free_lines(front
);
1580 *new = tor_malloc_zero(sizeof(config_line_t
));
1583 /* Each keyword may be prefixed with one or two dashes. */
1589 (*new)->key
= tor_strdup(expand_abbrev(&options_format
, s
, 1, 1));
1590 (*new)->value
= tor_strdup(argv
[i
+1]);
1591 (*new)->next
= NULL
;
1592 log(LOG_DEBUG
, LD_CONFIG
, "command line: parsed keyword '%s', value '%s'",
1593 (*new)->key
, (*new)->value
);
1595 new = &((*new)->next
);
1602 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1603 * append it to *<b>lst</b>. */
1605 config_line_append(config_line_t
**lst
,
1609 config_line_t
*newline
;
1611 newline
= tor_malloc(sizeof(config_line_t
));
1612 newline
->key
= tor_strdup(key
);
1613 newline
->value
= tor_strdup(val
);
1614 newline
->next
= NULL
;
1616 lst
= &((*lst
)->next
);
1621 /** Helper: parse the config string and strdup into key/value
1622 * strings. Set *result to the list, or NULL if parsing the string
1623 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1624 * misformatted lines. */
1626 config_get_lines(const char *string
, config_line_t
**result
)
1628 config_line_t
*list
= NULL
, **next
;
1634 string
= parse_config_line_from_str(string
, &k
, &v
);
1636 config_free_lines(list
);
1642 /* This list can get long, so we keep a pointer to the end of it
1643 * rather than using config_line_append over and over and getting
1644 * n^2 performance. */
1645 *next
= tor_malloc(sizeof(config_line_t
));
1648 (*next
)->next
= NULL
;
1649 next
= &((*next
)->next
);
1661 * Free all the configuration lines on the linked list <b>front</b>.
1664 config_free_lines(config_line_t
*front
)
1673 tor_free(tmp
->value
);
1678 /** Return the description for a given configuration variable, or NULL if no
1679 * description exists. */
1681 config_find_description(config_format_t
*fmt
, const char *name
)
1684 for (i
=0; fmt
->descriptions
[i
].name
; ++i
) {
1685 if (!strcasecmp(name
, fmt
->descriptions
[i
].name
))
1686 return fmt
->descriptions
[i
].description
;
1691 /** If <b>key</b> is a configuration option, return the corresponding
1692 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1693 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1695 static config_var_t
*
1696 config_find_option(config_format_t
*fmt
, const char *key
)
1699 size_t keylen
= strlen(key
);
1701 return NULL
; /* if they say "--" on the command line, it's not an option */
1702 /* First, check for an exact (case-insensitive) match */
1703 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
1704 if (!strcasecmp(key
, fmt
->vars
[i
].name
)) {
1705 return &fmt
->vars
[i
];
1708 /* If none, check for an abbreviated match */
1709 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
1710 if (!strncasecmp(key
, fmt
->vars
[i
].name
, keylen
)) {
1711 log_warn(LD_CONFIG
, "The abbreviation '%s' is deprecated. "
1712 "Please use '%s' instead",
1713 key
, fmt
->vars
[i
].name
);
1714 return &fmt
->vars
[i
];
1717 /* Okay, unrecognized option */
1722 * Functions to assign config options.
1725 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1726 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1728 * Called from config_assign_line() and option_reset().
1731 config_assign_value(config_format_t
*fmt
, or_options_t
*options
,
1732 config_line_t
*c
, char **msg
)
1739 CHECK(fmt
, options
);
1741 var
= config_find_option(fmt
, c
->key
);
1744 lvalue
= STRUCT_VAR_P(options
, var
->var_offset
);
1746 switch (var
->type
) {
1748 case CONFIG_TYPE_UINT
:
1749 i
= (int)tor_parse_long(c
->value
, 10, 0, INT_MAX
, &ok
, NULL
);
1751 r
= tor_snprintf(buf
, sizeof(buf
),
1752 "Int keyword '%s %s' is malformed or out of bounds.",
1754 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1760 case CONFIG_TYPE_INTERVAL
: {
1761 i
= config_parse_interval(c
->value
, &ok
);
1763 r
= tor_snprintf(buf
, sizeof(buf
),
1764 "Interval '%s %s' is malformed or out of bounds.",
1766 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1773 case CONFIG_TYPE_MEMUNIT
: {
1774 uint64_t u64
= config_parse_memunit(c
->value
, &ok
);
1776 r
= tor_snprintf(buf
, sizeof(buf
),
1777 "Value '%s %s' is malformed or out of bounds.",
1779 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1782 *(uint64_t *)lvalue
= u64
;
1786 case CONFIG_TYPE_BOOL
:
1787 i
= (int)tor_parse_long(c
->value
, 10, 0, 1, &ok
, NULL
);
1789 r
= tor_snprintf(buf
, sizeof(buf
),
1790 "Boolean '%s %s' expects 0 or 1.",
1792 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1798 case CONFIG_TYPE_STRING
:
1799 case CONFIG_TYPE_FILENAME
:
1800 tor_free(*(char **)lvalue
);
1801 *(char **)lvalue
= tor_strdup(c
->value
);
1804 case CONFIG_TYPE_DOUBLE
:
1805 *(double *)lvalue
= atof(c
->value
);
1808 case CONFIG_TYPE_ISOTIME
:
1809 if (parse_iso_time(c
->value
, (time_t *)lvalue
)) {
1810 r
= tor_snprintf(buf
, sizeof(buf
),
1811 "Invalid time '%s' for keyword '%s'", c
->value
, c
->key
);
1812 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1817 case CONFIG_TYPE_ROUTERSET
:
1818 if (*(routerset_t
**)lvalue
) {
1819 routerset_free(*(routerset_t
**)lvalue
);
1821 *(routerset_t
**)lvalue
= routerset_new();
1822 if (routerset_parse(*(routerset_t
**)lvalue
, c
->value
, c
->key
)<0) {
1823 tor_snprintf(buf
, sizeof(buf
), "Invalid exit list '%s' for option '%s'",
1825 *msg
= tor_strdup(buf
);
1830 case CONFIG_TYPE_CSV
:
1831 if (*(smartlist_t
**)lvalue
) {
1832 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
1833 smartlist_clear(*(smartlist_t
**)lvalue
);
1835 *(smartlist_t
**)lvalue
= smartlist_create();
1838 smartlist_split_string(*(smartlist_t
**)lvalue
, c
->value
, ",",
1839 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1842 case CONFIG_TYPE_LINELIST
:
1843 case CONFIG_TYPE_LINELIST_S
:
1844 config_line_append((config_line_t
**)lvalue
, c
->key
, c
->value
);
1846 case CONFIG_TYPE_OBSOLETE
:
1847 log_warn(LD_CONFIG
, "Skipping obsolete configuration option '%s'", c
->key
);
1849 case CONFIG_TYPE_LINELIST_V
:
1850 r
= tor_snprintf(buf
, sizeof(buf
),
1851 "You may not provide a value for virtual option '%s'", c
->key
);
1852 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1861 /** If <b>c</b> is a syntactically valid configuration line, update
1862 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1863 * key, -2 for bad value.
1865 * If <b>clear_first</b> is set, clear the value first. Then if
1866 * <b>use_defaults</b> is set, set the value to the default.
1868 * Called from config_assign().
1871 config_assign_line(config_format_t
*fmt
, or_options_t
*options
,
1872 config_line_t
*c
, int use_defaults
,
1873 int clear_first
, char **msg
)
1877 CHECK(fmt
, options
);
1879 var
= config_find_option(fmt
, c
->key
);
1882 void *lvalue
= STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
1884 "Found unrecognized option '%s'; saving it.", c
->key
);
1885 config_line_append((config_line_t
**)lvalue
, c
->key
, c
->value
);
1889 int tmp
= tor_snprintf(buf
, sizeof(buf
),
1890 "Unknown option '%s'. Failing.", c
->key
);
1891 *msg
= tor_strdup(tmp
>= 0 ? buf
: "internal error");
1895 /* Put keyword into canonical case. */
1896 if (strcmp(var
->name
, c
->key
)) {
1898 c
->key
= tor_strdup(var
->name
);
1901 if (!strlen(c
->value
)) {
1902 /* reset or clear it, then return */
1904 if (var
->type
== CONFIG_TYPE_LINELIST
||
1905 var
->type
== CONFIG_TYPE_LINELIST_S
) {
1906 /* We got an empty linelist from the torrc or command line.
1907 As a special case, call this an error. Warn and ignore. */
1909 "Linelist option '%s' has no value. Skipping.", c
->key
);
1910 } else { /* not already cleared */
1911 option_reset(fmt
, options
, var
, use_defaults
);
1917 if (config_assign_value(fmt
, options
, c
, msg
) < 0)
1922 /** Restore the option named <b>key</b> in options to its default value.
1923 * Called from config_assign(). */
1925 config_reset_line(config_format_t
*fmt
, or_options_t
*options
,
1926 const char *key
, int use_defaults
)
1930 CHECK(fmt
, options
);
1932 var
= config_find_option(fmt
, key
);
1934 return; /* give error on next pass. */
1936 option_reset(fmt
, options
, var
, use_defaults
);
1939 /** Return true iff key is a valid configuration option. */
1941 option_is_recognized(const char *key
)
1943 config_var_t
*var
= config_find_option(&options_format
, key
);
1944 return (var
!= NULL
);
1947 /** Return the canonical name of a configuration option, or NULL
1948 * if no such option exists. */
1950 option_get_canonical_name(const char *key
)
1952 config_var_t
*var
= config_find_option(&options_format
, key
);
1953 return var
? var
->name
: NULL
;
1956 /** Return a canonical list of the options assigned for key.
1959 option_get_assignment(or_options_t
*options
, const char *key
)
1961 return get_assigned_option(&options_format
, options
, key
, 1);
1964 /** Return true iff value needs to be quoted and escaped to be used in
1965 * a configuration file. */
1967 config_value_needs_escape(const char *value
)
1977 /* Note: quotes and backspaces need special handling when we are using
1978 * quotes, not otherwise, so they don't trigger escaping on their
1982 if (!TOR_ISPRINT(*value
))
1990 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1991 static config_line_t
*
1992 config_lines_dup(const config_line_t
*inp
)
1994 config_line_t
*result
= NULL
;
1995 config_line_t
**next_out
= &result
;
1997 *next_out
= tor_malloc(sizeof(config_line_t
));
1998 (*next_out
)->key
= tor_strdup(inp
->key
);
1999 (*next_out
)->value
= tor_strdup(inp
->value
);
2001 next_out
= &((*next_out
)->next
);
2007 /** Return newly allocated line or lines corresponding to <b>key</b> in the
2008 * configuration <b>options</b>. If <b>escape_val</b> is true and a
2009 * value needs to be quoted before it's put in a config file, quote and
2010 * escape that value. Return NULL if no such key exists. */
2011 static config_line_t
*
2012 get_assigned_option(config_format_t
*fmt
, void *options
,
2013 const char *key
, int escape_val
)
2018 config_line_t
*result
;
2019 tor_assert(options
&& key
);
2021 CHECK(fmt
, options
);
2023 var
= config_find_option(fmt
, key
);
2025 log_warn(LD_CONFIG
, "Unknown option '%s'. Failing.", key
);
2028 value
= STRUCT_VAR_P(options
, var
->var_offset
);
2030 result
= tor_malloc_zero(sizeof(config_line_t
));
2031 result
->key
= tor_strdup(var
->name
);
2034 case CONFIG_TYPE_STRING
:
2035 case CONFIG_TYPE_FILENAME
:
2036 if (*(char**)value
) {
2037 result
->value
= tor_strdup(*(char**)value
);
2039 tor_free(result
->key
);
2044 case CONFIG_TYPE_ISOTIME
:
2045 if (*(time_t*)value
) {
2046 result
->value
= tor_malloc(ISO_TIME_LEN
+1);
2047 format_iso_time(result
->value
, *(time_t*)value
);
2049 tor_free(result
->key
);
2052 escape_val
= 0; /* Can't need escape. */
2054 case CONFIG_TYPE_INTERVAL
:
2055 case CONFIG_TYPE_UINT
:
2056 /* This means every or_options_t uint or bool element
2057 * needs to be an int. Not, say, a uint16_t or char. */
2058 tor_snprintf(buf
, sizeof(buf
), "%d", *(int*)value
);
2059 result
->value
= tor_strdup(buf
);
2060 escape_val
= 0; /* Can't need escape. */
2062 case CONFIG_TYPE_MEMUNIT
:
2063 tor_snprintf(buf
, sizeof(buf
), U64_FORMAT
,
2064 U64_PRINTF_ARG(*(uint64_t*)value
));
2065 result
->value
= tor_strdup(buf
);
2066 escape_val
= 0; /* Can't need escape. */
2068 case CONFIG_TYPE_DOUBLE
:
2069 tor_snprintf(buf
, sizeof(buf
), "%f", *(double*)value
);
2070 result
->value
= tor_strdup(buf
);
2071 escape_val
= 0; /* Can't need escape. */
2073 case CONFIG_TYPE_BOOL
:
2074 result
->value
= tor_strdup(*(int*)value
? "1" : "0");
2075 escape_val
= 0; /* Can't need escape. */
2077 case CONFIG_TYPE_ROUTERSET
:
2078 result
->value
= routerset_to_string(*(routerset_t
**)value
);
2080 case CONFIG_TYPE_CSV
:
2081 if (*(smartlist_t
**)value
)
2083 smartlist_join_strings(*(smartlist_t
**)value
, ",", 0, NULL
);
2085 result
->value
= tor_strdup("");
2087 case CONFIG_TYPE_OBSOLETE
:
2088 log_fn(LOG_PROTOCOL_WARN
, LD_CONFIG
,
2089 "You asked me for the value of an obsolete config option '%s'.",
2091 tor_free(result
->key
);
2094 case CONFIG_TYPE_LINELIST_S
:
2096 "Can't return context-sensitive '%s' on its own", key
);
2097 tor_free(result
->key
);
2100 case CONFIG_TYPE_LINELIST
:
2101 case CONFIG_TYPE_LINELIST_V
:
2102 tor_free(result
->key
);
2104 result
= config_lines_dup(*(const config_line_t
**)value
);
2107 tor_free(result
->key
);
2109 log_warn(LD_BUG
,"Unknown type %d for known key '%s'",
2115 config_line_t
*line
;
2116 for (line
= result
; line
; line
= line
->next
) {
2117 if (line
->value
&& config_value_needs_escape(line
->value
)) {
2118 char *newval
= esc_for_log(line
->value
);
2119 tor_free(line
->value
);
2120 line
->value
= newval
;
2128 /** Iterate through the linked list of requested options <b>list</b>.
2129 * For each item, convert as appropriate and assign to <b>options</b>.
2130 * If an item is unrecognized, set *msg and return -1 immediately,
2131 * else return 0 for success.
2133 * If <b>clear_first</b>, interpret config options as replacing (not
2134 * extending) their previous values. If <b>clear_first</b> is set,
2135 * then <b>use_defaults</b> to decide if you set to defaults after
2136 * clearing, or make the value 0 or NULL.
2138 * Here are the use cases:
2139 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
2140 * if linelist, replaces current if csv.
2141 * 2. An empty AllowInvalid line in your torrc. Should clear it.
2142 * 3. "RESETCONF AllowInvalid" sets it to default.
2143 * 4. "SETCONF AllowInvalid" makes it NULL.
2144 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
2146 * Use_defaults Clear_first
2148 * 1 0 undefined, don't use
2149 * 0 1 "set to null first"
2150 * 1 1 "set to defaults first"
2151 * Return 0 on success, -1 on bad key, -2 on bad value.
2153 * As an additional special case, if a LINELIST config option has
2154 * no value and clear_first is 0, then warn and ignore it.
2158 There are three call cases for config_assign() currently.
2160 Case one: Torrc entry
2161 options_init_from_torrc() calls config_assign(0, 0)
2162 calls config_assign_line(0, 0).
2163 if value is empty, calls option_reset(0) and returns.
2164 calls config_assign_value(), appends.
2167 options_trial_assign() calls config_assign(0, 1)
2168 calls config_reset_line(0)
2169 calls option_reset(0)
2170 calls option_clear().
2171 calls config_assign_line(0, 1).
2172 if value is empty, returns.
2173 calls config_assign_value(), appends.
2175 Case three: resetconf
2176 options_trial_assign() calls config_assign(1, 1)
2177 calls config_reset_line(1)
2178 calls option_reset(1)
2179 calls option_clear().
2180 calls config_assign_value(default)
2181 calls config_assign_line(1, 1).
2185 config_assign(config_format_t
*fmt
, void *options
, config_line_t
*list
,
2186 int use_defaults
, int clear_first
, char **msg
)
2190 CHECK(fmt
, options
);
2192 /* pass 1: normalize keys */
2193 for (p
= list
; p
; p
= p
->next
) {
2194 const char *full
= expand_abbrev(fmt
, p
->key
, 0, 1);
2195 if (strcmp(full
,p
->key
)) {
2197 p
->key
= tor_strdup(full
);
2201 /* pass 2: if we're reading from a resetting source, clear all
2202 * mentioned config options, and maybe set to their defaults. */
2204 for (p
= list
; p
; p
= p
->next
)
2205 config_reset_line(fmt
, options
, p
->key
, use_defaults
);
2208 /* pass 3: assign. */
2211 if ((r
=config_assign_line(fmt
, options
, list
, use_defaults
,
2219 /** Try assigning <b>list</b> to the global options. You do this by duping
2220 * options, assigning list to the new one, then validating it. If it's
2221 * ok, then throw out the old one and stick with the new one. Else,
2222 * revert to old and return failure. Return SETOPT_OK on success, or
2223 * a setopt_err_t on failure.
2225 * If not success, point *<b>msg</b> to a newly allocated string describing
2229 options_trial_assign(config_line_t
*list
, int use_defaults
,
2230 int clear_first
, char **msg
)
2233 or_options_t
*trial_options
= options_dup(&options_format
, get_options());
2235 if ((r
=config_assign(&options_format
, trial_options
,
2236 list
, use_defaults
, clear_first
, msg
)) < 0) {
2237 config_free(&options_format
, trial_options
);
2241 if (options_validate(get_options(), trial_options
, 1, msg
) < 0) {
2242 config_free(&options_format
, trial_options
);
2243 return SETOPT_ERR_PARSE
; /*XXX make this a separate return value. */
2246 if (options_transition_allowed(get_options(), trial_options
, msg
) < 0) {
2247 config_free(&options_format
, trial_options
);
2248 return SETOPT_ERR_TRANSITION
;
2251 if (set_options(trial_options
, msg
)<0) {
2252 config_free(&options_format
, trial_options
);
2253 return SETOPT_ERR_SETTING
;
2256 /* we liked it. put it in place. */
2260 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2261 * Called from option_reset() and config_free(). */
2263 option_clear(config_format_t
*fmt
, or_options_t
*options
, config_var_t
*var
)
2265 void *lvalue
= STRUCT_VAR_P(options
, var
->var_offset
);
2266 (void)fmt
; /* unused */
2267 switch (var
->type
) {
2268 case CONFIG_TYPE_STRING
:
2269 case CONFIG_TYPE_FILENAME
:
2270 tor_free(*(char**)lvalue
);
2272 case CONFIG_TYPE_DOUBLE
:
2273 *(double*)lvalue
= 0.0;
2275 case CONFIG_TYPE_ISOTIME
:
2276 *(time_t*)lvalue
= 0;
2278 case CONFIG_TYPE_INTERVAL
:
2279 case CONFIG_TYPE_UINT
:
2280 case CONFIG_TYPE_BOOL
:
2283 case CONFIG_TYPE_MEMUNIT
:
2284 *(uint64_t*)lvalue
= 0;
2286 case CONFIG_TYPE_ROUTERSET
:
2287 if (*(routerset_t
**)lvalue
) {
2288 routerset_free(*(routerset_t
**)lvalue
);
2289 *(routerset_t
**)lvalue
= NULL
;
2292 case CONFIG_TYPE_CSV
:
2293 if (*(smartlist_t
**)lvalue
) {
2294 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
2295 smartlist_free(*(smartlist_t
**)lvalue
);
2296 *(smartlist_t
**)lvalue
= NULL
;
2299 case CONFIG_TYPE_LINELIST
:
2300 case CONFIG_TYPE_LINELIST_S
:
2301 config_free_lines(*(config_line_t
**)lvalue
);
2302 *(config_line_t
**)lvalue
= NULL
;
2304 case CONFIG_TYPE_LINELIST_V
:
2305 /* handled by linelist_s. */
2307 case CONFIG_TYPE_OBSOLETE
:
2312 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2313 * <b>use_defaults</b>, set it to its default value.
2314 * Called by config_init() and option_reset_line() and option_assign_line(). */
2316 option_reset(config_format_t
*fmt
, or_options_t
*options
,
2317 config_var_t
*var
, int use_defaults
)
2321 CHECK(fmt
, options
);
2322 option_clear(fmt
, options
, var
); /* clear it first */
2324 return; /* all done */
2325 if (var
->initvalue
) {
2326 c
= tor_malloc_zero(sizeof(config_line_t
));
2327 c
->key
= tor_strdup(var
->name
);
2328 c
->value
= tor_strdup(var
->initvalue
);
2329 if (config_assign_value(fmt
, options
, c
, &msg
) < 0) {
2330 log_warn(LD_BUG
, "Failed to assign default: %s", msg
);
2331 tor_free(msg
); /* if this happens it's a bug */
2333 config_free_lines(c
);
2337 /** Print a usage message for tor. */
2342 "Copyright (c) 2001-2004, Roger Dingledine\n"
2343 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2344 "Copyright (c) 2007-2009, The Tor Project, Inc.\n\n"
2345 "tor -f <torrc> [args]\n"
2346 "See man page for options, or https://www.torproject.org/ for "
2347 "documentation.\n");
2350 /** Print all non-obsolete torrc options. */
2352 list_torrc_options(void)
2355 smartlist_t
*lines
= smartlist_create();
2356 for (i
= 0; _option_vars
[i
].name
; ++i
) {
2357 config_var_t
*var
= &_option_vars
[i
];
2359 if (var
->type
== CONFIG_TYPE_OBSOLETE
||
2360 var
->type
== CONFIG_TYPE_LINELIST_V
)
2362 desc
= config_find_description(&options_format
, var
->name
);
2363 printf("%s\n", var
->name
);
2365 wrap_string(lines
, desc
, 76, " ", " ");
2366 SMARTLIST_FOREACH(lines
, char *, cp
, {
2370 smartlist_clear(lines
);
2373 smartlist_free(lines
);
2376 /** Last value actually set by resolve_my_address. */
2377 static uint32_t last_resolved_addr
= 0;
2379 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2380 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2381 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2382 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2383 * public IP address.
2386 resolve_my_address(int warn_severity
, or_options_t
*options
,
2387 uint32_t *addr_out
, char **hostname_out
)
2390 struct hostent
*rent
;
2393 int explicit_hostname
=1;
2394 int from_interface
=0;
2395 char tmpbuf
[INET_NTOA_BUF_LEN
];
2396 const char *address
= options
->Address
;
2397 int notice_severity
= warn_severity
<= LOG_NOTICE
?
2398 LOG_NOTICE
: warn_severity
;
2400 tor_assert(addr_out
);
2402 if (address
&& *address
) {
2403 strlcpy(hostname
, address
, sizeof(hostname
));
2404 } else { /* then we need to guess our address */
2405 explicit_ip
= 0; /* it's implicit */
2406 explicit_hostname
= 0; /* it's implicit */
2408 if (gethostname(hostname
, sizeof(hostname
)) < 0) {
2409 log_fn(warn_severity
, LD_NET
,"Error obtaining local hostname");
2412 log_debug(LD_CONFIG
,"Guessed local host name as '%s'",hostname
);
2415 /* now we know hostname. resolve it and keep only the IP address */
2417 if (tor_inet_aton(hostname
, &in
) == 0) {
2418 /* then we have to resolve it */
2420 rent
= (struct hostent
*)gethostbyname(hostname
);
2422 uint32_t interface_ip
;
2424 if (explicit_hostname
) {
2425 log_fn(warn_severity
, LD_CONFIG
,
2426 "Could not resolve local Address '%s'. Failing.", hostname
);
2429 log_fn(notice_severity
, LD_CONFIG
,
2430 "Could not resolve guessed local hostname '%s'. "
2431 "Trying something else.", hostname
);
2432 if (get_interface_address(warn_severity
, &interface_ip
)) {
2433 log_fn(warn_severity
, LD_CONFIG
,
2434 "Could not get local interface IP address. Failing.");
2438 in
.s_addr
= htonl(interface_ip
);
2439 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2440 log_fn(notice_severity
, LD_CONFIG
, "Learned IP address '%s' for "
2441 "local interface. Using that.", tmpbuf
);
2442 strlcpy(hostname
, "<guessed from interfaces>", sizeof(hostname
));
2444 tor_assert(rent
->h_length
== 4);
2445 memcpy(&in
.s_addr
, rent
->h_addr
, rent
->h_length
);
2447 if (!explicit_hostname
&&
2448 is_internal_IP(ntohl(in
.s_addr
), 0)) {
2449 uint32_t interface_ip
;
2451 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2452 log_fn(notice_severity
, LD_CONFIG
, "Guessed local hostname '%s' "
2453 "resolves to a private IP address (%s). Trying something "
2454 "else.", hostname
, tmpbuf
);
2456 if (get_interface_address(warn_severity
, &interface_ip
)) {
2457 log_fn(warn_severity
, LD_CONFIG
,
2458 "Could not get local interface IP address. Too bad.");
2459 } else if (is_internal_IP(interface_ip
, 0)) {
2461 in2
.s_addr
= htonl(interface_ip
);
2462 tor_inet_ntoa(&in2
,tmpbuf
,sizeof(tmpbuf
));
2463 log_fn(notice_severity
, LD_CONFIG
,
2464 "Interface IP address '%s' is a private address too. "
2465 "Ignoring.", tmpbuf
);
2468 in
.s_addr
= htonl(interface_ip
);
2469 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2470 log_fn(notice_severity
, LD_CONFIG
,
2471 "Learned IP address '%s' for local interface."
2472 " Using that.", tmpbuf
);
2473 strlcpy(hostname
, "<guessed from interfaces>", sizeof(hostname
));
2479 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2480 if (is_internal_IP(ntohl(in
.s_addr
), 0) &&
2481 options
->_PublishServerDescriptor
) {
2482 /* make sure we're ok with publishing an internal IP */
2483 if (!options
->DirServers
&& !options
->AlternateDirAuthority
) {
2484 /* if they are using the default dirservers, disallow internal IPs
2486 log_fn(warn_severity
, LD_CONFIG
,
2487 "Address '%s' resolves to private IP address '%s'. "
2488 "Tor servers that use the default DirServers must have public "
2489 "IP addresses.", hostname
, tmpbuf
);
2493 /* even if they've set their own dirservers, require an explicit IP if
2494 * they're using an internal address. */
2495 log_fn(warn_severity
, LD_CONFIG
, "Address '%s' resolves to private "
2496 "IP address '%s'. Please set the Address config option to be "
2497 "the IP address you want to use.", hostname
, tmpbuf
);
2502 log_debug(LD_CONFIG
, "Resolved Address to '%s'.", tmpbuf
);
2503 *addr_out
= ntohl(in
.s_addr
);
2504 if (last_resolved_addr
&& last_resolved_addr
!= *addr_out
) {
2505 /* Leave this as a notice, regardless of the requested severity,
2506 * at least until dynamic IP address support becomes bulletproof. */
2508 "Your IP address seems to have changed to %s. Updating.",
2510 ip_address_changed(0);
2512 if (last_resolved_addr
!= *addr_out
) {
2514 const char *h
= hostname
;
2516 method
= "CONFIGURED";
2518 } else if (explicit_hostname
) {
2519 method
= "RESOLVED";
2520 } else if (from_interface
) {
2521 method
= "INTERFACE";
2524 method
= "GETHOSTNAME";
2526 control_event_server_status(LOG_NOTICE
,
2527 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2528 tmpbuf
, method
, h
?"HOSTNAME=":"", h
);
2530 last_resolved_addr
= *addr_out
;
2532 *hostname_out
= tor_strdup(hostname
);
2536 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2537 * on a private network.
2540 is_local_addr(const tor_addr_t
*addr
)
2542 if (tor_addr_is_internal(addr
, 0))
2544 /* Check whether ip is on the same /24 as we are. */
2545 if (get_options()->EnforceDistinctSubnets
== 0)
2547 if (tor_addr_family(addr
) == AF_INET
) {
2548 /*XXXX022 IP6 what corresponds to an /24? */
2549 uint32_t ip
= tor_addr_to_ipv4h(addr
);
2551 /* It's possible that this next check will hit before the first time
2552 * resolve_my_address actually succeeds. (For clients, it is likely that
2553 * resolve_my_address will never be called at all). In those cases,
2554 * last_resolved_addr will be 0, and so checking to see whether ip is on
2555 * the same /24 as last_resolved_addr will be the same as checking whether
2556 * it was on net 0, which is already done by is_internal_IP.
2558 if ((last_resolved_addr
& (uint32_t)0xffffff00ul
)
2559 == (ip
& (uint32_t)0xffffff00ul
))
2565 /** Called when we don't have a nickname set. Try to guess a good nickname
2566 * based on the hostname, and return it in a newly allocated string. If we
2567 * can't, return NULL and let the caller warn if it wants to. */
2569 get_default_nickname(void)
2571 static const char * const bad_default_nicknames
[] = {
2575 char localhostname
[256];
2576 char *cp
, *out
, *outp
;
2579 if (gethostname(localhostname
, sizeof(localhostname
)) < 0)
2582 /* Put it in lowercase; stop at the first dot. */
2583 if ((cp
= strchr(localhostname
, '.')))
2585 tor_strlower(localhostname
);
2587 /* Strip invalid characters. */
2589 out
= outp
= tor_malloc(strlen(localhostname
) + 1);
2591 if (strchr(LEGAL_NICKNAME_CHARACTERS
, *cp
))
2598 /* Enforce length. */
2599 if (strlen(out
) > MAX_NICKNAME_LEN
)
2600 out
[MAX_NICKNAME_LEN
]='\0';
2602 /* Check for dumb names. */
2603 for (i
= 0; bad_default_nicknames
[i
]; ++i
) {
2604 if (!strcmp(out
, bad_default_nicknames
[i
])) {
2613 /** Release storage held by <b>options</b>. */
2615 config_free(config_format_t
*fmt
, void *options
)
2624 for (i
=0; fmt
->vars
[i
].name
; ++i
)
2625 option_clear(fmt
, options
, &(fmt
->vars
[i
]));
2627 config_line_t
**linep
= STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
2628 config_free_lines(*linep
);
2634 /** Return true iff a and b contain identical keys and values in identical
2637 config_lines_eq(config_line_t
*a
, config_line_t
*b
)
2640 if (strcasecmp(a
->key
, b
->key
) || strcmp(a
->value
, b
->value
))
2650 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2651 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2654 option_is_same(config_format_t
*fmt
,
2655 or_options_t
*o1
, or_options_t
*o2
, const char *name
)
2657 config_line_t
*c1
, *c2
;
2662 c1
= get_assigned_option(fmt
, o1
, name
, 0);
2663 c2
= get_assigned_option(fmt
, o2
, name
, 0);
2664 r
= config_lines_eq(c1
, c2
);
2665 config_free_lines(c1
);
2666 config_free_lines(c2
);
2670 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2671 static or_options_t
*
2672 options_dup(config_format_t
*fmt
, or_options_t
*old
)
2674 or_options_t
*newopts
;
2676 config_line_t
*line
;
2678 newopts
= config_alloc(fmt
);
2679 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2680 if (fmt
->vars
[i
].type
== CONFIG_TYPE_LINELIST_S
)
2682 if (fmt
->vars
[i
].type
== CONFIG_TYPE_OBSOLETE
)
2684 line
= get_assigned_option(fmt
, old
, fmt
->vars
[i
].name
, 0);
2687 if (config_assign(fmt
, newopts
, line
, 0, 0, &msg
) < 0) {
2688 log_err(LD_BUG
, "Config_get_assigned_option() generated "
2689 "something we couldn't config_assign(): %s", msg
);
2694 config_free_lines(line
);
2699 /** Return a new empty or_options_t. Used for testing. */
2703 return config_alloc(&options_format
);
2706 /** Set <b>options</b> to hold reasonable defaults for most options.
2707 * Each option defaults to zero. */
2709 options_init(or_options_t
*options
)
2711 config_init(&options_format
, options
);
2714 /* Check if the port number given in <b>port_option</b> in combination with
2715 * the specified port in <b>listen_options</b> will result in Tor actually
2716 * opening a low port (meaning a port lower than 1024). Return 1 if
2717 * it is, or 0 if it isn't or the concept of a low port isn't applicable for
2718 * the platform we're on. */
2720 is_listening_on_low_port(uint16_t port_option
,
2721 const config_line_t
*listen_options
)
2725 (void) listen_options
;
2726 return 0; /* No port is too low for windows. */
2728 const config_line_t
*l
;
2730 if (port_option
== 0)
2731 return 0; /* We're not listening */
2732 if (listen_options
== NULL
)
2733 return (port_option
< 1024);
2735 for (l
= listen_options
; l
; l
= l
->next
) {
2736 parse_addr_port(LOG_WARN
, l
->value
, NULL
, NULL
, &p
);
2745 /** Set all vars in the configuration object <b>options</b> to their default
2748 config_init(config_format_t
*fmt
, void *options
)
2752 CHECK(fmt
, options
);
2754 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2755 var
= &fmt
->vars
[i
];
2756 if (!var
->initvalue
)
2757 continue; /* defaults to NULL or 0 */
2758 option_reset(fmt
, options
, var
, 1);
2762 /** Allocate and return a new string holding the written-out values of the vars
2763 * in 'options'. If 'minimal', do not write out any default-valued vars.
2764 * Else, if comment_defaults, write default values as comments.
2767 config_dump(config_format_t
*fmt
, void *options
, int minimal
,
2768 int comment_defaults
)
2770 smartlist_t
*elements
;
2771 or_options_t
*defaults
;
2772 config_line_t
*line
, *assigned
;
2778 defaults
= config_alloc(fmt
);
2779 config_init(fmt
, defaults
);
2781 /* XXX use a 1 here so we don't add a new log line while dumping */
2782 if (fmt
->validate_fn(NULL
,defaults
, 1, &msg
) < 0) {
2783 log_err(LD_BUG
, "Failed to validate default config.");
2788 elements
= smartlist_create();
2789 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2790 int comment_option
= 0;
2791 if (fmt
->vars
[i
].type
== CONFIG_TYPE_OBSOLETE
||
2792 fmt
->vars
[i
].type
== CONFIG_TYPE_LINELIST_S
)
2794 /* Don't save 'hidden' control variables. */
2795 if (!strcmpstart(fmt
->vars
[i
].name
, "__"))
2797 if (minimal
&& option_is_same(fmt
, options
, defaults
, fmt
->vars
[i
].name
))
2799 else if (comment_defaults
&&
2800 option_is_same(fmt
, options
, defaults
, fmt
->vars
[i
].name
))
2803 desc
= config_find_description(fmt
, fmt
->vars
[i
].name
);
2804 line
= assigned
= get_assigned_option(fmt
, options
, fmt
->vars
[i
].name
, 1);
2807 /* Only dump the description if there's something to describe. */
2808 wrap_string(elements
, desc
, 78, "# ", "# ");
2811 for (; line
; line
= line
->next
) {
2812 size_t len
= strlen(line
->key
) + strlen(line
->value
) + 5;
2814 tmp
= tor_malloc(len
);
2815 if (tor_snprintf(tmp
, len
, "%s%s %s\n",
2816 comment_option
? "# " : "",
2817 line
->key
, line
->value
)<0) {
2818 log_err(LD_BUG
,"Internal error writing option value");
2821 smartlist_add(elements
, tmp
);
2823 config_free_lines(assigned
);
2827 line
= *(config_line_t
**)STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
2828 for (; line
; line
= line
->next
) {
2829 size_t len
= strlen(line
->key
) + strlen(line
->value
) + 3;
2831 tmp
= tor_malloc(len
);
2832 if (tor_snprintf(tmp
, len
, "%s %s\n", line
->key
, line
->value
)<0) {
2833 log_err(LD_BUG
,"Internal error writing option value");
2836 smartlist_add(elements
, tmp
);
2840 result
= smartlist_join_strings(elements
, "", 0, NULL
);
2841 SMARTLIST_FOREACH(elements
, char *, cp
, tor_free(cp
));
2842 smartlist_free(elements
);
2843 config_free(fmt
, defaults
);
2847 /** Return a string containing a possible configuration file that would give
2848 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2849 * include options that are the same as Tor's defaults.
2852 options_dump(or_options_t
*options
, int minimal
)
2854 return config_dump(&options_format
, options
, minimal
, 0);
2857 /** Return 0 if every element of sl is a string holding a decimal
2858 * representation of a port number, or if sl is NULL.
2859 * Otherwise set *msg and return -1. */
2861 validate_ports_csv(smartlist_t
*sl
, const char *name
, char **msg
)
2870 SMARTLIST_FOREACH(sl
, const char *, cp
,
2873 if (i
< 1 || i
> 65535) {
2874 int r
= tor_snprintf(buf
, sizeof(buf
),
2875 "Port '%s' out of range in %s", cp
, name
);
2876 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
2883 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2884 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2888 ensure_bandwidth_cap(uint64_t *value
, const char *desc
, char **msg
)
2892 if (*value
> ROUTER_MAX_DECLARED_BANDWIDTH
) {
2893 /* This handles an understandable special case where somebody says "2gb"
2894 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2897 if (*value
> ROUTER_MAX_DECLARED_BANDWIDTH
) {
2898 r
= tor_snprintf(buf
, sizeof(buf
), "%s ("U64_FORMAT
") must be at most %d",
2899 desc
, U64_PRINTF_ARG(*value
),
2900 ROUTER_MAX_DECLARED_BANDWIDTH
);
2901 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
2907 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2908 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2909 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2911 * Return 0 on success or -1 if not a recognized authority type (in which
2912 * case the value of _PublishServerDescriptor is undefined). */
2914 compute_publishserverdescriptor(or_options_t
*options
)
2916 smartlist_t
*list
= options
->PublishServerDescriptor
;
2917 authority_type_t
*auth
= &options
->_PublishServerDescriptor
;
2918 *auth
= NO_AUTHORITY
;
2919 if (!list
) /* empty list, answer is none */
2921 SMARTLIST_FOREACH(list
, const char *, string
, {
2922 if (!strcasecmp(string
, "v1"))
2923 *auth
|= V1_AUTHORITY
;
2924 else if (!strcmp(string
, "1"))
2925 if (options
->BridgeRelay
)
2926 *auth
|= BRIDGE_AUTHORITY
;
2928 *auth
|= V2_AUTHORITY
| V3_AUTHORITY
;
2929 else if (!strcasecmp(string
, "v2"))
2930 *auth
|= V2_AUTHORITY
;
2931 else if (!strcasecmp(string
, "v3"))
2932 *auth
|= V3_AUTHORITY
;
2933 else if (!strcasecmp(string
, "bridge"))
2934 *auth
|= BRIDGE_AUTHORITY
;
2935 else if (!strcasecmp(string
, "hidserv"))
2936 *auth
|= HIDSERV_AUTHORITY
;
2937 else if (!strcasecmp(string
, "") || !strcmp(string
, "0"))
2945 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2946 * services can overload the directory system. */
2947 #define MIN_REND_POST_PERIOD (10*60)
2949 /** Highest allowable value for RendPostPeriod. */
2950 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2952 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2953 * will generate too many circuits and potentially overload the network. */
2954 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2956 /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
2957 * will generate too many circuits and potentially overload the network. */
2958 #define MIN_CIRCUIT_STREAM_TIMEOUT 10
2960 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2961 * permissible transition from <b>old_options</b>. Else return -1.
2962 * Should have no side effects, except for normalizing the contents of
2965 * On error, tor_strdup an error explanation into *<b>msg</b>.
2968 * If <b>from_setconf</b>, we were called by the controller, and our
2969 * Log line should stay empty. If it's 0, then give us a default log
2970 * if there are no logs defined.
2973 options_validate(or_options_t
*old_options
, or_options_t
*options
,
2974 int from_setconf
, char **msg
)
2978 const char *uname
= get_uname();
2980 #define REJECT(arg) \
2981 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2982 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2987 if (options
->ORPort
< 0 || options
->ORPort
> 65535)
2988 REJECT("ORPort option out of bounds.");
2990 if (server_mode(options
) &&
2991 (!strcmpstart(uname
, "Windows 95") ||
2992 !strcmpstart(uname
, "Windows 98") ||
2993 !strcmpstart(uname
, "Windows Me"))) {
2994 log(LOG_WARN
, LD_CONFIG
, "Tor is running as a server, but you are "
2995 "running %s; this probably won't work. See "
2996 "https://wiki.torproject.org/TheOnionRouter/TorFAQ#ServerOS "
2997 "for details.", uname
);
3000 if (options
->ORPort
== 0 && options
->ORListenAddress
!= NULL
)
3001 REJECT("ORPort must be defined if ORListenAddress is defined.");
3003 if (options
->DirPort
== 0 && options
->DirListenAddress
!= NULL
)
3004 REJECT("DirPort must be defined if DirListenAddress is defined.");
3006 if (options
->DNSPort
== 0 && options
->DNSListenAddress
!= NULL
)
3007 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
3009 if (options
->ControlPort
== 0 && options
->ControlListenAddress
!= NULL
)
3010 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
3012 if (options
->TransPort
== 0 && options
->TransListenAddress
!= NULL
)
3013 REJECT("TransPort must be defined if TransListenAddress is defined.");
3015 if (options
->NatdPort
== 0 && options
->NatdListenAddress
!= NULL
)
3016 REJECT("NatdPort must be defined if NatdListenAddress is defined.");
3018 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
3019 * configuration does this. */
3021 for (i
= 0; i
< 3; ++i
) {
3022 int is_socks
= i
==0;
3023 int is_trans
= i
==1;
3024 config_line_t
*line
, *opt
, *old
;
3027 opt
= options
->SocksListenAddress
;
3028 old
= old_options
? old_options
->SocksListenAddress
: NULL
;
3030 } else if (is_trans
) {
3031 opt
= options
->TransListenAddress
;
3032 old
= old_options
? old_options
->TransListenAddress
: NULL
;
3033 tp
= "transparent proxy";
3035 opt
= options
->NatdListenAddress
;
3036 old
= old_options
? old_options
->NatdListenAddress
: NULL
;
3040 for (line
= opt
; line
; line
= line
->next
) {
3041 char *address
= NULL
;
3044 if (parse_addr_port(LOG_WARN
, line
->value
, &address
, &addr
, &port
)<0)
3045 continue; /* We'll warn about this later. */
3046 if (!is_internal_IP(addr
, 1) &&
3047 (!old_options
|| !config_lines_eq(old
, opt
))) {
3049 "You specified a public address '%s' for a %s. Other "
3050 "people on the Internet might find your computer and use it as "
3051 "an open %s. Please don't allow this unless you have "
3052 "a good reason.", address
, tp
, tp
);
3058 if (validate_data_directory(options
)<0)
3059 REJECT("Invalid DataDirectory");
3061 if (options
->Nickname
== NULL
) {
3062 if (server_mode(options
)) {
3063 if (!(options
->Nickname
= get_default_nickname())) {
3064 log_notice(LD_CONFIG
, "Couldn't pick a nickname based on "
3065 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME
);
3066 options
->Nickname
= tor_strdup(UNNAMED_ROUTER_NICKNAME
);
3068 log_notice(LD_CONFIG
, "Choosing default nickname '%s'",
3073 if (!is_legal_nickname(options
->Nickname
)) {
3074 r
= tor_snprintf(buf
, sizeof(buf
),
3075 "Nickname '%s' is wrong length or contains illegal characters.",
3077 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3082 if (server_mode(options
) && !options
->ContactInfo
)
3083 log(LOG_NOTICE
, LD_CONFIG
, "Your ContactInfo config option is not set. "
3084 "Please consider setting it, so we can contact you if your server is "
3085 "misconfigured or something else goes wrong.");
3087 /* Special case on first boot if no Log options are given. */
3088 if (!options
->Logs
&& !options
->RunAsDaemon
&& !from_setconf
)
3089 config_line_append(&options
->Logs
, "Log", "notice stdout");
3091 if (options_init_logs(options
, 1)<0) /* Validate the log(s) */
3092 REJECT("Failed to validate Log options. See logs for details.");
3094 if (options
->NoPublish
) {
3095 log(LOG_WARN
, LD_CONFIG
,
3096 "NoPublish is obsolete. Use PublishServerDescriptor instead.");
3097 SMARTLIST_FOREACH(options
->PublishServerDescriptor
, char *, s
,
3099 smartlist_clear(options
->PublishServerDescriptor
);
3102 if (authdir_mode(options
)) {
3103 /* confirm that our address isn't broken, so we can complain now */
3105 if (resolve_my_address(LOG_WARN
, options
, &tmp
, NULL
) < 0)
3106 REJECT("Failed to resolve/guess local address. See logs for details.");
3110 if (options
->RunAsDaemon
&& torrc_fname
&& path_is_relative(torrc_fname
))
3111 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
3114 if (options
->SocksPort
< 0 || options
->SocksPort
> 65535)
3115 REJECT("SocksPort option out of bounds.");
3117 if (options
->DNSPort
< 0 || options
->DNSPort
> 65535)
3118 REJECT("DNSPort option out of bounds.");
3120 if (options
->TransPort
< 0 || options
->TransPort
> 65535)
3121 REJECT("TransPort option out of bounds.");
3123 if (options
->NatdPort
< 0 || options
->NatdPort
> 65535)
3124 REJECT("NatdPort option out of bounds.");
3126 if (options
->SocksPort
== 0 && options
->TransPort
== 0 &&
3127 options
->NatdPort
== 0 && options
->ORPort
== 0 &&
3128 options
->DNSPort
== 0 && !options
->RendConfigLines
)
3129 log(LOG_WARN
, LD_CONFIG
,
3130 "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
3131 "undefined, and there aren't any hidden services configured. "
3132 "Tor will still run, but probably won't do anything.");
3134 if (options
->ControlPort
< 0 || options
->ControlPort
> 65535)
3135 REJECT("ControlPort option out of bounds.");
3137 if (options
->DirPort
< 0 || options
->DirPort
> 65535)
3138 REJECT("DirPort option out of bounds.");
3140 #ifndef USE_TRANSPARENT
3141 if (options
->TransPort
|| options
->TransListenAddress
)
3142 REJECT("TransPort and TransListenAddress are disabled in this build.");
3145 if (options
->AccountingMax
&&
3146 (is_listening_on_low_port(options
->ORPort
, options
->ORListenAddress
) ||
3147 is_listening_on_low_port(options
->DirPort
, options
->DirListenAddress
)))
3149 log(LOG_WARN
, LD_CONFIG
,
3150 "You have set AccountingMax to use hibernation. You have also "
3151 "chosen a low DirPort or OrPort. This combination can make Tor stop "
3152 "working when it tries to re-attach the port after a period of "
3153 "hibernation. Please choose a different port or turn off "
3154 "hibernation unless you know this combination will work on your "
3158 if (options
->ExcludeExitNodes
|| options
->ExcludeNodes
) {
3159 options
->_ExcludeExitNodesUnion
= routerset_new();
3160 routerset_union(options
->_ExcludeExitNodesUnion
,options
->ExcludeExitNodes
);
3161 routerset_union(options
->_ExcludeExitNodesUnion
,options
->ExcludeNodes
);
3164 if (options
->StrictExitNodes
&&
3165 (!options
->ExitNodes
) &&
3167 (old_options
->StrictExitNodes
!= options
->StrictExitNodes
) ||
3168 (!routerset_equal(old_options
->ExitNodes
,options
->ExitNodes
))))
3169 COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
3171 if (options
->StrictEntryNodes
&&
3172 (!options
->EntryNodes
) &&
3174 (old_options
->StrictEntryNodes
!= options
->StrictEntryNodes
) ||
3175 (!routerset_equal(old_options
->EntryNodes
,options
->EntryNodes
))))
3176 COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
3178 if (options
->EntryNodes
&& !routerset_is_list(options
->EntryNodes
)) {
3179 /* XXXX fix this; see entry_guards_prepend_from_config(). */
3180 REJECT("IPs or countries are not yet supported in EntryNodes.");
3183 if (options
->AuthoritativeDir
) {
3184 if (!options
->ContactInfo
&& !options
->TestingTorNetwork
)
3185 REJECT("Authoritative directory servers must set ContactInfo");
3186 if (options
->V1AuthoritativeDir
&& !options
->RecommendedVersions
)
3187 REJECT("V1 authoritative dir servers must set RecommendedVersions.");
3188 if (!options
->RecommendedClientVersions
)
3189 options
->RecommendedClientVersions
=
3190 config_lines_dup(options
->RecommendedVersions
);
3191 if (!options
->RecommendedServerVersions
)
3192 options
->RecommendedServerVersions
=
3193 config_lines_dup(options
->RecommendedVersions
);
3194 if (options
->VersioningAuthoritativeDir
&&
3195 (!options
->RecommendedClientVersions
||
3196 !options
->RecommendedServerVersions
))
3197 REJECT("Versioning authoritative dir servers must set "
3198 "Recommended*Versions.");
3199 if (options
->UseEntryGuards
) {
3200 log_info(LD_CONFIG
, "Authoritative directory servers can't set "
3201 "UseEntryGuards. Disabling.");
3202 options
->UseEntryGuards
= 0;
3204 if (!options
->DownloadExtraInfo
&& authdir_mode_any_main(options
)) {
3205 log_info(LD_CONFIG
, "Authoritative directories always try to download "
3206 "extra-info documents. Setting DownloadExtraInfo.");
3207 options
->DownloadExtraInfo
= 1;
3209 if (!(options
->BridgeAuthoritativeDir
|| options
->HSAuthoritativeDir
||
3210 options
->V1AuthoritativeDir
|| options
->V2AuthoritativeDir
||
3211 options
->V3AuthoritativeDir
))
3212 REJECT("AuthoritativeDir is set, but none of "
3213 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
3214 /* If we have a v3bandwidthsfile and it's broken, complain on startup */
3215 if (options
->V3BandwidthsFile
&& !old_options
) {
3216 dirserv_read_measured_bandwidths(options
->V3BandwidthsFile
, NULL
);
3220 if (options
->AuthoritativeDir
&& !options
->DirPort
)
3221 REJECT("Running as authoritative directory, but no DirPort set.");
3223 if (options
->AuthoritativeDir
&& !options
->ORPort
)
3224 REJECT("Running as authoritative directory, but no ORPort set.");
3226 if (options
->AuthoritativeDir
&& options
->ClientOnly
)
3227 REJECT("Running as authoritative directory, but ClientOnly also set.");
3229 if (options
->HSAuthorityRecordStats
&& !options
->HSAuthoritativeDir
)
3230 REJECT("HSAuthorityRecordStats is set but we're not running as "
3231 "a hidden service authority.");
3233 if (options
->FetchDirInfoExtraEarly
&& !options
->FetchDirInfoEarly
)
3234 REJECT("FetchDirInfoExtraEarly requires that you also set "
3235 "FetchDirInfoEarly");
3237 if (options
->ConnLimit
<= 0) {
3238 r
= tor_snprintf(buf
, sizeof(buf
),
3239 "ConnLimit must be greater than 0, but was set to %d",
3240 options
->ConnLimit
);
3241 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3245 if (validate_ports_csv(options
->FirewallPorts
, "FirewallPorts", msg
) < 0)
3248 if (validate_ports_csv(options
->LongLivedPorts
, "LongLivedPorts", msg
) < 0)
3251 if (validate_ports_csv(options
->RejectPlaintextPorts
,
3252 "RejectPlaintextPorts", msg
) < 0)
3255 if (validate_ports_csv(options
->WarnPlaintextPorts
,
3256 "WarnPlaintextPorts", msg
) < 0)
3259 if (options
->FascistFirewall
&& !options
->ReachableAddresses
) {
3260 if (options
->FirewallPorts
&& smartlist_len(options
->FirewallPorts
)) {
3261 /* We already have firewall ports set, so migrate them to
3262 * ReachableAddresses, which will set ReachableORAddresses and
3263 * ReachableDirAddresses if they aren't set explicitly. */
3264 smartlist_t
*instead
= smartlist_create();
3265 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
3266 new_line
->key
= tor_strdup("ReachableAddresses");
3267 /* If we're configured with the old format, we need to prepend some
3269 SMARTLIST_FOREACH(options
->FirewallPorts
, const char *, portno
,
3271 int p
= atoi(portno
);
3275 tor_snprintf(s
, 16, "*:%d", p
);
3276 smartlist_add(instead
, s
);
3278 new_line
->value
= smartlist_join_strings(instead
,",",0,NULL
);
3279 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3280 log(LOG_NOTICE
, LD_CONFIG
,
3281 "Converting FascistFirewall and FirewallPorts "
3282 "config options to new format: \"ReachableAddresses %s\"",
3284 options
->ReachableAddresses
= new_line
;
3285 SMARTLIST_FOREACH(instead
, char *, cp
, tor_free(cp
));
3286 smartlist_free(instead
);
3288 /* We do not have FirewallPorts set, so add 80 to
3289 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3290 if (!options
->ReachableDirAddresses
) {
3291 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
3292 new_line
->key
= tor_strdup("ReachableDirAddresses");
3293 new_line
->value
= tor_strdup("*:80");
3294 options
->ReachableDirAddresses
= new_line
;
3295 log(LOG_NOTICE
, LD_CONFIG
, "Converting FascistFirewall config option "
3296 "to new format: \"ReachableDirAddresses *:80\"");
3298 if (!options
->ReachableORAddresses
) {
3299 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
3300 new_line
->key
= tor_strdup("ReachableORAddresses");
3301 new_line
->value
= tor_strdup("*:443");
3302 options
->ReachableORAddresses
= new_line
;
3303 log(LOG_NOTICE
, LD_CONFIG
, "Converting FascistFirewall config option "
3304 "to new format: \"ReachableORAddresses *:443\"");
3309 for (i
=0; i
<3; i
++) {
3310 config_line_t
**linep
=
3311 (i
==0) ? &options
->ReachableAddresses
:
3312 (i
==1) ? &options
->ReachableORAddresses
:
3313 &options
->ReachableDirAddresses
;
3316 /* We need to end with a reject *:*, not an implicit accept *:* */
3318 if (!strcmp((*linep
)->value
, "reject *:*")) /* already there */
3320 linep
= &((*linep
)->next
);
3322 *linep
= tor_malloc_zero(sizeof(config_line_t
));
3323 (*linep
)->key
= tor_strdup(
3324 (i
==0) ? "ReachableAddresses" :
3325 (i
==1) ? "ReachableORAddresses" :
3326 "ReachableDirAddresses");
3327 (*linep
)->value
= tor_strdup("reject *:*");
3333 if ((options
->ReachableAddresses
||
3334 options
->ReachableORAddresses
||
3335 options
->ReachableDirAddresses
) &&
3336 server_mode(options
))
3337 REJECT("Servers must be able to freely connect to the rest "
3338 "of the Internet, so they must not set Reachable*Addresses "
3339 "or FascistFirewall.");
3341 if (options
->UseBridges
&&
3342 server_mode(options
))
3343 REJECT("Servers must be able to freely connect to the rest "
3344 "of the Internet, so they must not set UseBridges.");
3346 options
->_AllowInvalid
= 0;
3347 if (options
->AllowInvalidNodes
) {
3348 SMARTLIST_FOREACH(options
->AllowInvalidNodes
, const char *, cp
, {
3349 if (!strcasecmp(cp
, "entry"))
3350 options
->_AllowInvalid
|= ALLOW_INVALID_ENTRY
;
3351 else if (!strcasecmp(cp
, "exit"))
3352 options
->_AllowInvalid
|= ALLOW_INVALID_EXIT
;
3353 else if (!strcasecmp(cp
, "middle"))
3354 options
->_AllowInvalid
|= ALLOW_INVALID_MIDDLE
;
3355 else if (!strcasecmp(cp
, "introduction"))
3356 options
->_AllowInvalid
|= ALLOW_INVALID_INTRODUCTION
;
3357 else if (!strcasecmp(cp
, "rendezvous"))
3358 options
->_AllowInvalid
|= ALLOW_INVALID_RENDEZVOUS
;
3360 r
= tor_snprintf(buf
, sizeof(buf
),
3361 "Unrecognized value '%s' in AllowInvalidNodes", cp
);
3362 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3368 if (compute_publishserverdescriptor(options
) < 0) {
3369 r
= tor_snprintf(buf
, sizeof(buf
),
3370 "Unrecognized value in PublishServerDescriptor");
3371 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3375 if ((options
->BridgeRelay
3376 || options
->_PublishServerDescriptor
& BRIDGE_AUTHORITY
)
3377 && (options
->_PublishServerDescriptor
3378 & (V1_AUTHORITY
|V2_AUTHORITY
|V3_AUTHORITY
))) {
3379 REJECT("Bridges are not supposed to publish router descriptors to the "
3380 "directory authorities. Please correct your "
3381 "PublishServerDescriptor line.");
3384 if (options
->MinUptimeHidServDirectoryV2
< 0) {
3385 log_warn(LD_CONFIG
, "MinUptimeHidServDirectoryV2 option must be at "
3386 "least 0 seconds. Changing to 0.");
3387 options
->MinUptimeHidServDirectoryV2
= 0;
3390 if (options
->RendPostPeriod
< MIN_REND_POST_PERIOD
) {
3391 log_warn(LD_CONFIG
, "RendPostPeriod option is too short; "
3392 "raising to %d seconds.", MIN_REND_POST_PERIOD
);
3393 options
->RendPostPeriod
= MIN_REND_POST_PERIOD
;
3396 if (options
->RendPostPeriod
> MAX_DIR_PERIOD
) {
3397 log_warn(LD_CONFIG
, "RendPostPeriod is too large; clipping to %ds.",
3399 options
->RendPostPeriod
= MAX_DIR_PERIOD
;
3402 if (options
->MaxCircuitDirtiness
< MIN_MAX_CIRCUIT_DIRTINESS
) {
3403 log_warn(LD_CONFIG
, "MaxCircuitDirtiness option is too short; "
3404 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS
);
3405 options
->MaxCircuitDirtiness
= MIN_MAX_CIRCUIT_DIRTINESS
;
3408 if (options
->CircuitStreamTimeout
&&
3409 options
->CircuitStreamTimeout
< MIN_CIRCUIT_STREAM_TIMEOUT
) {
3410 log_warn(LD_CONFIG
, "CircuitStreamTimeout option is too short; "
3411 "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT
);
3412 options
->CircuitStreamTimeout
= MIN_CIRCUIT_STREAM_TIMEOUT
;
3415 if (options
->KeepalivePeriod
< 1)
3416 REJECT("KeepalivePeriod option must be positive.");
3418 if (ensure_bandwidth_cap(&options
->BandwidthRate
,
3419 "BandwidthRate", msg
) < 0)
3421 if (ensure_bandwidth_cap(&options
->BandwidthBurst
,
3422 "BandwidthBurst", msg
) < 0)
3424 if (ensure_bandwidth_cap(&options
->MaxAdvertisedBandwidth
,
3425 "MaxAdvertisedBandwidth", msg
) < 0)
3427 if (ensure_bandwidth_cap(&options
->RelayBandwidthRate
,
3428 "RelayBandwidthRate", msg
) < 0)
3430 if (ensure_bandwidth_cap(&options
->RelayBandwidthBurst
,
3431 "RelayBandwidthBurst", msg
) < 0)
3434 if (server_mode(options
)) {
3435 if (options
->BandwidthRate
< ROUTER_REQUIRED_MIN_BANDWIDTH
) {
3436 r
= tor_snprintf(buf
, sizeof(buf
),
3437 "BandwidthRate is set to %d bytes/second. "
3438 "For servers, it must be at least %d.",
3439 (int)options
->BandwidthRate
,
3440 ROUTER_REQUIRED_MIN_BANDWIDTH
);
3441 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3443 } else if (options
->MaxAdvertisedBandwidth
<
3444 ROUTER_REQUIRED_MIN_BANDWIDTH
/2) {
3445 r
= tor_snprintf(buf
, sizeof(buf
),
3446 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3447 "For servers, it must be at least %d.",
3448 (int)options
->MaxAdvertisedBandwidth
,
3449 ROUTER_REQUIRED_MIN_BANDWIDTH
/2);
3450 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3453 if (options
->RelayBandwidthRate
&&
3454 options
->RelayBandwidthRate
< ROUTER_REQUIRED_MIN_BANDWIDTH
) {
3455 r
= tor_snprintf(buf
, sizeof(buf
),
3456 "RelayBandwidthRate is set to %d bytes/second. "
3457 "For servers, it must be at least %d.",
3458 (int)options
->RelayBandwidthRate
,
3459 ROUTER_REQUIRED_MIN_BANDWIDTH
);
3460 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3465 if (options
->RelayBandwidthRate
&& !options
->RelayBandwidthBurst
)
3466 options
->RelayBandwidthBurst
= options
->RelayBandwidthRate
;
3468 if (options
->RelayBandwidthRate
> options
->RelayBandwidthBurst
)
3469 REJECT("RelayBandwidthBurst must be at least equal "
3470 "to RelayBandwidthRate.");
3472 if (options
->BandwidthRate
> options
->BandwidthBurst
)
3473 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3475 /* if they set relaybandwidth* really high but left bandwidth*
3476 * at the default, raise the defaults. */
3477 if (options
->RelayBandwidthRate
> options
->BandwidthRate
)
3478 options
->BandwidthRate
= options
->RelayBandwidthRate
;
3479 if (options
->RelayBandwidthBurst
> options
->BandwidthBurst
)
3480 options
->BandwidthBurst
= options
->RelayBandwidthBurst
;
3482 if (accounting_parse_options(options
, 1)<0)
3483 REJECT("Failed to parse accounting options. See logs for details.");
3485 if (options
->HttpProxy
) { /* parse it now */
3486 if (tor_addr_port_parse(options
->HttpProxy
,
3487 &options
->HttpProxyAddr
, &options
->HttpProxyPort
) < 0)
3488 REJECT("HttpProxy failed to parse or resolve. Please fix.");
3489 if (options
->HttpProxyPort
== 0) { /* give it a default */
3490 options
->HttpProxyPort
= 80;
3494 if (options
->HttpProxyAuthenticator
) {
3495 if (strlen(options
->HttpProxyAuthenticator
) >= 48)
3496 REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
3499 if (options
->HttpsProxy
) { /* parse it now */
3500 if (tor_addr_port_parse(options
->HttpsProxy
,
3501 &options
->HttpsProxyAddr
, &options
->HttpsProxyPort
) <0)
3502 REJECT("HttpsProxy failed to parse or resolve. Please fix.");
3503 if (options
->HttpsProxyPort
== 0) { /* give it a default */
3504 options
->HttpsProxyPort
= 443;
3508 if (options
->HttpsProxyAuthenticator
) {
3509 if (strlen(options
->HttpsProxyAuthenticator
) >= 48)
3510 REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
3513 if (options
->Socks4Proxy
) { /* parse it now */
3514 if (tor_addr_port_parse(options
->Socks4Proxy
,
3515 &options
->Socks4ProxyAddr
,
3516 &options
->Socks4ProxyPort
) <0)
3517 REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
3518 if (options
->Socks4ProxyPort
== 0) { /* give it a default */
3519 options
->Socks4ProxyPort
= 1080;
3523 if (options
->Socks5Proxy
) { /* parse it now */
3524 if (tor_addr_port_parse(options
->Socks5Proxy
,
3525 &options
->Socks5ProxyAddr
,
3526 &options
->Socks5ProxyPort
) <0)
3527 REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
3528 if (options
->Socks5ProxyPort
== 0) { /* give it a default */
3529 options
->Socks5ProxyPort
= 1080;
3533 if (options
->Socks4Proxy
&& options
->Socks5Proxy
)
3534 REJECT("You cannot specify both Socks4Proxy and SOCKS5Proxy");
3536 if (options
->Socks5ProxyUsername
) {
3539 len
= strlen(options
->Socks5ProxyUsername
);
3540 if (len
< 1 || len
> 255)
3541 REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
3543 if (!options
->Socks5ProxyPassword
)
3544 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3546 len
= strlen(options
->Socks5ProxyPassword
);
3547 if (len
< 1 || len
> 255)
3548 REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
3549 } else if (options
->Socks5ProxyPassword
)
3550 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3552 if (options
->HashedControlPassword
) {
3553 smartlist_t
*sl
= decode_hashed_passwords(options
->HashedControlPassword
);
3555 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3557 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
3562 if (options
->HashedControlSessionPassword
) {
3563 smartlist_t
*sl
= decode_hashed_passwords(
3564 options
->HashedControlSessionPassword
);
3566 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3568 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
3573 if (options
->ControlListenAddress
) {
3574 int all_are_local
= 1;
3576 for (ln
= options
->ControlListenAddress
; ln
; ln
= ln
->next
) {
3577 if (strcmpstart(ln
->value
, "127."))
3580 if (!all_are_local
) {
3581 if (!options
->HashedControlPassword
&&
3582 !options
->HashedControlSessionPassword
&&
3583 !options
->CookieAuthentication
) {
3585 "You have a ControlListenAddress set to accept "
3586 "unauthenticated connections from a non-local address. "
3587 "This means that programs not running on your computer "
3588 "can reconfigure your Tor, without even having to guess a "
3589 "password. That's so bad that I'm closing your ControlPort "
3590 "for you. If you need to control your Tor remotely, try "
3591 "enabling authentication and using a tool like stunnel or "
3592 "ssh to encrypt remote access.");
3593 options
->ControlPort
= 0;
3595 log_warn(LD_CONFIG
, "You have a ControlListenAddress set to accept "
3596 "connections from a non-local address. This means that "
3597 "programs not running on your computer can reconfigure your "
3598 "Tor. That's pretty bad, since the controller "
3599 "protocol isn't encrypted! Maybe you should just listen on "
3600 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
3601 "remote connections to your control port.");
3606 if (options
->ControlPort
&& !options
->HashedControlPassword
&&
3607 !options
->HashedControlSessionPassword
&&
3608 !options
->CookieAuthentication
) {
3609 log_warn(LD_CONFIG
, "ControlPort is open, but no authentication method "
3610 "has been configured. This means that any program on your "
3611 "computer can reconfigure your Tor. That's bad! You should "
3612 "upgrade your Tor controller as soon as possible.");
3615 if (options
->UseEntryGuards
&& ! options
->NumEntryGuards
)
3616 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3618 if (check_nickname_list(options
->MyFamily
, "MyFamily", msg
))
3620 for (cl
= options
->NodeFamilies
; cl
; cl
= cl
->next
) {
3621 if (check_nickname_list(cl
->value
, "NodeFamily", msg
))
3625 if (validate_addr_policies(options
, msg
) < 0)
3628 if (validate_dir_authorities(options
, old_options
) < 0)
3629 REJECT("Directory authority line did not parse. See logs for details.");
3631 if (options
->UseBridges
&& !options
->Bridges
)
3632 REJECT("If you set UseBridges, you must specify at least one bridge.");
3633 if (options
->UseBridges
&& !options
->TunnelDirConns
)
3634 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3635 if (options
->Bridges
) {
3636 for (cl
= options
->Bridges
; cl
; cl
= cl
->next
) {
3637 if (parse_bridge_line(cl
->value
, 1)<0)
3638 REJECT("Bridge line did not parse. See logs for details.");
3642 if (options
->ConstrainedSockets
) {
3643 /* If the user wants to constrain socket buffer use, make sure the desired
3644 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3645 if (options
->ConstrainedSockSize
< MIN_CONSTRAINED_TCP_BUFFER
||
3646 options
->ConstrainedSockSize
> MAX_CONSTRAINED_TCP_BUFFER
||
3647 options
->ConstrainedSockSize
% 1024) {
3648 r
= tor_snprintf(buf
, sizeof(buf
),
3649 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3650 "in 1024 byte increments.",
3651 MIN_CONSTRAINED_TCP_BUFFER
, MAX_CONSTRAINED_TCP_BUFFER
);
3652 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3655 if (options
->DirPort
) {
3656 /* Providing cached directory entries while system TCP buffers are scarce
3657 * will exacerbate the socket errors. Suggest that this be disabled. */
3658 COMPLAIN("You have requested constrained socket buffers while also "
3659 "serving directory entries via DirPort. It is strongly "
3660 "suggested that you disable serving directory requests when "
3661 "system TCP buffer resources are scarce.");
3665 if (options
->V3AuthVoteDelay
+ options
->V3AuthDistDelay
>=
3666 options
->V3AuthVotingInterval
/2) {
3667 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3668 "V3AuthVotingInterval");
3670 if (options
->V3AuthVoteDelay
< MIN_VOTE_SECONDS
)
3671 REJECT("V3AuthVoteDelay is way too low.");
3672 if (options
->V3AuthDistDelay
< MIN_DIST_SECONDS
)
3673 REJECT("V3AuthDistDelay is way too low.");
3675 if (options
->V3AuthNIntervalsValid
< 2)
3676 REJECT("V3AuthNIntervalsValid must be at least 2.");
3678 if (options
->V3AuthVotingInterval
< MIN_VOTE_INTERVAL
) {
3679 REJECT("V3AuthVotingInterval is insanely low.");
3680 } else if (options
->V3AuthVotingInterval
> 24*60*60) {
3681 REJECT("V3AuthVotingInterval is insanely high.");
3682 } else if (((24*60*60) % options
->V3AuthVotingInterval
) != 0) {
3683 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3686 if (rend_config_services(options
, 1) < 0)
3687 REJECT("Failed to configure rendezvous options. See logs for details.");
3689 /* Parse client-side authorization for hidden services. */
3690 if (rend_parse_service_authorization(options
, 1) < 0)
3691 REJECT("Failed to configure client authorization for hidden services. "
3692 "See logs for details.");
3694 if (parse_virtual_addr_network(options
->VirtualAddrNetwork
, 1, NULL
)<0)
3697 if (options
->PreferTunneledDirConns
&& !options
->TunnelDirConns
)
3698 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3700 if ((options
->Socks4Proxy
|| options
->Socks5Proxy
) &&
3701 !options
->HttpProxy
&& !options
->PreferTunneledDirConns
)
3702 REJECT("When Socks4Proxy or Socks5Proxy is configured, "
3703 "PreferTunneledDirConns and TunnelDirConns must both be "
3704 "set to 1, or HttpProxy must be configured.");
3706 if (options
->AutomapHostsSuffixes
) {
3707 SMARTLIST_FOREACH(options
->AutomapHostsSuffixes
, char *, suf
,
3709 size_t len
= strlen(suf
);
3710 if (len
&& suf
[len
-1] == '.')
3715 if (options
->TestingTorNetwork
&& !options
->DirServers
) {
3716 REJECT("TestingTorNetwork may only be configured in combination with "
3717 "a non-default set of DirServers.");
3720 /*XXXX022 checking for defaults manually like this is a bit fragile.*/
3722 /* Keep changes to hard-coded values synchronous to man page and default
3724 if (options
->TestingV3AuthInitialVotingInterval
!= 30*60 &&
3725 !options
->TestingTorNetwork
) {
3726 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
3728 } else if (options
->TestingV3AuthInitialVotingInterval
< MIN_VOTE_INTERVAL
) {
3729 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3730 } else if (((30*60) % options
->TestingV3AuthInitialVotingInterval
) != 0) {
3731 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3735 if (options
->TestingV3AuthInitialVoteDelay
!= 5*60 &&
3736 !options
->TestingTorNetwork
) {
3737 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
3739 } else if (options
->TestingV3AuthInitialVoteDelay
< MIN_VOTE_SECONDS
) {
3740 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3743 if (options
->TestingV3AuthInitialDistDelay
!= 5*60 &&
3744 !options
->TestingTorNetwork
) {
3745 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
3747 } else if (options
->TestingV3AuthInitialDistDelay
< MIN_DIST_SECONDS
) {
3748 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3751 if (options
->TestingV3AuthInitialVoteDelay
+
3752 options
->TestingV3AuthInitialDistDelay
>=
3753 options
->TestingV3AuthInitialVotingInterval
/2) {
3754 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3755 "must be less than half TestingV3AuthInitialVotingInterval");
3758 if (options
->TestingAuthDirTimeToLearnReachability
!= 30*60 &&
3759 !options
->TestingTorNetwork
) {
3760 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
3761 "testing Tor networks!");
3762 } else if (options
->TestingAuthDirTimeToLearnReachability
< 0) {
3763 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3764 } else if (options
->TestingAuthDirTimeToLearnReachability
> 2*60*60) {
3765 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3768 if (options
->TestingEstimatedDescriptorPropagationTime
!= 10*60 &&
3769 !options
->TestingTorNetwork
) {
3770 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
3771 "testing Tor networks!");
3772 } else if (options
->TestingEstimatedDescriptorPropagationTime
< 0) {
3773 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3774 } else if (options
->TestingEstimatedDescriptorPropagationTime
> 60*60) {
3775 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3778 if (options
->TestingTorNetwork
) {
3779 log_warn(LD_CONFIG
, "TestingTorNetwork is set. This will make your node "
3780 "almost unusable in the public Tor network, and is "
3781 "therefore only advised if you are building a "
3782 "testing Tor network!");
3785 if (options
->AccelName
&& !options
->HardwareAccel
)
3786 options
->HardwareAccel
= 1;
3787 if (options
->AccelDir
&& !options
->AccelName
)
3788 REJECT("Can't use hardware crypto accelerator dir without engine name.");
3795 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3798 opt_streq(const char *s1
, const char *s2
)
3802 else if (s1
&& s2
&& !strcmp(s1
,s2
))
3808 /** Check if any of the previous options have changed but aren't allowed to. */
3810 options_transition_allowed(or_options_t
*old
, or_options_t
*new_val
,
3816 if (!opt_streq(old
->PidFile
, new_val
->PidFile
)) {
3817 *msg
= tor_strdup("PidFile is not allowed to change.");
3821 if (old
->RunAsDaemon
!= new_val
->RunAsDaemon
) {
3822 *msg
= tor_strdup("While Tor is running, changing RunAsDaemon "
3827 if (strcmp(old
->DataDirectory
,new_val
->DataDirectory
)!=0) {
3829 int r
= tor_snprintf(buf
, sizeof(buf
),
3830 "While Tor is running, changing DataDirectory "
3831 "(\"%s\"->\"%s\") is not allowed.",
3832 old
->DataDirectory
, new_val
->DataDirectory
);
3833 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3837 if (!opt_streq(old
->User
, new_val
->User
)) {
3838 *msg
= tor_strdup("While Tor is running, changing User is not allowed.");
3842 if (!opt_streq(old
->Group
, new_val
->Group
)) {
3843 *msg
= tor_strdup("While Tor is running, changing Group is not allowed.");
3847 if ((old
->HardwareAccel
!= new_val
->HardwareAccel
)
3848 || !opt_streq(old
->AccelName
, new_val
->AccelName
)
3849 || !opt_streq(old
->AccelDir
, new_val
->AccelDir
)) {
3850 *msg
= tor_strdup("While Tor is running, changing OpenSSL hardware "
3851 "acceleration engine is not allowed.");
3855 if (old
->TestingTorNetwork
!= new_val
->TestingTorNetwork
) {
3856 *msg
= tor_strdup("While Tor is running, changing TestingTorNetwork "
3861 if (old
->CellStatistics
!= new_val
->CellStatistics
||
3862 old
->DirReqStatistics
!= new_val
->DirReqStatistics
||
3863 old
->EntryStatistics
!= new_val
->EntryStatistics
||
3864 old
->ExitPortStatistics
!= new_val
->ExitPortStatistics
) {
3865 *msg
= tor_strdup("While Tor is running, changing either "
3866 "CellStatistics, DirReqStatistics, EntryStatistics, "
3867 "or ExitPortStatistics is not allowed.");
3871 if (old
->DisableAllSwap
!= new_val
->DisableAllSwap
) {
3872 *msg
= tor_strdup("While Tor is running, changing DisableAllSwap "
3880 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3881 * will require us to rotate the CPU and DNS workers; else return 0. */
3883 options_transition_affects_workers(or_options_t
*old_options
,
3884 or_options_t
*new_options
)
3886 if (!opt_streq(old_options
->DataDirectory
, new_options
->DataDirectory
) ||
3887 old_options
->NumCpus
!= new_options
->NumCpus
||
3888 old_options
->ORPort
!= new_options
->ORPort
||
3889 old_options
->ServerDNSSearchDomains
!=
3890 new_options
->ServerDNSSearchDomains
||
3891 old_options
->SafeLogging
!= new_options
->SafeLogging
||
3892 old_options
->ClientOnly
!= new_options
->ClientOnly
||
3893 !config_lines_eq(old_options
->Logs
, new_options
->Logs
))
3896 /* Check whether log options match. */
3898 /* Nothing that changed matters. */
3902 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3903 * will require us to generate a new descriptor; else return 0. */
3905 options_transition_affects_descriptor(or_options_t
*old_options
,
3906 or_options_t
*new_options
)
3908 /* XXX We can be smarter here. If your DirPort isn't being
3909 * published and you just turned it off, no need to republish. Etc. */
3910 if (!opt_streq(old_options
->DataDirectory
, new_options
->DataDirectory
) ||
3911 !opt_streq(old_options
->Nickname
,new_options
->Nickname
) ||
3912 !opt_streq(old_options
->Address
,new_options
->Address
) ||
3913 !config_lines_eq(old_options
->ExitPolicy
,new_options
->ExitPolicy
) ||
3914 old_options
->ExitPolicyRejectPrivate
!=
3915 new_options
->ExitPolicyRejectPrivate
||
3916 old_options
->ORPort
!= new_options
->ORPort
||
3917 old_options
->DirPort
!= new_options
->DirPort
||
3918 old_options
->ClientOnly
!= new_options
->ClientOnly
||
3919 old_options
->NoPublish
!= new_options
->NoPublish
||
3920 old_options
->_PublishServerDescriptor
!=
3921 new_options
->_PublishServerDescriptor
||
3922 get_effective_bwrate(old_options
) != get_effective_bwrate(new_options
) ||
3923 get_effective_bwburst(old_options
) !=
3924 get_effective_bwburst(new_options
) ||
3925 !opt_streq(old_options
->ContactInfo
, new_options
->ContactInfo
) ||
3926 !opt_streq(old_options
->MyFamily
, new_options
->MyFamily
) ||
3927 !opt_streq(old_options
->AccountingStart
, new_options
->AccountingStart
) ||
3928 old_options
->AccountingMax
!= new_options
->AccountingMax
)
3935 /** Return the directory on windows where we expect to find our application
3938 get_windows_conf_root(void)
3940 static int is_set
= 0;
3941 static char path
[MAX_PATH
+1];
3950 /* Find X:\documents and settings\username\application data\ .
3951 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3953 #ifdef ENABLE_LOCAL_APPDATA
3954 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
3956 #define APPDATA_PATH CSIDL_APPDATA
3958 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL
, APPDATA_PATH
, &idl
))) {
3959 GetCurrentDirectory(MAX_PATH
, path
);
3962 "I couldn't find your application data folder: are you "
3963 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3967 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3968 result
= SHGetPathFromIDList(idl
, path
);
3969 /* Now we need to free the */
3972 m
->lpVtbl
->Free(m
, idl
);
3973 m
->lpVtbl
->Release(m
);
3975 if (!SUCCEEDED(result
)) {
3978 strlcat(path
,"\\tor",MAX_PATH
);
3984 /** Return the default location for our torrc file. */
3986 get_default_conf_file(void)
3989 static char path
[MAX_PATH
+1];
3990 strlcpy(path
, get_windows_conf_root(), MAX_PATH
);
3991 strlcat(path
,"\\torrc",MAX_PATH
);
3994 return (CONFDIR
"/torrc");
3998 /** Verify whether lst is a string containing valid-looking comma-separated
3999 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
4002 check_nickname_list(const char *lst
, const char *name
, char **msg
)
4009 sl
= smartlist_create();
4011 smartlist_split_string(sl
, lst
, ",",
4012 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
|SPLIT_STRIP_SPACE
, 0);
4014 SMARTLIST_FOREACH(sl
, const char *, s
,
4016 if (!is_legal_nickname_or_hexdigest(s
)) {
4018 int tmp
= tor_snprintf(buf
, sizeof(buf
),
4019 "Invalid nickname '%s' in %s line", s
, name
);
4020 *msg
= tor_strdup(tmp
>= 0 ? buf
: "internal error");
4025 SMARTLIST_FOREACH(sl
, char *, s
, tor_free(s
));
4030 /** Learn config file name from command line arguments, or use the default */
4032 find_torrc_filename(int argc
, char **argv
,
4033 int *using_default_torrc
, int *ignore_missing_torrc
)
4038 for (i
= 1; i
< argc
; ++i
) {
4039 if (i
< argc
-1 && !strcmp(argv
[i
],"-f")) {
4041 log(LOG_WARN
, LD_CONFIG
, "Duplicate -f options on command line.");
4045 /* XXX one day we might want to extend expand_filename to work
4046 * under Windows as well. */
4047 fname
= tor_strdup(argv
[i
+1]);
4049 fname
= expand_filename(argv
[i
+1]);
4051 *using_default_torrc
= 0;
4053 } else if (!strcmp(argv
[i
],"--ignore-missing-torrc")) {
4054 *ignore_missing_torrc
= 1;
4058 if (*using_default_torrc
) {
4059 /* didn't find one, try CONFDIR */
4060 const char *dflt
= get_default_conf_file();
4061 if (dflt
&& file_status(dflt
) == FN_FILE
) {
4062 fname
= tor_strdup(dflt
);
4066 fn
= expand_filename("~/.torrc");
4067 if (fn
&& file_status(fn
) == FN_FILE
) {
4071 fname
= tor_strdup(dflt
);
4074 fname
= tor_strdup(dflt
);
4081 /** Load torrc from disk, setting torrc_fname if successful */
4083 load_torrc_from_disk(int argc
, char **argv
)
4087 int using_default_torrc
= 1;
4088 int ignore_missing_torrc
= 0;
4090 fname
= find_torrc_filename(argc
, argv
,
4091 &using_default_torrc
, &ignore_missing_torrc
);
4093 log(LOG_DEBUG
, LD_CONFIG
, "Opening config file \"%s\"", fname
);
4095 tor_free(torrc_fname
);
4096 torrc_fname
= fname
;
4098 /* Open config file */
4099 if (file_status(fname
) != FN_FILE
||
4100 !(cf
= read_file_to_str(fname
,0,NULL
))) {
4101 if (using_default_torrc
== 1 || ignore_missing_torrc
) {
4102 log(LOG_NOTICE
, LD_CONFIG
, "Configuration file \"%s\" not present, "
4103 "using reasonable defaults.", fname
);
4104 tor_free(fname
); /* sets fname to NULL */
4106 cf
= tor_strdup("");
4108 log(LOG_WARN
, LD_CONFIG
,
4109 "Unable to open configuration file \"%s\".", fname
);
4121 /** Read a configuration file into <b>options</b>, finding the configuration
4122 * file location based on the command line. After loading the file
4123 * call options_init_from_string() to load the config.
4124 * Return 0 if success, -1 if failure. */
4126 options_init_from_torrc(int argc
, char **argv
)
4129 int i
, retval
, command
;
4130 static char **backup_argv
;
4131 static int backup_argc
;
4132 char *command_arg
= NULL
;
4135 if (argv
) { /* first time we're called. save command line args */
4138 } else { /* we're reloading. need to clean up old options first. */
4142 if (argc
> 1 && (!strcmp(argv
[1], "-h") || !strcmp(argv
[1],"--help"))) {
4146 if (argc
> 1 && !strcmp(argv
[1], "--list-torrc-options")) {
4147 /* For documenting validating whether we've documented everything. */
4148 list_torrc_options();
4152 if (argc
> 1 && (!strcmp(argv
[1],"--version"))) {
4153 printf("Tor version %s.\n",get_version());
4156 if (argc
> 1 && (!strcmp(argv
[1],"--digests"))) {
4157 printf("Tor version %s.\n",get_version());
4158 printf("%s", libor_get_digests());
4159 printf("%s", tor_get_digests());
4163 /* Go through command-line variables */
4164 if (!global_cmdline_options
) {
4165 /* Or we could redo the list every time we pass this place.
4166 * It does not really matter */
4167 if (config_get_commandlines(argc
, argv
, &global_cmdline_options
) < 0) {
4172 command
= CMD_RUN_TOR
;
4173 for (i
= 1; i
< argc
; ++i
) {
4174 if (!strcmp(argv
[i
],"--list-fingerprint")) {
4175 command
= CMD_LIST_FINGERPRINT
;
4176 } else if (!strcmp(argv
[i
],"--hash-password")) {
4177 command
= CMD_HASH_PASSWORD
;
4178 command_arg
= tor_strdup( (i
< argc
-1) ? argv
[i
+1] : "");
4180 } else if (!strcmp(argv
[i
],"--verify-config")) {
4181 command
= CMD_VERIFY_CONFIG
;
4185 if (command
== CMD_HASH_PASSWORD
) {
4186 cf
= tor_strdup("");
4188 cf
= load_torrc_from_disk(argc
, argv
);
4193 retval
= options_init_from_string(cf
, command
, command_arg
, &errmsg
);
4202 log(LOG_WARN
,LD_CONFIG
,"%s", errmsg
);
4208 /** Load the options from the configuration in <b>cf</b>, validate
4209 * them for consistency and take actions based on them.
4211 * Return 0 if success, negative on error:
4212 * * -1 for general errors.
4213 * * -2 for failure to parse/validate,
4214 * * -3 for transition not allowed
4215 * * -4 for error while setting the new options
4218 options_init_from_string(const char *cf
,
4219 int command
, const char *command_arg
,
4222 or_options_t
*oldoptions
, *newoptions
;
4225 setopt_err_t err
= SETOPT_ERR_MISC
;
4228 oldoptions
= global_options
; /* get_options unfortunately asserts if
4229 this is the first time we run*/
4231 newoptions
= tor_malloc_zero(sizeof(or_options_t
));
4232 newoptions
->_magic
= OR_OPTIONS_MAGIC
;
4233 options_init(newoptions
);
4234 newoptions
->command
= command
;
4235 newoptions
->command_arg
= command_arg
;
4237 /* get config lines, assign them */
4238 retval
= config_get_lines(cf
, &cl
);
4240 err
= SETOPT_ERR_PARSE
;
4243 retval
= config_assign(&options_format
, newoptions
, cl
, 0, 0, msg
);
4244 config_free_lines(cl
);
4246 err
= SETOPT_ERR_PARSE
;
4250 /* Go through command-line variables too */
4251 retval
= config_assign(&options_format
, newoptions
,
4252 global_cmdline_options
, 0, 0, msg
);
4254 err
= SETOPT_ERR_PARSE
;
4258 /* If this is a testing network configuration, change defaults
4259 * for a list of dependent config options, re-initialize newoptions
4260 * with the new defaults, and assign all options to it second time. */
4261 if (newoptions
->TestingTorNetwork
) {
4262 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4263 * this? We could, for example, make the parsing algorithm do two passes
4264 * over the configuration. If it finds any "suite" options like
4265 * TestingTorNetwork, it could change the defaults before its second pass.
4266 * Not urgent so long as this seems to work, but at any sign of trouble,
4267 * let's clean it up. -NM */
4269 /* Change defaults. */
4271 for (i
= 0; testing_tor_network_defaults
[i
].name
; ++i
) {
4272 config_var_t
*new_var
= &testing_tor_network_defaults
[i
];
4273 config_var_t
*old_var
=
4274 config_find_option(&options_format
, new_var
->name
);
4275 tor_assert(new_var
);
4276 tor_assert(old_var
);
4277 old_var
->initvalue
= new_var
->initvalue
;
4280 /* Clear newoptions and re-initialize them with new defaults. */
4281 config_free(&options_format
, newoptions
);
4282 newoptions
= tor_malloc_zero(sizeof(or_options_t
));
4283 newoptions
->_magic
= OR_OPTIONS_MAGIC
;
4284 options_init(newoptions
);
4285 newoptions
->command
= command
;
4286 newoptions
->command_arg
= command_arg
;
4288 /* Assign all options a second time. */
4289 retval
= config_get_lines(cf
, &cl
);
4291 err
= SETOPT_ERR_PARSE
;
4294 retval
= config_assign(&options_format
, newoptions
, cl
, 0, 0, msg
);
4295 config_free_lines(cl
);
4297 err
= SETOPT_ERR_PARSE
;
4300 retval
= config_assign(&options_format
, newoptions
,
4301 global_cmdline_options
, 0, 0, msg
);
4303 err
= SETOPT_ERR_PARSE
;
4308 /* Validate newoptions */
4309 if (options_validate(oldoptions
, newoptions
, 0, msg
) < 0) {
4310 err
= SETOPT_ERR_PARSE
; /*XXX make this a separate return value.*/
4314 if (options_transition_allowed(oldoptions
, newoptions
, msg
) < 0) {
4315 err
= SETOPT_ERR_TRANSITION
;
4319 if (set_options(newoptions
, msg
)) {
4320 err
= SETOPT_ERR_SETTING
;
4321 goto err
; /* frees and replaces old options */
4327 config_free(&options_format
, newoptions
);
4329 int len
= (int)strlen(*msg
)+256;
4330 char *newmsg
= tor_malloc(len
);
4332 tor_snprintf(newmsg
, len
, "Failed to parse/validate config: %s", *msg
);
4339 /** Return the location for our configuration file.
4342 get_torrc_fname(void)
4347 return get_default_conf_file();
4350 /** Adjust the address map based on the MapAddress elements in the
4351 * configuration <b>options</b>
4354 config_register_addressmaps(or_options_t
*options
)
4360 addressmap_clear_configured();
4361 elts
= smartlist_create();
4362 for (opt
= options
->AddressMap
; opt
; opt
= opt
->next
) {
4363 smartlist_split_string(elts
, opt
->value
, NULL
,
4364 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
4365 if (smartlist_len(elts
) >= 2) {
4366 from
= smartlist_get(elts
,0);
4367 to
= smartlist_get(elts
,1);
4368 if (address_is_invalid_destination(to
, 1)) {
4370 "Skipping invalid argument '%s' to MapAddress", to
);
4372 addressmap_register(from
, tor_strdup(to
), 0, ADDRMAPSRC_TORRC
);
4373 if (smartlist_len(elts
)>2) {
4374 log_warn(LD_CONFIG
,"Ignoring extra arguments to MapAddress.");
4378 log_warn(LD_CONFIG
,"MapAddress '%s' has too few arguments. Ignoring.",
4381 SMARTLIST_FOREACH(elts
, char*, cp
, tor_free(cp
));
4382 smartlist_clear(elts
);
4384 smartlist_free(elts
);
4388 * Initialize the logs based on the configuration file.
4391 options_init_logs(or_options_t
*options
, int validate_only
)
4400 options
->RunAsDaemon
;
4404 elts
= smartlist_create();
4406 for (opt
= options
->Logs
; opt
; opt
= opt
->next
) {
4407 log_severity_list_t
*severity
;
4408 const char *cfg
= opt
->value
;
4409 severity
= tor_malloc_zero(sizeof(log_severity_list_t
));
4410 if (parse_log_severity_config(&cfg
, severity
) < 0) {
4411 log_warn(LD_CONFIG
, "Couldn't parse log levels in Log option 'Log %s'",
4413 ok
= 0; goto cleanup
;
4416 smartlist_split_string(elts
, cfg
, NULL
,
4417 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
4419 if (smartlist_len(elts
) == 0)
4420 smartlist_add(elts
, tor_strdup("stdout"));
4422 if (smartlist_len(elts
) == 1 &&
4423 (!strcasecmp(smartlist_get(elts
,0), "stdout") ||
4424 !strcasecmp(smartlist_get(elts
,0), "stderr"))) {
4425 int err
= smartlist_len(elts
) &&
4426 !strcasecmp(smartlist_get(elts
,0), "stderr");
4427 if (!validate_only
) {
4430 "Can't log to %s with RunAsDaemon set; skipping stdout",
4431 err
?"stderr":"stdout");
4433 add_stream_log(severity
, err
?"<stderr>":"<stdout>",
4434 fileno(err
?stderr
:stdout
));
4439 if (smartlist_len(elts
) == 1 &&
4440 !strcasecmp(smartlist_get(elts
,0), "syslog")) {
4441 #ifdef HAVE_SYSLOG_H
4442 if (!validate_only
) {
4443 add_syslog_log(severity
);
4446 log_warn(LD_CONFIG
, "Syslog is not supported on this system. Sorry.");
4451 if (smartlist_len(elts
) == 2 &&
4452 !strcasecmp(smartlist_get(elts
,0), "file")) {
4453 if (!validate_only
) {
4454 if (add_file_log(severity
, smartlist_get(elts
, 1)) < 0) {
4455 log_warn(LD_CONFIG
, "Couldn't open file for 'Log %s': %s",
4456 opt
->value
, strerror(errno
));
4463 log_warn(LD_CONFIG
, "Bad syntax on file Log option 'Log %s'",
4465 ok
= 0; goto cleanup
;
4468 SMARTLIST_FOREACH(elts
, char*, cp
, tor_free(cp
));
4469 smartlist_clear(elts
);
4472 smartlist_free(elts
);
4477 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4478 * if the line is well-formed, and -1 if it isn't. If
4479 * <b>validate_only</b> is 0, and the line is well-formed, then add
4480 * the bridge described in the line to our internal bridge list. */
4482 parse_bridge_line(const char *line
, int validate_only
)
4484 smartlist_t
*items
= NULL
;
4486 char *addrport
=NULL
, *fingerprint
=NULL
;
4489 char digest
[DIGEST_LEN
];
4491 items
= smartlist_create();
4492 smartlist_split_string(items
, line
, NULL
,
4493 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, -1);
4494 if (smartlist_len(items
) < 1) {
4495 log_warn(LD_CONFIG
, "Too few arguments to Bridge line.");
4498 addrport
= smartlist_get(items
, 0);
4499 smartlist_del_keeporder(items
, 0);
4500 if (tor_addr_port_parse(addrport
, &addr
, &port
)<0) {
4501 log_warn(LD_CONFIG
, "Error parsing Bridge address '%s'", addrport
);
4506 "Bridge address '%s' has no port; using default port 443.",
4511 if (smartlist_len(items
)) {
4512 fingerprint
= smartlist_join_strings(items
, "", 0, NULL
);
4513 if (strlen(fingerprint
) != HEX_DIGEST_LEN
) {
4514 log_warn(LD_CONFIG
, "Key digest for Bridge is wrong length.");
4517 if (base16_decode(digest
, DIGEST_LEN
, fingerprint
, HEX_DIGEST_LEN
)<0) {
4518 log_warn(LD_CONFIG
, "Unable to decode Bridge key digest.");
4523 if (!validate_only
) {
4524 log_debug(LD_DIR
, "Bridge at %s:%d (%s)", fmt_addr(&addr
),
4526 fingerprint
? fingerprint
: "no key listed");
4527 bridge_add_from_config(&addr
, port
, fingerprint
? digest
: NULL
);
4537 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
4538 smartlist_free(items
);
4540 tor_free(fingerprint
);
4544 /** Read the contents of a DirServer line from <b>line</b>. If
4545 * <b>validate_only</b> is 0, and the line is well-formed, and it
4546 * shares any bits with <b>required_type</b> or <b>required_type</b>
4547 * is 0, then add the dirserver described in the line (minus whatever
4548 * bits it's missing) as a valid authority. Return 0 on success,
4549 * or -1 if the line isn't well-formed or if we can't add it. */
4551 parse_dir_server_line(const char *line
, authority_type_t required_type
,
4554 smartlist_t
*items
= NULL
;
4556 char *addrport
=NULL
, *address
=NULL
, *nickname
=NULL
, *fingerprint
=NULL
;
4557 uint16_t dir_port
= 0, or_port
= 0;
4558 char digest
[DIGEST_LEN
];
4559 char v3_digest
[DIGEST_LEN
];
4560 authority_type_t type
= V2_AUTHORITY
;
4561 int is_not_hidserv_authority
= 0, is_not_v2_authority
= 0;
4563 items
= smartlist_create();
4564 smartlist_split_string(items
, line
, NULL
,
4565 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, -1);
4566 if (smartlist_len(items
) < 1) {
4567 log_warn(LD_CONFIG
, "No arguments on DirServer line.");
4571 if (is_legal_nickname(smartlist_get(items
, 0))) {
4572 nickname
= smartlist_get(items
, 0);
4573 smartlist_del_keeporder(items
, 0);
4576 while (smartlist_len(items
)) {
4577 char *flag
= smartlist_get(items
, 0);
4578 if (TOR_ISDIGIT(flag
[0]))
4580 if (!strcasecmp(flag
, "v1")) {
4581 type
|= (V1_AUTHORITY
| HIDSERV_AUTHORITY
);
4582 } else if (!strcasecmp(flag
, "hs")) {
4583 type
|= HIDSERV_AUTHORITY
;
4584 } else if (!strcasecmp(flag
, "no-hs")) {
4585 is_not_hidserv_authority
= 1;
4586 } else if (!strcasecmp(flag
, "bridge")) {
4587 type
|= BRIDGE_AUTHORITY
;
4588 } else if (!strcasecmp(flag
, "no-v2")) {
4589 is_not_v2_authority
= 1;
4590 } else if (!strcasecmpstart(flag
, "orport=")) {
4592 char *portstring
= flag
+ strlen("orport=");
4593 or_port
= (uint16_t) tor_parse_long(portstring
, 10, 1, 65535, &ok
, NULL
);
4595 log_warn(LD_CONFIG
, "Invalid orport '%s' on DirServer line.",
4597 } else if (!strcasecmpstart(flag
, "v3ident=")) {
4598 char *idstr
= flag
+ strlen("v3ident=");
4599 if (strlen(idstr
) != HEX_DIGEST_LEN
||
4600 base16_decode(v3_digest
, DIGEST_LEN
, idstr
, HEX_DIGEST_LEN
)<0) {
4601 log_warn(LD_CONFIG
, "Bad v3 identity digest '%s' on DirServer line",
4604 type
|= V3_AUTHORITY
;
4607 log_warn(LD_CONFIG
, "Unrecognized flag '%s' on DirServer line",
4611 smartlist_del_keeporder(items
, 0);
4613 if (is_not_hidserv_authority
)
4614 type
&= ~HIDSERV_AUTHORITY
;
4615 if (is_not_v2_authority
)
4616 type
&= ~V2_AUTHORITY
;
4618 if (smartlist_len(items
) < 2) {
4619 log_warn(LD_CONFIG
, "Too few arguments to DirServer line.");
4622 addrport
= smartlist_get(items
, 0);
4623 smartlist_del_keeporder(items
, 0);
4624 if (parse_addr_port(LOG_WARN
, addrport
, &address
, NULL
, &dir_port
)<0) {
4625 log_warn(LD_CONFIG
, "Error parsing DirServer address '%s'", addrport
);
4629 log_warn(LD_CONFIG
, "Missing port in DirServer address '%s'",addrport
);
4633 fingerprint
= smartlist_join_strings(items
, "", 0, NULL
);
4634 if (strlen(fingerprint
) != HEX_DIGEST_LEN
) {
4635 log_warn(LD_CONFIG
, "Key digest for DirServer is wrong length %d.",
4636 (int)strlen(fingerprint
));
4639 if (!strcmp(fingerprint
, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4640 /* a known bad fingerprint. refuse to use it. We can remove this
4641 * clause once Tor 0.1.2.17 is obsolete. */
4642 log_warn(LD_CONFIG
, "Dangerous dirserver line. To correct, erase your "
4643 "torrc file (%s), or reinstall Tor and use the default torrc.",
4647 if (base16_decode(digest
, DIGEST_LEN
, fingerprint
, HEX_DIGEST_LEN
)<0) {
4648 log_warn(LD_CONFIG
, "Unable to decode DirServer key digest.");
4652 if (!validate_only
&& (!required_type
|| required_type
& type
)) {
4654 type
&= required_type
; /* pare down what we think of them as an
4656 log_debug(LD_DIR
, "Trusted %d dirserver at %s:%d (%s)", (int)type
,
4657 address
, (int)dir_port
, (char*)smartlist_get(items
,0));
4658 if (!add_trusted_dir_server(nickname
, address
, dir_port
, or_port
,
4659 digest
, v3_digest
, type
))
4670 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
4671 smartlist_free(items
);
4675 tor_free(fingerprint
);
4679 /** Adjust the value of options->DataDirectory, or fill it in if it's
4680 * absent. Return 0 on success, -1 on failure. */
4682 normalize_data_directory(or_options_t
*options
)
4686 if (options
->DataDirectory
)
4687 return 0; /* all set */
4688 p
= tor_malloc(MAX_PATH
);
4689 strlcpy(p
,get_windows_conf_root(),MAX_PATH
);
4690 options
->DataDirectory
= p
;
4693 const char *d
= options
->DataDirectory
;
4697 if (strncmp(d
,"~/",2) == 0) {
4698 char *fn
= expand_filename(d
);
4700 log_warn(LD_CONFIG
,"Failed to expand filename \"%s\".", d
);
4703 if (!options
->DataDirectory
&& !strcmp(fn
,"/.tor")) {
4704 /* If our homedir is /, we probably don't want to use it. */
4705 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4708 "Default DataDirectory is \"~/.tor\". This expands to "
4709 "\"%s\", which is probably not what you want. Using "
4710 "\"%s"PATH_SEPARATOR
"tor\" instead
", fn, LOCALSTATEDIR);
4712 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor
");
4714 tor_free(options->DataDirectory);
4715 options->DataDirectory = fn;
4721 /** Check and normalize the value of options->DataDirectory; return 0 if it
4722 * sane, -1 otherwise. */
4724 validate_data_directory(or_options_t *options)
4726 if (normalize_data_directory(options) < 0)
4728 tor_assert(options->DataDirectory);
4729 if (strlen(options->DataDirectory) > (512-128)) {
4730 log_warn(LD_CONFIG, "DataDirectory is too
long.");
4736 /** This string must remain the same forevermore. It is how we
4737 * recognize that the torrc file doesn't need to be backed up. */
4738 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4739 "if you edit it, comments will not be preserved"
4740 /** This string can change; it tries to give the reader an idea
4741 * that editing this file by hand is not a good plan. */
4742 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4743 "to torrc.orig.1 or similar, and Tor will ignore it"
4745 /** Save a configuration file for the configuration in <b>options</b>
4746 * into the file <b>fname</b>. If the file already exists, and
4747 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4748 * replace it. Return 0 on success, -1 on failure. */
4750 write_configuration_file(const char *fname, or_options_t *options)
4752 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4753 int rename_old = 0, r;
4758 switch (file_status(fname)) {
4760 old_val = read_file_to_str(fname, 0, NULL);
4761 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4772 "Config file \"%s\" is not a file? Failing.", fname);
4776 if (!(new_conf = options_dump(options, 1))) {
4777 log_warn(LD_BUG, "Couldn't get configuration string");
4781 len = strlen(new_conf)+256;
4782 new_val = tor_malloc(len);
4783 tor_snprintf(new_val, len, "%s\n%s\n\n%s",
4784 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4788 size_t fn_tmp_len = strlen(fname)+32;
4790 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4791 fn_tmp = tor_malloc(fn_tmp_len);
4793 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4794 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4798 if (file_status(fn_tmp) == FN_NOENT)
4802 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4803 if (rename(fname, fn_tmp) < 0) {
4805 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4806 fname, fn_tmp, strerror(errno));
4813 if (write_str_to_file(fname, new_val, 0) < 0)
4827 * Save the current configuration file value to disk. Return 0 on
4828 * success, -1 on failure.
4831 options_save_current(void)
4834 /* This fails if we can't write to our configuration file.
4836 * If we try falling back to datadirectory or something, we have a better
4837 * chance of saving the configuration, but a better chance of doing
4838 * something the user never expected. Let's just warn instead. */
4839 return write_configuration_file(torrc_fname, get_options());
4841 return write_configuration_file(get_default_conf_file(), get_options());
4844 /** Mapping from a unit name to a multiplier for converting that unit into a
4846 struct unit_table_t {
4848 uint64_t multiplier;
4851 /** Table to map the names of memory units to the number of bytes they
4853 static struct unit_table_t memory_units[] = {
4860 { "kbytes", 1<<10 },
4861 { "kilobyte", 1<<10 },
4862 { "kilobytes", 1<<10 },
4866 { "mbytes", 1<<20 },
4867 { "megabyte", 1<<20 },
4868 { "megabytes", 1<<20 },
4871 { "gbytes", 1<<30 },
4872 { "gigabyte", 1<<30 },
4873 { "gigabytes", 1<<30 },
4874 { "tb", U64_LITERAL(1)<<40 },
4875 { "terabyte", U64_LITERAL(1)<<40 },
4876 { "terabytes", U64_LITERAL(1)<<40 },
4880 /** Table to map the names of time units to the number of seconds they
4882 static struct unit_table_t time_units[] = {
4890 { "day", 24*60*60 },
4891 { "days", 24*60*60 },
4892 { "week", 7*24*60*60 },
4893 { "weeks", 7*24*60*60 },
4897 /** Parse a string <b>val</b> containing a number, zero or more
4898 * spaces, and an optional unit string. If the unit appears in the
4899 * table <b>u</b>, then multiply the number by the unit multiplier.
4900 * On success, set *<b>ok</b> to 1 and return this product.
4901 * Otherwise, set *<b>ok</b> to 0.
4904 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4913 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4914 if (!*ok || (cp && *cp == '.')) {
4915 d = tor_parse_double(val, 0, UINT64_MAX, ok, &cp);
4923 v = use_float ? DBL_TO_U64(d) : v;
4927 cp = (char*) eat_whitespace(cp);
4929 for ( ;u->unit;++u) {
4930 if (!strcasecmp(u->unit, cp)) {
4932 v = u->multiplier * d;
4939 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4949 /** Parse a string in the format "number unit", where unit is a unit of
4950 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4951 * and return the number of bytes specified. Otherwise, set
4952 * *<b>ok</b> to false and return 0. */
4954 config_parse_memunit(const char *s, int *ok)
4956 uint64_t u = config_parse_units(s, memory_units, ok);
4960 /** Parse a string in the format "number unit", where unit is a unit of time.
4961 * On success, set *<b>ok</b> to true and return the number of seconds in
4962 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4965 config_parse_interval(const char *s, int *ok)
4968 r = config_parse_units(s, time_units, ok);
4972 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4980 * Initialize the libevent library.
4985 const char *badness=NULL;
4987 configure_libevent_logging();
4988 /* If the kernel complains that some method (say, epoll) doesn't
4989 * exist, we don't care about it, since libevent will cope.
4991 suppress_libevent_log_msg("Function not implemented");
4993 tor_check_libevent_header_compatibility();
4995 tor_libevent_initialize();
4997 suppress_libevent_log_msg(NULL);
4999 tor_check_libevent_version(tor_libevent_get_method(),
5000 get_options()->ORPort != 0,
5003 const char *v = tor_libevent_get_version_str();
5004 const char *m = tor_libevent_get_method();
5005 control_event_general_status(LOG_WARN,
5006 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
5011 /** Return the persistent state struct for this Tor. */
5015 tor_assert(global_state);
5016 return global_state;
5019 /** Return a newly allocated string holding a filename relative to the data
5020 * directory. If <b>sub1</b> is present, it is the first path component after
5021 * the data directory. If <b>sub2</b> is also present, it is the second path
5022 * component after the data directory. If <b>suffix</b> is present, it
5023 * is appended to the filename.
5026 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
5027 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
5028 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
5029 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
5031 * Note: Consider using the get_datadir_fname* macros in or.h.
5034 options_get_datadir_fname2_suffix(or_options_t *options,
5035 const char *sub1, const char *sub2,
5040 tor_assert(options);
5041 tor_assert(options->DataDirectory);
5042 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
5043 len = strlen(options->DataDirectory);
5045 len += strlen(sub1)+1;
5047 len += strlen(sub2)+1;
5050 len += strlen(suffix);
5052 fname = tor_malloc(len);
5055 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
5056 options->DataDirectory, sub1, sub2);
5058 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
5059 options->DataDirectory, sub1);
5062 strlcpy(fname, options->DataDirectory, len);
5065 strlcat(fname, suffix, len);
5069 /** Return 0 if every setting in <b>state</b> is reasonable, and a
5070 * permissible transition from <b>old_state</b>. Else warn and return -1.
5071 * Should have no side effects, except for normalizing the contents of
5074 /* XXX from_setconf is here because of bug 238 */
5076 or_state_validate(or_state_t *old_state, or_state_t *state,
5077 int from_setconf, char **msg)
5079 /* We don't use these; only options do. Still, we need to match that
5081 (void) from_setconf;
5084 if (entry_guards_parse_state(state, 0, msg)<0)
5090 /** Replace the current persistent state with <b>new_state</b> */
5092 or_state_set(or_state_t *new_state)
5095 tor_assert(new_state);
5096 config_free(&state_format, global_state);
5097 global_state = new_state;
5098 if (entry_guards_parse_state(global_state, 1, &err)<0) {
5099 log_warn(LD_GENERAL,"%s",err);
5102 if (rep_hist_load_state(global_state, &err)<0) {
5103 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
5106 if (circuit_build_times_parse_state(&circ_times, global_state, &err) < 0) {
5107 log_warn(LD_GENERAL,"%s",err);
5112 /** Reload the persistent state from disk, generating a new state as needed.
5113 * Return 0 on success, less than 0 on failure.
5118 or_state_t *new_state = NULL;
5119 char *contents = NULL, *fname;
5120 char *errmsg = NULL;
5121 int r = -1, badstate = 0;
5123 fname = get_datadir_fname("state");
5124 switch (file_status(fname)) {
5126 if (!(contents = read_file_to_str(fname, 0, NULL))) {
5127 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
5136 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
5139 new_state = tor_malloc_zero(sizeof(or_state_t));
5140 new_state->_magic = OR_STATE_MAGIC;
5141 config_init(&state_format, new_state);
5143 config_line_t *lines=NULL;
5145 if (config_get_lines(contents, &lines)<0)
5147 assign_retval = config_assign(&state_format, new_state,
5148 lines, 0, 0, &errmsg);
5149 config_free_lines(lines);
5150 if (assign_retval<0)
5153 log_warn(LD_GENERAL, "%s", errmsg);
5158 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
5162 log_warn(LD_GENERAL, "%s", errmsg);
5166 if (badstate && !contents) {
5167 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
5168 " This is a bug in Tor.");
5170 } else if (badstate && contents) {
5172 file_status_t status;
5173 size_t len = strlen(fname)+16;
5174 char *fname2 = tor_malloc(len);
5175 for (i = 0; i < 100; ++i) {
5176 tor_snprintf(fname2, len, "%s.%d", fname, i);
5177 status = file_status(fname2);
5178 if (status == FN_NOENT)
5182 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
5183 "state files to move aside. Discarding the old state file.",
5187 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
5188 "to \"%s\". This could be a bug in Tor; please tell "
5189 "the developers.", fname, fname2);
5190 if (rename(fname, fname2) < 0) {
5191 log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
5192 "OS gave an error of %s", strerror(errno));
5197 config_free(&state_format, new_state);
5199 new_state = tor_malloc_zero(sizeof(or_state_t));
5200 new_state->_magic = OR_STATE_MAGIC;
5201 config_init(&state_format, new_state);
5202 } else if (contents) {
5203 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
5205 log_info(LD_GENERAL, "Initialized state");
5207 or_state_set(new_state);
5210 global_state->next_write = 0;
5211 or_state_save(time(NULL));
5219 config_free(&state_format, new_state);
5224 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
5226 or_state_save(time_t now)
5228 char *state, *contents;
5229 char tbuf[ISO_TIME_LEN+1];
5233 tor_assert(global_state);
5235 if (global_state->next_write > now)
5238 /* Call everything else that might dirty the state even more, in order
5239 * to avoid redundant writes. */
5240 entry_guards_update_state(global_state);
5241 rep_hist_update_state(global_state);
5242 circuit_build_times_update_state(&circ_times, global_state);
5243 if (accounting_is_enabled(get_options()))
5244 accounting_run_housekeeping(now);
5246 global_state->LastWritten = time(NULL);
5247 tor_free(global_state->TorVersion);
5248 len = strlen(get_version())+8;
5249 global_state->TorVersion = tor_malloc(len);
5250 tor_snprintf(global_state->TorVersion, len, "Tor %s", get_version());
5252 state = config_dump(&state_format, global_state, 1, 0);
5253 len = strlen(state)+256;
5254 contents = tor_malloc(len);
5255 format_local_iso_time(tbuf, time(NULL));
5256 tor_snprintf(contents, len,
5257 "# Tor state file last generated on %s local time\n"
5258 "# Other times below are in GMT\n"
5259 "# You *do not* need to edit this file.\n\n%s",
5262 fname = get_datadir_fname("state");
5263 if (write_str_to_file(fname, contents, 0)<0) {
5264 log_warn(LD_FS, "Unable to write state to file \"%s\"", fname);
5269 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
5273 global_state->next_write = TIME_MAX;
5277 /** Given a file name check to see whether the file exists but has not been
5278 * modified for a very long time. If so, remove it. */
5280 remove_file_if_very_old(const char *fname, time_t now)
5282 #define VERY_OLD_FILE_AGE (28*24*60*60)
5285 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
5286 char buf[ISO_TIME_LEN+1];
5287 format_local_iso_time(buf, st.st_mtime);
5288 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
5289 "Removing it.", fname, buf);
5294 /** Helper to implement GETINFO functions about configuration variables (not
5295 * their values). Given a "config/names" question, set *<b>answer</b> to a
5296 * new string describing the supported configuration variables and their
5299 getinfo_helper_config(control_connection_t *conn,
5300 const char *question, char **answer)
5303 if (!strcmp(question, "config/names")) {
5304 smartlist_t *sl = smartlist_create();
5306 for (i = 0; _option_vars[i].name; ++i) {
5307 config_var_t *var = &_option_vars[i];
5308 const char *type, *desc;
5311 desc = config_find_description(&options_format, var->name);
5312 switch (var->type) {
5313 case CONFIG_TYPE_STRING: type = "String"; break;
5314 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
5315 case CONFIG_TYPE_UINT: type = "Integer"; break;
5316 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
5317 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
5318 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
5319 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
5320 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
5321 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
5322 case CONFIG_TYPE_CSV: type = "CommaList"; break;
5323 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
5324 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
5325 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
5327 case CONFIG_TYPE_OBSOLETE:
5332 len = strlen(var->name)+strlen(type)+16;
5334 len += strlen(desc);
5335 line = tor_malloc(len);
5337 tor_snprintf(line, len, "%s %s %s\n",var->name,type,desc);
5339 tor_snprintf(line, len, "%s %s\n",var->name,type);
5340 smartlist_add(sl, line);
5342 *answer = smartlist_join_strings(sl, "", 0, NULL);
5343 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));