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-2008, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 const char config_c_id
[] = \
12 * \brief Code to parse and interpret configuration files.
15 #define CONFIG_PRIVATE
22 /** Enumeration of types which option values can take */
23 typedef enum config_type_t
{
24 CONFIG_TYPE_STRING
= 0, /**< An arbitrary string. */
25 CONFIG_TYPE_FILENAME
, /**< A filename: some prefixes get expanded. */
26 CONFIG_TYPE_UINT
, /**< A non-negative integer less than MAX_INT */
27 CONFIG_TYPE_INTERVAL
, /**< A number of seconds, with optional units*/
28 CONFIG_TYPE_MEMUNIT
, /**< A number of bytes, with optional units*/
29 CONFIG_TYPE_DOUBLE
, /**< A floating-point value */
30 CONFIG_TYPE_BOOL
, /**< A boolean value, expressed as 0 or 1. */
31 CONFIG_TYPE_ISOTIME
, /**< An ISO-formated time relative to GMT. */
32 CONFIG_TYPE_CSV
, /**< A list of strings, separated by commas and
33 * optional whitespace. */
34 CONFIG_TYPE_LINELIST
, /**< Uninterpreted config lines */
35 CONFIG_TYPE_LINELIST_S
, /**< Uninterpreted, context-sensitive config lines,
36 * mixed with other keywords. */
37 CONFIG_TYPE_LINELIST_V
, /**< Catch-all "virtual" option to summarize
38 * context-sensitive config lines when fetching.
40 CONFIG_TYPE_ROUTERSET
, /**< A list of router names, addrs, and fps,
41 * parsed into a routerset_t. */
42 CONFIG_TYPE_OBSOLETE
, /**< Obsolete (ignored) option. */
45 /** An abbreviation for a configuration option allowed on the command line. */
46 typedef struct config_abbrev_t
{
47 const char *abbreviated
;
53 /* Handy macro for declaring "In the config file or on the command line,
54 * you can abbreviate <b>tok</b>s as <b>tok</b>". */
55 #define PLURAL(tok) { #tok, #tok "s", 0, 0 }
57 /** A list of abbreviations and aliases to map command-line options, obsolete
58 * option names, or alternative option names, to their current values. */
59 static config_abbrev_t _option_abbrevs
[] = {
64 PLURAL(LongLivedPort
),
65 PLURAL(HiddenServiceNode
),
66 PLURAL(HiddenServiceExcludeNode
),
69 PLURAL(RendExcludeNode
),
70 PLURAL(StrictEntryNode
),
71 PLURAL(StrictExitNode
),
73 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
74 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
75 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
76 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
77 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
78 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
79 { "MaxConn", "ConnLimit", 0, 1},
80 { "ORBindAddress", "ORListenAddress", 0, 0},
81 { "DirBindAddress", "DirListenAddress", 0, 0},
82 { "SocksBindAddress", "SocksListenAddress", 0, 0},
83 { "UseHelperNodes", "UseEntryGuards", 0, 0},
84 { "NumHelperNodes", "NumEntryGuards", 0, 0},
85 { "UseEntryNodes", "UseEntryGuards", 0, 0},
86 { "NumEntryNodes", "NumEntryGuards", 0, 0},
87 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
88 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
89 { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0 },
90 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
91 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
92 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
96 /** A list of state-file "abbreviations," for compatibility. */
97 static config_abbrev_t _state_abbrevs
[] = {
98 { "AccountingBytesReadInterval", "AccountingBytesReadInInterval", 0, 0 },
99 { "HelperNode", "EntryGuard", 0, 0 },
100 { "HelperNodeDownSince", "EntryGuardDownSince", 0, 0 },
101 { "HelperNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
102 { "EntryNode", "EntryGuard", 0, 0 },
103 { "EntryNodeDownSince", "EntryGuardDownSince", 0, 0 },
104 { "EntryNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
109 /** A variable allowed in the configuration file or on the command line. */
110 typedef struct config_var_t
{
111 const char *name
; /**< The full keyword (case insensitive). */
112 config_type_t type
; /**< How to interpret the type and turn it into a
114 off_t var_offset
; /**< Offset of the corresponding member of or_options_t. */
115 const char *initvalue
; /**< String (or null) describing initial value. */
118 /** An entry for config_vars: "The option <b>name</b> has type
119 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
120 * or_options_t.<b>member</b>"
122 #define VAR(name,conftype,member,initvalue) \
123 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
125 /** As VAR, but the option name and member name are the same. */
126 #define V(member,conftype,initvalue) \
127 VAR(#member, conftype, member, initvalue)
128 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
129 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
131 /** Array of configuration options. Until we disallow nonstandard
132 * abbreviations, order is significant, since the first matching option will
135 static config_var_t _option_vars
[] = {
136 OBSOLETE("AccountingMaxKB"),
137 V(AccountingMax
, MEMUNIT
, "0 bytes"),
138 V(AccountingStart
, STRING
, NULL
),
139 V(Address
, STRING
, NULL
),
140 V(AllowInvalidNodes
, CSV
, "middle,rendezvous"),
141 V(AllowNonRFC953Hostnames
, BOOL
, "0"),
142 V(AllowSingleHopCircuits
, BOOL
, "0"),
143 V(AllowSingleHopExits
, BOOL
, "0"),
144 V(AlternateBridgeAuthority
, LINELIST
, NULL
),
145 V(AlternateDirAuthority
, LINELIST
, NULL
),
146 V(AlternateHSAuthority
, LINELIST
, NULL
),
147 V(AssumeReachable
, BOOL
, "0"),
148 V(AuthDirBadDir
, LINELIST
, NULL
),
149 V(AuthDirBadExit
, LINELIST
, NULL
),
150 V(AuthDirInvalid
, LINELIST
, NULL
),
151 V(AuthDirReject
, LINELIST
, NULL
),
152 V(AuthDirRejectUnlisted
, BOOL
, "0"),
153 V(AuthDirListBadDirs
, BOOL
, "0"),
154 V(AuthDirListBadExits
, BOOL
, "0"),
155 V(AuthDirMaxServersPerAddr
, UINT
, "2"),
156 V(AuthDirMaxServersPerAuthAddr
,UINT
, "5"),
157 VAR("AuthoritativeDirectory", BOOL
, AuthoritativeDir
, "0"),
158 V(AutomapHostsOnResolve
, BOOL
, "0"),
159 V(AutomapHostsSuffixes
, CSV
, ".onion,.exit"),
160 V(AvoidDiskWrites
, BOOL
, "0"),
161 V(BandwidthBurst
, MEMUNIT
, "10 MB"),
162 V(BandwidthRate
, MEMUNIT
, "5 MB"),
163 V(BridgeAuthoritativeDir
, BOOL
, "0"),
164 VAR("Bridge", LINELIST
, Bridges
, NULL
),
165 V(BridgePassword
, STRING
, NULL
),
166 V(BridgeRecordUsageByCountry
, BOOL
, "1"),
167 V(BridgeRelay
, BOOL
, "0"),
168 V(CircuitBuildTimeout
, INTERVAL
, "1 minute"),
169 V(CircuitIdleTimeout
, INTERVAL
, "1 hour"),
170 V(ClientDNSRejectInternalAddresses
, BOOL
,"1"),
171 V(ClientOnly
, BOOL
, "0"),
172 V(ConnLimit
, UINT
, "1000"),
173 V(ConstrainedSockets
, BOOL
, "0"),
174 V(ConstrainedSockSize
, MEMUNIT
, "8192"),
175 V(ContactInfo
, STRING
, NULL
),
176 V(ControlListenAddress
, LINELIST
, NULL
),
177 V(ControlPort
, UINT
, "0"),
178 V(ControlSocket
, LINELIST
, NULL
),
179 V(CookieAuthentication
, BOOL
, "0"),
180 V(CookieAuthFileGroupReadable
, BOOL
, "0"),
181 V(CookieAuthFile
, STRING
, NULL
),
182 V(DataDirectory
, FILENAME
, NULL
),
183 OBSOLETE("DebugLogFile"),
184 V(DirAllowPrivateAddresses
, BOOL
, NULL
),
185 V(TestingAuthDirTimeToLearnReachability
, INTERVAL
, "30 minutes"),
186 V(DirListenAddress
, LINELIST
, NULL
),
187 OBSOLETE("DirFetchPeriod"),
188 V(DirPolicy
, LINELIST
, NULL
),
189 V(DirPort
, UINT
, "0"),
190 V(DirPortFrontPage
, FILENAME
, NULL
),
191 OBSOLETE("DirPostPeriod"),
192 #ifdef ENABLE_GEOIP_STATS
193 V(DirRecordUsageByCountry
, BOOL
, "0"),
194 V(DirRecordUsageGranularity
, UINT
, "4"),
195 V(DirRecordUsageRetainIPs
, INTERVAL
, "14 days"),
196 V(DirRecordUsageSaveInterval
, INTERVAL
, "6 hours"),
198 VAR("DirServer", LINELIST
, DirServers
, NULL
),
199 V(DNSPort
, UINT
, "0"),
200 V(DNSListenAddress
, LINELIST
, NULL
),
201 V(DownloadExtraInfo
, BOOL
, "0"),
202 V(EnforceDistinctSubnets
, BOOL
, "1"),
203 V(EntryNodes
, ROUTERSET
, NULL
),
204 V(TestingEstimatedDescriptorPropagationTime
, INTERVAL
, "10 minutes"),
205 V(ExcludeNodes
, ROUTERSET
, NULL
),
206 V(ExcludeExitNodes
, ROUTERSET
, NULL
),
207 V(ExcludeSingleHopRelays
, BOOL
, "1"),
208 V(ExitNodes
, ROUTERSET
, NULL
),
209 V(ExitPolicy
, LINELIST
, NULL
),
210 V(ExitPolicyRejectPrivate
, BOOL
, "1"),
211 V(FallbackNetworkstatusFile
, FILENAME
,
212 SHARE_DATADIR PATH_SEPARATOR
"tor" PATH_SEPARATOR
"fallback-consensus"),
213 V(FascistFirewall
, BOOL
, "0"),
214 V(FirewallPorts
, CSV
, ""),
215 V(FastFirstHopPK
, BOOL
, "1"),
216 V(FetchDirInfoEarly
, BOOL
, "0"),
217 V(FetchServerDescriptors
, BOOL
, "1"),
218 V(FetchHidServDescriptors
, BOOL
, "1"),
219 V(FetchUselessDescriptors
, BOOL
, "0"),
221 V(GeoIPFile
, FILENAME
, "<default>"),
223 V(GeoIPFile
, FILENAME
,
224 SHARE_DATADIR PATH_SEPARATOR
"tor" PATH_SEPARATOR
"geoip"),
227 V(HardwareAccel
, BOOL
, "0"),
228 V(HashedControlPassword
, LINELIST
, NULL
),
229 V(HidServDirectoryV2
, BOOL
, "1"),
230 VAR("HiddenServiceDir", LINELIST_S
, RendConfigLines
, NULL
),
231 OBSOLETE("HiddenServiceExcludeNodes"),
232 OBSOLETE("HiddenServiceNodes"),
233 VAR("HiddenServiceOptions",LINELIST_V
, RendConfigLines
, NULL
),
234 VAR("HiddenServicePort", LINELIST_S
, RendConfigLines
, NULL
),
235 VAR("HiddenServiceVersion",LINELIST_S
, RendConfigLines
, NULL
),
236 VAR("HiddenServiceAuthorizeClient",LINELIST_S
,RendConfigLines
, NULL
),
237 V(HidServAuth
, LINELIST
, NULL
),
238 V(HSAuthoritativeDir
, BOOL
, "0"),
239 V(HSAuthorityRecordStats
, BOOL
, "0"),
240 V(HttpProxy
, STRING
, NULL
),
241 V(HttpProxyAuthenticator
, STRING
, NULL
),
242 V(HttpsProxy
, STRING
, NULL
),
243 V(HttpsProxyAuthenticator
, STRING
, NULL
),
244 OBSOLETE("IgnoreVersion"),
245 V(KeepalivePeriod
, INTERVAL
, "5 minutes"),
246 VAR("Log", LINELIST
, Logs
, NULL
),
247 OBSOLETE("LinkPadding"),
248 OBSOLETE("LogLevel"),
250 V(LongLivedPorts
, CSV
,
251 "21,22,706,1863,5050,5190,5222,5223,6667,6697,8300"),
252 VAR("MapAddress", LINELIST
, AddressMap
, NULL
),
253 V(MaxAdvertisedBandwidth
, MEMUNIT
, "1 GB"),
254 V(MaxCircuitDirtiness
, INTERVAL
, "10 minutes"),
255 V(MaxOnionsPending
, UINT
, "100"),
256 OBSOLETE("MonthlyAccountingStart"),
257 V(MyFamily
, STRING
, NULL
),
258 V(NewCircuitPeriod
, INTERVAL
, "30 seconds"),
259 VAR("NamingAuthoritativeDirectory",BOOL
, NamingAuthoritativeDir
, "0"),
260 V(NatdListenAddress
, LINELIST
, NULL
),
261 V(NatdPort
, UINT
, "0"),
262 V(Nickname
, STRING
, NULL
),
263 V(NoPublish
, BOOL
, "0"),
264 VAR("NodeFamily", LINELIST
, NodeFamilies
, NULL
),
265 V(NumCpus
, UINT
, "1"),
266 V(NumEntryGuards
, UINT
, "3"),
267 V(ORListenAddress
, LINELIST
, NULL
),
268 V(ORPort
, UINT
, "0"),
269 V(OutboundBindAddress
, STRING
, NULL
),
270 OBSOLETE("PathlenCoinWeight"),
271 V(PidFile
, STRING
, NULL
),
272 V(TestingTorNetwork
, BOOL
, "0"),
273 V(PreferTunneledDirConns
, BOOL
, "1"),
274 V(ProtocolWarnings
, BOOL
, "0"),
275 V(PublishServerDescriptor
, CSV
, "1"),
276 V(PublishHidServDescriptors
, BOOL
, "1"),
277 V(ReachableAddresses
, LINELIST
, NULL
),
278 V(ReachableDirAddresses
, LINELIST
, NULL
),
279 V(ReachableORAddresses
, LINELIST
, NULL
),
280 V(RecommendedVersions
, LINELIST
, NULL
),
281 V(RecommendedClientVersions
, LINELIST
, NULL
),
282 V(RecommendedServerVersions
, LINELIST
, NULL
),
283 OBSOLETE("RedirectExit"),
284 V(RejectPlaintextPorts
, CSV
, ""),
285 V(RelayBandwidthBurst
, MEMUNIT
, "0"),
286 V(RelayBandwidthRate
, MEMUNIT
, "0"),
287 OBSOLETE("RendExcludeNodes"),
288 OBSOLETE("RendNodes"),
289 V(RendPostPeriod
, INTERVAL
, "1 hour"),
290 V(RephistTrackTime
, INTERVAL
, "24 hours"),
291 OBSOLETE("RouterFile"),
292 V(RunAsDaemon
, BOOL
, "0"),
293 V(RunTesting
, BOOL
, "0"),
294 V(SafeLogging
, BOOL
, "1"),
295 V(SafeSocks
, BOOL
, "0"),
296 V(ServerDNSAllowBrokenConfig
, BOOL
, "1"),
297 V(ServerDNSAllowNonRFC953Hostnames
, BOOL
,"0"),
298 V(ServerDNSDetectHijacking
, BOOL
, "1"),
299 V(ServerDNSRandomizeCase
, BOOL
, "1"),
300 V(ServerDNSResolvConfFile
, STRING
, NULL
),
301 V(ServerDNSSearchDomains
, BOOL
, "0"),
302 V(ServerDNSTestAddresses
, CSV
,
303 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
304 V(ShutdownWaitLength
, INTERVAL
, "30 seconds"),
305 V(SocksListenAddress
, LINELIST
, NULL
),
306 V(SocksPolicy
, LINELIST
, NULL
),
307 V(SocksPort
, UINT
, "9050"),
308 V(SocksTimeout
, INTERVAL
, "2 minutes"),
309 OBSOLETE("StatusFetchPeriod"),
310 V(StrictEntryNodes
, BOOL
, "0"),
311 V(StrictExitNodes
, BOOL
, "0"),
313 V(TestSocks
, BOOL
, "0"),
315 V(TrackHostExits
, CSV
, NULL
),
316 V(TrackHostExitsExpire
, INTERVAL
, "30 minutes"),
317 OBSOLETE("TrafficShaping"),
318 V(TransListenAddress
, LINELIST
, NULL
),
319 V(TransPort
, UINT
, "0"),
320 V(TunnelDirConns
, BOOL
, "1"),
321 V(UpdateBridgesFromAuthority
, BOOL
, "0"),
322 V(UseBridges
, BOOL
, "0"),
323 V(UseEntryGuards
, BOOL
, "1"),
324 V(User
, STRING
, NULL
),
325 VAR("V1AuthoritativeDirectory",BOOL
, V1AuthoritativeDir
, "0"),
326 VAR("V2AuthoritativeDirectory",BOOL
, V2AuthoritativeDir
, "0"),
327 VAR("V3AuthoritativeDirectory",BOOL
, V3AuthoritativeDir
, "0"),
328 V(TestingV3AuthInitialVotingInterval
, INTERVAL
, "30 minutes"),
329 V(TestingV3AuthInitialVoteDelay
, INTERVAL
, "5 minutes"),
330 V(TestingV3AuthInitialDistDelay
, INTERVAL
, "5 minutes"),
331 V(V3AuthVotingInterval
, INTERVAL
, "1 hour"),
332 V(V3AuthVoteDelay
, INTERVAL
, "5 minutes"),
333 V(V3AuthDistDelay
, INTERVAL
, "5 minutes"),
334 V(V3AuthNIntervalsValid
, UINT
, "3"),
335 V(V3AuthUseLegacyKey
, BOOL
, "0"),
336 VAR("VersioningAuthoritativeDirectory",BOOL
,VersioningAuthoritativeDir
, "0"),
337 V(VirtualAddrNetwork
, STRING
, "127.192.0.0/10"),
338 V(WarnPlaintextPorts
, CSV
, "23,109,110,143"),
339 VAR("__ReloadTorrcOnSIGHUP", BOOL
, ReloadTorrcOnSIGHUP
, "1"),
340 VAR("__AllDirActionsPrivate", BOOL
, AllDirActionsPrivate
, "0"),
341 VAR("__DisablePredictedCircuits",BOOL
,DisablePredictedCircuits
, "0"),
342 VAR("__LeaveStreamsUnattached",BOOL
, LeaveStreamsUnattached
, "0"),
343 VAR("__HashedControlSessionPassword", LINELIST
, HashedControlSessionPassword
,
345 V(MinUptimeHidServDirectoryV2
, INTERVAL
, "24 hours"),
346 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
349 /** Override default values with these if the user sets the TestingTorNetwork
351 static config_var_t testing_tor_network_defaults
[] = {
352 V(ServerDNSAllowBrokenConfig
, BOOL
, "1"),
353 V(DirAllowPrivateAddresses
, BOOL
, "1"),
354 V(EnforceDistinctSubnets
, BOOL
, "0"),
355 V(AssumeReachable
, BOOL
, "1"),
356 V(AuthDirMaxServersPerAddr
, UINT
, "0"),
357 V(AuthDirMaxServersPerAuthAddr
,UINT
, "0"),
358 V(ClientDNSRejectInternalAddresses
, BOOL
,"0"),
359 V(ExitPolicyRejectPrivate
, BOOL
, "0"),
360 V(V3AuthVotingInterval
, INTERVAL
, "5 minutes"),
361 V(V3AuthVoteDelay
, INTERVAL
, "20 seconds"),
362 V(V3AuthDistDelay
, INTERVAL
, "20 seconds"),
363 V(TestingV3AuthInitialVotingInterval
, INTERVAL
, "5 minutes"),
364 V(TestingV3AuthInitialVoteDelay
, INTERVAL
, "20 seconds"),
365 V(TestingV3AuthInitialDistDelay
, INTERVAL
, "20 seconds"),
366 V(TestingAuthDirTimeToLearnReachability
, INTERVAL
, "0 minutes"),
367 V(TestingEstimatedDescriptorPropagationTime
, INTERVAL
, "0 minutes"),
368 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
372 #define VAR(name,conftype,member,initvalue) \
373 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
376 /** Array of "state" variables saved to the ~/.tor/state file. */
377 static config_var_t _state_vars
[] = {
378 V(AccountingBytesReadInInterval
, MEMUNIT
, NULL
),
379 V(AccountingBytesWrittenInInterval
, MEMUNIT
, NULL
),
380 V(AccountingExpectedUsage
, MEMUNIT
, NULL
),
381 V(AccountingIntervalStart
, ISOTIME
, NULL
),
382 V(AccountingSecondsActive
, INTERVAL
, NULL
),
384 VAR("EntryGuard", LINELIST_S
, EntryGuards
, NULL
),
385 VAR("EntryGuardDownSince", LINELIST_S
, EntryGuards
, NULL
),
386 VAR("EntryGuardUnlistedSince", LINELIST_S
, EntryGuards
, NULL
),
387 VAR("EntryGuardAddedBy", LINELIST_S
, EntryGuards
, NULL
),
388 V(EntryGuards
, LINELIST_V
, NULL
),
390 V(BWHistoryReadEnds
, ISOTIME
, NULL
),
391 V(BWHistoryReadInterval
, UINT
, "900"),
392 V(BWHistoryReadValues
, CSV
, ""),
393 V(BWHistoryWriteEnds
, ISOTIME
, NULL
),
394 V(BWHistoryWriteInterval
, UINT
, "900"),
395 V(BWHistoryWriteValues
, CSV
, ""),
397 V(TorVersion
, STRING
, NULL
),
399 V(LastRotatedOnionKey
, ISOTIME
, NULL
),
400 V(LastWritten
, ISOTIME
, NULL
),
402 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
409 /** Represents an English description of a configuration variable; used when
410 * generating configuration file comments. */
411 typedef struct config_var_description_t
{
413 const char *description
;
414 } config_var_description_t
;
416 /** Descriptions of the configuration options, to be displayed by online
418 /* XXXX022 did anybody want this? at all? If not, kill it.*/
419 static config_var_description_t options_description
[] = {
420 /* ==== general options */
421 { "AvoidDiskWrites", "If non-zero, try to write to disk less frequently than"
422 " we would otherwise." },
423 { "BandwidthRate", "A token bucket limits the average incoming bandwidth on "
424 "this node to the specified number of bytes per second." },
425 { "BandwidthBurst", "Limit the maximum token buffer size (also known as "
426 "burst) to the given number of bytes." },
427 { "ConnLimit", "Minimum number of simultaneous sockets we must have." },
428 { "ConstrainedSockets", "Shrink tx and rx buffers for sockets to avoid "
429 "system limits on vservers and related environments. See man page for "
430 "more information regarding this option." },
431 { "ConstrainedSockSize", "Limit socket buffers to this size when "
432 "ConstrainedSockets is enabled." },
433 /* ControlListenAddress */
434 { "ControlPort", "If set, Tor will accept connections from the same machine "
435 "(localhost only) on this port, and allow those connections to control "
436 "the Tor process using the Tor Control Protocol (described in "
437 "control-spec.txt).", },
438 { "CookieAuthentication", "If this option is set to 1, don't allow any "
439 "connections to the control port except when the connecting process "
440 "can read a file that Tor creates in its data directory." },
441 { "DataDirectory", "Store working data, state, keys, and caches here." },
442 { "DirServer", "Tor only trusts directories signed with one of these "
443 "servers' keys. Used to override the standard list of directory "
445 /* { "FastFirstHopPK", "" }, */
446 /* FetchServerDescriptors, FetchHidServDescriptors,
447 * FetchUselessDescriptors */
448 { "HardwareAccel", "If set, Tor tries to use hardware crypto accelerators "
450 /* HashedControlPassword */
451 { "HTTPProxy", "Force Tor to make all HTTP directory requests through this "
452 "host:port (or host:80 if port is not set)." },
453 { "HTTPProxyAuthenticator", "A username:password pair to be used with "
455 { "HTTPSProxy", "Force Tor to make all TLS (SSL) connectinos through this "
456 "host:port (or host:80 if port is not set)." },
457 { "HTTPSProxyAuthenticator", "A username:password pair to be used with "
459 { "KeepalivePeriod", "Send a padding cell every N seconds to keep firewalls "
460 "from closing our connections while Tor is not in use." },
461 { "Log", "Where to send logging messages. Format is "
462 "minSeverity[-maxSeverity] (stderr|stdout|syslog|file FILENAME)." },
463 { "OutboundBindAddress", "Make all outbound connections originate from the "
464 "provided IP address (only useful for multiple network interfaces)." },
465 { "PIDFile", "On startup, write our PID to this file. On clean shutdown, "
466 "remove the file." },
467 { "PreferTunneledDirConns", "If non-zero, avoid directory servers that "
468 "don't support tunneled connections." },
469 /* PreferTunneledDirConns */
470 /* ProtocolWarnings */
471 /* RephistTrackTime */
472 { "RunAsDaemon", "If set, Tor forks and daemonizes to the background when "
473 "started. Unix only." },
474 { "SafeLogging", "If set to 0, Tor logs potentially sensitive strings "
475 "rather than replacing them with the string [scrubbed]." },
476 { "TunnelDirConns", "If non-zero, when a directory server we contact "
477 "supports it, we will build a one-hop circuit and make an encrypted "
478 "connection via its ORPort." },
479 { "User", "On startup, setuid to this user." },
481 /* ==== client options */
482 { "AllowInvalidNodes", "Where on our circuits should Tor allow servers "
483 "that the directory authorities haven't called \"valid\"?" },
484 { "AllowNonRFC953Hostnames", "If set to 1, we don't automatically reject "
485 "hostnames for having invalid characters." },
486 /* CircuitBuildTimeout, CircuitIdleTimeout */
487 { "ClientOnly", "If set to 1, Tor will under no circumstances run as a "
488 "server, even if ORPort is enabled." },
489 { "EntryNodes", "A list of preferred entry nodes to use for the first hop "
490 "in circuits, when possible." },
491 /* { "EnforceDistinctSubnets" , "" }, */
492 { "ExitNodes", "A list of preferred nodes to use for the last hop in "
493 "circuits, when possible." },
494 { "ExcludeNodes", "A list of nodes never to use when building a circuit." },
495 { "FascistFirewall", "If set, Tor will only create outgoing connections to "
496 "servers running on the ports listed in FirewallPorts." },
497 { "FirewallPorts", "A list of ports that we can connect to. Only used "
498 "when FascistFirewall is set." },
499 { "LongLivedPorts", "A list of ports for services that tend to require "
500 "high-uptime connections." },
501 { "MapAddress", "Force Tor to treat all requests for one address as if "
502 "they were for another." },
503 { "NewCircuitPeriod", "Force Tor to consider whether to build a new circuit "
504 "every NUM seconds." },
505 { "MaxCircuitDirtiness", "Do not attach new streams to a circuit that has "
506 "been used more than this many seconds ago." },
507 /* NatdPort, NatdListenAddress */
508 { "NodeFamily", "A list of servers that constitute a 'family' and should "
509 "never be used in the same circuit." },
510 { "NumEntryGuards", "How many entry guards should we keep at a time?" },
511 /* PathlenCoinWeight */
512 { "ReachableAddresses", "Addresses we can connect to, as IP/bits:port-port. "
513 "By default, we assume all addresses are reachable." },
514 /* reachablediraddresses, reachableoraddresses. */
516 { "SOCKSPort", "The port where we listen for SOCKS connections from "
518 { "SOCKSListenAddress", "Bind to this address to listen to connections from "
519 "SOCKS-speaking applications." },
520 { "SOCKSPolicy", "Set an entry policy to limit which addresses can connect "
521 "to the SOCKSPort." },
523 { "StrictExitNodes", "If set, Tor will fail to operate when none of the "
524 "configured ExitNodes can be used." },
525 { "StrictEntryNodes", "If set, Tor will fail to operate when none of the "
526 "configured EntryNodes can be used." },
528 { "TrackHostsExit", "Hosts and domains which should, if possible, be "
529 "accessed from the same exit node each time we connect to them." },
530 { "TrackHostsExitExpire", "Time after which we forget which exit we were "
531 "using to connect to hosts in TrackHostsExit." },
532 /* "TransPort", "TransListenAddress */
533 { "UseEntryGuards", "Set to 0 if we want to pick from the whole set of "
534 "servers for the first position in each circuit, rather than picking a "
535 "set of 'Guards' to prevent profiling attacks." },
537 /* === server options */
538 { "Address", "The advertised (external) address we should use." },
539 /* Accounting* options. */
540 /* AssumeReachable */
541 { "ContactInfo", "Administrative contact information to advertise for this "
543 { "ExitPolicy", "Address/port ranges for which to accept or reject outgoing "
544 "connections on behalf of Tor users." },
545 /* { "ExitPolicyRejectPrivate, "" }, */
546 { "MaxAdvertisedBandwidth", "If set, we will not advertise more than this "
547 "amount of bandwidth for our bandwidth rate, regardless of how much "
548 "bandwidth we actually detect." },
549 { "MaxOnionsPending", "Reject new attempts to extend circuits when we "
550 "already have this many pending." },
551 { "MyFamily", "Declare a list of other servers as belonging to the same "
552 "family as this one, so that clients will not use two from the same "
553 "family in the same circuit." },
554 { "Nickname", "Set the server nickname." },
555 { "NoPublish", "{DEPRECATED}" },
556 { "NumCPUs", "How many processes to use at once for public-key crypto." },
557 { "ORPort", "Advertise this port to listen for connections from Tor clients "
559 { "ORListenAddress", "Bind to this address to listen for connections from "
560 "clients and servers, instead of the default 0.0.0.0:ORPort." },
561 { "PublishServerDescriptor", "Set to 0 to keep the server from "
562 "uploading info to the directory authorities." },
563 /* ServerDNS: DetectHijacking, ResolvConfFile, SearchDomains */
564 { "ShutdownWaitLength", "Wait this long for clients to finish when "
565 "shutting down because of a SIGINT." },
567 /* === directory cache options */
568 { "DirPort", "Serve directory information from this port, and act as a "
569 "directory cache." },
570 { "DirPortFrontPage", "Serve a static html disclaimer on DirPort." },
571 { "DirListenAddress", "Bind to this address to listen for connections from "
572 "clients and servers, instead of the default 0.0.0.0:DirPort." },
573 { "DirPolicy", "Set a policy to limit who can connect to the directory "
576 /* Authority options: AuthDirBadExit, AuthDirInvalid, AuthDirReject,
577 * AuthDirRejectUnlisted, AuthDirListBadExits, AuthoritativeDirectory,
578 * DirAllowPrivateAddresses, HSAuthoritativeDir,
579 * NamingAuthoritativeDirectory, RecommendedVersions,
580 * RecommendedClientVersions, RecommendedServerVersions, RendPostPeriod,
581 * RunTesting, V1AuthoritativeDirectory, VersioningAuthoritativeDirectory, */
583 /* Hidden service options: HiddenService: dir,excludenodes, nodes,
584 * options, port. PublishHidServDescriptor */
586 /* Nonpersistent options: __LeaveStreamsUnattached, __AllDirActionsPrivate */
590 /** Online description of state variables. */
591 static config_var_description_t state_description
[] = {
592 { "AccountingBytesReadInInterval",
593 "How many bytes have we read in this accounting period?" },
594 { "AccountingBytesWrittenInInterval",
595 "How many bytes have we written in this accounting period?" },
596 { "AccountingExpectedUsage",
597 "How many bytes did we expect to use per minute? (0 for no estimate.)" },
598 { "AccountingIntervalStart", "When did this accounting period begin?" },
599 { "AccountingSecondsActive", "How long have we been awake in this period?" },
601 { "BWHistoryReadEnds", "When does the last-recorded read-interval end?" },
602 { "BWHistoryReadInterval", "How long is each read-interval (in seconds)?" },
603 { "BWHistoryReadValues", "Number of bytes read in each interval." },
604 { "BWHistoryWriteEnds", "When does the last-recorded write-interval end?" },
605 { "BWHistoryWriteInterval", "How long is each write-interval (in seconds)?"},
606 { "BWHistoryWriteValues", "Number of bytes written in each interval." },
608 { "EntryGuard", "One of the nodes we have chosen as a fixed entry" },
609 { "EntryGuardDownSince",
610 "The last entry guard has been unreachable since this time." },
611 { "EntryGuardUnlistedSince",
612 "The last entry guard has been unusable since this time." },
614 { "LastRotatedOnionKey",
615 "The last time at which we changed the medium-term private key used for "
616 "building circuits." },
617 { "LastWritten", "When was this state file last regenerated?" },
619 { "TorVersion", "Which version of Tor generated this state file?" },
623 /** Type of a callback to validate whether a given configuration is
624 * well-formed and consistent. See options_trial_assign() for documentation
626 typedef int (*validate_fn_t
)(void*,void*,int,char**);
628 /** Information on the keys, value types, key-to-struct-member mappings,
629 * variable descriptions, validation functions, and abbreviations for a
630 * configuration or storage format. */
632 size_t size
; /**< Size of the struct that everything gets parsed into. */
633 uint32_t magic
; /**< Required 'magic value' to make sure we have a struct
634 * of the right type. */
635 off_t magic_offset
; /**< Offset of the magic value within the struct. */
636 config_abbrev_t
*abbrevs
; /**< List of abbreviations that we expand when
637 * parsing this format. */
638 config_var_t
*vars
; /**< List of variables we recognize, their default
639 * values, and where we stick them in the structure. */
640 validate_fn_t validate_fn
; /**< Function to validate config. */
641 /** Documentation for configuration variables. */
642 config_var_description_t
*descriptions
;
643 /** If present, extra is a LINELIST variable for unrecognized
644 * lines. Otherwise, unrecognized lines are an error. */
648 /** Macro: assert that <b>cfg</b> has the right magic field for format
650 #define CHECK(fmt, cfg) STMT_BEGIN \
651 tor_assert(fmt && cfg); \
652 tor_assert((fmt)->magic == \
653 *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
657 static char *get_windows_conf_root(void);
659 static void config_line_append(config_line_t
**lst
,
660 const char *key
, const char *val
);
661 static void option_clear(config_format_t
*fmt
, or_options_t
*options
,
663 static void option_reset(config_format_t
*fmt
, or_options_t
*options
,
664 config_var_t
*var
, int use_defaults
);
665 static void config_free(config_format_t
*fmt
, void *options
);
666 static int config_lines_eq(config_line_t
*a
, config_line_t
*b
);
667 static int option_is_same(config_format_t
*fmt
,
668 or_options_t
*o1
, or_options_t
*o2
,
670 static or_options_t
*options_dup(config_format_t
*fmt
, or_options_t
*old
);
671 static int options_validate(or_options_t
*old_options
, or_options_t
*options
,
672 int from_setconf
, char **msg
);
673 static int options_act_reversible(or_options_t
*old_options
, char **msg
);
674 static int options_act(or_options_t
*old_options
);
675 static int options_transition_allowed(or_options_t
*old
, or_options_t
*new,
677 static int options_transition_affects_workers(or_options_t
*old_options
,
678 or_options_t
*new_options
);
679 static int options_transition_affects_descriptor(or_options_t
*old_options
,
680 or_options_t
*new_options
);
681 static int check_nickname_list(const char *lst
, const char *name
, char **msg
);
682 static void config_register_addressmaps(or_options_t
*options
);
684 static int parse_bridge_line(const char *line
, int validate_only
);
685 static int parse_dir_server_line(const char *line
,
686 authority_type_t required_type
,
688 static int validate_data_directory(or_options_t
*options
);
689 static int write_configuration_file(const char *fname
, or_options_t
*options
);
690 static config_line_t
*get_assigned_option(config_format_t
*fmt
,
691 or_options_t
*options
, const char *key
,
693 static void config_init(config_format_t
*fmt
, void *options
);
694 static int or_state_validate(or_state_t
*old_options
, or_state_t
*options
,
695 int from_setconf
, char **msg
);
696 static int or_state_load(void);
697 static int options_init_logs(or_options_t
*options
, int validate_only
);
699 static uint64_t config_parse_memunit(const char *s
, int *ok
);
700 static int config_parse_interval(const char *s
, int *ok
);
701 static void print_svn_version(void);
702 static void init_libevent(void);
703 static int opt_streq(const char *s1
, const char *s2
);
704 /** Versions of libevent. */
706 /* Note: we compare these, so it's important that "old" precede everything,
707 * and that "other" come last. */
708 LE_OLD
=0, LE_10C
, LE_10D
, LE_10E
, LE_11
, LE_11A
, LE_11B
, LE_12
, LE_12A
,
709 LE_13
, LE_13A
, LE_13B
, LE_13C
, LE_13D
,
712 static le_version_t
decode_libevent_version(void);
713 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
714 static void check_libevent_version(const char *m
, int server
);
717 /** Magic value for or_options_t. */
718 #define OR_OPTIONS_MAGIC 9090909
720 /** Configuration format for or_options_t. */
721 static config_format_t options_format
= {
722 sizeof(or_options_t
),
724 STRUCT_OFFSET(or_options_t
, _magic
),
727 (validate_fn_t
)options_validate
,
732 /** Magic value for or_state_t. */
733 #define OR_STATE_MAGIC 0x57A73f57
735 /** "Extra" variable in the state that receives lines we can't parse. This
736 * lets us preserve options from versions of Tor newer than us. */
737 static config_var_t state_extra_var
= {
738 "__extra", CONFIG_TYPE_LINELIST
, STRUCT_OFFSET(or_state_t
, ExtraLines
), NULL
741 /** Configuration format for or_state_t. */
742 static config_format_t state_format
= {
745 STRUCT_OFFSET(or_state_t
, _magic
),
748 (validate_fn_t
)or_state_validate
,
754 * Functions to read and write the global options pointer.
757 /** Command-line and config-file options. */
758 static or_options_t
*global_options
= NULL
;
759 /** Name of most recently read torrc file. */
760 static char *torrc_fname
= NULL
;
761 /** Persistent serialized state. */
762 static or_state_t
*global_state
= NULL
;
763 /** Configuration Options set by command line. */
764 static config_line_t
*global_cmdline_options
= NULL
;
765 /** Contents of most recently read DirPortFrontPage file. */
766 static char *global_dirfrontpagecontents
= NULL
;
768 /** Return the contents of our frontpage string, or NULL if not configured. */
770 get_dirportfrontpage(void)
772 return global_dirfrontpagecontents
;
775 /** Allocate an empty configuration object of a given format type. */
777 config_alloc(config_format_t
*fmt
)
779 void *opts
= tor_malloc_zero(fmt
->size
);
780 *(uint32_t*)STRUCT_VAR_P(opts
, fmt
->magic_offset
) = fmt
->magic
;
785 /** Return the currently configured options. */
789 tor_assert(global_options
);
790 return global_options
;
793 /** Change the current global options to contain <b>new_val</b> instead of
794 * their current value; take action based on the new value; free the old value
795 * as necessary. Returns 0 on success, -1 on failure.
798 set_options(or_options_t
*new_val
, char **msg
)
800 or_options_t
*old_options
= global_options
;
801 global_options
= new_val
;
802 /* Note that we pass the *old* options below, for comparison. It
803 * pulls the new options directly out of global_options. */
804 if (options_act_reversible(old_options
, msg
)<0) {
806 global_options
= old_options
;
809 if (options_act(old_options
) < 0) { /* acting on the options failed. die. */
811 "Acting on config options left us in a broken state. Dying.");
815 config_free(&options_format
, old_options
);
820 extern const char tor_svn_revision
[]; /* from tor_main.c */
822 /** The version of this Tor process, as parsed. */
823 static char *_version
= NULL
;
825 /** Return the current Tor version. */
829 if (_version
== NULL
) {
830 if (strlen(tor_svn_revision
)) {
831 size_t len
= strlen(VERSION
)+strlen(tor_svn_revision
)+8;
832 _version
= tor_malloc(len
);
833 tor_snprintf(_version
, len
, "%s (r%s)", VERSION
, tor_svn_revision
);
835 _version
= tor_strdup(VERSION
);
841 /** Release additional memory allocated in options
844 or_options_free(or_options_t
*options
)
846 if (options
->_ExcludeExitNodesUnion
)
847 routerset_free(options
->_ExcludeExitNodesUnion
);
848 config_free(&options_format
, options
);
851 /** Release all memory and resources held by global configuration structures.
854 config_free_all(void)
856 if (global_options
) {
857 or_options_free(global_options
);
858 global_options
= NULL
;
861 config_free(&state_format
, global_state
);
864 if (global_cmdline_options
) {
865 config_free_lines(global_cmdline_options
);
866 global_cmdline_options
= NULL
;
868 tor_free(torrc_fname
);
870 tor_free(global_dirfrontpagecontents
);
873 /** If options->SafeLogging is on, return a not very useful string,
874 * else return address.
877 safe_str(const char *address
)
880 if (get_options()->SafeLogging
)
886 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
887 * escaped(): don't use this outside the main thread, or twice in the same
890 escaped_safe_str(const char *address
)
892 if (get_options()->SafeLogging
)
895 return escaped(address
);
898 /** Add the default directory authorities directly into the trusted dir list,
899 * but only add them insofar as they share bits with <b>type</b>. */
901 add_default_trusted_dir_authorities(authority_type_t type
)
904 const char *dirservers
[] = {
905 "moria1 v1 orport=9001 v3ident=E2A2AF570166665D738736D0DD58169CC61D8A8B "
906 "128.31.0.34:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441",
907 "moria2 v1 orport=9002 128.31.0.34:9032 "
908 "719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF",
909 "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
910 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
911 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
912 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
913 "Tonga orport=443 bridge no-v2 82.94.251.206:80 "
914 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
915 "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
916 "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
917 "gabelmoo orport=443 no-v2 "
918 "v3ident=81349FC1F2DBA2C2C11B45CB9706637D480AB913 "
919 "80.190.246.100:80 6833 3D07 61BC F397 A587 A0C0 B963 E4A9 E99E C4D3",
920 "dannenberg orport=443 no-v2 "
921 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
922 "213.73.91.31:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
925 for (i
=0; dirservers
[i
]; i
++) {
926 if (parse_dir_server_line(dirservers
[i
], type
, 0)<0) {
927 log_err(LD_BUG
, "Couldn't parse internal dirserver line %s",
933 /** Look at all the config options for using alternate directory
934 * authorities, and make sure none of them are broken. Also, warn the
935 * user if we changed any dangerous ones.
938 validate_dir_authorities(or_options_t
*options
, or_options_t
*old_options
)
942 if (options
->DirServers
&&
943 (options
->AlternateDirAuthority
|| options
->AlternateBridgeAuthority
||
944 options
->AlternateHSAuthority
)) {
946 "You cannot set both DirServers and Alternate*Authority.");
950 /* do we want to complain to the user about being partitionable? */
951 if ((options
->DirServers
&&
953 !config_lines_eq(options
->DirServers
, old_options
->DirServers
))) ||
954 (options
->AlternateDirAuthority
&&
956 !config_lines_eq(options
->AlternateDirAuthority
,
957 old_options
->AlternateDirAuthority
)))) {
959 "You have used DirServer or AlternateDirAuthority to "
960 "specify alternate directory authorities in "
961 "your configuration. This is potentially dangerous: it can "
962 "make you look different from all other Tor users, and hurt "
963 "your anonymity. Even if you've specified the same "
964 "authorities as Tor uses by default, the defaults could "
965 "change in the future. Be sure you know what you're doing.");
968 /* Now go through the four ways you can configure an alternate
969 * set of directory authorities, and make sure none are broken. */
970 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
)
971 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
973 for (cl
= options
->AlternateBridgeAuthority
; cl
; cl
= cl
->next
)
974 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
976 for (cl
= options
->AlternateDirAuthority
; cl
; cl
= cl
->next
)
977 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
979 for (cl
= options
->AlternateHSAuthority
; cl
; cl
= cl
->next
)
980 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
985 /** Look at all the config options and assign new dir authorities
989 consider_adding_dir_authorities(or_options_t
*options
,
990 or_options_t
*old_options
)
994 !smartlist_len(router_get_trusted_dir_servers()) || !old_options
||
995 !config_lines_eq(options
->DirServers
, old_options
->DirServers
) ||
996 !config_lines_eq(options
->AlternateBridgeAuthority
,
997 old_options
->AlternateBridgeAuthority
) ||
998 !config_lines_eq(options
->AlternateDirAuthority
,
999 old_options
->AlternateDirAuthority
) ||
1000 !config_lines_eq(options
->AlternateHSAuthority
,
1001 old_options
->AlternateHSAuthority
);
1003 if (!need_to_update
)
1004 return 0; /* all done */
1006 /* Start from a clean slate. */
1007 clear_trusted_dir_servers();
1009 if (!options
->DirServers
) {
1010 /* then we may want some of the defaults */
1011 authority_type_t type
= NO_AUTHORITY
;
1012 if (!options
->AlternateBridgeAuthority
)
1013 type
|= BRIDGE_AUTHORITY
;
1014 if (!options
->AlternateDirAuthority
)
1015 type
|= V1_AUTHORITY
| V2_AUTHORITY
| V3_AUTHORITY
;
1016 if (!options
->AlternateHSAuthority
)
1017 type
|= HIDSERV_AUTHORITY
;
1018 add_default_trusted_dir_authorities(type
);
1021 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
)
1022 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
1024 for (cl
= options
->AlternateBridgeAuthority
; cl
; cl
= cl
->next
)
1025 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
1027 for (cl
= options
->AlternateDirAuthority
; cl
; cl
= cl
->next
)
1028 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
1030 for (cl
= options
->AlternateHSAuthority
; cl
; cl
= cl
->next
)
1031 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
1036 /** Fetch the active option list, and take actions based on it. All of the
1037 * things we do should survive being done repeatedly. If present,
1038 * <b>old_options</b> contains the previous value of the options.
1040 * Return 0 if all goes well, return -1 if things went badly.
1043 options_act_reversible(or_options_t
*old_options
, char **msg
)
1045 smartlist_t
*new_listeners
= smartlist_create();
1046 smartlist_t
*replaced_listeners
= smartlist_create();
1047 static int libevent_initialized
= 0;
1048 or_options_t
*options
= get_options();
1049 int running_tor
= options
->command
== CMD_RUN_TOR
;
1050 int set_conn_limit
= 0;
1052 int logs_marked
= 0;
1054 /* Daemonize _first_, since we only want to open most of this stuff in
1055 * the subprocess. Libevent bases can't be reliably inherited across
1057 if (running_tor
&& options
->RunAsDaemon
) {
1058 /* No need to roll back, since you can't change the value. */
1062 #ifndef HAVE_SYS_UN_H
1063 if (options
->ControlSocket
) {
1064 *msg
= tor_strdup("Unix domain sockets (ControlSocket) not supported"
1065 " on this OS/with this build.");
1071 /* We need to set the connection limit before we can open the listeners. */
1072 if (set_max_file_descriptors((unsigned)options
->ConnLimit
,
1073 &options
->_ConnLimit
) < 0) {
1074 *msg
= tor_strdup("Problem with ConnLimit value. See logs for details.");
1079 /* Set up libevent. (We need to do this before we can register the
1080 * listeners as listeners.) */
1081 if (running_tor
&& !libevent_initialized
) {
1083 libevent_initialized
= 1;
1086 /* Launch the listeners. (We do this before we setuid, so we can bind to
1087 * ports under 1024.) */
1088 if (retry_all_listeners(replaced_listeners
, new_listeners
) < 0) {
1089 *msg
= tor_strdup("Failed to bind one of the listener ports.");
1094 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1095 /* Open /dev/pf before dropping privileges. */
1096 if (options
->TransPort
) {
1097 if (get_pf_socket() < 0) {
1098 *msg
= tor_strdup("Unable to open /dev/pf for transparent proxy.");
1104 /* Setuid/setgid as appropriate */
1105 if (options
->User
) {
1106 if (switch_id(options
->User
) != 0) {
1107 /* No need to roll back, since you can't change the value. */
1108 *msg
= tor_strdup("Problem with User value. See logs for details.");
1113 /* Ensure data directory is private; create if possible. */
1114 if (check_private_dir(options
->DataDirectory
,
1115 running_tor
? CPD_CREATE
: CPD_CHECK
)<0) {
1117 int tmp
= tor_snprintf(buf
, sizeof(buf
),
1118 "Couldn't access/create private data directory \"%s\"",
1119 options
->DataDirectory
);
1120 *msg
= tor_strdup(tmp
>= 0 ? buf
: "internal error");
1122 /* No need to roll back, since you can't change the value. */
1125 if (directory_caches_v2_dir_info(options
)) {
1126 size_t len
= strlen(options
->DataDirectory
)+32;
1127 char *fn
= tor_malloc(len
);
1128 tor_snprintf(fn
, len
, "%s"PATH_SEPARATOR
"cached-status",
1129 options
->DataDirectory
);
1130 if (check_private_dir(fn
, running_tor
? CPD_CREATE
: CPD_CHECK
) < 0) {
1132 int tmp
= tor_snprintf(buf
, sizeof(buf
),
1133 "Couldn't access/create private data directory \"%s\"", fn
);
1134 *msg
= tor_strdup(tmp
>= 0 ? buf
: "internal error");
1141 /* Bail out at this point if we're not going to be a client or server:
1142 * we don't run Tor itself. */
1146 mark_logs_temp(); /* Close current logs once new logs are open. */
1148 if (options_init_logs(options
, 0)<0) { /* Configure the log(s) */
1149 *msg
= tor_strdup("Failed to init Log options. See logs for details.");
1156 log_severity_list_t
*severity
=
1157 tor_malloc_zero(sizeof(log_severity_list_t
));
1159 add_callback_log(severity
, control_event_logmsg
);
1160 control_adjust_event_log_severity();
1163 SMARTLIST_FOREACH(replaced_listeners
, connection_t
*, conn
,
1165 log_notice(LD_NET
, "Closing old %s on %s:%d",
1166 conn_type_to_string(conn
->type
), conn
->address
, conn
->port
);
1167 connection_close_immediate(conn
);
1168 connection_mark_for_close(conn
);
1177 rollback_log_changes();
1178 control_adjust_event_log_severity();
1181 if (set_conn_limit
&& old_options
)
1182 set_max_file_descriptors((unsigned)old_options
->ConnLimit
,
1183 &options
->_ConnLimit
);
1185 SMARTLIST_FOREACH(new_listeners
, connection_t
*, conn
,
1187 log_notice(LD_NET
, "Closing partially-constructed listener %s on %s:%d",
1188 conn_type_to_string(conn
->type
), conn
->address
, conn
->port
);
1189 connection_close_immediate(conn
);
1190 connection_mark_for_close(conn
);
1194 smartlist_free(new_listeners
);
1195 smartlist_free(replaced_listeners
);
1199 /** If we need to have a GEOIP ip-to-country map to run with our configured
1200 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1202 options_need_geoip_info(or_options_t
*options
, const char **reason_out
)
1205 options
->BridgeRelay
&& options
->BridgeRecordUsageByCountry
;
1206 int routerset_usage
=
1207 routerset_needs_geoip(options
->EntryNodes
) ||
1208 routerset_needs_geoip(options
->ExitNodes
) ||
1209 routerset_needs_geoip(options
->ExcludeExitNodes
) ||
1210 routerset_needs_geoip(options
->ExcludeNodes
);
1212 if (routerset_usage
&& reason_out
) {
1213 *reason_out
= "We've been configured to use (or avoid) nodes in certain "
1214 "contries, and we need GEOIP information to figure out which ones they "
1216 } else if (bridge_usage
&& reason_out
) {
1217 *reason_out
= "We've been configured to see which countries can access "
1218 "us as a bridge, and we need GEOIP information to tell which countries "
1221 return bridge_usage
|| routerset_usage
;
1224 /** Fetch the active option list, and take actions based on it. All of the
1225 * things we do should survive being done repeatedly. If present,
1226 * <b>old_options</b> contains the previous value of the options.
1228 * Return 0 if all goes well, return -1 if it's time to die.
1230 * Note: We haven't moved all the "act on new configuration" logic
1231 * here yet. Some is still in do_hup() and other places.
1234 options_act(or_options_t
*old_options
)
1237 or_options_t
*options
= get_options();
1238 int running_tor
= options
->command
== CMD_RUN_TOR
;
1241 if (running_tor
&& !have_lockfile()) {
1242 if (try_locking(options
, 1) < 0)
1246 if (consider_adding_dir_authorities(options
, old_options
) < 0)
1249 if (options
->Bridges
) {
1250 clear_bridge_list();
1251 for (cl
= options
->Bridges
; cl
; cl
= cl
->next
) {
1252 if (parse_bridge_line(cl
->value
, 0)<0) {
1254 "Previously validated Bridge line could not be added!");
1260 if (running_tor
&& rend_config_services(options
, 0)<0) {
1262 "Previously validated hidden services line could not be added!");
1266 if (running_tor
&& rend_parse_service_authorization(options
, 0) < 0) {
1267 log_warn(LD_BUG
, "Previously validated client authorization for "
1268 "hidden services could not be added!");
1273 if (! global_state
&& running_tor
) {
1274 if (or_state_load())
1276 rep_hist_load_mtbf_data(time(NULL
));
1279 /* Bail out at this point if we're not going to be a client or server:
1280 * we want to not fork, and to log stuff to stderr. */
1284 /* Finish backgrounding the process */
1285 if (running_tor
&& options
->RunAsDaemon
) {
1286 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1287 finish_daemon(options
->DataDirectory
);
1290 /* Write our pid to the pid file. If we do not have write permissions we
1291 * will log a warning */
1292 if (running_tor
&& options
->PidFile
)
1293 write_pidfile(options
->PidFile
);
1295 /* Register addressmap directives */
1296 config_register_addressmaps(options
);
1297 parse_virtual_addr_network(options
->VirtualAddrNetwork
, 0, &msg
);
1299 /* Update address policies. */
1300 if (policies_parse_from_options(options
) < 0) {
1301 /* This should be impossible, but let's be sure. */
1302 log_warn(LD_BUG
,"Error parsing already-validated policy options.");
1306 if (init_cookie_authentication(options
->CookieAuthentication
) < 0) {
1307 log_warn(LD_CONFIG
,"Error creating cookie authentication file.");
1311 /* reload keys as needed for rendezvous services. */
1312 if (rend_service_load_keys()<0) {
1313 log_warn(LD_GENERAL
,"Error loading rendezvous service keys");
1317 /* Set up accounting */
1318 if (accounting_parse_options(options
, 0)<0) {
1319 log_warn(LD_CONFIG
,"Error in accounting options");
1322 if (accounting_is_enabled(options
))
1323 configure_accounting(time(NULL
));
1325 /* Check for transitions that need action. */
1327 if (options
->UseEntryGuards
&& !old_options
->UseEntryGuards
) {
1329 "Switching to entry guards; abandoning previous circuits");
1330 circuit_mark_all_unused_circs();
1331 circuit_expire_all_dirty_circs();
1334 if (options_transition_affects_workers(old_options
, options
)) {
1335 log_info(LD_GENERAL
,
1336 "Worker-related options changed. Rotating workers.");
1337 if (server_mode(options
) && !server_mode(old_options
)) {
1338 if (init_keys() < 0) {
1339 log_warn(LD_BUG
,"Error initializing keys; exiting");
1342 ip_address_changed(0);
1343 if (has_completed_circuit
|| !any_predicted_circuits(time(NULL
)))
1344 inform_testing_reachability();
1346 cpuworkers_rotate();
1354 if (options
->V3AuthoritativeDir
&& !old_options
->V3AuthoritativeDir
)
1358 /* Maybe load geoip file */
1359 if (options
->GeoIPFile
&&
1360 ((!old_options
|| !opt_streq(old_options
->GeoIPFile
, options
->GeoIPFile
))
1361 || !geoip_is_loaded())) {
1362 /* XXXX Don't use this "<default>" junk; make our filename options
1363 * understand prefixes somehow. -NM */
1364 /* XXXX021 Reload GeoIPFile on SIGHUP. -NM */
1365 char *actual_fname
= tor_strdup(options
->GeoIPFile
);
1367 if (!strcmp(actual_fname
, "<default>")) {
1368 const char *conf_root
= get_windows_conf_root();
1369 size_t len
= strlen(conf_root
)+16;
1370 tor_free(actual_fname
);
1371 actual_fname
= tor_malloc(len
+1);
1372 tor_snprintf(actual_fname
, len
, "%s\\geoip", conf_root
);
1375 geoip_load_file(actual_fname
, options
);
1376 tor_free(actual_fname
);
1378 /* XXXX Would iterating through all option_var's routersets be better? */
1379 if (options
->EntryNodes
)
1380 routerset_refresh_countries(options
->EntryNodes
);
1381 if (options
->ExitNodes
)
1382 routerset_refresh_countries(options
->ExitNodes
);
1383 if (options
->ExcludeNodes
)
1384 routerset_refresh_countries(options
->ExcludeNodes
);
1385 if (options
->ExcludeExitNodes
)
1386 routerset_refresh_countries(options
->ExcludeExitNodes
);
1387 routerlist_refresh_countries();
1389 /* Check if we need to parse and add the EntryNodes config option. */
1390 if (options
->EntryNodes
&&
1392 (!routerset_equal(old_options
->EntryNodes
,options
->EntryNodes
))))
1393 entry_nodes_should_be_added();
1395 /* Since our options changed, we might need to regenerate and upload our
1396 * server descriptor.
1399 options_transition_affects_descriptor(old_options
, options
))
1400 mark_my_descriptor_dirty();
1402 /* We may need to reschedule some directory stuff if our status changed. */
1404 if (authdir_mode_v3(options
) && !authdir_mode_v3(old_options
))
1405 dirvote_recalculate_timing(options
, time(NULL
));
1406 if (!bool_eq(directory_fetches_dir_info_early(options
),
1407 directory_fetches_dir_info_early(old_options
)) ||
1408 !bool_eq(directory_fetches_dir_info_later(options
),
1409 directory_fetches_dir_info_later(old_options
))) {
1410 /* Make sure update_router_have_min_dir_info gets called. */
1411 router_dir_info_changed();
1412 /* We might need to download a new consensus status later or sooner than
1413 * we had expected. */
1414 update_consensus_networkstatus_fetch_time(time(NULL
));
1418 /* Load the webpage we're going to serve everytime someone asks for '/' on
1420 tor_free(global_dirfrontpagecontents
);
1421 if (options
->DirPortFrontPage
) {
1422 global_dirfrontpagecontents
=
1423 read_file_to_str(options
->DirPortFrontPage
, 0, NULL
);
1424 if (!global_dirfrontpagecontents
) {
1426 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1427 options
->DirPortFrontPage
);
1435 * Functions to parse config options
1438 /** If <b>option</b> is an official abbreviation for a longer option,
1439 * return the longer option. Otherwise return <b>option</b>.
1440 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1441 * apply abbreviations that work for the config file and the command line.
1442 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1444 expand_abbrev(config_format_t
*fmt
, const char *option
, int command_line
,
1450 for (i
=0; fmt
->abbrevs
[i
].abbreviated
; ++i
) {
1451 /* Abbreviations are casei. */
1452 if (!strcasecmp(option
,fmt
->abbrevs
[i
].abbreviated
) &&
1453 (command_line
|| !fmt
->abbrevs
[i
].commandline_only
)) {
1454 if (warn_obsolete
&& fmt
->abbrevs
[i
].warn
) {
1456 "The configuration option '%s' is deprecated; "
1457 "use '%s' instead.",
1458 fmt
->abbrevs
[i
].abbreviated
,
1459 fmt
->abbrevs
[i
].full
);
1461 return fmt
->abbrevs
[i
].full
;
1467 /** Helper: Read a list of configuration options from the command line.
1468 * If successful, put them in *<b>result</b> and return 0, and return
1469 * -1 and leave *<b>result</b> alone. */
1471 config_get_commandlines(int argc
, char **argv
, config_line_t
**result
)
1473 config_line_t
*front
= NULL
;
1474 config_line_t
**new = &front
;
1479 if (!strcmp(argv
[i
],"-f") ||
1480 !strcmp(argv
[i
],"--hash-password")) {
1481 i
+= 2; /* command-line option with argument. ignore them. */
1483 } else if (!strcmp(argv
[i
],"--list-fingerprint") ||
1484 !strcmp(argv
[i
],"--verify-config") ||
1485 !strcmp(argv
[i
],"--ignore-missing-torrc") ||
1486 !strcmp(argv
[i
],"--quiet") ||
1487 !strcmp(argv
[i
],"--hush")) {
1488 i
+= 1; /* command-line option. ignore it. */
1490 } else if (!strcmp(argv
[i
],"--nt-service") ||
1491 !strcmp(argv
[i
],"-nt-service")) {
1497 log_warn(LD_CONFIG
,"Command-line option '%s' with no value. Failing.",
1499 config_free_lines(front
);
1503 *new = tor_malloc_zero(sizeof(config_line_t
));
1509 (*new)->key
= tor_strdup(expand_abbrev(&options_format
, s
, 1, 1));
1510 (*new)->value
= tor_strdup(argv
[i
+1]);
1511 (*new)->next
= NULL
;
1512 log(LOG_DEBUG
, LD_CONFIG
, "Commandline: parsed keyword '%s', value '%s'",
1513 (*new)->key
, (*new)->value
);
1515 new = &((*new)->next
);
1522 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1523 * append it to *<b>lst</b>. */
1525 config_line_append(config_line_t
**lst
,
1529 config_line_t
*newline
;
1531 newline
= tor_malloc(sizeof(config_line_t
));
1532 newline
->key
= tor_strdup(key
);
1533 newline
->value
= tor_strdup(val
);
1534 newline
->next
= NULL
;
1536 lst
= &((*lst
)->next
);
1541 /** Helper: parse the config string and strdup into key/value
1542 * strings. Set *result to the list, or NULL if parsing the string
1543 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1544 * misformatted lines. */
1546 config_get_lines(const char *string
, config_line_t
**result
)
1548 config_line_t
*list
= NULL
, **next
;
1554 string
= parse_config_line_from_str(string
, &k
, &v
);
1556 config_free_lines(list
);
1562 /* This list can get long, so we keep a pointer to the end of it
1563 * rather than using config_line_append over and over and getting
1564 * n^2 performance. */
1565 *next
= tor_malloc(sizeof(config_line_t
));
1568 (*next
)->next
= NULL
;
1569 next
= &((*next
)->next
);
1581 * Free all the configuration lines on the linked list <b>front</b>.
1584 config_free_lines(config_line_t
*front
)
1593 tor_free(tmp
->value
);
1598 /** Return the description for a given configuration variable, or NULL if no
1599 * description exists. */
1601 config_find_description(config_format_t
*fmt
, const char *name
)
1604 for (i
=0; fmt
->descriptions
[i
].name
; ++i
) {
1605 if (!strcasecmp(name
, fmt
->descriptions
[i
].name
))
1606 return fmt
->descriptions
[i
].description
;
1611 /** If <b>key</b> is a configuration option, return the corresponding
1612 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1613 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1615 static config_var_t
*
1616 config_find_option(config_format_t
*fmt
, const char *key
)
1619 size_t keylen
= strlen(key
);
1621 return NULL
; /* if they say "--" on the commandline, it's not an option */
1622 /* First, check for an exact (case-insensitive) match */
1623 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
1624 if (!strcasecmp(key
, fmt
->vars
[i
].name
)) {
1625 return &fmt
->vars
[i
];
1628 /* If none, check for an abbreviated match */
1629 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
1630 if (!strncasecmp(key
, fmt
->vars
[i
].name
, keylen
)) {
1631 log_warn(LD_CONFIG
, "The abbreviation '%s' is deprecated. "
1632 "Please use '%s' instead",
1633 key
, fmt
->vars
[i
].name
);
1634 return &fmt
->vars
[i
];
1637 /* Okay, unrecognized option */
1642 * Functions to assign config options.
1645 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1646 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1648 * Called from config_assign_line() and option_reset().
1651 config_assign_value(config_format_t
*fmt
, or_options_t
*options
,
1652 config_line_t
*c
, char **msg
)
1659 CHECK(fmt
, options
);
1661 var
= config_find_option(fmt
, c
->key
);
1664 lvalue
= STRUCT_VAR_P(options
, var
->var_offset
);
1666 switch (var
->type
) {
1668 case CONFIG_TYPE_UINT
:
1669 i
= (int)tor_parse_long(c
->value
, 10, 0, INT_MAX
, &ok
, NULL
);
1671 r
= tor_snprintf(buf
, sizeof(buf
),
1672 "Int keyword '%s %s' is malformed or out of bounds.",
1674 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1680 case CONFIG_TYPE_INTERVAL
: {
1681 i
= config_parse_interval(c
->value
, &ok
);
1683 r
= tor_snprintf(buf
, sizeof(buf
),
1684 "Interval '%s %s' is malformed or out of bounds.",
1686 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1693 case CONFIG_TYPE_MEMUNIT
: {
1694 uint64_t u64
= config_parse_memunit(c
->value
, &ok
);
1696 r
= tor_snprintf(buf
, sizeof(buf
),
1697 "Value '%s %s' is malformed or out of bounds.",
1699 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1702 *(uint64_t *)lvalue
= u64
;
1706 case CONFIG_TYPE_BOOL
:
1707 i
= (int)tor_parse_long(c
->value
, 10, 0, 1, &ok
, NULL
);
1709 r
= tor_snprintf(buf
, sizeof(buf
),
1710 "Boolean '%s %s' expects 0 or 1.",
1712 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1718 case CONFIG_TYPE_STRING
:
1719 case CONFIG_TYPE_FILENAME
:
1720 tor_free(*(char **)lvalue
);
1721 *(char **)lvalue
= tor_strdup(c
->value
);
1724 case CONFIG_TYPE_DOUBLE
:
1725 *(double *)lvalue
= atof(c
->value
);
1728 case CONFIG_TYPE_ISOTIME
:
1729 if (parse_iso_time(c
->value
, (time_t *)lvalue
)) {
1730 r
= tor_snprintf(buf
, sizeof(buf
),
1731 "Invalid time '%s' for keyword '%s'", c
->value
, c
->key
);
1732 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1737 case CONFIG_TYPE_ROUTERSET
:
1738 if (*(routerset_t
**)lvalue
) {
1739 routerset_free(*(routerset_t
**)lvalue
);
1741 *(routerset_t
**)lvalue
= routerset_new();
1742 if (routerset_parse(*(routerset_t
**)lvalue
, c
->value
, c
->key
)<0) {
1743 tor_snprintf(buf
, sizeof(buf
), "Invalid exit list '%s' for option '%s'",
1745 *msg
= tor_strdup(buf
);
1750 case CONFIG_TYPE_CSV
:
1751 if (*(smartlist_t
**)lvalue
) {
1752 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
1753 smartlist_clear(*(smartlist_t
**)lvalue
);
1755 *(smartlist_t
**)lvalue
= smartlist_create();
1758 smartlist_split_string(*(smartlist_t
**)lvalue
, c
->value
, ",",
1759 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1762 case CONFIG_TYPE_LINELIST
:
1763 case CONFIG_TYPE_LINELIST_S
:
1764 config_line_append((config_line_t
**)lvalue
, c
->key
, c
->value
);
1766 case CONFIG_TYPE_OBSOLETE
:
1767 log_warn(LD_CONFIG
, "Skipping obsolete configuration option '%s'", c
->key
);
1769 case CONFIG_TYPE_LINELIST_V
:
1770 r
= tor_snprintf(buf
, sizeof(buf
),
1771 "You may not provide a value for virtual option '%s'", c
->key
);
1772 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1781 /** If <b>c</b> is a syntactically valid configuration line, update
1782 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1783 * key, -2 for bad value.
1785 * If <b>clear_first</b> is set, clear the value first. Then if
1786 * <b>use_defaults</b> is set, set the value to the default.
1788 * Called from config_assign().
1791 config_assign_line(config_format_t
*fmt
, or_options_t
*options
,
1792 config_line_t
*c
, int use_defaults
,
1793 int clear_first
, char **msg
)
1797 CHECK(fmt
, options
);
1799 var
= config_find_option(fmt
, c
->key
);
1802 void *lvalue
= STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
1804 "Found unrecognized option '%s'; saving it.", c
->key
);
1805 config_line_append((config_line_t
**)lvalue
, c
->key
, c
->value
);
1809 int tmp
= tor_snprintf(buf
, sizeof(buf
),
1810 "Unknown option '%s'. Failing.", c
->key
);
1811 *msg
= tor_strdup(tmp
>= 0 ? buf
: "internal error");
1815 /* Put keyword into canonical case. */
1816 if (strcmp(var
->name
, c
->key
)) {
1818 c
->key
= tor_strdup(var
->name
);
1821 if (!strlen(c
->value
)) {
1822 /* reset or clear it, then return */
1824 if (var
->type
== CONFIG_TYPE_LINELIST
||
1825 var
->type
== CONFIG_TYPE_LINELIST_S
) {
1826 /* We got an empty linelist from the torrc or commandline.
1827 As a special case, call this an error. Warn and ignore. */
1829 "Linelist option '%s' has no value. Skipping.", c
->key
);
1830 } else { /* not already cleared */
1831 option_reset(fmt
, options
, var
, use_defaults
);
1837 if (config_assign_value(fmt
, options
, c
, msg
) < 0)
1842 /** Restore the option named <b>key</b> in options to its default value.
1843 * Called from config_assign(). */
1845 config_reset_line(config_format_t
*fmt
, or_options_t
*options
,
1846 const char *key
, int use_defaults
)
1850 CHECK(fmt
, options
);
1852 var
= config_find_option(fmt
, key
);
1854 return; /* give error on next pass. */
1856 option_reset(fmt
, options
, var
, use_defaults
);
1859 /** Return true iff key is a valid configuration option. */
1861 option_is_recognized(const char *key
)
1863 config_var_t
*var
= config_find_option(&options_format
, key
);
1864 return (var
!= NULL
);
1867 /** Return the canonical name of a configuration option, or NULL
1868 * if no such option exists. */
1870 option_get_canonical_name(const char *key
)
1872 config_var_t
*var
= config_find_option(&options_format
, key
);
1873 return var
? var
->name
: NULL
;
1876 /** Return a canonicalized list of the options assigned for key.
1879 option_get_assignment(or_options_t
*options
, const char *key
)
1881 return get_assigned_option(&options_format
, options
, key
, 1);
1884 /** Return true iff value needs to be quoted and escaped to be used in
1885 * a configuration file. */
1887 config_value_needs_escape(const char *value
)
1897 /* Note: quotes and backspaces need special handling when we are using
1898 * quotes, not otherwise, so they don't trigger escaping on their
1902 if (!TOR_ISPRINT(*value
))
1910 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1911 static config_line_t
*
1912 config_lines_dup(const config_line_t
*inp
)
1914 config_line_t
*result
= NULL
;
1915 config_line_t
**next_out
= &result
;
1917 *next_out
= tor_malloc(sizeof(config_line_t
));
1918 (*next_out
)->key
= tor_strdup(inp
->key
);
1919 (*next_out
)->value
= tor_strdup(inp
->value
);
1921 next_out
= &((*next_out
)->next
);
1927 /** Return newly allocated line or lines corresponding to <b>key</b> in the
1928 * configuration <b>options</b>. If <b>escape_val</b> is true and a
1929 * value needs to be quoted before it's put in a config file, quote and
1930 * escape that value. Return NULL if no such key exists. */
1931 static config_line_t
*
1932 get_assigned_option(config_format_t
*fmt
, or_options_t
*options
,
1933 const char *key
, int escape_val
)
1934 /* XXXX argument is options, but fmt is provided. Inconsistent. */
1939 config_line_t
*result
;
1940 tor_assert(options
&& key
);
1942 CHECK(fmt
, options
);
1944 var
= config_find_option(fmt
, key
);
1946 log_warn(LD_CONFIG
, "Unknown option '%s'. Failing.", key
);
1949 value
= STRUCT_VAR_P(options
, var
->var_offset
);
1951 result
= tor_malloc_zero(sizeof(config_line_t
));
1952 result
->key
= tor_strdup(var
->name
);
1955 case CONFIG_TYPE_STRING
:
1956 case CONFIG_TYPE_FILENAME
:
1957 if (*(char**)value
) {
1958 result
->value
= tor_strdup(*(char**)value
);
1960 tor_free(result
->key
);
1965 case CONFIG_TYPE_ISOTIME
:
1966 if (*(time_t*)value
) {
1967 result
->value
= tor_malloc(ISO_TIME_LEN
+1);
1968 format_iso_time(result
->value
, *(time_t*)value
);
1970 tor_free(result
->key
);
1973 escape_val
= 0; /* Can't need escape. */
1975 case CONFIG_TYPE_INTERVAL
:
1976 case CONFIG_TYPE_UINT
:
1977 /* This means every or_options_t uint or bool element
1978 * needs to be an int. Not, say, a uint16_t or char. */
1979 tor_snprintf(buf
, sizeof(buf
), "%d", *(int*)value
);
1980 result
->value
= tor_strdup(buf
);
1981 escape_val
= 0; /* Can't need escape. */
1983 case CONFIG_TYPE_MEMUNIT
:
1984 tor_snprintf(buf
, sizeof(buf
), U64_FORMAT
,
1985 U64_PRINTF_ARG(*(uint64_t*)value
));
1986 result
->value
= tor_strdup(buf
);
1987 escape_val
= 0; /* Can't need escape. */
1989 case CONFIG_TYPE_DOUBLE
:
1990 tor_snprintf(buf
, sizeof(buf
), "%f", *(double*)value
);
1991 result
->value
= tor_strdup(buf
);
1992 escape_val
= 0; /* Can't need escape. */
1994 case CONFIG_TYPE_BOOL
:
1995 result
->value
= tor_strdup(*(int*)value
? "1" : "0");
1996 escape_val
= 0; /* Can't need escape. */
1998 case CONFIG_TYPE_ROUTERSET
:
1999 result
->value
= routerset_to_string(*(routerset_t
**)value
);
2001 case CONFIG_TYPE_CSV
:
2002 if (*(smartlist_t
**)value
)
2004 smartlist_join_strings(*(smartlist_t
**)value
, ",", 0, NULL
);
2006 result
->value
= tor_strdup("");
2008 case CONFIG_TYPE_OBSOLETE
:
2009 log_fn(LOG_PROTOCOL_WARN
, LD_CONFIG
,
2010 "You asked me for the value of an obsolete config option '%s'.",
2012 tor_free(result
->key
);
2015 case CONFIG_TYPE_LINELIST_S
:
2017 "Can't return context-sensitive '%s' on its own", key
);
2018 tor_free(result
->key
);
2021 case CONFIG_TYPE_LINELIST
:
2022 case CONFIG_TYPE_LINELIST_V
:
2023 tor_free(result
->key
);
2025 result
= config_lines_dup(*(const config_line_t
**)value
);
2028 tor_free(result
->key
);
2030 log_warn(LD_BUG
,"Unknown type %d for known key '%s'",
2036 config_line_t
*line
;
2037 for (line
= result
; line
; line
= line
->next
) {
2038 if (line
->value
&& config_value_needs_escape(line
->value
)) {
2039 char *newval
= esc_for_log(line
->value
);
2040 tor_free(line
->value
);
2041 line
->value
= newval
;
2049 /** Iterate through the linked list of requested options <b>list</b>.
2050 * For each item, convert as appropriate and assign to <b>options</b>.
2051 * If an item is unrecognized, set *msg and return -1 immediately,
2052 * else return 0 for success.
2054 * If <b>clear_first</b>, interpret config options as replacing (not
2055 * extending) their previous values. If <b>clear_first</b> is set,
2056 * then <b>use_defaults</b> to decide if you set to defaults after
2057 * clearing, or make the value 0 or NULL.
2059 * Here are the use cases:
2060 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
2061 * if linelist, replaces current if csv.
2062 * 2. An empty AllowInvalid line in your torrc. Should clear it.
2063 * 3. "RESETCONF AllowInvalid" sets it to default.
2064 * 4. "SETCONF AllowInvalid" makes it NULL.
2065 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
2067 * Use_defaults Clear_first
2069 * 1 0 undefined, don't use
2070 * 0 1 "set to null first"
2071 * 1 1 "set to defaults first"
2072 * Return 0 on success, -1 on bad key, -2 on bad value.
2074 * As an additional special case, if a LINELIST config option has
2075 * no value and clear_first is 0, then warn and ignore it.
2079 There are three call cases for config_assign() currently.
2081 Case one: Torrc entry
2082 options_init_from_torrc() calls config_assign(0, 0)
2083 calls config_assign_line(0, 0).
2084 if value is empty, calls option_reset(0) and returns.
2085 calls config_assign_value(), appends.
2088 options_trial_assign() calls config_assign(0, 1)
2089 calls config_reset_line(0)
2090 calls option_reset(0)
2091 calls option_clear().
2092 calls config_assign_line(0, 1).
2093 if value is empty, returns.
2094 calls config_assign_value(), appends.
2096 Case three: resetconf
2097 options_trial_assign() calls config_assign(1, 1)
2098 calls config_reset_line(1)
2099 calls option_reset(1)
2100 calls option_clear().
2101 calls config_assign_value(default)
2102 calls config_assign_line(1, 1).
2106 config_assign(config_format_t
*fmt
, void *options
, config_line_t
*list
,
2107 int use_defaults
, int clear_first
, char **msg
)
2111 CHECK(fmt
, options
);
2113 /* pass 1: normalize keys */
2114 for (p
= list
; p
; p
= p
->next
) {
2115 const char *full
= expand_abbrev(fmt
, p
->key
, 0, 1);
2116 if (strcmp(full
,p
->key
)) {
2118 p
->key
= tor_strdup(full
);
2122 /* pass 2: if we're reading from a resetting source, clear all
2123 * mentioned config options, and maybe set to their defaults. */
2125 for (p
= list
; p
; p
= p
->next
)
2126 config_reset_line(fmt
, options
, p
->key
, use_defaults
);
2129 /* pass 3: assign. */
2132 if ((r
=config_assign_line(fmt
, options
, list
, use_defaults
,
2140 /** Try assigning <b>list</b> to the global options. You do this by duping
2141 * options, assigning list to the new one, then validating it. If it's
2142 * ok, then throw out the old one and stick with the new one. Else,
2143 * revert to old and return failure. Return SETOPT_OK on success, or
2144 * a setopt_err_t on failure.
2146 * If not success, point *<b>msg</b> to a newly allocated string describing
2150 options_trial_assign(config_line_t
*list
, int use_defaults
,
2151 int clear_first
, char **msg
)
2154 or_options_t
*trial_options
= options_dup(&options_format
, get_options());
2156 if ((r
=config_assign(&options_format
, trial_options
,
2157 list
, use_defaults
, clear_first
, msg
)) < 0) {
2158 config_free(&options_format
, trial_options
);
2162 if (options_validate(get_options(), trial_options
, 1, msg
) < 0) {
2163 config_free(&options_format
, trial_options
);
2164 return SETOPT_ERR_PARSE
; /*XXX make this a separate return value. */
2167 if (options_transition_allowed(get_options(), trial_options
, msg
) < 0) {
2168 config_free(&options_format
, trial_options
);
2169 return SETOPT_ERR_TRANSITION
;
2172 if (set_options(trial_options
, msg
)<0) {
2173 config_free(&options_format
, trial_options
);
2174 return SETOPT_ERR_SETTING
;
2177 /* we liked it. put it in place. */
2181 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2182 * Called from option_reset() and config_free(). */
2184 option_clear(config_format_t
*fmt
, or_options_t
*options
, config_var_t
*var
)
2186 void *lvalue
= STRUCT_VAR_P(options
, var
->var_offset
);
2187 (void)fmt
; /* unused */
2188 switch (var
->type
) {
2189 case CONFIG_TYPE_STRING
:
2190 case CONFIG_TYPE_FILENAME
:
2191 tor_free(*(char**)lvalue
);
2193 case CONFIG_TYPE_DOUBLE
:
2194 *(double*)lvalue
= 0.0;
2196 case CONFIG_TYPE_ISOTIME
:
2197 *(time_t*)lvalue
= 0;
2198 case CONFIG_TYPE_INTERVAL
:
2199 case CONFIG_TYPE_UINT
:
2200 case CONFIG_TYPE_BOOL
:
2203 case CONFIG_TYPE_MEMUNIT
:
2204 *(uint64_t*)lvalue
= 0;
2206 case CONFIG_TYPE_ROUTERSET
:
2207 if (*(routerset_t
**)lvalue
) {
2208 routerset_free(*(routerset_t
**)lvalue
);
2209 *(routerset_t
**)lvalue
= NULL
;
2211 case CONFIG_TYPE_CSV
:
2212 if (*(smartlist_t
**)lvalue
) {
2213 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
2214 smartlist_free(*(smartlist_t
**)lvalue
);
2215 *(smartlist_t
**)lvalue
= NULL
;
2218 case CONFIG_TYPE_LINELIST
:
2219 case CONFIG_TYPE_LINELIST_S
:
2220 config_free_lines(*(config_line_t
**)lvalue
);
2221 *(config_line_t
**)lvalue
= NULL
;
2223 case CONFIG_TYPE_LINELIST_V
:
2224 /* handled by linelist_s. */
2226 case CONFIG_TYPE_OBSOLETE
:
2231 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2232 * <b>use_defaults</b>, set it to its default value.
2233 * Called by config_init() and option_reset_line() and option_assign_line(). */
2235 option_reset(config_format_t
*fmt
, or_options_t
*options
,
2236 config_var_t
*var
, int use_defaults
)
2240 CHECK(fmt
, options
);
2241 option_clear(fmt
, options
, var
); /* clear it first */
2243 return; /* all done */
2244 if (var
->initvalue
) {
2245 c
= tor_malloc_zero(sizeof(config_line_t
));
2246 c
->key
= tor_strdup(var
->name
);
2247 c
->value
= tor_strdup(var
->initvalue
);
2248 if (config_assign_value(fmt
, options
, c
, &msg
) < 0) {
2249 log_warn(LD_BUG
, "Failed to assign default: %s", msg
);
2250 tor_free(msg
); /* if this happens it's a bug */
2252 config_free_lines(c
);
2256 /** Print a usage message for tor. */
2261 "Copyright (c) 2001-2004, Roger Dingledine\n"
2262 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2263 "Copyright (c) 2007-2008, The Tor Project, Inc.\n\n"
2264 "tor -f <torrc> [args]\n"
2265 "See man page for options, or https://www.torproject.org/ for "
2266 "documentation.\n");
2269 /** Print all non-obsolete torrc options. */
2271 list_torrc_options(void)
2274 smartlist_t
*lines
= smartlist_create();
2275 for (i
= 0; _option_vars
[i
].name
; ++i
) {
2276 config_var_t
*var
= &_option_vars
[i
];
2278 if (var
->type
== CONFIG_TYPE_OBSOLETE
||
2279 var
->type
== CONFIG_TYPE_LINELIST_V
)
2281 desc
= config_find_description(&options_format
, var
->name
);
2282 printf("%s\n", var
->name
);
2284 wrap_string(lines
, desc
, 76, " ", " ");
2285 SMARTLIST_FOREACH(lines
, char *, cp
, {
2289 smartlist_clear(lines
);
2292 smartlist_free(lines
);
2295 /** Last value actually set by resolve_my_address. */
2296 static uint32_t last_resolved_addr
= 0;
2298 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2299 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2300 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2301 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2302 * public IP address.
2305 resolve_my_address(int warn_severity
, or_options_t
*options
,
2306 uint32_t *addr_out
, char **hostname_out
)
2309 struct hostent
*rent
;
2312 int explicit_hostname
=1;
2313 int from_interface
=0;
2314 char tmpbuf
[INET_NTOA_BUF_LEN
];
2315 const char *address
= options
->Address
;
2316 int notice_severity
= warn_severity
<= LOG_NOTICE
?
2317 LOG_NOTICE
: warn_severity
;
2319 tor_assert(addr_out
);
2321 if (address
&& *address
) {
2322 strlcpy(hostname
, address
, sizeof(hostname
));
2323 } else { /* then we need to guess our address */
2324 explicit_ip
= 0; /* it's implicit */
2325 explicit_hostname
= 0; /* it's implicit */
2327 if (gethostname(hostname
, sizeof(hostname
)) < 0) {
2328 log_fn(warn_severity
, LD_NET
,"Error obtaining local hostname");
2331 log_debug(LD_CONFIG
,"Guessed local host name as '%s'",hostname
);
2334 /* now we know hostname. resolve it and keep only the IP address */
2336 if (tor_inet_aton(hostname
, &in
) == 0) {
2337 /* then we have to resolve it */
2339 rent
= (struct hostent
*)gethostbyname(hostname
);
2341 uint32_t interface_ip
;
2343 if (explicit_hostname
) {
2344 log_fn(warn_severity
, LD_CONFIG
,
2345 "Could not resolve local Address '%s'. Failing.", hostname
);
2348 log_fn(notice_severity
, LD_CONFIG
,
2349 "Could not resolve guessed local hostname '%s'. "
2350 "Trying something else.", hostname
);
2351 if (get_interface_address(warn_severity
, &interface_ip
)) {
2352 log_fn(warn_severity
, LD_CONFIG
,
2353 "Could not get local interface IP address. Failing.");
2357 in
.s_addr
= htonl(interface_ip
);
2358 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2359 log_fn(notice_severity
, LD_CONFIG
, "Learned IP address '%s' for "
2360 "local interface. Using that.", tmpbuf
);
2361 strlcpy(hostname
, "<guessed from interfaces>", sizeof(hostname
));
2363 tor_assert(rent
->h_length
== 4);
2364 memcpy(&in
.s_addr
, rent
->h_addr
, rent
->h_length
);
2366 if (!explicit_hostname
&&
2367 is_internal_IP(ntohl(in
.s_addr
), 0)) {
2368 uint32_t interface_ip
;
2370 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2371 log_fn(notice_severity
, LD_CONFIG
, "Guessed local hostname '%s' "
2372 "resolves to a private IP address (%s). Trying something "
2373 "else.", hostname
, tmpbuf
);
2375 if (get_interface_address(warn_severity
, &interface_ip
)) {
2376 log_fn(warn_severity
, LD_CONFIG
,
2377 "Could not get local interface IP address. Too bad.");
2378 } else if (is_internal_IP(interface_ip
, 0)) {
2380 in2
.s_addr
= htonl(interface_ip
);
2381 tor_inet_ntoa(&in2
,tmpbuf
,sizeof(tmpbuf
));
2382 log_fn(notice_severity
, LD_CONFIG
,
2383 "Interface IP address '%s' is a private address too. "
2384 "Ignoring.", tmpbuf
);
2387 in
.s_addr
= htonl(interface_ip
);
2388 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2389 log_fn(notice_severity
, LD_CONFIG
,
2390 "Learned IP address '%s' for local interface."
2391 " Using that.", tmpbuf
);
2392 strlcpy(hostname
, "<guessed from interfaces>", sizeof(hostname
));
2398 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2399 if (is_internal_IP(ntohl(in
.s_addr
), 0) &&
2400 options
->_PublishServerDescriptor
) {
2401 /* make sure we're ok with publishing an internal IP */
2402 if (!options
->DirServers
&& !options
->AlternateDirAuthority
) {
2403 /* if they are using the default dirservers, disallow internal IPs
2405 log_fn(warn_severity
, LD_CONFIG
,
2406 "Address '%s' resolves to private IP address '%s'. "
2407 "Tor servers that use the default DirServers must have public "
2408 "IP addresses.", hostname
, tmpbuf
);
2412 /* even if they've set their own dirservers, require an explicit IP if
2413 * they're using an internal address. */
2414 log_fn(warn_severity
, LD_CONFIG
, "Address '%s' resolves to private "
2415 "IP address '%s'. Please set the Address config option to be "
2416 "the IP address you want to use.", hostname
, tmpbuf
);
2421 log_debug(LD_CONFIG
, "Resolved Address to '%s'.", tmpbuf
);
2422 *addr_out
= ntohl(in
.s_addr
);
2423 if (last_resolved_addr
&& last_resolved_addr
!= *addr_out
) {
2424 /* Leave this as a notice, regardless of the requested severity,
2425 * at least until dynamic IP address support becomes bulletproof. */
2427 "Your IP address seems to have changed to %s. Updating.",
2429 ip_address_changed(0);
2431 if (last_resolved_addr
!= *addr_out
) {
2433 const char *h
= hostname
;
2435 method
= "CONFIGURED";
2437 } else if (explicit_hostname
) {
2438 method
= "RESOLVED";
2439 } else if (from_interface
) {
2440 method
= "INTERFACE";
2443 method
= "GETHOSTNAME";
2445 control_event_server_status(LOG_NOTICE
,
2446 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2447 tmpbuf
, method
, h
?"HOSTNAME=":"", h
);
2449 last_resolved_addr
= *addr_out
;
2451 *hostname_out
= tor_strdup(hostname
);
2455 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2456 * on a private network.
2459 is_local_addr(const tor_addr_t
*addr
)
2461 if (tor_addr_is_internal(addr
, 0))
2463 /* Check whether ip is on the same /24 as we are. */
2464 if (get_options()->EnforceDistinctSubnets
== 0)
2466 if (tor_addr_family(addr
) == AF_INET
) {
2467 /*XXXX021 IP6 what corresponds to an /24? */
2468 uint32_t ip
= tor_addr_to_ipv4h(addr
);
2470 /* It's possible that this next check will hit before the first time
2471 * resolve_my_address actually succeeds. (For clients, it is likely that
2472 * resolve_my_address will never be called at all). In those cases,
2473 * last_resolved_addr will be 0, and so checking to see whether ip is on
2474 * the same /24 as last_resolved_addr will be the same as checking whether
2475 * it was on net 0, which is already done by is_internal_IP.
2477 if ((last_resolved_addr
& 0xffffff00ul
) == (ip
& 0xffffff00ul
))
2483 /** Called when we don't have a nickname set. Try to guess a good nickname
2484 * based on the hostname, and return it in a newly allocated string. If we
2485 * can't, return NULL and let the caller warn if it wants to. */
2487 get_default_nickname(void)
2489 static const char * const bad_default_nicknames
[] = {
2493 char localhostname
[256];
2494 char *cp
, *out
, *outp
;
2497 if (gethostname(localhostname
, sizeof(localhostname
)) < 0)
2500 /* Put it in lowercase; stop at the first dot. */
2501 if ((cp
= strchr(localhostname
, '.')))
2503 tor_strlower(localhostname
);
2505 /* Strip invalid characters. */
2507 out
= outp
= tor_malloc(strlen(localhostname
) + 1);
2509 if (strchr(LEGAL_NICKNAME_CHARACTERS
, *cp
))
2516 /* Enforce length. */
2517 if (strlen(out
) > MAX_NICKNAME_LEN
)
2518 out
[MAX_NICKNAME_LEN
]='\0';
2520 /* Check for dumb names. */
2521 for (i
= 0; bad_default_nicknames
[i
]; ++i
) {
2522 if (!strcmp(out
, bad_default_nicknames
[i
])) {
2531 /** Release storage held by <b>options</b>. */
2533 config_free(config_format_t
*fmt
, void *options
)
2537 tor_assert(options
);
2539 for (i
=0; fmt
->vars
[i
].name
; ++i
)
2540 option_clear(fmt
, options
, &(fmt
->vars
[i
]));
2542 config_line_t
**linep
= STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
2543 config_free_lines(*linep
);
2549 /** Return true iff a and b contain identical keys and values in identical
2552 config_lines_eq(config_line_t
*a
, config_line_t
*b
)
2555 if (strcasecmp(a
->key
, b
->key
) || strcmp(a
->value
, b
->value
))
2565 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2566 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2569 option_is_same(config_format_t
*fmt
,
2570 or_options_t
*o1
, or_options_t
*o2
, const char *name
)
2572 config_line_t
*c1
, *c2
;
2577 c1
= get_assigned_option(fmt
, o1
, name
, 0);
2578 c2
= get_assigned_option(fmt
, o2
, name
, 0);
2579 r
= config_lines_eq(c1
, c2
);
2580 config_free_lines(c1
);
2581 config_free_lines(c2
);
2585 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2586 static or_options_t
*
2587 options_dup(config_format_t
*fmt
, or_options_t
*old
)
2589 or_options_t
*newopts
;
2591 config_line_t
*line
;
2593 newopts
= config_alloc(fmt
);
2594 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2595 if (fmt
->vars
[i
].type
== CONFIG_TYPE_LINELIST_S
)
2597 if (fmt
->vars
[i
].type
== CONFIG_TYPE_OBSOLETE
)
2599 line
= get_assigned_option(fmt
, old
, fmt
->vars
[i
].name
, 0);
2602 if (config_assign(fmt
, newopts
, line
, 0, 0, &msg
) < 0) {
2603 log_err(LD_BUG
, "Config_get_assigned_option() generated "
2604 "something we couldn't config_assign(): %s", msg
);
2609 config_free_lines(line
);
2614 /** Return a new empty or_options_t. Used for testing. */
2618 return config_alloc(&options_format
);
2621 /** Set <b>options</b> to hold reasonable defaults for most options.
2622 * Each option defaults to zero. */
2624 options_init(or_options_t
*options
)
2626 config_init(&options_format
, options
);
2629 /** Set all vars in the configuration object <b>options</b> to their default
2632 config_init(config_format_t
*fmt
, void *options
)
2636 CHECK(fmt
, options
);
2638 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2639 var
= &fmt
->vars
[i
];
2640 if (!var
->initvalue
)
2641 continue; /* defaults to NULL or 0 */
2642 option_reset(fmt
, options
, var
, 1);
2646 /** Allocate and return a new string holding the written-out values of the vars
2647 * in 'options'. If 'minimal', do not write out any default-valued vars.
2648 * Else, if comment_defaults, write default values as comments.
2651 config_dump(config_format_t
*fmt
, void *options
, int minimal
,
2652 int comment_defaults
)
2654 smartlist_t
*elements
;
2655 or_options_t
*defaults
;
2656 config_line_t
*line
, *assigned
;
2662 defaults
= config_alloc(fmt
);
2663 config_init(fmt
, defaults
);
2665 /* XXX use a 1 here so we don't add a new log line while dumping */
2666 if (fmt
->validate_fn(NULL
,defaults
, 1, &msg
) < 0) {
2667 log_err(LD_BUG
, "Failed to validate default config.");
2672 elements
= smartlist_create();
2673 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2674 int comment_option
= 0;
2675 if (fmt
->vars
[i
].type
== CONFIG_TYPE_OBSOLETE
||
2676 fmt
->vars
[i
].type
== CONFIG_TYPE_LINELIST_S
)
2678 /* Don't save 'hidden' control variables. */
2679 if (!strcmpstart(fmt
->vars
[i
].name
, "__"))
2681 if (minimal
&& option_is_same(fmt
, options
, defaults
, fmt
->vars
[i
].name
))
2683 else if (comment_defaults
&&
2684 option_is_same(fmt
, options
, defaults
, fmt
->vars
[i
].name
))
2687 desc
= config_find_description(fmt
, fmt
->vars
[i
].name
);
2688 line
= assigned
= get_assigned_option(fmt
, options
, fmt
->vars
[i
].name
, 1);
2691 /* Only dump the description if there's something to describe. */
2692 wrap_string(elements
, desc
, 78, "# ", "# ");
2695 for (; line
; line
= line
->next
) {
2696 size_t len
= strlen(line
->key
) + strlen(line
->value
) + 5;
2698 tmp
= tor_malloc(len
);
2699 if (tor_snprintf(tmp
, len
, "%s%s %s\n",
2700 comment_option
? "# " : "",
2701 line
->key
, line
->value
)<0) {
2702 log_err(LD_BUG
,"Internal error writing option value");
2705 smartlist_add(elements
, tmp
);
2707 config_free_lines(assigned
);
2711 line
= *(config_line_t
**)STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
2712 for (; line
; line
= line
->next
) {
2713 size_t len
= strlen(line
->key
) + strlen(line
->value
) + 3;
2715 tmp
= tor_malloc(len
);
2716 if (tor_snprintf(tmp
, len
, "%s %s\n", line
->key
, line
->value
)<0) {
2717 log_err(LD_BUG
,"Internal error writing option value");
2720 smartlist_add(elements
, tmp
);
2724 result
= smartlist_join_strings(elements
, "", 0, NULL
);
2725 SMARTLIST_FOREACH(elements
, char *, cp
, tor_free(cp
));
2726 smartlist_free(elements
);
2727 config_free(fmt
, defaults
);
2731 /** Return a string containing a possible configuration file that would give
2732 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2733 * include options that are the same as Tor's defaults.
2736 options_dump(or_options_t
*options
, int minimal
)
2738 return config_dump(&options_format
, options
, minimal
, 0);
2741 /** Return 0 if every element of sl is a string holding a decimal
2742 * representation of a port number, or if sl is NULL.
2743 * Otherwise set *msg and return -1. */
2745 validate_ports_csv(smartlist_t
*sl
, const char *name
, char **msg
)
2754 SMARTLIST_FOREACH(sl
, const char *, cp
,
2757 if (i
< 1 || i
> 65535) {
2758 int r
= tor_snprintf(buf
, sizeof(buf
),
2759 "Port '%s' out of range in %s", cp
, name
);
2760 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
2767 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2768 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2772 ensure_bandwidth_cap(uint64_t *value
, const char *desc
, char **msg
)
2776 if (*value
> ROUTER_MAX_DECLARED_BANDWIDTH
) {
2777 /* This handles an understandable special case where somebody says "2gb"
2778 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2781 if (*value
> ROUTER_MAX_DECLARED_BANDWIDTH
) {
2782 r
= tor_snprintf(buf
, sizeof(buf
), "%s ("U64_FORMAT
") must be at most %d",
2783 desc
, U64_PRINTF_ARG(*value
),
2784 ROUTER_MAX_DECLARED_BANDWIDTH
);
2785 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
2791 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2792 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2793 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2795 * Return 0 on success or -1 if not a recognized authority type (in which
2796 * case the value of _PublishServerDescriptor is undefined). */
2798 compute_publishserverdescriptor(or_options_t
*options
)
2800 smartlist_t
*list
= options
->PublishServerDescriptor
;
2801 authority_type_t
*auth
= &options
->_PublishServerDescriptor
;
2802 *auth
= NO_AUTHORITY
;
2803 if (!list
) /* empty list, answer is none */
2805 SMARTLIST_FOREACH(list
, const char *, string
, {
2806 if (!strcasecmp(string
, "v1"))
2807 *auth
|= V1_AUTHORITY
;
2808 else if (!strcmp(string
, "1"))
2809 if (options
->BridgeRelay
)
2810 *auth
|= BRIDGE_AUTHORITY
;
2812 *auth
|= V2_AUTHORITY
| V3_AUTHORITY
;
2813 else if (!strcasecmp(string
, "v2"))
2814 *auth
|= V2_AUTHORITY
;
2815 else if (!strcasecmp(string
, "v3"))
2816 *auth
|= V3_AUTHORITY
;
2817 else if (!strcasecmp(string
, "bridge"))
2818 *auth
|= BRIDGE_AUTHORITY
;
2819 else if (!strcasecmp(string
, "hidserv"))
2820 *auth
|= HIDSERV_AUTHORITY
;
2821 else if (!strcasecmp(string
, "") || !strcmp(string
, "0"))
2829 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2830 * services can overload the directory system. */
2831 #define MIN_REND_POST_PERIOD (10*60)
2833 /** Highest allowable value for RendPostPeriod. */
2834 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2836 /** Lowest allowable value for CircuitBuildTimeout; values too low will
2837 * increase network load because of failing connections being retried, and
2838 * might prevent users from connecting to the network at all. */
2839 #define MIN_CIRCUIT_BUILD_TIMEOUT 30
2841 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2842 * will generate too many circuits and potentially overload the network. */
2843 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2845 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2846 * permissible transition from <b>old_options</b>. Else return -1.
2847 * Should have no side effects, except for normalizing the contents of
2850 * On error, tor_strdup an error explanation into *<b>msg</b>.
2853 * If <b>from_setconf</b>, we were called by the controller, and our
2854 * Log line should stay empty. If it's 0, then give us a default log
2855 * if there are no logs defined.
2858 options_validate(or_options_t
*old_options
, or_options_t
*options
,
2859 int from_setconf
, char **msg
)
2863 const char *uname
= get_uname();
2865 #define REJECT(arg) \
2866 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2867 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2872 if (options
->ORPort
< 0 || options
->ORPort
> 65535)
2873 REJECT("ORPort option out of bounds.");
2875 if (server_mode(options
) &&
2876 (!strcmpstart(uname
, "Windows 95") ||
2877 !strcmpstart(uname
, "Windows 98") ||
2878 !strcmpstart(uname
, "Windows Me"))) {
2879 log(LOG_WARN
, LD_CONFIG
, "Tor is running as a server, but you are "
2880 "running %s; this probably won't work. See "
2881 "http://wiki.noreply.org/noreply/TheOnionRouter/TorFAQ#ServerOS "
2882 "for details.", uname
);
2885 if (options
->ORPort
== 0 && options
->ORListenAddress
!= NULL
)
2886 REJECT("ORPort must be defined if ORListenAddress is defined.");
2888 if (options
->DirPort
== 0 && options
->DirListenAddress
!= NULL
)
2889 REJECT("DirPort must be defined if DirListenAddress is defined.");
2891 if (options
->DNSPort
== 0 && options
->DNSListenAddress
!= NULL
)
2892 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
2894 if (options
->ControlPort
== 0 && options
->ControlListenAddress
!= NULL
)
2895 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
2897 if (options
->TransPort
== 0 && options
->TransListenAddress
!= NULL
)
2898 REJECT("TransPort must be defined if TransListenAddress is defined.");
2900 if (options
->NatdPort
== 0 && options
->NatdListenAddress
!= NULL
)
2901 REJECT("NatdPort must be defined if NatdListenAddress is defined.");
2903 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
2904 * configuration does this. */
2906 for (i
= 0; i
< 3; ++i
) {
2907 int is_socks
= i
==0;
2908 int is_trans
= i
==1;
2909 config_line_t
*line
, *opt
, *old
;
2912 opt
= options
->SocksListenAddress
;
2913 old
= old_options
? old_options
->SocksListenAddress
: NULL
;
2915 } else if (is_trans
) {
2916 opt
= options
->TransListenAddress
;
2917 old
= old_options
? old_options
->TransListenAddress
: NULL
;
2918 tp
= "transparent proxy";
2920 opt
= options
->NatdListenAddress
;
2921 old
= old_options
? old_options
->NatdListenAddress
: NULL
;
2925 for (line
= opt
; line
; line
= line
->next
) {
2926 char *address
= NULL
;
2929 if (parse_addr_port(LOG_WARN
, line
->value
, &address
, &addr
, &port
)<0)
2930 continue; /* We'll warn about this later. */
2931 if (!is_internal_IP(addr
, 1) &&
2932 (!old_options
|| !config_lines_eq(old
, opt
))) {
2934 "You specified a public address '%s' for a %s. Other "
2935 "people on the Internet might find your computer and use it as "
2936 "an open %s. Please don't allow this unless you have "
2937 "a good reason.", address
, tp
, tp
);
2943 if (validate_data_directory(options
)<0)
2944 REJECT("Invalid DataDirectory");
2946 if (options
->Nickname
== NULL
) {
2947 if (server_mode(options
)) {
2948 if (!(options
->Nickname
= get_default_nickname())) {
2949 log_notice(LD_CONFIG
, "Couldn't pick a nickname based on "
2950 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME
);
2951 options
->Nickname
= tor_strdup(UNNAMED_ROUTER_NICKNAME
);
2953 log_notice(LD_CONFIG
, "Choosing default nickname '%s'",
2958 if (!is_legal_nickname(options
->Nickname
)) {
2959 r
= tor_snprintf(buf
, sizeof(buf
),
2960 "Nickname '%s' is wrong length or contains illegal characters.",
2962 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
2967 if (server_mode(options
) && !options
->ContactInfo
)
2968 log(LOG_NOTICE
, LD_CONFIG
, "Your ContactInfo config option is not set. "
2969 "Please consider setting it, so we can contact you if your server is "
2970 "misconfigured or something else goes wrong.");
2972 /* Special case on first boot if no Log options are given. */
2973 if (!options
->Logs
&& !options
->RunAsDaemon
&& !from_setconf
)
2974 config_line_append(&options
->Logs
, "Log", "notice stdout");
2976 if (options_init_logs(options
, 1)<0) /* Validate the log(s) */
2977 REJECT("Failed to validate Log options. See logs for details.");
2979 if (options
->NoPublish
) {
2980 log(LOG_WARN
, LD_CONFIG
,
2981 "NoPublish is obsolete. Use PublishServerDescriptor instead.");
2982 SMARTLIST_FOREACH(options
->PublishServerDescriptor
, char *, s
,
2984 smartlist_clear(options
->PublishServerDescriptor
);
2987 if (authdir_mode(options
)) {
2988 /* confirm that our address isn't broken, so we can complain now */
2990 if (resolve_my_address(LOG_WARN
, options
, &tmp
, NULL
) < 0)
2991 REJECT("Failed to resolve/guess local address. See logs for details.");
2995 if (options
->RunAsDaemon
&& torrc_fname
&& path_is_relative(torrc_fname
))
2996 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
2999 if (options
->SocksPort
< 0 || options
->SocksPort
> 65535)
3000 REJECT("SocksPort option out of bounds.");
3002 if (options
->DNSPort
< 0 || options
->DNSPort
> 65535)
3003 REJECT("DNSPort option out of bounds.");
3005 if (options
->TransPort
< 0 || options
->TransPort
> 65535)
3006 REJECT("TransPort option out of bounds.");
3008 if (options
->NatdPort
< 0 || options
->NatdPort
> 65535)
3009 REJECT("NatdPort option out of bounds.");
3011 if (options
->SocksPort
== 0 && options
->TransPort
== 0 &&
3012 options
->NatdPort
== 0 && options
->ORPort
== 0 &&
3013 options
->DNSPort
== 0 && !options
->RendConfigLines
)
3014 log(LOG_WARN
, LD_CONFIG
,
3015 "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
3016 "undefined, and there aren't any hidden services configured. "
3017 "Tor will still run, but probably won't do anything.");
3019 if (options
->ControlPort
< 0 || options
->ControlPort
> 65535)
3020 REJECT("ControlPort option out of bounds.");
3022 if (options
->DirPort
< 0 || options
->DirPort
> 65535)
3023 REJECT("DirPort option out of bounds.");
3025 #ifndef USE_TRANSPARENT
3026 if (options
->TransPort
|| options
->TransListenAddress
)
3027 REJECT("TransPort and TransListenAddress are disabled in this build.");
3030 if (options
->ExcludeExitNodes
|| options
->ExcludeNodes
) {
3031 options
->_ExcludeExitNodesUnion
= routerset_new();
3032 routerset_union(options
->_ExcludeExitNodesUnion
,options
->ExcludeExitNodes
);
3033 routerset_union(options
->_ExcludeExitNodesUnion
,options
->ExcludeNodes
);
3036 if (options
->StrictExitNodes
&&
3037 (!options
->ExitNodes
) &&
3039 (old_options
->StrictExitNodes
!= options
->StrictExitNodes
) ||
3040 (!routerset_equal(old_options
->ExitNodes
,options
->ExitNodes
))))
3041 COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
3043 if (options
->StrictEntryNodes
&&
3044 (!options
->EntryNodes
) &&
3046 (old_options
->StrictEntryNodes
!= options
->StrictEntryNodes
) ||
3047 (!routerset_equal(old_options
->EntryNodes
,options
->EntryNodes
))))
3048 COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
3050 if (options
->EntryNodes
&& !routerset_is_list(options
->EntryNodes
)) {
3051 /* XXXX fix this; see entry_guards_prepend_from_config(). */
3052 REJECT("IPs or countries are not yet supported in EntryNodes.");
3055 if (options
->AuthoritativeDir
) {
3056 if (!options
->ContactInfo
)
3057 REJECT("Authoritative directory servers must set ContactInfo");
3058 if (options
->V1AuthoritativeDir
&& !options
->RecommendedVersions
)
3059 REJECT("V1 auth dir servers must set RecommendedVersions.");
3060 if (!options
->RecommendedClientVersions
)
3061 options
->RecommendedClientVersions
=
3062 config_lines_dup(options
->RecommendedVersions
);
3063 if (!options
->RecommendedServerVersions
)
3064 options
->RecommendedServerVersions
=
3065 config_lines_dup(options
->RecommendedVersions
);
3066 if (options
->VersioningAuthoritativeDir
&&
3067 (!options
->RecommendedClientVersions
||
3068 !options
->RecommendedServerVersions
))
3069 REJECT("Versioning auth dir servers must set Recommended*Versions.");
3070 if (options
->UseEntryGuards
) {
3071 log_info(LD_CONFIG
, "Authoritative directory servers can't set "
3072 "UseEntryGuards. Disabling.");
3073 options
->UseEntryGuards
= 0;
3075 if (!options
->DownloadExtraInfo
&& authdir_mode_any_main(options
)) {
3076 log_info(LD_CONFIG
, "Authoritative directories always try to download "
3077 "extra-info documents. Setting DownloadExtraInfo.");
3078 options
->DownloadExtraInfo
= 1;
3080 if (!(options
->BridgeAuthoritativeDir
|| options
->HSAuthoritativeDir
||
3081 options
->V1AuthoritativeDir
|| options
->V2AuthoritativeDir
||
3082 options
->V3AuthoritativeDir
))
3083 REJECT("AuthoritativeDir is set, but none of "
3084 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
3087 if (options
->AuthoritativeDir
&& !options
->DirPort
)
3088 REJECT("Running as authoritative directory, but no DirPort set.");
3090 if (options
->AuthoritativeDir
&& !options
->ORPort
)
3091 REJECT("Running as authoritative directory, but no ORPort set.");
3093 if (options
->AuthoritativeDir
&& options
->ClientOnly
)
3094 REJECT("Running as authoritative directory, but ClientOnly also set.");
3096 if (options
->HSAuthorityRecordStats
&& !options
->HSAuthoritativeDir
)
3097 REJECT("HSAuthorityRecordStats is set but we're not running as "
3098 "a hidden service authority.");
3100 if (options
->ConnLimit
<= 0) {
3101 r
= tor_snprintf(buf
, sizeof(buf
),
3102 "ConnLimit must be greater than 0, but was set to %d",
3103 options
->ConnLimit
);
3104 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3108 if (validate_ports_csv(options
->FirewallPorts
, "FirewallPorts", msg
) < 0)
3111 if (validate_ports_csv(options
->LongLivedPorts
, "LongLivedPorts", msg
) < 0)
3114 if (validate_ports_csv(options
->RejectPlaintextPorts
,
3115 "RejectPlaintextPorts", msg
) < 0)
3118 if (validate_ports_csv(options
->WarnPlaintextPorts
,
3119 "WarnPlaintextPorts", msg
) < 0)
3122 if (options
->FascistFirewall
&& !options
->ReachableAddresses
) {
3123 if (options
->FirewallPorts
&& smartlist_len(options
->FirewallPorts
)) {
3124 /* We already have firewall ports set, so migrate them to
3125 * ReachableAddresses, which will set ReachableORAddresses and
3126 * ReachableDirAddresses if they aren't set explicitly. */
3127 smartlist_t
*instead
= smartlist_create();
3128 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
3129 new_line
->key
= tor_strdup("ReachableAddresses");
3130 /* If we're configured with the old format, we need to prepend some
3132 SMARTLIST_FOREACH(options
->FirewallPorts
, const char *, portno
,
3134 int p
= atoi(portno
);
3138 tor_snprintf(s
, 16, "*:%d", p
);
3139 smartlist_add(instead
, s
);
3141 new_line
->value
= smartlist_join_strings(instead
,",",0,NULL
);
3142 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3143 log(LOG_NOTICE
, LD_CONFIG
,
3144 "Converting FascistFirewall and FirewallPorts "
3145 "config options to new format: \"ReachableAddresses %s\"",
3147 options
->ReachableAddresses
= new_line
;
3148 SMARTLIST_FOREACH(instead
, char *, cp
, tor_free(cp
));
3149 smartlist_free(instead
);
3151 /* We do not have FirewallPorts set, so add 80 to
3152 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3153 if (!options
->ReachableDirAddresses
) {
3154 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
3155 new_line
->key
= tor_strdup("ReachableDirAddresses");
3156 new_line
->value
= tor_strdup("*:80");
3157 options
->ReachableDirAddresses
= new_line
;
3158 log(LOG_NOTICE
, LD_CONFIG
, "Converting FascistFirewall config option "
3159 "to new format: \"ReachableDirAddresses *:80\"");
3161 if (!options
->ReachableORAddresses
) {
3162 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
3163 new_line
->key
= tor_strdup("ReachableORAddresses");
3164 new_line
->value
= tor_strdup("*:443");
3165 options
->ReachableORAddresses
= new_line
;
3166 log(LOG_NOTICE
, LD_CONFIG
, "Converting FascistFirewall config option "
3167 "to new format: \"ReachableORAddresses *:443\"");
3172 for (i
=0; i
<3; i
++) {
3173 config_line_t
**linep
=
3174 (i
==0) ? &options
->ReachableAddresses
:
3175 (i
==1) ? &options
->ReachableORAddresses
:
3176 &options
->ReachableDirAddresses
;
3179 /* We need to end with a reject *:*, not an implicit accept *:* */
3181 if (!strcmp((*linep
)->value
, "reject *:*")) /* already there */
3183 linep
= &((*linep
)->next
);
3185 *linep
= tor_malloc_zero(sizeof(config_line_t
));
3186 (*linep
)->key
= tor_strdup(
3187 (i
==0) ? "ReachableAddresses" :
3188 (i
==1) ? "ReachableORAddresses" :
3189 "ReachableDirAddresses");
3190 (*linep
)->value
= tor_strdup("reject *:*");
3196 if ((options
->ReachableAddresses
||
3197 options
->ReachableORAddresses
||
3198 options
->ReachableDirAddresses
) &&
3199 server_mode(options
))
3200 REJECT("Servers must be able to freely connect to the rest "
3201 "of the Internet, so they must not set Reachable*Addresses "
3202 "or FascistFirewall.");
3204 if (options
->UseBridges
&&
3205 server_mode(options
))
3206 REJECT("Servers must be able to freely connect to the rest "
3207 "of the Internet, so they must not set UseBridges.");
3209 options
->_AllowInvalid
= 0;
3210 if (options
->AllowInvalidNodes
) {
3211 SMARTLIST_FOREACH(options
->AllowInvalidNodes
, const char *, cp
, {
3212 if (!strcasecmp(cp
, "entry"))
3213 options
->_AllowInvalid
|= ALLOW_INVALID_ENTRY
;
3214 else if (!strcasecmp(cp
, "exit"))
3215 options
->_AllowInvalid
|= ALLOW_INVALID_EXIT
;
3216 else if (!strcasecmp(cp
, "middle"))
3217 options
->_AllowInvalid
|= ALLOW_INVALID_MIDDLE
;
3218 else if (!strcasecmp(cp
, "introduction"))
3219 options
->_AllowInvalid
|= ALLOW_INVALID_INTRODUCTION
;
3220 else if (!strcasecmp(cp
, "rendezvous"))
3221 options
->_AllowInvalid
|= ALLOW_INVALID_RENDEZVOUS
;
3223 r
= tor_snprintf(buf
, sizeof(buf
),
3224 "Unrecognized value '%s' in AllowInvalidNodes", cp
);
3225 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3231 if (compute_publishserverdescriptor(options
) < 0) {
3232 r
= tor_snprintf(buf
, sizeof(buf
),
3233 "Unrecognized value in PublishServerDescriptor");
3234 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3238 if (options
->MinUptimeHidServDirectoryV2
< 0) {
3239 log_warn(LD_CONFIG
, "MinUptimeHidServDirectoryV2 option must be at "
3240 "least 0 seconds. Changing to 0.");
3241 options
->MinUptimeHidServDirectoryV2
= 0;
3244 if (options
->RendPostPeriod
< MIN_REND_POST_PERIOD
) {
3245 log(LOG_WARN
,LD_CONFIG
,"RendPostPeriod option is too short; "
3246 "raising to %d seconds.", MIN_REND_POST_PERIOD
);
3247 options
->RendPostPeriod
= MIN_REND_POST_PERIOD
;
3250 if (options
->RendPostPeriod
> MAX_DIR_PERIOD
) {
3251 log(LOG_WARN
, LD_CONFIG
, "RendPostPeriod is too large; clipping to %ds.",
3253 options
->RendPostPeriod
= MAX_DIR_PERIOD
;
3256 if (options
->CircuitBuildTimeout
< MIN_CIRCUIT_BUILD_TIMEOUT
) {
3257 log(LOG_WARN
, LD_CONFIG
, "CircuitBuildTimeout option is too short; "
3258 "raising to %d seconds.", MIN_CIRCUIT_BUILD_TIMEOUT
);
3259 options
->CircuitBuildTimeout
= MIN_CIRCUIT_BUILD_TIMEOUT
;
3262 if (options
->MaxCircuitDirtiness
< MIN_MAX_CIRCUIT_DIRTINESS
) {
3263 log(LOG_WARN
, LD_CONFIG
, "MaxCircuitDirtiness option is too short; "
3264 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS
);
3265 options
->MaxCircuitDirtiness
= MIN_MAX_CIRCUIT_DIRTINESS
;
3268 if (options
->KeepalivePeriod
< 1)
3269 REJECT("KeepalivePeriod option must be positive.");
3271 if (ensure_bandwidth_cap(&options
->BandwidthRate
,
3272 "BandwidthRate", msg
) < 0)
3274 if (ensure_bandwidth_cap(&options
->BandwidthBurst
,
3275 "BandwidthBurst", msg
) < 0)
3277 if (ensure_bandwidth_cap(&options
->MaxAdvertisedBandwidth
,
3278 "MaxAdvertisedBandwidth", msg
) < 0)
3280 if (ensure_bandwidth_cap(&options
->RelayBandwidthRate
,
3281 "RelayBandwidthRate", msg
) < 0)
3283 if (ensure_bandwidth_cap(&options
->RelayBandwidthBurst
,
3284 "RelayBandwidthBurst", msg
) < 0)
3287 if (server_mode(options
)) {
3288 if (options
->BandwidthRate
< ROUTER_REQUIRED_MIN_BANDWIDTH
*2) {
3289 r
= tor_snprintf(buf
, sizeof(buf
),
3290 "BandwidthRate is set to %d bytes/second. "
3291 "For servers, it must be at least %d.",
3292 (int)options
->BandwidthRate
,
3293 ROUTER_REQUIRED_MIN_BANDWIDTH
*2);
3294 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3296 } else if (options
->MaxAdvertisedBandwidth
<
3297 ROUTER_REQUIRED_MIN_BANDWIDTH
) {
3298 r
= tor_snprintf(buf
, sizeof(buf
),
3299 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3300 "For servers, it must be at least %d.",
3301 (int)options
->MaxAdvertisedBandwidth
,
3302 ROUTER_REQUIRED_MIN_BANDWIDTH
);
3303 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3306 if (options
->RelayBandwidthRate
&&
3307 options
->RelayBandwidthRate
< ROUTER_REQUIRED_MIN_BANDWIDTH
) {
3308 r
= tor_snprintf(buf
, sizeof(buf
),
3309 "RelayBandwidthRate is set to %d bytes/second. "
3310 "For servers, it must be at least %d.",
3311 (int)options
->RelayBandwidthRate
,
3312 ROUTER_REQUIRED_MIN_BANDWIDTH
);
3313 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3318 if (options
->RelayBandwidthRate
&& !options
->RelayBandwidthBurst
)
3319 options
->RelayBandwidthBurst
= options
->RelayBandwidthRate
;
3321 if (options
->RelayBandwidthRate
> options
->RelayBandwidthBurst
)
3322 REJECT("RelayBandwidthBurst must be at least equal "
3323 "to RelayBandwidthRate.");
3325 if (options
->BandwidthRate
> options
->BandwidthBurst
)
3326 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3328 /* if they set relaybandwidth* really high but left bandwidth*
3329 * at the default, raise the defaults. */
3330 if (options
->RelayBandwidthRate
> options
->BandwidthRate
)
3331 options
->BandwidthRate
= options
->RelayBandwidthRate
;
3332 if (options
->RelayBandwidthBurst
> options
->BandwidthBurst
)
3333 options
->BandwidthBurst
= options
->RelayBandwidthBurst
;
3335 if (accounting_parse_options(options
, 1)<0)
3336 REJECT("Failed to parse accounting options. See logs for details.");
3338 if (options
->HttpProxy
) { /* parse it now */
3339 if (parse_addr_port(LOG_WARN
, options
->HttpProxy
, NULL
,
3340 &options
->HttpProxyAddr
, &options
->HttpProxyPort
) < 0)
3341 REJECT("HttpProxy failed to parse or resolve. Please fix.");
3342 if (options
->HttpProxyPort
== 0) { /* give it a default */
3343 options
->HttpProxyPort
= 80;
3347 if (options
->HttpProxyAuthenticator
) {
3348 if (strlen(options
->HttpProxyAuthenticator
) >= 48)
3349 REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
3352 if (options
->HttpsProxy
) { /* parse it now */
3353 if (parse_addr_port(LOG_WARN
, options
->HttpsProxy
, NULL
,
3354 &options
->HttpsProxyAddr
, &options
->HttpsProxyPort
) <0)
3355 REJECT("HttpsProxy failed to parse or resolve. Please fix.");
3356 if (options
->HttpsProxyPort
== 0) { /* give it a default */
3357 options
->HttpsProxyPort
= 443;
3361 if (options
->HttpsProxyAuthenticator
) {
3362 if (strlen(options
->HttpsProxyAuthenticator
) >= 48)
3363 REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
3366 if (options
->HashedControlPassword
) {
3367 smartlist_t
*sl
= decode_hashed_passwords(options
->HashedControlPassword
);
3369 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3371 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
3376 if (options
->HashedControlSessionPassword
) {
3377 smartlist_t
*sl
= decode_hashed_passwords(
3378 options
->HashedControlSessionPassword
);
3380 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3382 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
3387 if (options
->ControlListenAddress
) {
3388 int all_are_local
= 1;
3390 for (ln
= options
->ControlListenAddress
; ln
; ln
= ln
->next
) {
3391 if (strcmpstart(ln
->value
, "127."))
3394 if (!all_are_local
) {
3395 if (!options
->HashedControlPassword
&&
3396 !options
->HashedControlSessionPassword
&&
3397 !options
->CookieAuthentication
) {
3398 log_warn(LD_CONFIG
, "You have a ControlListenAddress set to accept "
3399 "connections from a non-local address. This means that "
3400 "any program on the internet can reconfigure your Tor. "
3401 "That's so bad that I'm closing your ControlPort for you.");
3402 options
->ControlPort
= 0;
3404 log_warn(LD_CONFIG
, "You have a ControlListenAddress set to accept "
3405 "connections from a non-local address. This means that "
3406 "programs not running on your computer can reconfigure your "
3407 "Tor. That's pretty bad!");
3412 if (options
->ControlPort
&& !options
->HashedControlPassword
&&
3413 !options
->HashedControlSessionPassword
&&
3414 !options
->CookieAuthentication
) {
3415 log_warn(LD_CONFIG
, "ControlPort is open, but no authentication method "
3416 "has been configured. This means that any program on your "
3417 "computer can reconfigure your Tor. That's bad! You should "
3418 "upgrade your Tor controller as soon as possible.");
3421 if (options
->UseEntryGuards
&& ! options
->NumEntryGuards
)
3422 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3424 if (check_nickname_list(options
->MyFamily
, "MyFamily", msg
))
3426 for (cl
= options
->NodeFamilies
; cl
; cl
= cl
->next
) {
3427 if (check_nickname_list(cl
->value
, "NodeFamily", msg
))
3431 if (validate_addr_policies(options
, msg
) < 0)
3434 if (validate_dir_authorities(options
, old_options
) < 0)
3435 REJECT("Directory authority line did not parse. See logs for details.");
3437 if (options
->UseBridges
&& !options
->Bridges
)
3438 REJECT("If you set UseBridges, you must specify at least one bridge.");
3439 if (options
->UseBridges
&& !options
->TunnelDirConns
)
3440 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3441 if (options
->Bridges
) {
3442 for (cl
= options
->Bridges
; cl
; cl
= cl
->next
) {
3443 if (parse_bridge_line(cl
->value
, 1)<0)
3444 REJECT("Bridge line did not parse. See logs for details.");
3448 if (options
->ConstrainedSockets
) {
3449 /* If the user wants to constrain socket buffer use, make sure the desired
3450 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3451 if (options
->ConstrainedSockSize
< MIN_CONSTRAINED_TCP_BUFFER
||
3452 options
->ConstrainedSockSize
> MAX_CONSTRAINED_TCP_BUFFER
||
3453 options
->ConstrainedSockSize
% 1024) {
3454 r
= tor_snprintf(buf
, sizeof(buf
),
3455 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3456 "in 1024 byte increments.",
3457 MIN_CONSTRAINED_TCP_BUFFER
, MAX_CONSTRAINED_TCP_BUFFER
);
3458 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3461 if (options
->DirPort
) {
3462 /* Providing cached directory entries while system TCP buffers are scarce
3463 * will exacerbate the socket errors. Suggest that this be disabled. */
3464 COMPLAIN("You have requested constrained socket buffers while also "
3465 "serving directory entries via DirPort. It is strongly "
3466 "suggested that you disable serving directory requests when "
3467 "system TCP buffer resources are scarce.");
3471 if (options
->V3AuthVoteDelay
+ options
->V3AuthDistDelay
>=
3472 options
->V3AuthVotingInterval
/2) {
3473 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3474 "V3AuthVotingInterval");
3476 if (options
->V3AuthVoteDelay
< MIN_VOTE_SECONDS
)
3477 REJECT("V3AuthVoteDelay is way too low.");
3478 if (options
->V3AuthDistDelay
< MIN_DIST_SECONDS
)
3479 REJECT("V3AuthDistDelay is way too low.");
3481 if (options
->V3AuthNIntervalsValid
< 2)
3482 REJECT("V3AuthNIntervalsValid must be at least 2.");
3484 if (options
->V3AuthVotingInterval
< MIN_VOTE_INTERVAL
) {
3485 REJECT("V3AuthVotingInterval is insanely low.");
3486 } else if (options
->V3AuthVotingInterval
> 24*60*60) {
3487 REJECT("V3AuthVotingInterval is insanely high.");
3488 } else if (((24*60*60) % options
->V3AuthVotingInterval
) != 0) {
3489 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3492 if (rend_config_services(options
, 1) < 0)
3493 REJECT("Failed to configure rendezvous options. See logs for details.");
3495 /* Parse client-side authorization for hidden services. */
3496 if (rend_parse_service_authorization(options
, 1) < 0)
3497 REJECT("Failed to configure client authorization for hidden services. "
3498 "See logs for details.");
3500 if (parse_virtual_addr_network(options
->VirtualAddrNetwork
, 1, NULL
)<0)
3503 if (options
->PreferTunneledDirConns
&& !options
->TunnelDirConns
)
3504 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3506 if (options
->AutomapHostsSuffixes
) {
3507 SMARTLIST_FOREACH(options
->AutomapHostsSuffixes
, char *, suf
,
3509 size_t len
= strlen(suf
);
3510 if (len
&& suf
[len
-1] == '.')
3515 if (options
->TestingTorNetwork
&& !options
->DirServers
) {
3516 REJECT("TestingTorNetwork may only be configured in combination with "
3517 "a non-default set of DirServers.");
3520 /*XXXX021 checking for defaults manually like this is a bit fragile.*/
3522 /* Keep changes to hard-coded values synchronous to man page and default
3524 if (options
->TestingV3AuthInitialVotingInterval
!= 30*60 &&
3525 !options
->TestingTorNetwork
) {
3526 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
3528 } else if (options
->TestingV3AuthInitialVotingInterval
< MIN_VOTE_INTERVAL
) {
3529 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3530 } else if (((30*60) % options
->TestingV3AuthInitialVotingInterval
) != 0) {
3531 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3535 if (options
->TestingV3AuthInitialVoteDelay
!= 5*60 &&
3536 !options
->TestingTorNetwork
) {
3537 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
3539 } else if (options
->TestingV3AuthInitialVoteDelay
< MIN_VOTE_SECONDS
) {
3540 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3543 if (options
->TestingV3AuthInitialDistDelay
!= 5*60 &&
3544 !options
->TestingTorNetwork
) {
3545 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
3547 } else if (options
->TestingV3AuthInitialDistDelay
< MIN_DIST_SECONDS
) {
3548 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3551 if (options
->TestingV3AuthInitialVoteDelay
+
3552 options
->TestingV3AuthInitialDistDelay
>=
3553 options
->TestingV3AuthInitialVotingInterval
/2) {
3554 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3555 "must be less than half TestingV3AuthInitialVotingInterval");
3558 if (options
->TestingAuthDirTimeToLearnReachability
!= 30*60 &&
3559 !options
->TestingTorNetwork
) {
3560 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
3561 "testing Tor networks!");
3562 } else if (options
->TestingAuthDirTimeToLearnReachability
< 0) {
3563 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3564 } else if (options
->TestingAuthDirTimeToLearnReachability
> 2*60*60) {
3565 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3568 if (options
->TestingEstimatedDescriptorPropagationTime
!= 10*60 &&
3569 !options
->TestingTorNetwork
) {
3570 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
3571 "testing Tor networks!");
3572 } else if (options
->TestingEstimatedDescriptorPropagationTime
< 0) {
3573 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3574 } else if (options
->TestingEstimatedDescriptorPropagationTime
> 60*60) {
3575 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3578 if (options
->TestingTorNetwork
) {
3579 log_warn(LD_CONFIG
, "TestingTorNetwork is set. This will make your node "
3580 "almost unusable in the public Tor network, and is "
3581 "therefore only advised if you are building a "
3582 "testing Tor network!");
3590 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3593 opt_streq(const char *s1
, const char *s2
)
3597 else if (s1
&& s2
&& !strcmp(s1
,s2
))
3603 /** Check if any of the previous options have changed but aren't allowed to. */
3605 options_transition_allowed(or_options_t
*old
, or_options_t
*new_val
,
3611 if (!opt_streq(old
->PidFile
, new_val
->PidFile
)) {
3612 *msg
= tor_strdup("PidFile is not allowed to change.");
3616 if (old
->RunAsDaemon
!= new_val
->RunAsDaemon
) {
3617 *msg
= tor_strdup("While Tor is running, changing RunAsDaemon "
3622 if (strcmp(old
->DataDirectory
,new_val
->DataDirectory
)!=0) {
3624 int r
= tor_snprintf(buf
, sizeof(buf
),
3625 "While Tor is running, changing DataDirectory "
3626 "(\"%s\"->\"%s\") is not allowed.",
3627 old
->DataDirectory
, new_val
->DataDirectory
);
3628 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3632 if (!opt_streq(old
->User
, new_val
->User
)) {
3633 *msg
= tor_strdup("While Tor is running, changing User is not allowed.");
3637 if (!opt_streq(old
->Group
, new_val
->Group
)) {
3638 *msg
= tor_strdup("While Tor is running, changing Group is not allowed.");
3642 if (old
->HardwareAccel
!= new_val
->HardwareAccel
) {
3643 *msg
= tor_strdup("While Tor is running, changing HardwareAccel is "
3648 if (old
->TestingTorNetwork
!= new_val
->TestingTorNetwork
) {
3649 *msg
= tor_strdup("While Tor is running, changing TestingTorNetwork "
3657 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3658 * will require us to rotate the cpu and dns workers; else return 0. */
3660 options_transition_affects_workers(or_options_t
*old_options
,
3661 or_options_t
*new_options
)
3663 if (!opt_streq(old_options
->DataDirectory
, new_options
->DataDirectory
) ||
3664 old_options
->NumCpus
!= new_options
->NumCpus
||
3665 old_options
->ORPort
!= new_options
->ORPort
||
3666 old_options
->ServerDNSSearchDomains
!=
3667 new_options
->ServerDNSSearchDomains
||
3668 old_options
->SafeLogging
!= new_options
->SafeLogging
||
3669 old_options
->ClientOnly
!= new_options
->ClientOnly
||
3670 !config_lines_eq(old_options
->Logs
, new_options
->Logs
))
3673 /* Check whether log options match. */
3675 /* Nothing that changed matters. */
3679 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3680 * will require us to generate a new descriptor; else return 0. */
3682 options_transition_affects_descriptor(or_options_t
*old_options
,
3683 or_options_t
*new_options
)
3685 /* XXX We can be smarter here. If your DirPort isn't being
3686 * published and you just turned it off, no need to republish. If
3687 * you changed your bandwidthrate but maxadvertisedbandwidth still
3688 * trumps, no need to republish. Etc. */
3689 if (!opt_streq(old_options
->DataDirectory
, new_options
->DataDirectory
) ||
3690 !opt_streq(old_options
->Nickname
,new_options
->Nickname
) ||
3691 !opt_streq(old_options
->Address
,new_options
->Address
) ||
3692 !config_lines_eq(old_options
->ExitPolicy
,new_options
->ExitPolicy
) ||
3693 old_options
->ExitPolicyRejectPrivate
!=
3694 new_options
->ExitPolicyRejectPrivate
||
3695 old_options
->ORPort
!= new_options
->ORPort
||
3696 old_options
->DirPort
!= new_options
->DirPort
||
3697 old_options
->ClientOnly
!= new_options
->ClientOnly
||
3698 old_options
->NoPublish
!= new_options
->NoPublish
||
3699 old_options
->_PublishServerDescriptor
!=
3700 new_options
->_PublishServerDescriptor
||
3701 old_options
->BandwidthRate
!= new_options
->BandwidthRate
||
3702 old_options
->BandwidthBurst
!= new_options
->BandwidthBurst
||
3703 old_options
->MaxAdvertisedBandwidth
!=
3704 new_options
->MaxAdvertisedBandwidth
||
3705 !opt_streq(old_options
->ContactInfo
, new_options
->ContactInfo
) ||
3706 !opt_streq(old_options
->MyFamily
, new_options
->MyFamily
) ||
3707 !opt_streq(old_options
->AccountingStart
, new_options
->AccountingStart
) ||
3708 old_options
->AccountingMax
!= new_options
->AccountingMax
)
3715 /** Return the directory on windows where we expect to find our application
3718 get_windows_conf_root(void)
3720 static int is_set
= 0;
3721 static char path
[MAX_PATH
+1];
3730 /* Find X:\documents and settings\username\application data\ .
3731 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3733 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL
, CSIDL_APPDATA
,
3735 GetCurrentDirectory(MAX_PATH
, path
);
3738 "I couldn't find your application data folder: are you "
3739 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3743 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3744 result
= SHGetPathFromIDList(idl
, path
);
3745 /* Now we need to free the */
3748 m
->lpVtbl
->Free(m
, idl
);
3749 m
->lpVtbl
->Release(m
);
3751 if (!SUCCEEDED(result
)) {
3754 strlcat(path
,"\\tor",MAX_PATH
);
3760 /** Return the default location for our torrc file. */
3762 get_default_conf_file(void)
3765 static char path
[MAX_PATH
+1];
3766 strlcpy(path
, get_windows_conf_root(), MAX_PATH
);
3767 strlcat(path
,"\\torrc",MAX_PATH
);
3770 return (CONFDIR
"/torrc");
3774 /** Verify whether lst is a string containing valid-looking comma-separated
3775 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3778 check_nickname_list(const char *lst
, const char *name
, char **msg
)
3785 sl
= smartlist_create();
3787 smartlist_split_string(sl
, lst
, ",",
3788 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
|SPLIT_STRIP_SPACE
, 0);
3790 SMARTLIST_FOREACH(sl
, const char *, s
,
3792 if (!is_legal_nickname_or_hexdigest(s
)) {
3794 int tmp
= tor_snprintf(buf
, sizeof(buf
),
3795 "Invalid nickname '%s' in %s line", s
, name
);
3796 *msg
= tor_strdup(tmp
>= 0 ? buf
: "internal error");
3801 SMARTLIST_FOREACH(sl
, char *, s
, tor_free(s
));
3806 /** Learn config file name from command line arguments, or use the default */
3808 find_torrc_filename(int argc
, char **argv
,
3809 int *using_default_torrc
, int *ignore_missing_torrc
)
3814 for (i
= 1; i
< argc
; ++i
) {
3815 if (i
< argc
-1 && !strcmp(argv
[i
],"-f")) {
3817 log(LOG_WARN
, LD_CONFIG
, "Duplicate -f options on command line.");
3821 /* XXX one day we might want to extend expand_filename to work
3822 * under Windows as well. */
3823 fname
= tor_strdup(argv
[i
+1]);
3825 fname
= expand_filename(argv
[i
+1]);
3827 *using_default_torrc
= 0;
3829 } else if (!strcmp(argv
[i
],"--ignore-missing-torrc")) {
3830 *ignore_missing_torrc
= 1;
3834 if (*using_default_torrc
) {
3835 /* didn't find one, try CONFDIR */
3836 const char *dflt
= get_default_conf_file();
3837 if (dflt
&& file_status(dflt
) == FN_FILE
) {
3838 fname
= tor_strdup(dflt
);
3842 fn
= expand_filename("~/.torrc");
3843 if (fn
&& file_status(fn
) == FN_FILE
) {
3847 fname
= tor_strdup(dflt
);
3850 fname
= tor_strdup(dflt
);
3857 /** Load torrc from disk, setting torrc_fname if successful */
3859 load_torrc_from_disk(int argc
, char **argv
)
3863 int using_default_torrc
= 1;
3864 int ignore_missing_torrc
= 0;
3866 fname
= find_torrc_filename(argc
, argv
,
3867 &using_default_torrc
, &ignore_missing_torrc
);
3869 log(LOG_DEBUG
, LD_CONFIG
, "Opening config file \"%s\"", fname
);
3871 tor_free(torrc_fname
);
3872 torrc_fname
= fname
;
3874 /* Open config file */
3875 if (file_status(fname
) != FN_FILE
||
3876 !(cf
= read_file_to_str(fname
,0,NULL
))) {
3877 if (using_default_torrc
== 1 || ignore_missing_torrc
) {
3878 log(LOG_NOTICE
, LD_CONFIG
, "Configuration file \"%s\" not present, "
3879 "using reasonable defaults.", fname
);
3880 tor_free(fname
); /* sets fname to NULL */
3882 cf
= tor_strdup("");
3884 log(LOG_WARN
, LD_CONFIG
,
3885 "Unable to open configuration file \"%s\".", fname
);
3897 /** Read a configuration file into <b>options</b>, finding the configuration
3898 * file location based on the command line. After loading the file
3899 * call options_init_from_string() to load the config.
3900 * Return 0 if success, -1 if failure. */
3902 options_init_from_torrc(int argc
, char **argv
)
3905 int i
, retval
, command
;
3906 static char **backup_argv
;
3907 static int backup_argc
;
3908 char *command_arg
= NULL
;
3911 if (argv
) { /* first time we're called. save commandline args */
3914 } else { /* we're reloading. need to clean up old options first. */
3918 if (argc
> 1 && (!strcmp(argv
[1], "-h") || !strcmp(argv
[1],"--help"))) {
3922 if (argc
> 1 && !strcmp(argv
[1], "--list-torrc-options")) {
3923 /* For documenting validating whether we've documented everything. */
3924 list_torrc_options();
3928 if (argc
> 1 && (!strcmp(argv
[1],"--version"))) {
3929 printf("Tor version %s.\n",get_version());
3930 if (argc
> 2 && (!strcmp(argv
[2],"--version"))) {
3931 print_svn_version();
3936 /* Go through command-line variables */
3937 if (!global_cmdline_options
) {
3938 /* Or we could redo the list every time we pass this place.
3939 * It does not really matter */
3940 if (config_get_commandlines(argc
, argv
, &global_cmdline_options
) < 0) {
3945 command
= CMD_RUN_TOR
;
3946 for (i
= 1; i
< argc
; ++i
) {
3947 if (!strcmp(argv
[i
],"--list-fingerprint")) {
3948 command
= CMD_LIST_FINGERPRINT
;
3949 } else if (!strcmp(argv
[i
],"--hash-password")) {
3950 command
= CMD_HASH_PASSWORD
;
3951 command_arg
= tor_strdup( (i
< argc
-1) ? argv
[i
+1] : "");
3953 } else if (!strcmp(argv
[i
],"--verify-config")) {
3954 command
= CMD_VERIFY_CONFIG
;
3958 if (command
== CMD_HASH_PASSWORD
) {
3959 cf
= tor_strdup("");
3961 cf
= load_torrc_from_disk(argc
, argv
);
3966 retval
= options_init_from_string(cf
, command
, command_arg
, &errmsg
);
3975 log(LOG_WARN
,LD_CONFIG
,"%s", errmsg
);
3981 /** Load the options from the configuration in <b>cf</b>, validate
3982 * them for consistency and take actions based on them.
3984 * Return 0 if success, negative on error:
3985 * * -1 for general errors.
3986 * * -2 for failure to parse/validate,
3987 * * -3 for transition not allowed
3988 * * -4 for error while setting the new options
3991 options_init_from_string(const char *cf
,
3992 int command
, const char *command_arg
,
3995 or_options_t
*oldoptions
, *newoptions
;
3998 setopt_err_t err
= SETOPT_ERR_MISC
;
4001 oldoptions
= global_options
; /* get_options unfortunately asserts if
4002 this is the first time we run*/
4004 newoptions
= tor_malloc_zero(sizeof(or_options_t
));
4005 newoptions
->_magic
= OR_OPTIONS_MAGIC
;
4006 options_init(newoptions
);
4007 newoptions
->command
= command
;
4008 newoptions
->command_arg
= command_arg
;
4010 /* get config lines, assign them */
4011 retval
= config_get_lines(cf
, &cl
);
4013 err
= SETOPT_ERR_PARSE
;
4016 retval
= config_assign(&options_format
, newoptions
, cl
, 0, 0, msg
);
4017 config_free_lines(cl
);
4019 err
= SETOPT_ERR_PARSE
;
4023 /* Go through command-line variables too */
4024 retval
= config_assign(&options_format
, newoptions
,
4025 global_cmdline_options
, 0, 0, msg
);
4027 err
= SETOPT_ERR_PARSE
;
4031 /* If this is a testing network configuration, change defaults
4032 * for a list of dependent config options, re-initialize newoptions
4033 * with the new defaults, and assign all options to it second time. */
4034 if (newoptions
->TestingTorNetwork
) {
4035 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4036 * this? We could, for example, make the parsing algorithm do two passes
4037 * over the configuration. If it finds any "suite" options like
4038 * TestingTorNetwork, it could change the defaults before its second pass.
4039 * Not urgent so long as this seems to work, but at any sign of trouble,
4040 * let's clean it up. -NM */
4042 /* Change defaults. */
4044 for (i
= 0; testing_tor_network_defaults
[i
].name
; ++i
) {
4045 config_var_t
*new_var
= &testing_tor_network_defaults
[i
];
4046 config_var_t
*old_var
=
4047 config_find_option(&options_format
, new_var
->name
);
4048 tor_assert(new_var
);
4049 tor_assert(old_var
);
4050 old_var
->initvalue
= new_var
->initvalue
;
4053 /* Clear newoptions and re-initialize them with new defaults. */
4054 config_free(&options_format
, newoptions
);
4055 newoptions
= tor_malloc_zero(sizeof(or_options_t
));
4056 newoptions
->_magic
= OR_OPTIONS_MAGIC
;
4057 options_init(newoptions
);
4058 newoptions
->command
= command
;
4059 newoptions
->command_arg
= command_arg
;
4061 /* Assign all options a second time. */
4062 retval
= config_get_lines(cf
, &cl
);
4064 err
= SETOPT_ERR_PARSE
;
4067 retval
= config_assign(&options_format
, newoptions
, cl
, 0, 0, msg
);
4068 config_free_lines(cl
);
4070 err
= SETOPT_ERR_PARSE
;
4073 retval
= config_assign(&options_format
, newoptions
,
4074 global_cmdline_options
, 0, 0, msg
);
4076 err
= SETOPT_ERR_PARSE
;
4081 /* Validate newoptions */
4082 if (options_validate(oldoptions
, newoptions
, 0, msg
) < 0) {
4083 err
= SETOPT_ERR_PARSE
; /*XXX make this a separate return value.*/
4087 if (options_transition_allowed(oldoptions
, newoptions
, msg
) < 0) {
4088 err
= SETOPT_ERR_TRANSITION
;
4092 if (set_options(newoptions
, msg
)) {
4093 err
= SETOPT_ERR_SETTING
;
4094 goto err
; /* frees and replaces old options */
4100 config_free(&options_format
, newoptions
);
4102 int len
= strlen(*msg
)+256;
4103 char *newmsg
= tor_malloc(len
);
4105 tor_snprintf(newmsg
, len
, "Failed to parse/validate config: %s", *msg
);
4112 /** Return the location for our configuration file.
4115 get_torrc_fname(void)
4120 return get_default_conf_file();
4123 /** Adjust the address map mased on the MapAddress elements in the
4124 * configuration <b>options</b>
4127 config_register_addressmaps(or_options_t
*options
)
4133 addressmap_clear_configured();
4134 elts
= smartlist_create();
4135 for (opt
= options
->AddressMap
; opt
; opt
= opt
->next
) {
4136 smartlist_split_string(elts
, opt
->value
, NULL
,
4137 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
4138 if (smartlist_len(elts
) >= 2) {
4139 from
= smartlist_get(elts
,0);
4140 to
= smartlist_get(elts
,1);
4141 if (address_is_invalid_destination(to
, 1)) {
4143 "Skipping invalid argument '%s' to MapAddress", to
);
4145 addressmap_register(from
, tor_strdup(to
), 0, ADDRMAPSRC_TORRC
);
4146 if (smartlist_len(elts
)>2) {
4147 log_warn(LD_CONFIG
,"Ignoring extra arguments to MapAddress.");
4151 log_warn(LD_CONFIG
,"MapAddress '%s' has too few arguments. Ignoring.",
4154 SMARTLIST_FOREACH(elts
, char*, cp
, tor_free(cp
));
4155 smartlist_clear(elts
);
4157 smartlist_free(elts
);
4161 * Initialize the logs based on the configuration file.
4164 options_init_logs(or_options_t
*options
, int validate_only
)
4173 options
->RunAsDaemon
;
4177 elts
= smartlist_create();
4179 for (opt
= options
->Logs
; opt
; opt
= opt
->next
) {
4180 log_severity_list_t
*severity
;
4181 const char *cfg
= opt
->value
;
4182 severity
= tor_malloc_zero(sizeof(log_severity_list_t
));
4183 if (parse_log_severity_config(&cfg
, severity
) < 0) {
4184 log_warn(LD_CONFIG
, "Couldn't parse log levels in Log option 'Log %s'",
4186 ok
= 0; goto cleanup
;
4189 smartlist_split_string(elts
, cfg
, NULL
,
4190 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
4192 if (smartlist_len(elts
) == 0)
4193 smartlist_add(elts
, tor_strdup("stdout"));
4195 if (smartlist_len(elts
) == 1 &&
4196 (!strcasecmp(smartlist_get(elts
,0), "stdout") ||
4197 !strcasecmp(smartlist_get(elts
,0), "stderr"))) {
4198 int err
= smartlist_len(elts
) &&
4199 !strcasecmp(smartlist_get(elts
,0), "stderr");
4200 if (!validate_only
) {
4203 "Can't log to %s with RunAsDaemon set; skipping stdout",
4204 err
?"stderr":"stdout");
4206 add_stream_log(severity
, err
?"<stderr>":"<stdout>",
4207 fileno(err
?stderr
:stdout
));
4212 if (smartlist_len(elts
) == 1 &&
4213 !strcasecmp(smartlist_get(elts
,0), "syslog")) {
4214 #ifdef HAVE_SYSLOG_H
4215 if (!validate_only
) {
4216 add_syslog_log(severity
);
4219 log_warn(LD_CONFIG
, "Syslog is not supported on this system. Sorry.");
4224 if (smartlist_len(elts
) == 2 &&
4225 !strcasecmp(smartlist_get(elts
,0), "file")) {
4226 if (!validate_only
) {
4227 if (add_file_log(severity
, smartlist_get(elts
, 1)) < 0) {
4228 log_warn(LD_CONFIG
, "Couldn't open file for 'Log %s': %s",
4229 opt
->value
, strerror(errno
));
4236 log_warn(LD_CONFIG
, "Bad syntax on file Log option 'Log %s'",
4238 ok
= 0; goto cleanup
;
4241 SMARTLIST_FOREACH(elts
, char*, cp
, tor_free(cp
));
4242 smartlist_clear(elts
);
4245 smartlist_free(elts
);
4250 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4251 * if the line is well-formed, and -1 if it isn't. If
4252 * <b>validate_only</b> is 0, and the line is well-formed, then add
4253 * the bridge described in the line to our internal bridge list. */
4255 parse_bridge_line(const char *line
, int validate_only
)
4257 smartlist_t
*items
= NULL
;
4259 char *addrport
=NULL
, *fingerprint
=NULL
;
4262 char digest
[DIGEST_LEN
];
4264 items
= smartlist_create();
4265 smartlist_split_string(items
, line
, NULL
,
4266 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, -1);
4267 if (smartlist_len(items
) < 1) {
4268 log_warn(LD_CONFIG
, "Too few arguments to Bridge line.");
4271 addrport
= smartlist_get(items
, 0);
4272 smartlist_del_keeporder(items
, 0);
4273 if (tor_addr_port_parse(addrport
, &addr
, &port
)<0) {
4274 log_warn(LD_CONFIG
, "Error parsing Bridge address '%s'", addrport
);
4278 log_warn(LD_CONFIG
, "Missing port in Bridge address '%s'",addrport
);
4282 if (smartlist_len(items
)) {
4283 fingerprint
= smartlist_join_strings(items
, "", 0, NULL
);
4284 if (strlen(fingerprint
) != HEX_DIGEST_LEN
) {
4285 log_warn(LD_CONFIG
, "Key digest for Bridge is wrong length.");
4288 if (base16_decode(digest
, DIGEST_LEN
, fingerprint
, HEX_DIGEST_LEN
)<0) {
4289 log_warn(LD_CONFIG
, "Unable to decode Bridge key digest.");
4294 if (!validate_only
) {
4295 log_debug(LD_DIR
, "Bridge at %s:%d (%s)", fmt_addr(&addr
),
4297 fingerprint
? fingerprint
: "no key listed");
4298 bridge_add_from_config(&addr
, port
, fingerprint
? digest
: NULL
);
4308 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
4309 smartlist_free(items
);
4311 tor_free(fingerprint
);
4315 /** Read the contents of a DirServer line from <b>line</b>. If
4316 * <b>validate_only</b> is 0, and the line is well-formed, and it
4317 * shares any bits with <b>required_type</b> or <b>required_type</b>
4318 * is 0, then add the dirserver described in the line (minus whatever
4319 * bits it's missing) as a valid authority. Return 0 on success,
4320 * or -1 if the line isn't well-formed or if we can't add it. */
4322 parse_dir_server_line(const char *line
, authority_type_t required_type
,
4325 smartlist_t
*items
= NULL
;
4327 char *addrport
=NULL
, *address
=NULL
, *nickname
=NULL
, *fingerprint
=NULL
;
4328 uint16_t dir_port
= 0, or_port
= 0;
4329 char digest
[DIGEST_LEN
];
4330 char v3_digest
[DIGEST_LEN
];
4331 authority_type_t type
= V2_AUTHORITY
;
4332 int is_not_hidserv_authority
= 0, is_not_v2_authority
= 0;
4334 items
= smartlist_create();
4335 smartlist_split_string(items
, line
, NULL
,
4336 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, -1);
4337 if (smartlist_len(items
) < 1) {
4338 log_warn(LD_CONFIG
, "No arguments on DirServer line.");
4342 if (is_legal_nickname(smartlist_get(items
, 0))) {
4343 nickname
= smartlist_get(items
, 0);
4344 smartlist_del_keeporder(items
, 0);
4347 while (smartlist_len(items
)) {
4348 char *flag
= smartlist_get(items
, 0);
4349 if (TOR_ISDIGIT(flag
[0]))
4351 if (!strcasecmp(flag
, "v1")) {
4352 type
|= (V1_AUTHORITY
| HIDSERV_AUTHORITY
);
4353 } else if (!strcasecmp(flag
, "hs")) {
4354 type
|= HIDSERV_AUTHORITY
;
4355 } else if (!strcasecmp(flag
, "no-hs")) {
4356 is_not_hidserv_authority
= 1;
4357 } else if (!strcasecmp(flag
, "bridge")) {
4358 type
|= BRIDGE_AUTHORITY
;
4359 } else if (!strcasecmp(flag
, "no-v2")) {
4360 is_not_v2_authority
= 1;
4361 } else if (!strcasecmpstart(flag
, "orport=")) {
4363 char *portstring
= flag
+ strlen("orport=");
4364 or_port
= (uint16_t) tor_parse_long(portstring
, 10, 1, 65535, &ok
, NULL
);
4366 log_warn(LD_CONFIG
, "Invalid orport '%s' on DirServer line.",
4368 } else if (!strcasecmpstart(flag
, "v3ident=")) {
4369 char *idstr
= flag
+ strlen("v3ident=");
4370 if (strlen(idstr
) != HEX_DIGEST_LEN
||
4371 base16_decode(v3_digest
, DIGEST_LEN
, idstr
, HEX_DIGEST_LEN
)<0) {
4372 log_warn(LD_CONFIG
, "Bad v3 identity digest '%s' on DirServer line",
4375 type
|= V3_AUTHORITY
;
4378 log_warn(LD_CONFIG
, "Unrecognized flag '%s' on DirServer line",
4382 smartlist_del_keeporder(items
, 0);
4384 if (is_not_hidserv_authority
)
4385 type
&= ~HIDSERV_AUTHORITY
;
4386 if (is_not_v2_authority
)
4387 type
&= ~V2_AUTHORITY
;
4389 if (smartlist_len(items
) < 2) {
4390 log_warn(LD_CONFIG
, "Too few arguments to DirServer line.");
4393 addrport
= smartlist_get(items
, 0);
4394 smartlist_del_keeporder(items
, 0);
4395 if (parse_addr_port(LOG_WARN
, addrport
, &address
, NULL
, &dir_port
)<0) {
4396 log_warn(LD_CONFIG
, "Error parsing DirServer address '%s'", addrport
);
4400 log_warn(LD_CONFIG
, "Missing port in DirServer address '%s'",addrport
);
4404 fingerprint
= smartlist_join_strings(items
, "", 0, NULL
);
4405 if (strlen(fingerprint
) != HEX_DIGEST_LEN
) {
4406 log_warn(LD_CONFIG
, "Key digest for DirServer is wrong length %d.",
4407 (int)strlen(fingerprint
));
4410 if (!strcmp(fingerprint
, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4411 /* a known bad fingerprint. refuse to use it. We can remove this
4412 * clause once Tor 0.1.2.17 is obsolete. */
4413 log_warn(LD_CONFIG
, "Dangerous dirserver line. To correct, erase your "
4414 "torrc file (%s), or reinstall Tor and use the default torrc.",
4418 if (base16_decode(digest
, DIGEST_LEN
, fingerprint
, HEX_DIGEST_LEN
)<0) {
4419 log_warn(LD_CONFIG
, "Unable to decode DirServer key digest.");
4423 if (!validate_only
&& (!required_type
|| required_type
& type
)) {
4425 type
&= required_type
; /* pare down what we think of them as an
4427 log_debug(LD_DIR
, "Trusted %d dirserver at %s:%d (%s)", (int)type
,
4428 address
, (int)dir_port
, (char*)smartlist_get(items
,0));
4429 if (!add_trusted_dir_server(nickname
, address
, dir_port
, or_port
,
4430 digest
, v3_digest
, type
))
4441 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
4442 smartlist_free(items
);
4446 tor_free(fingerprint
);
4450 /** Adjust the value of options->DataDirectory, or fill it in if it's
4451 * absent. Return 0 on success, -1 on failure. */
4453 normalize_data_directory(or_options_t
*options
)
4457 if (options
->DataDirectory
)
4458 return 0; /* all set */
4459 p
= tor_malloc(MAX_PATH
);
4460 strlcpy(p
,get_windows_conf_root(),MAX_PATH
);
4461 options
->DataDirectory
= p
;
4464 const char *d
= options
->DataDirectory
;
4468 if (strncmp(d
,"~/",2) == 0) {
4469 char *fn
= expand_filename(d
);
4471 log_warn(LD_CONFIG
,"Failed to expand filename \"%s\".", d
);
4474 if (!options
->DataDirectory
&& !strcmp(fn
,"/.tor")) {
4475 /* If our homedir is /, we probably don't want to use it. */
4476 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4479 "Default DataDirectory is \"~/.tor\". This expands to "
4480 "\"%s\", which is probably not what you want. Using "
4481 "\"%s"PATH_SEPARATOR
"tor\" instead
", fn, LOCALSTATEDIR);
4483 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor
");
4485 tor_free(options->DataDirectory);
4486 options->DataDirectory = fn;
4492 /** Check and normalize the value of options->DataDirectory; return 0 if it
4493 * sane, -1 otherwise. */
4495 validate_data_directory(or_options_t *options)
4497 if (normalize_data_directory(options) < 0)
4499 tor_assert(options->DataDirectory);
4500 if (strlen(options->DataDirectory) > (512-128)) {
4501 log_warn(LD_CONFIG, "DataDirectory is too
long.");
4507 /** This string must remain the same forevermore. It is how we
4508 * recognize that the torrc file doesn't need to be backed up. */
4509 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4510 "if you edit it, comments will not be preserved"
4511 /** This string can change; it tries to give the reader an idea
4512 * that editing this file by hand is not a good plan. */
4513 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4514 "to torrc.orig.1 or similar, and Tor will ignore it"
4516 /** Save a configuration file for the configuration in <b>options</b>
4517 * into the file <b>fname</b>. If the file already exists, and
4518 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4519 * replace it. Return 0 on success, -1 on failure. */
4521 write_configuration_file(const char *fname, or_options_t *options)
4523 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4524 int rename_old = 0, r;
4529 switch (file_status(fname)) {
4531 old_val = read_file_to_str(fname, 0, NULL);
4532 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4543 "Config file \"%s\" is not a file? Failing.", fname);
4547 if (!(new_conf = options_dump(options, 1))) {
4548 log_warn(LD_BUG, "Couldn't get configuration string");
4552 len = strlen(new_conf)+256;
4553 new_val = tor_malloc(len);
4554 tor_snprintf(new_val, len, "%s\n%s\n\n%s",
4555 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4559 size_t fn_tmp_len = strlen(fname)+32;
4561 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4562 fn_tmp = tor_malloc(fn_tmp_len);
4564 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4565 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4569 if (file_status(fn_tmp) == FN_NOENT)
4573 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4574 if (rename(fname, fn_tmp) < 0) {
4576 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4577 fname, fn_tmp, strerror(errno));
4584 if (write_str_to_file(fname, new_val, 0) < 0)
4598 * Save the current configuration file value to disk. Return 0 on
4599 * success, -1 on failure.
4602 options_save_current(void)
4605 /* This fails if we can't write to our configuration file.
4607 * If we try falling back to datadirectory or something, we have a better
4608 * chance of saving the configuration, but a better chance of doing
4609 * something the user never expected. Let's just warn instead. */
4610 return write_configuration_file(torrc_fname, get_options());
4612 return write_configuration_file(get_default_conf_file(), get_options());
4615 /** Mapping from a unit name to a multiplier for converting that unit into a
4617 struct unit_table_t {
4619 uint64_t multiplier;
4622 /** Table to map the names of memory units to the number of bytes they
4624 static struct unit_table_t memory_units[] = {
4631 { "kbytes", 1<<10 },
4632 { "kilobyte", 1<<10 },
4633 { "kilobytes", 1<<10 },
4637 { "mbytes", 1<<20 },
4638 { "megabyte", 1<<20 },
4639 { "megabytes", 1<<20 },
4642 { "gbytes", 1<<30 },
4643 { "gigabyte", 1<<30 },
4644 { "gigabytes", 1<<30 },
4645 { "tb", U64_LITERAL(1)<<40 },
4646 { "terabyte", U64_LITERAL(1)<<40 },
4647 { "terabytes", U64_LITERAL(1)<<40 },
4651 /** Table to map the names of time units to the number of seconds they
4653 static struct unit_table_t time_units[] = {
4661 { "day", 24*60*60 },
4662 { "days", 24*60*60 },
4663 { "week", 7*24*60*60 },
4664 { "weeks", 7*24*60*60 },
4668 /** Parse a string <b>val</b> containing a number, zero or more
4669 * spaces, and an optional unit string. If the unit appears in the
4670 * table <b>u</b>, then multiply the number by the unit multiplier.
4671 * On success, set *<b>ok</b> to 1 and return this product.
4672 * Otherwise, set *<b>ok</b> to 0.
4675 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4682 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4689 while (TOR_ISSPACE(*cp))
4691 for ( ;u->unit;++u) {
4692 if (!strcasecmp(u->unit, cp)) {
4698 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4703 /** Parse a string in the format "number unit", where unit is a unit of
4704 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4705 * and return the number of bytes specified. Otherwise, set
4706 * *<b>ok</b> to false and return 0. */
4708 config_parse_memunit(const char *s, int *ok)
4710 return config_parse_units(s, memory_units, ok);
4713 /** Parse a string in the format "number unit", where unit is a unit of time.
4714 * On success, set *<b>ok</b> to true and return the number of seconds in
4715 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4718 config_parse_interval(const char *s, int *ok)
4721 r = config_parse_units(s, time_units, ok);
4725 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4733 * Initialize the libevent library.
4738 configure_libevent_logging();
4739 /* If the kernel complains that some method (say, epoll) doesn't
4740 * exist, we don't care about it, since libevent will cope.
4742 suppress_libevent_log_msg("Function not implemented");
4744 if (decode_libevent_version() < LE_11B) {
4745 setenv("EVENT_NOKQUEUE","1",1);
4749 suppress_libevent_log_msg(NULL);
4750 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4751 /* Making this a NOTICE for now so we can link bugs to a libevent versions
4752 * or methods better. */
4753 log(LOG_NOTICE, LD_GENERAL,
4754 "Initialized libevent version %s using method %s. Good.",
4755 event_get_version(), event_get_method());
4756 check_libevent_version(event_get_method(), get_options()->ORPort != 0);
4758 log(LOG_NOTICE, LD_GENERAL,
4759 "Initialized old libevent (version 1.0b or earlier).");
4760 log(LOG_WARN, LD_GENERAL,
4761 "You have a *VERY* old version of libevent. It is likely to be buggy; "
4762 "please build Tor with a more recent version.");
4766 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4767 /** Table mapping return value of event_get_version() to le_version_t. */
4768 static const struct {
4769 const char *name; le_version_t version;
4770 } le_version_table[] = {
4771 /* earlier versions don't have get_version. */
4788 /** Return the le_version_t for the current version of libevent. If the
4789 * version is very new, return LE_OTHER. If the version is so old that it
4790 * doesn't support event_get_version(), return LE_OLD. */
4792 decode_libevent_version(void)
4794 const char *v = event_get_version();
4796 for (i=0; le_version_table[i].name; ++i) {
4797 if (!strcmp(le_version_table[i].name, v)) {
4798 return le_version_table[i].version;
4805 * Compare the given libevent method and version to a list of versions
4806 * which are known not to work. Warn the user as appropriate.
4809 check_libevent_version(const char *m, int server)
4811 int buggy = 0, iffy = 0, slow = 0, thread_unsafe = 0;
4812 le_version_t version;
4813 const char *v = event_get_version();
4814 const char *badness = NULL;
4815 const char *sad_os = "";
4817 version = decode_libevent_version();
4819 /* XXX Would it be worthwhile disabling the methods that we know
4820 * are buggy, rather than just warning about them and then proceeding
4821 * to use them? If so, we should probably not wrap this whole thing
4822 * in HAVE_EVENT_GET_VERSION and HAVE_EVENT_GET_METHOD. -RD */
4823 /* XXXX The problem is that it's not trivial to get libevent to change it's
4824 * method once it's initialized, and it's not trivial to tell what method it
4825 * will use without initializing it. I guess we could preemptively disable
4826 * buggy libevent modes based on the version _before_ initializing it,
4827 * though, but then there's no good way (afaict) to warn "I would have used
4828 * kqueue
, but instead I
'm using select." -NM */
4829 if (!strcmp(m, "kqueue")) {
4830 if (version < LE_11B)
4832 } else if (!strcmp(m, "epoll")) {
4833 if (version < LE_11)
4835 } else if (!strcmp(m, "poll")) {
4836 if (version < LE_10E)
4838 else if (version < LE_11)
4840 } else if (!strcmp(m, "select")) {
4841 if (version < LE_11)
4843 } else if (!strcmp(m, "win32")) {
4844 if (version < LE_11B)
4848 /* Libevent versions before 1.3b do very badly on operating systems with
4849 * user-space threading implementations. */
4850 #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
4851 if (server && version < LE_13B) {
4853 sad_os = "BSD variants";
4855 #elif defined(__APPLE__) || defined(__darwin__)
4856 if (server && version < LE_13B) {
4858 sad_os = "Mac OS X";
4862 if (thread_unsafe) {
4863 log(LOG_WARN, LD_GENERAL,
4864 "Libevent version %s often crashes when running a Tor server with %s. "
4865 "Please use the latest version of libevent (1.3b or later)",v,sad_os);
4868 log(LOG_WARN, LD_GENERAL,
4869 "There are serious bugs in using %s with libevent %s. "
4870 "Please use the latest version of libevent.", m, v);
4873 log(LOG_WARN, LD_GENERAL,
4874 "There are minor bugs in using %s with libevent %s. "
4875 "You may want to use the latest version of libevent.", m, v);
4877 } else if (slow && server) {
4878 log(LOG_WARN, LD_GENERAL,
4879 "libevent %s can be very slow with %s. "
4880 "When running a server, please use the latest version of libevent.",
4885 control_event_general_status(LOG_WARN,
4886 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
4893 decode_libevent_version(void)
4899 /** Return the persistent state struct for this Tor. */
4903 tor_assert(global_state);
4904 return global_state;
4907 /** Return a newly allocated string holding a filename relative to the data
4908 * directory. If <b>sub1</b> is present, it is the first path component after
4909 * the data directory. If <b>sub2</b> is also present, it is the second path
4910 * component after the data directory. If <b>suffix</b> is present, it
4911 * is appended to the filename.
4914 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
4915 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
4916 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
4917 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
4919 * Note: Consider using the get_datadir_fname* macros in or.h.
4922 options_get_datadir_fname2_suffix(or_options_t *options,
4923 const char *sub1, const char *sub2,
4928 tor_assert(options);
4929 tor_assert(options->DataDirectory);
4930 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
4931 len = strlen(options->DataDirectory);
4933 len += strlen(sub1)+1;
4935 len += strlen(sub2)+1;
4938 len += strlen(suffix);
4940 fname = tor_malloc(len);
4943 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
4944 options->DataDirectory, sub1, sub2);
4946 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
4947 options->DataDirectory, sub1);
4950 strlcpy(fname, options->DataDirectory, len);
4953 strlcat(fname, suffix, len);
4957 /** Return 0 if every setting in <b>state</b> is reasonable, and a
4958 * permissible transition from <b>old_state</b>. Else warn and return -1.
4959 * Should have no side effects, except for normalizing the contents of
4962 /* XXX from_setconf is here because of bug 238 */
4964 or_state_validate(or_state_t *old_state, or_state_t *state,
4965 int from_setconf, char **msg)
4967 /* We don't use these
; only options
do. Still
, we need to match that
4969 (void) from_setconf
;
4972 if (entry_guards_parse_state(state
, 0, msg
)<0)
4978 /** Replace the current persistent state with <b>new_state</b> */
4980 or_state_set(or_state_t
*new_state
)
4983 tor_assert(new_state
);
4985 config_free(&state_format
, global_state
);
4986 global_state
= new_state
;
4987 if (entry_guards_parse_state(global_state
, 1, &err
)<0) {
4988 log_warn(LD_GENERAL
,"%s",err
);
4991 if (rep_hist_load_state(global_state
, &err
)<0) {
4992 log_warn(LD_GENERAL
,"Unparseable bandwidth history state: %s",err
);
4997 /** Reload the persistent state from disk, generating a new state as needed.
4998 * Return 0 on success, less than 0 on failure.
5003 or_state_t
*new_state
= NULL
;
5004 char *contents
= NULL
, *fname
;
5005 char *errmsg
= NULL
;
5006 int r
= -1, badstate
= 0;
5008 fname
= get_datadir_fname("state");
5009 switch (file_status(fname
)) {
5011 if (!(contents
= read_file_to_str(fname
, 0, NULL
))) {
5012 log_warn(LD_FS
, "Unable to read state file \"%s\"", fname
);
5021 log_warn(LD_GENERAL
,"State file \"%s\" is not a file? Failing.", fname
);
5024 new_state
= tor_malloc_zero(sizeof(or_state_t
));
5025 new_state
->_magic
= OR_STATE_MAGIC
;
5026 config_init(&state_format
, new_state
);
5028 config_line_t
*lines
=NULL
;
5030 if (config_get_lines(contents
, &lines
)<0)
5032 assign_retval
= config_assign(&state_format
, new_state
,
5033 lines
, 0, 0, &errmsg
);
5034 config_free_lines(lines
);
5035 if (assign_retval
<0)
5038 log_warn(LD_GENERAL
, "%s", errmsg
);
5043 if (!badstate
&& or_state_validate(NULL
, new_state
, 1, &errmsg
) < 0)
5047 log_warn(LD_GENERAL
, "%s", errmsg
);
5051 if (badstate
&& !contents
) {
5052 log_warn(LD_BUG
, "Uh oh. We couldn't even validate our own default state."
5053 " This is a bug in Tor.");
5055 } else if (badstate
&& contents
) {
5057 file_status_t status
;
5058 size_t len
= strlen(fname
)+16;
5059 char *fname2
= tor_malloc(len
);
5060 for (i
= 0; i
< 100; ++i
) {
5061 tor_snprintf(fname2
, len
, "%s.%d", fname
, i
);
5062 status
= file_status(fname2
);
5063 if (status
== FN_NOENT
)
5067 log_warn(LD_BUG
, "Unable to parse state in \"%s\"; too many saved bad "
5068 "state files to move aside. Discarding the old state file.",
5072 log_warn(LD_BUG
, "Unable to parse state in \"%s\". Moving it aside "
5073 "to \"%s\". This could be a bug in Tor; please tell "
5074 "the developers.", fname
, fname2
);
5075 if (rename(fname
, fname2
) < 0) {
5076 log_warn(LD_BUG
, "Weirdly, I couldn't even move the state aside. The "
5077 "OS gave an error of %s", strerror(errno
));
5082 config_free(&state_format
, new_state
);
5084 new_state
= tor_malloc_zero(sizeof(or_state_t
));
5085 new_state
->_magic
= OR_STATE_MAGIC
;
5086 config_init(&state_format
, new_state
);
5087 } else if (contents
) {
5088 log_info(LD_GENERAL
, "Loaded state from \"%s\"", fname
);
5090 log_info(LD_GENERAL
, "Initialized state");
5092 or_state_set(new_state
);
5095 global_state
->next_write
= 0;
5096 or_state_save(time(NULL
));
5104 config_free(&state_format
, new_state
);
5109 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
5111 or_state_save(time_t now
)
5113 char *state
, *contents
;
5114 char tbuf
[ISO_TIME_LEN
+1];
5118 tor_assert(global_state
);
5120 if (global_state
->next_write
> now
)
5123 /* Call everything else that might dirty the state even more, in order
5124 * to avoid redundant writes. */
5125 entry_guards_update_state(global_state
);
5126 rep_hist_update_state(global_state
);
5127 if (accounting_is_enabled(get_options()))
5128 accounting_run_housekeeping(now
);
5130 global_state
->LastWritten
= time(NULL
);
5131 tor_free(global_state
->TorVersion
);
5132 len
= strlen(get_version())+8;
5133 global_state
->TorVersion
= tor_malloc(len
);
5134 tor_snprintf(global_state
->TorVersion
, len
, "Tor %s", get_version());
5136 state
= config_dump(&state_format
, global_state
, 1, 0);
5137 len
= strlen(state
)+256;
5138 contents
= tor_malloc(len
);
5139 format_local_iso_time(tbuf
, time(NULL
));
5140 tor_snprintf(contents
, len
,
5141 "# Tor state file last generated on %s local time\n"
5142 "# Other times below are in GMT\n"
5143 "# You *do not* need to edit this file.\n\n%s",
5146 fname
= get_datadir_fname("state");
5147 if (write_str_to_file(fname
, contents
, 0)<0) {
5148 log_warn(LD_FS
, "Unable to write state to file \"%s\"", fname
);
5153 log_info(LD_GENERAL
, "Saved state to \"%s\"", fname
);
5157 global_state
->next_write
= TIME_MAX
;
5161 /** Given a file name check to see whether the file exists but has not been
5162 * modified for a very long time. If so, remove it. */
5164 remove_file_if_very_old(const char *fname
, time_t now
)
5166 #define VERY_OLD_FILE_AGE (28*24*60*60)
5169 if (stat(fname
, &st
)==0 && st
.st_mtime
< now
-VERY_OLD_FILE_AGE
) {
5170 char buf
[ISO_TIME_LEN
+1];
5171 format_local_iso_time(buf
, st
.st_mtime
);
5172 log_notice(LD_GENERAL
, "Obsolete file %s hasn't been modified since %s. "
5173 "Removing it.", fname
, buf
);
5178 /** Helper to implement GETINFO functions about configuration variables (not
5179 * their values). Given a "config/names" question, set *<b>answer</b> to a
5180 * new string describing the supported configuration variables and their
5183 getinfo_helper_config(control_connection_t
*conn
,
5184 const char *question
, char **answer
)
5187 if (!strcmp(question
, "config/names")) {
5188 smartlist_t
*sl
= smartlist_create();
5190 for (i
= 0; _option_vars
[i
].name
; ++i
) {
5191 config_var_t
*var
= &_option_vars
[i
];
5192 const char *type
, *desc
;
5195 desc
= config_find_description(&options_format
, var
->name
);
5196 switch (var
->type
) {
5197 case CONFIG_TYPE_STRING
: type
= "String"; break;
5198 case CONFIG_TYPE_FILENAME
: type
= "Filename"; break;
5199 case CONFIG_TYPE_UINT
: type
= "Integer"; break;
5200 case CONFIG_TYPE_INTERVAL
: type
= "TimeInterval"; break;
5201 case CONFIG_TYPE_MEMUNIT
: type
= "DataSize"; break;
5202 case CONFIG_TYPE_DOUBLE
: type
= "Float"; break;
5203 case CONFIG_TYPE_BOOL
: type
= "Boolean"; break;
5204 case CONFIG_TYPE_ISOTIME
: type
= "Time"; break;
5205 case CONFIG_TYPE_ROUTERSET
: type
= "RouterList"; break;
5206 case CONFIG_TYPE_CSV
: type
= "CommaList"; break;
5207 case CONFIG_TYPE_LINELIST
: type
= "LineList"; break;
5208 case CONFIG_TYPE_LINELIST_S
: type
= "Dependant"; break;
5209 case CONFIG_TYPE_LINELIST_V
: type
= "Virtual"; break;
5211 case CONFIG_TYPE_OBSOLETE
:
5216 len
= strlen(var
->name
)+strlen(type
)+16;
5218 len
+= strlen(desc
);
5219 line
= tor_malloc(len
);
5221 tor_snprintf(line
, len
, "%s %s %s\n",var
->name
,type
,desc
);
5223 tor_snprintf(line
, len
, "%s %s\n",var
->name
,type
);
5224 smartlist_add(sl
, line
);
5226 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
5227 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
5237 extern const char address_c_id
[];
5238 extern const char aes_c_id
[];
5239 extern const char compat_c_id
[];
5240 extern const char container_c_id
[];
5241 extern const char crypto_c_id
[];
5242 extern const char log_c_id
[];
5243 extern const char torgzip_c_id
[];
5244 extern const char tortls_c_id
[];
5245 extern const char util_c_id
[];
5247 extern const char buffers_c_id
[];
5248 extern const char circuitbuild_c_id
[];
5249 extern const char circuitlist_c_id
[];
5250 extern const char circuituse_c_id
[];
5251 extern const char command_c_id
[];
5252 // extern const char config_c_id[];
5253 extern const char connection_c_id
[];
5254 extern const char connection_edge_c_id
[];
5255 extern const char connection_or_c_id
[];
5256 extern const char control_c_id
[];
5257 extern const char cpuworker_c_id
[];
5258 extern const char directory_c_id
[];
5259 extern const char dirserv_c_id
[];
5260 extern const char dns_c_id
[];
5261 extern const char hibernate_c_id
[];
5262 extern const char main_c_id
[];
5264 extern const char ntmain_c_id
[];
5266 extern const char onion_c_id
[];
5267 extern const char policies_c_id
[];
5268 extern const char relay_c_id
[];
5269 extern const char rendclient_c_id
[];
5270 extern const char rendcommon_c_id
[];
5271 extern const char rendmid_c_id
[];
5272 extern const char rendservice_c_id
[];
5273 extern const char rephist_c_id
[];
5274 extern const char router_c_id
[];
5275 extern const char routerlist_c_id
[];
5276 extern const char routerparse_c_id
[];
5278 /** Dump the version of every file to the log. */
5280 print_svn_version(void)
5285 puts(CONTAINER_H_ID
);
5297 puts(container_c_id
);
5306 puts(circuitbuild_c_id
);
5307 puts(circuitlist_c_id
);
5308 puts(circuituse_c_id
);
5311 puts(connection_c_id
);
5312 puts(connection_edge_c_id
);
5313 puts(connection_or_c_id
);
5315 puts(cpuworker_c_id
);
5316 puts(directory_c_id
);
5319 puts(hibernate_c_id
);
5325 puts(policies_c_id
);
5327 puts(rendclient_c_id
);
5328 puts(rendcommon_c_id
);
5330 puts(rendservice_c_id
);
5333 puts(routerlist_c_id
);
5334 puts(routerparse_c_id
);